code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def create_tf_record_dataset( filenames: MutableSequence[Text], batch_size: int, shuffle_buffer_size_per_record: int = 100, shuffle_buffer_size: int = 100, load_buffer_size: int = 100000000, num_shards: int = 50, cycle_length: int = tf.data.experimental.AUTOTUNE, block_length: int = 10, ...
Create a TF dataset from a list of filenames. A dataset is created for each record file and these are interleaved together to create the final dataset. Args: filenames: List of filenames of a TFRecord dataset containing TF Examples. batch_size: The batch size of tensors in the returned dataset. shuf...
create_tf_record_dataset
python
tensorflow/agents
tf_agents/examples/cql_sac/kumar20/data_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/cql_sac/kumar20/data_utils.py
Apache-2.0
def create_collect_data_spec( dataset_dict: EpisodeDictType, use_trajectories: bool = True ) -> Union[trajectory.Transition, trajectory.Trajectory]: """Create a spec that describes the data collected by agent.collect_policy.""" reward = dataset_dict['rewards'][0] discount = dataset_dict['discounts'][0] obse...
Create a spec that describes the data collected by agent.collect_policy.
create_collect_data_spec
python
tensorflow/agents
tf_agents/examples/cql_sac/kumar20/dataset/dataset_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/cql_sac/kumar20/dataset/dataset_utils.py
Apache-2.0
def create_trajectory( state: types.Array, action: types.Array, discount: types.Array, reward: types.Array, step_type: types.Array, next_step_type: types.Array, ) -> trajectory.Trajectory: """Creates a Trajectory from current and next state information.""" return trajectory.Trajectory( ...
Creates a Trajectory from current and next state information.
create_trajectory
python
tensorflow/agents
tf_agents/examples/cql_sac/kumar20/dataset/file_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/cql_sac/kumar20/dataset/file_utils.py
Apache-2.0
def create_transition( state: types.Array, action: types.Array, next_state: types.Array, discount: types.Array, reward: types.Array, step_type: types.Array, next_step_type: types.Array, ) -> trajectory.Transition: """Creates a Transition from current and next state information.""" tfagen...
Creates a Transition from current and next state information.
create_transition
python
tensorflow/agents
tf_agents/examples/cql_sac/kumar20/dataset/file_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/cql_sac/kumar20/dataset/file_utils.py
Apache-2.0
def write_samples_to_tfrecord( dataset_dict: Dict[str, types.Array], collect_data_spec: trajectory.Transition, dataset_path: str, start_episode: int, end_episode: int, use_trajectories: bool = True, ) -> None: """Creates and writes samples to a TFRecord file.""" tfrecord_observer = example_e...
Creates and writes samples to a TFRecord file.
write_samples_to_tfrecord
python
tensorflow/agents
tf_agents/examples/cql_sac/kumar20/dataset/file_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/cql_sac/kumar20/dataset/file_utils.py
Apache-2.0
def q_lstm_network(num_actions): """Create the RNN based on layer parameters.""" lstm_cell = tf.keras.layers.LSTM( # pylint: disable=g-complex-comprehension 20, implementation=KERAS_LSTM_FUSED, return_state=True, return_sequences=True, ) return sequential.Sequential( [dense(50), ...
Create the RNN based on layer parameters.
q_lstm_network
python
tensorflow/agents
tf_agents/examples/dqn/dqn_train_eval_rnn.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/dqn/dqn_train_eval_rnn.py
Apache-2.0
def create_q_network(num_actions): """Create a Q network following the architecture from Minh 15.""" kernel_initializer = tf.keras.initializers.VarianceScaling(scale=2.0) conv2d = functools.partial( tf.keras.layers.Conv2D, activation=tf.keras.activations.relu, kernel_initializer=kernel_initiali...
Create a Q network following the architecture from Minh 15.
create_q_network
python
tensorflow/agents
tf_agents/examples/dqn/mnih15/dqn_train_eval_atari.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/dqn/mnih15/dqn_train_eval_atari.py
Apache-2.0
def ppo_clip_train_eval( root_dir, num_iterations, reverb_port=None, eval_interval=0 ): """Executes train and eval for ppo_clip. gin is used to configure parameters related to the agent and environment. Arguments related to the execution, e.g. number of iterations and how often to eval, are set directly by...
Executes train and eval for ppo_clip. gin is used to configure parameters related to the agent and environment. Arguments related to the execution, e.g. number of iterations and how often to eval, are set directly by this method. This keeps the gin config focused on the agent and execution level arguments quic...
ppo_clip_train_eval
python
tensorflow/agents
tf_agents/examples/ppo/schulman17/ppo_clip_train_eval.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/ppo/schulman17/ppo_clip_train_eval.py
Apache-2.0
def __call__(self, trajectory): """Writes the trajectory into the underlying replay buffer. Allows trajectory to be a flattened trajectory. No batch dimension allowed. Args: trajectory: The trajectory to be written which could be (possibly nested) trajectory object or a flattened version of ...
Writes the trajectory into the underlying replay buffer. Allows trajectory to be a flattened trajectory. No batch dimension allowed. Args: trajectory: The trajectory to be written which could be (possibly nested) trajectory object or a flattened version of a trajectory. It assumes there ...
__call__
python
tensorflow/agents
tf_agents/examples/ppo/schulman17/train_eval_lib.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/ppo/schulman17/train_eval_lib.py
Apache-2.0
def train_eval( root_dir, env_name='HalfCheetah-v2', # Training params num_iterations=1600, actor_fc_layers=(64, 64), value_fc_layers=(64, 64), learning_rate=3e-4, collect_sequence_length=2048, minibatch_size=64, num_epochs=10, # Agent params importance_ratio_clipping=0.2...
Trains and evaluates PPO (Importance Ratio Clipping). Args: root_dir: Main directory path where checkpoints, saved_models, and summaries will be written to. env_name: Name for the Mujoco environment to load. num_iterations: The number of iterations to perform collection and training. actor_fc_l...
train_eval
python
tensorflow/agents
tf_agents/examples/ppo/schulman17/train_eval_lib.py
https://github.com/tensorflow/agents/blob/master/tf_agents/examples/ppo/schulman17/train_eval_lib.py
Apache-2.0
def __init__( self, server_address: Text, table_names: Iterable[Text] = (DEFAULT_TABLE,) ): """Initializes the class. Args: server_address: The address of the Reverb server. table_names: Table names. By default, it is assumed that only a single table is used with the name `variables...
Initializes the class. Args: server_address: The address of the Reverb server. table_names: Table names. By default, it is assumed that only a single table is used with the name `variables`. Each table assumed to exist in the server, has signature defined, and set the capacity to 1. ...
__init__
python
tensorflow/agents
tf_agents/experimental/distributed/reverb_variable_container.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/reverb_variable_container.py
Apache-2.0
def push( self, values: types.NestedTensor, table: Text = DEFAULT_TABLE ) -> None: """Pushes values into a Reverb table. Args: values: Nested structure of tensors. table: The name of the table. Raises: KeyError: If the table name is not provided during construction time. tf...
Pushes values into a Reverb table. Args: values: Nested structure of tensors. table: The name of the table. Raises: KeyError: If the table name is not provided during construction time. tf.errors.InvalidArgumentError: If the nested structure of the variable does not match the s...
push
python
tensorflow/agents
tf_agents/experimental/distributed/reverb_variable_container.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/reverb_variable_container.py
Apache-2.0
def pull(self, table: Text = DEFAULT_TABLE) -> types.NestedTensor: """Pulls values from a Reverb table and returns them as nested tensors.""" sample = self._tf_client.sample(table, data_dtypes=[self._dtypes[table]]) # The data is received in the form of a sequence. In the case of variable # container th...
Pulls values from a Reverb table and returns them as nested tensors.
pull
python
tensorflow/agents
tf_agents/experimental/distributed/reverb_variable_container.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/reverb_variable_container.py
Apache-2.0
def update( self, variables: types.NestedVariable, table: Text = DEFAULT_TABLE ) -> None: """Updates variables using values pulled from a Reverb table. Args: variables: Nested structure of variables. table: The name of the table. Raises: KeyError: If the table name is not provide...
Updates variables using values pulled from a Reverb table. Args: variables: Nested structure of variables. table: The name of the table. Raises: KeyError: If the table name is not provided during construction time. ValueError: If the nested structure of the variable does not match the ...
update
python
tensorflow/agents
tf_agents/experimental/distributed/reverb_variable_container.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/reverb_variable_container.py
Apache-2.0
def _assign( self, variables: types.NestedVariable, values: types.NestedTensor, check_types: bool = False, ) -> None: """Assigns the nested values to variables.""" nest_utils.assert_same_structure(variables, values, check_types=check_types) for variable, value in zip( tf.ne...
Assigns the nested values to variables.
_assign
python
tensorflow/agents
tf_agents/experimental/distributed/reverb_variable_container.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/reverb_variable_container.py
Apache-2.0
def evaluate( summary_dir: Text, environment_name: Text, policy: py_tf_eager_policy.PyTFEagerPolicyBase, variable_container: reverb_variable_container.ReverbVariableContainer, suite_load_fn: Callable[ [Text], py_environment.PyEnvironment ] = suite_mujoco.load, additional_metrics: Opt...
Evaluates a policy iteratively fetching weights from variable container. Args: summary_dir: Directory which is used to store the summaries. environment_name: Name of the environment used to evaluate the policy. policy: The policy being evaluated. The weights of this policy are fetched from the vari...
evaluate
python
tensorflow/agents
tf_agents/experimental/distributed/examples/eval_job.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/examples/eval_job.py
Apache-2.0
def run_eval( root_dir: Text, # TODO(b/178225158): Deprecate in favor of the reporting libray when ready. return_reporting_fn: Optional[Callable[[int, float], None]] = None, ) -> None: """Load the policy and evaluate it. Args: root_dir: the root directory for this experiment. return_reporting_f...
Load the policy and evaluate it. Args: root_dir: the root directory for this experiment. return_reporting_fn: Optional callback function of the form `fn(train_step, average_return)` which reports the average return to a custom destination.
run_eval
python
tensorflow/agents
tf_agents/experimental/distributed/examples/eval_job.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/examples/eval_job.py
Apache-2.0
def test_eval_job(self): """Tests the eval job doing an eval every 5 steps for 10 train steps.""" summary_dir = self.create_tempdir().full_path environment = test_envs.CountingEnv(steps_per_episode=4) action_tensor_spec = tensor_spec.from_spec(environment.action_spec()) time_step_tensor_spec = tenso...
Tests the eval job doing an eval every 5 steps for 10 train steps.
test_eval_job
python
tensorflow/agents
tf_agents/experimental/distributed/examples/eval_job_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/examples/eval_job_test.py
Apache-2.0
def test_eval_job_constant_eval(self): """Tests eval every step for 2 steps. This test's `variable_container` passes the same train step twice to test that `is_train_step_the_same_or_behind` is working as expected. If were not working, the number of train steps processed will be incorrect (2x higher). ...
Tests eval every step for 2 steps. This test's `variable_container` passes the same train step twice to test that `is_train_step_the_same_or_behind` is working as expected. If were not working, the number of train steps processed will be incorrect (2x higher).
test_eval_job_constant_eval
python
tensorflow/agents
tf_agents/experimental/distributed/examples/eval_job_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/examples/eval_job_test.py
Apache-2.0
def count_summary_scalar_tags_in_call_list(self, mock_summary_scalar, tag): """Returns the number of time the tag is found in `mock_summary_scalar`. This is used because `assert_has_calls` uses a list for verification that is cumbersome and produces confusing error messages on unit test failure. Exampl...
Returns the number of time the tag is found in `mock_summary_scalar`. This is used because `assert_has_calls` uses a list for verification that is cumbersome and produces confusing error messages on unit test failure. Example: Index out of bounds if more values exist than expected. This is not intutive...
count_summary_scalar_tags_in_call_list
python
tensorflow/agents
tf_agents/experimental/distributed/examples/eval_job_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/examples/eval_job_test.py
Apache-2.0
def collect( summary_dir: Text, environment_name: Text, collect_policy: py_tf_eager_policy.PyTFEagerPolicyBase, replay_buffer_server_address: Text, variable_container_server_address: Text, suite_load_fn: Callable[ [Text], py_environment.PyEnvironment ] = suite_mujoco.load, initia...
Collects experience using a policy updated after every episode.
collect
python
tensorflow/agents
tf_agents/experimental/distributed/examples/sac/sac_collect.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/distributed/examples/sac/sac_collect.py
Apache-2.0
def train_eval( root_dir, env_name='HalfCheetah-v2', # Training params num_iterations=1600, actor_fc_layers=(64, 64), value_fc_layers=(64, 64), learning_rate=3e-4, collect_sequence_length=2048, minibatch_size=64, num_epochs=10, # Agent params importance_ratio_clipping=0.2...
Trains and evaluates PPO (Importance Ratio Clipping). Args: root_dir: Main directory path where checkpoints, saved_models, and summaries will be written to. env_name: Name for the Mujoco environment to load. num_iterations: The number of iterations to perform collection and training. actor_fc_l...
train_eval
python
tensorflow/agents
tf_agents/experimental/examples/ppo/train_eval_lib.py
https://github.com/tensorflow/agents/blob/master/tf_agents/experimental/examples/ppo/train_eval_lib.py
Apache-2.0
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: ValueE...
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 empt...
_infer_state_dtype
python
tensorflow/agents
tf_agents/keras_layers/dynamic_unroll_layer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/dynamic_unroll_layer.py
Apache-2.0
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 ...
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 othe...
_best_effort_input_batch_size
python
tensorflow/agents
tf_agents/keras_layers/dynamic_unroll_layer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/dynamic_unroll_layer.py
Apache-2.0
def __init__(self, cell, parallel_iterations=20, swap_memory=None, **kwargs): """Create a `DynamicUnroll` layer. Args: cell: A `tf.nn.rnn_cell.RNNCell` or Keras `RNNCell` (e.g. `LSTMCell`) whose `call()` method has the signature `call(input, state, ...)`. Each tensor in the tuple is shape...
Create a `DynamicUnroll` layer. Args: cell: A `tf.nn.rnn_cell.RNNCell` or Keras `RNNCell` (e.g. `LSTMCell`) whose `call()` method has the signature `call(input, state, ...)`. Each tensor in the tuple is shaped `[batch_size, ...]`. parallel_iterations: Parallel iterations to pass to `tf....
__init__
python
tensorflow/agents
tf_agents/keras_layers/dynamic_unroll_layer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/dynamic_unroll_layer.py
Apache-2.0
def call(self, inputs, initial_state=None, reset_mask=None, training=False): """Perform the computation. Args: inputs: A tuple containing tensors in batch-major format, each shaped `[batch_size, n, ...]`. If none of the inputs has rank greater than 2 (i.e., all inputs are shaped `[batch_...
Perform the computation. Args: inputs: A tuple containing tensors in batch-major format, each shaped `[batch_size, n, ...]`. If none of the inputs has rank greater than 2 (i.e., all inputs are shaped `[batch_size, d]` or `[batch_size]`) then it is assumed that a single frame is being...
call
python
tensorflow/agents
tf_agents/keras_layers/dynamic_unroll_layer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/dynamic_unroll_layer.py
Apache-2.0
def _static_unroll_single_step( cell, inputs, reset_mask, state, zero_state, training ): """Helper for dynamic_unroll which runs a single step.""" def _squeeze(t): if not isinstance(t, tf.TensorArray) and t.shape.rank > 0: return tf.squeeze(t, [0]) else: return t # Remove time dimension....
Helper for dynamic_unroll which runs a single step.
_static_unroll_single_step
python
tensorflow/agents
tf_agents/keras_layers/dynamic_unroll_layer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/dynamic_unroll_layer.py
Apache-2.0
def body(time, state, output_tas): """Internal while_loop body. Args: time: time state: rnn state @ time output_tas: output tensorarrays Returns: - time + 1 - state: rnn state @ time + 1 - output_tas: output tensorarrays with values written @ time - masks_ta: opti...
Internal while_loop body. Args: time: time state: rnn state @ time output_tas: output tensorarrays Returns: - time + 1 - state: rnn state @ time + 1 - output_tas: output tensorarrays with values written @ time - masks_ta: optional mask tensorarray with mask written @ ...
body
python
tensorflow/agents
tf_agents/keras_layers/dynamic_unroll_layer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/dynamic_unroll_layer.py
Apache-2.0
def InnerReshape( current_shape: types.Shape, # pylint: disable=invalid-name new_shape: types.Shape, **kwargs ) -> tf.keras.layers.Layer: """Returns a Keras layer that reshapes the inner dimensions of tensors. Each tensor passed to an instance of `InnerReshape`, will be reshaped to: ```python sha...
Returns a Keras layer that reshapes the inner dimensions of tensors. Each tensor passed to an instance of `InnerReshape`, will be reshaped to: ```python shape(tensor)[:-len(current_shape)] + new_shape ``` (after its inner shape is validated against `current_shape`). Note: The `current_shape` may contain...
InnerReshape
python
tensorflow/agents
tf_agents/keras_layers/inner_reshape.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/inner_reshape.py
Apache-2.0
def _reshape_inner_dims( tensor: tf.Tensor, shape: tf.TensorShape, new_shape: tf.TensorShape ) -> tf.Tensor: """Reshapes tensor to: shape(tensor)[:-len(shape)] + new_shape.""" tensor_shape = tf.shape(tensor) ndims = shape.rank tensor.shape[-ndims:].assert_is_compatible_with(shape) new_shape_inner_tensor =...
Reshapes tensor to: shape(tensor)[:-len(shape)] + new_shape.
_reshape_inner_dims
python
tensorflow/agents
tf_agents/keras_layers/inner_reshape.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/inner_reshape.py
Apache-2.0
def __init__(self, layer: tf.keras.layers.RNN, **kwargs): """Create a `RNNWrapper`. Args: layer: An instance of `tf.keras.layers.RNN` or subclasses (including `tf.keras.layers.{LSTM,GRU,...}`. **kwargs: Extra args to `Layer` parent class. Raises: TypeError: If `layer` is not a su...
Create a `RNNWrapper`. Args: layer: An instance of `tf.keras.layers.RNN` or subclasses (including `tf.keras.layers.{LSTM,GRU,...}`. **kwargs: Extra args to `Layer` parent class. Raises: TypeError: If `layer` is not a subclass of `tf.keras.layers.RNN`. NotImplementedError: If `l...
__init__
python
tensorflow/agents
tf_agents/keras_layers/rnn_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/rnn_wrapper.py
Apache-2.0
def call(self, inputs, initial_state=None, mask=None, training=False): """Perform the computation. Args: inputs: A tuple containing tensors in batch-major format, each shaped `[batch_size, n, ...]`. initial_state: (Optional) An initial state for the wrapped layer. If not provided, `...
Perform the computation. Args: inputs: A tuple containing tensors in batch-major format, each shaped `[batch_size, n, ...]`. initial_state: (Optional) An initial state for the wrapped layer. If not provided, `get_initial_state()` is used instead. mask: The mask to pass down to the...
call
python
tensorflow/agents
tf_agents/keras_layers/rnn_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/rnn_wrapper.py
Apache-2.0
def __init__( self, wrapped: tf.keras.layers.Layer, inner_rank: int, **kwargs: Mapping[Text, Any] ): """Initialize `SquashedOuterWrapper`. Args: wrapped: The keras layer to wrap. inner_rank: The inner rank of inputs that will be passed to the layer. This value allo...
Initialize `SquashedOuterWrapper`. Args: wrapped: The keras layer to wrap. inner_rank: The inner rank of inputs that will be passed to the layer. This value allows us to infer the outer batch dimension regardless of the input shape to `build` or `call`. **kwargs: Additional argume...
__init__
python
tensorflow/agents
tf_agents/keras_layers/squashed_outer_wrapper.py
https://github.com/tensorflow/agents/blob/master/tf_agents/keras_layers/squashed_outer_wrapper.py
Apache-2.0
def call(self, batched_trajectory: traj.Trajectory): """Processes the batched_trajectory to update the metric. Args: batched_trajectory: A Trajectory containing batches of experience. Raises: ValueError: If the batch size is an unexpected value. """ trajectories = nest_utils.unstack_ne...
Processes the batched_trajectory to update the metric. Args: batched_trajectory: A Trajectory containing batches of experience. Raises: ValueError: If the batch size is an unexpected value.
call
python
tensorflow/agents
tf_agents/metrics/batched_py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/batched_py_metric.py
Apache-2.0
def reset(self): """Resets internal stat gathering variables used to compute the metric.""" if self._built: for metric in self._metrics: metric.reset()
Resets internal stat gathering variables used to compute the metric.
reset
python
tensorflow/agents
tf_agents/metrics/batched_py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/batched_py_metric.py
Apache-2.0
def result(self) -> Any: """Evaluates the current value of the metric.""" if self._built: return self._metric_class.aggregate(self._metrics) else: return np.array(0.0, dtype=self._dtype)
Evaluates the current value of the metric.
result
python
tensorflow/agents
tf_agents/metrics/batched_py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/batched_py_metric.py
Apache-2.0
def export_metrics(step, metrics, loss_info=None): """Exports the metrics and loss information to logging.info. Args: step: Integer denoting the round at which we log the metrics. metrics: List of `TF metrics` to log. loss_info: An optional instance of `LossInfo` whose value is logged. """ def log...
Exports the metrics and loss information to logging.info. Args: step: Integer denoting the round at which we log the metrics. metrics: List of `TF metrics` to log. loss_info: An optional instance of `LossInfo` whose value is logged.
export_metrics
python
tensorflow/agents
tf_agents/metrics/export_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/export_utils.py
Apache-2.0
def run_summaries( metrics: Sequence[PyMetricType], session: Optional[tf.compat.v1.Session] = None, ): """Execute summary ops for py_metrics. Args: metrics: A list of py_metric.Base objects. session: A TensorFlow session-like object. If it is not provided, it will use the current TensorFlow s...
Execute summary ops for py_metrics. Args: metrics: A list of py_metric.Base objects. session: A TensorFlow session-like object. If it is not provided, it will use the current TensorFlow session context manager. Raises: RuntimeError: If .tf_summaries() was not previously called on any of the ...
run_summaries
python
tensorflow/agents
tf_agents/metrics/py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metric.py
Apache-2.0
def tf_summaries( self, train_step: types.Int = None, step_metrics: Sequence[MetricType] = (), ) -> tf.Operation: """Build TF summary op and placeholder for this metric. To execute the op, call py_metric.run_summaries. Args: train_step: Step counter for training iterations. If No...
Build TF summary op and placeholder for this metric. To execute the op, call py_metric.run_summaries. Args: train_step: Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: Step values to plot as X axis in addition to global_step. ...
tf_summaries
python
tensorflow/agents
tf_agents/metrics/py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metric.py
Apache-2.0
def summary_placeholder(self) -> tf.compat.v1.placeholder: """TF placeholder to be used for the result of this metric.""" if self._summary_placeholder is None: result = self.result() if not isinstance(result, (np.ndarray, np.generic)): result = np.array(result) dtype = tf.as_dtype(resu...
TF placeholder to be used for the result of this metric.
summary_placeholder
python
tensorflow/agents
tf_agents/metrics/py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metric.py
Apache-2.0
def call(self, trajectory: traj.Trajectory): """Processes a trajectory to update the metric. Args: trajectory: A trajectory.Trajectory. """
Processes a trajectory to update the metric. Args: trajectory: A trajectory.Trajectory.
call
python
tensorflow/agents
tf_agents/metrics/py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metric.py
Apache-2.0
def result(self) -> np.float32: """Returns the value of this metric.""" if self._buffer: return self._buffer.mean(dtype=np.float32) return np.array(0.0, dtype=np.float32)
Returns the value of this metric.
result
python
tensorflow/agents
tf_agents/metrics/py_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metrics.py
Apache-2.0
def _batched_call(self, trajectory): """Processes the trajectory to update the metric. Args: trajectory: a tf_agents.trajectory.Trajectory. """ episode_return = self._np_state.episode_return is_first = np.where(trajectory.is_first()) episode_return[is_first] = 0 episode_return += tr...
Processes the trajectory to update the metric. Args: trajectory: a tf_agents.trajectory.Trajectory.
_batched_call
python
tensorflow/agents
tf_agents/metrics/py_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metrics.py
Apache-2.0
def _batched_call(self, trajectory): """Processes the trajectory to update the metric. Args: trajectory: a tf_agents.trajectory.Trajectory. """ episode_steps = self._np_state.episode_steps # Each non-boundary trajectory (first, mid or last) represents a step. episode_steps[np.where(~traj...
Processes the trajectory to update the metric. Args: trajectory: a tf_agents.trajectory.Trajectory.
_batched_call
python
tensorflow/agents
tf_agents/metrics/py_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/py_metrics.py
Apache-2.0
def init_variables(self): """Initializes this Metric's variables. Should be called after variables are created in the first execution of `__call__()`. If using graph execution, the return value should be `run()` in a session before running the op returned by `__call__()`. (See example above.) ...
Initializes this Metric's variables. Should be called after variables are created in the first execution of `__call__()`. If using graph execution, the return value should be `run()` in a session before running the op returned by `__call__()`. (See example above.) Returns: If using graph exe...
init_variables
python
tensorflow/agents
tf_agents/metrics/tf_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metric.py
Apache-2.0
def tf_summaries(self, train_step=None, step_metrics=()): """Generates summaries against train_step and all step_metrics. Args: train_step: (Optional) Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: (Optional) Iterable of step met...
Generates summaries against train_step and all step_metrics. Args: train_step: (Optional) Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: (Optional) Iterable of step metrics to generate summaries against. Returns: A...
tf_summaries
python
tensorflow/agents
tf_agents/metrics/tf_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metric.py
Apache-2.0
def tf_summaries(self, train_step=None, step_metrics=()): """Generates histogram summaries against train_step and all step_metrics. Args: train_step: (Optional) Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: (Optional) Iterable o...
Generates histogram summaries against train_step and all step_metrics. Args: train_step: (Optional) Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: (Optional) Iterable of step metrics to generate summaries against. Return...
tf_summaries
python
tensorflow/agents
tf_agents/metrics/tf_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metric.py
Apache-2.0
def tf_summaries(self, train_step=None, step_metrics=()): """Generates per-metric summaries against `train_step` and `step_metrics`. Args: train_step: (Optional) Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: (Optional) Iterable ...
Generates per-metric summaries against `train_step` and `step_metrics`. Args: train_step: (Optional) Step counter for training iterations. If None, no metric is generated against the global step. step_metrics: (Optional) Iterable of step metrics to generate summaries against. Retur...
tf_summaries
python
tensorflow/agents
tf_agents/metrics/tf_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metric.py
Apache-2.0
def call(self, trajectory): """Increase the number of environment_steps according to trajectory. Step count is not increased on trajectory.boundary() since that step is not part of any episode. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaini...
Increase the number of environment_steps according to trajectory. Step count is not increased on trajectory.boundary() since that step is not part of any episode. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining.
call
python
tensorflow/agents
tf_agents/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metrics.py
Apache-2.0
def call(self, trajectory): """Increase the number of number_episodes according to trajectory. It would increase for all trajectory.is_last(). Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining. """ # The __call__ will execute this. n...
Increase the number of number_episodes according to trajectory. It would increase for all trajectory.is_last(). Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining.
call
python
tensorflow/agents
tf_agents/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_metrics.py
Apache-2.0
def _check_not_called_concurrently(lock): """Checks the returned context is not executed concurrently with any other.""" if not lock.acquire(False): # Non-blocking. raise RuntimeError('Detected concurrent execution of TFPyMetric ops.') try: yield finally: lock.release()
Checks the returned context is not executed concurrently with any other.
_check_not_called_concurrently
python
tensorflow/agents
tf_agents/metrics/tf_py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_py_metric.py
Apache-2.0
def __init__(self, py_metric, name=None, dtype=tf.float32): """Creates a TF metric given a py metric to wrap. Args: py_metric: A batched python metric to wrap. name: Name of the metric. dtype: Data type of the metric. """ name = name or py_metric.name super(TFPyMetric, self).__ini...
Creates a TF metric given a py metric to wrap. Args: py_metric: A batched python metric to wrap. name: Name of the metric. dtype: Data type of the metric.
__init__
python
tensorflow/agents
tf_agents/metrics/tf_py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_py_metric.py
Apache-2.0
def call(self, trajectory): """Update the value of the metric using trajectory. The trajectory can be either batched or un-batched depending on the expected inputs for the py_metric being wrapped. Args: trajectory: A tf_agents.trajectory.Trajectory. Returns: The arguments, for easy ch...
Update the value of the metric using trajectory. The trajectory can be either batched or un-batched depending on the expected inputs for the py_metric being wrapped. Args: trajectory: A tf_agents.trajectory.Trajectory. Returns: The arguments, for easy chaining.
call
python
tensorflow/agents
tf_agents/metrics/tf_py_metric.py
https://github.com/tensorflow/agents/blob/master/tf_agents/metrics/tf_py_metric.py
Apache-2.0
def __init__( self, input_tensor_spec, output_tensor_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, fc_layer_params=(200, 100), dropout_layer_params=None, activation_fn=tf.keras.activations.relu, kernel_initializer=None, ...
Creates an instance of `ActorDistributionNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input. output_tensor_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the output. preprocessing_layers: (Optional.) A nest of `tf.keras.layer...
__init__
python
tensorflow/agents
tf_agents/networks/actor_distribution_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/actor_distribution_network.py
Apache-2.0
def __init__( self, input_tensor_spec, output_tensor_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, input_fc_layer_params=(200, 100), input_dropout_layer_params=None, lstm_size=None, output_fc_layer_params=(200, 100), ...
Creates an instance of `ActorDistributionRnnNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input. output_tensor_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the output. preprocessing_layers: (Optional.) A nest of `tf.keras.la...
__init__
python
tensorflow/agents
tf_agents/networks/actor_distribution_rnn_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/actor_distribution_rnn_network.py
Apache-2.0
def __init__( self, sample_spec, logits_init_output_factor=0.1, name='CategoricalProjectionNetwork', ): """Creates an instance of CategoricalProjectionNetwork. Args: sample_spec: A `tensor_spec.BoundedTensorSpec` detailing the shape and dtypes of samples pulled from the ...
Creates an instance of CategoricalProjectionNetwork. Args: sample_spec: A `tensor_spec.BoundedTensorSpec` detailing the shape and dtypes of samples pulled from the output distribution. logits_init_output_factor: Output factor for initializing kernel logits weights. name: A string ...
__init__
python
tensorflow/agents
tf_agents/networks/categorical_projection_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/categorical_projection_network.py
Apache-2.0
def __init__( self, input_tensor_spec, action_spec, num_atoms=51, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, fc_layer_params=None, activation_fn=tf.nn.relu, name='CategoricalQNetwork', ): """Creates an instance of `Ca...
Creates an instance of `CategoricalQNetwork`. The logits output by __call__ will ultimately have a shape of `[batch_size, num_actions, num_atoms]`, where `num_actions` is computed as `action_spec.maximum - action_spec.minimum + 1`. Each value is a logit for a particular action at a particular atom (see...
__init__
python
tensorflow/agents
tf_agents/networks/categorical_q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/categorical_q_network.py
Apache-2.0
def call(self, observation, step_type=None, network_state=(), training=False): """Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_s...
Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_state: A state tuple to pass to the network, mainly used by RNNs. training: Wheth...
call
python
tensorflow/agents
tf_agents/networks/categorical_q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/categorical_q_network.py
Apache-2.0
def __init__( self, input_tensor_spec, action_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, fc_layer_params=(75, 40), dropout_layer_params=None, activation_fn=tf.keras.activations.relu, kernel_initializer=None, bat...
Creates an instance of `DuelingQNetwork` as a subclass of QNetwork. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input observations. action_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the actions. preprocessing_layers: (Optional.) A...
__init__
python
tensorflow/agents
tf_agents/networks/dueling_q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/dueling_q_network.py
Apache-2.0
def call(self, observation, step_type=None, network_state=(), training=False): """Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_s...
Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_state: A state tuple to pass to the network, mainly used by RNNs. training: Wheth...
call
python
tensorflow/agents
tf_agents/networks/dueling_q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/dueling_q_network.py
Apache-2.0
def _copy_layer(layer): """Create a copy of a Keras layer with identical parameters. The new layer will not share weights with the old one. Args: layer: An instance of `tf.keras.layers.Layer`. Returns: A new keras layer. Raises: TypeError: If `layer` is not a keras layer. ValueError: If `l...
Create a copy of a Keras layer with identical parameters. The new layer will not share weights with the old one. Args: layer: An instance of `tf.keras.layers.Layer`. Returns: A new keras layer. Raises: TypeError: If `layer` is not a keras layer. ValueError: If `layer` cannot be correctly clo...
_copy_layer
python
tensorflow/agents
tf_agents/networks/encoding_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/encoding_network.py
Apache-2.0
def __init__( self, input_tensor_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, fc_layer_params=None, dropout_layer_params=None, activation_fn=tf.keras.activations.relu, weight_decay_params=None, kernel_initializer=None, ...
Creates an instance of `EncodingNetwork`. Network supports calls with shape outer_rank + input_tensor_spec.shape. Note outer_rank must be at least 1. For example an input tensor spec with shape `(2, 3)` will require inputs with at least a batch size, the input shape is `(?, 2, 3)`. Input preproce...
__init__
python
tensorflow/agents
tf_agents/networks/encoding_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/encoding_network.py
Apache-2.0
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() # Ignore Tra...
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
_count_params
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def _weight_memory_size(weights): """Calculate the memory footprint for weights based on their dtypes. Args: weights: An iterable contains the weights to compute weight size. Returns: The total memory size (in Bytes) of the weights. """ unique_weights = {id(w): w for w in weights}.values() to...
Calculate the memory footprint for weights based on their dtypes. Args: weights: An iterable contains the weights to compute weight size. Returns: The total memory size (in Bytes) of the weights.
_weight_memory_size
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def _get_layer_index_bound_by_layer_name(model, layer_range=None): """Get the layer indexes from the model based on layer names. The layer indexes can be used to slice the model into sub models for display. Args: model: `tf.keras.Model` instance. layer_range: a list or tuple of 2 strings, the star...
Get the layer indexes from the model based on layer names. The layer indexes can be used to slice the model into sub models for display. Args: model: `tf.keras.Model` instance. layer_range: a list or tuple of 2 strings, the starting layer name and ending layer name (both inclusive) for the r...
_get_layer_index_bound_by_layer_name
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def _readable_memory_size(weight_memory_size): """Convert the weight memory size (Bytes) to a readable string.""" units = ["Byte", "KB", "MB", "GB", "TB", "PB"] scale = 1024 for unit in units: if weight_memory_size / scale < 1: return "{:.2f} {}".format(weight_memory_size, unit) else: weight...
Convert the weight memory size (Bytes) to a readable string.
_readable_memory_size
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def _dtensor_variable_summary(weights): """Group and calculate DTensor based weights memory size. Since DTensor weights can be sharded across multiple device, the result will be grouped by the layout/sharding spec for the variables, so that the accurate per-device memory size can be calculated. Args: ...
Group and calculate DTensor based weights memory size. Since DTensor weights can be sharded across multiple device, the result will be grouped by the layout/sharding spec for the variables, so that the accurate per-device memory size can be calculated. Args: weights: An iterable contains the weights to ...
_dtensor_variable_summary
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def print_layer_summary(layer, nested_level=0): """Prints a summary for a single layer. Args: layer: target layer. nested_level: level of nesting of the layer inside its parent layer (e.g. 0 for a top-level layer, 1 for a nested layer). """ try: output_shape = layer.outp...
Prints a summary for a single layer. Args: layer: target layer. nested_level: level of nesting of the layer inside its parent layer (e.g. 0 for a top-level layer, 1 for a nested layer).
print_layer_summary
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def print_layer_summary_with_connections(layer, nested_level=0): """Prints a summary for a single layer (including its connections). Args: layer: target layer. nested_level: level of nesting of the layer inside its parent layer (e.g. 0 for a top-level layer, 1 for a nested layer). ...
Prints a summary for a single layer (including its connections). Args: layer: target layer. nested_level: level of nesting of the layer inside its parent layer (e.g. 0 for a top-level layer, 1 for a nested layer).
print_layer_summary_with_connections
python
tensorflow/agents
tf_agents/networks/layer_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/layer_utils.py
Apache-2.0
def __init__( self, input_tensor_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, input_fc_layer_params=(75, 40), lstm_size=None, output_fc_layer_params=(75, 40), activation_fn=tf.keras.activations.relu, rnn_construction_fn...
Creates an instance of `LSTMEncodingNetwork`. Input preprocessing is possible via `preprocessing_layers` and `preprocessing_combiner` Layers. If the `preprocessing_layers` nest is shallower than `input_tensor_spec`, then the layers will get the subnests. For example, if: ```python input_tenso...
__init__
python
tensorflow/agents
tf_agents/networks/lstm_encoding_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/lstm_encoding_network.py
Apache-2.0
def call(self, observation, step_type, network_state=(), training=False): """Apply the network. Args: observation: A tuple of tensors matching `input_tensor_spec`. step_type: A tensor of `StepType. network_state: (optional.) The network state. training: Whether the output is being used ...
Apply the network. Args: observation: A tuple of tensors matching `input_tensor_spec`. step_type: A tensor of `StepType. network_state: (optional.) The network state. training: Whether the output is being used for training. Returns: `(outputs, network_state)` - the network output...
call
python
tensorflow/agents
tf_agents/networks/lstm_encoding_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/lstm_encoding_network.py
Apache-2.0
def __init__( self, splitter_fn: types.Splitter, wrapped_network: network.Network, passthrough_mask: bool = False, input_tensor_spec: Optional[types.NestedTensorSpec] = None, name: Text = 'MaskSplitterNetwork', ): """Initializes an instance of `MaskSplitterNetwork`. Args: ...
Initializes an instance of `MaskSplitterNetwork`. Args: splitter_fn: A function used to process observations with action constraints (i.e. mask). *Note*: The input spec of the wrapped network must be compatible with the network-specific half of the output of the `splitter_fn` on the i...
__init__
python
tensorflow/agents
tf_agents/networks/mask_splitter_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/mask_splitter_network.py
Apache-2.0
def __init__( self, nested_layers: types.NestedLayer, input_spec: typing.Optional[types.NestedTensorSpec] = None, name: typing.Optional[typing.Text] = None, ): """Create a Sequential Network. Args: nested_layers: A nest of layers and/or networks. These will be used to p...
Create a Sequential Network. Args: nested_layers: A nest of layers and/or networks. These will be used to process the inputs (input nest structure will have to match this structure). Any layers that are subclasses of `tf.keras.layers.{RNN,LSTM,GRU,...}` are wrapped in `tf_ag...
__init__
python
tensorflow/agents
tf_agents/networks/nest_map.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/nest_map.py
Apache-2.0
def copy(self, **kwargs) -> 'NestMap': """Make a copy of a `NestMap` instance. **NOTE** A copy of a `NestMap` instance always performs a deep copy of the underlying layers, so the new instance will not share weights with the original - but it will start with the same weights. Args: **kwargs:...
Make a copy of a `NestMap` instance. **NOTE** A copy of a `NestMap` instance always performs a deep copy of the underlying layers, so the new instance will not share weights with the original - but it will start with the same weights. Args: **kwargs: Args to override when recreating this network...
copy
python
tensorflow/agents
tf_agents/networks/nest_map.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/nest_map.py
Apache-2.0
def __new__(mcs, classname, baseclasses, attrs): """Control the creation of subclasses of the Network class. 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 obj...
Control the creation of subclasses of the Network class. 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: RuntimeError: if the class __ini...
__new__
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def _capture_init(self, *args, **kwargs): """Captures init args and kwargs and stores them into `_saved_kwargs`.""" if len(args) > len(arg_spec.args) + 1: # Error case: more inputs than args. Call init so that the appropriate # error can be raised to the user. init(self, *args, **kw...
Captures init args and kwargs and stores them into `_saved_kwargs`.
_capture_init
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def __init__(self, input_tensor_spec=None, state_spec=(), name=None): """Creates an instance of `Network`. Args: input_tensor_spec: A nest of `tf.TypeSpec` representing the input observations. Optional. If not provided, `create_variables()` will fail unless a spec is provided. sta...
Creates an instance of `Network`. Args: input_tensor_spec: A nest of `tf.TypeSpec` representing the input observations. Optional. If not provided, `create_variables()` will fail unless a spec is provided. state_spec: A nest of `tensor_spec.TensorSpec` representing the state ne...
__init__
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def create_variables(self, input_tensor_spec=None, **kwargs): """Force creation of the network's variables. Return output specs. Args: input_tensor_spec: (Optional). Override or provide an input tensor spec when creating variables. **kwargs: Other arguments to `network.call()`, e.g. `...
Force creation of the network's variables. Return output specs. Args: input_tensor_spec: (Optional). Override or provide an input tensor spec when creating variables. **kwargs: Other arguments to `network.call()`, e.g. `training=True`. Returns: Output specs - a nested spec calc...
create_variables
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def _calc_unbatched_spec(x): """Build Network output spec by removing previously added batch dimension. Args: x: tfp.distributions.Distribution or Tensor. Returns: Specs without batch dimension representing x. """ if isinstance(x, tfp.distributions.Distribution): ...
Build Network output spec by removing previously added batch dimension. Args: x: tfp.distributions.Distribution or Tensor. Returns: Specs without batch dimension representing x.
_calc_unbatched_spec
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
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. i...
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: ...
get_layer
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
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 ele...
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,...
summary
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def _get_initial_state(self, batch_size): """Returns the initial state of the policy network. Args: batch_size: A constant or Tensor holding the batch size. Can be None, in which case the state will not have a batch dimension added. Returns: A nest of zero tensors matching the spec of ...
Returns the initial state of the policy network. Args: batch_size: A constant or Tensor holding the batch size. Can be None, in which case the state will not have a batch dimension added. Returns: A nest of zero tensors matching the spec of the policy network state.
_get_initial_state
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def _is_layer(obj): """Implicit check for Layer-like objects.""" # TODO(b/110718070): Replace with isinstance(obj, tf.keras.layers.Layer). return hasattr(obj, "_is_layer") and not isinstance(obj, type)
Implicit check for Layer-like objects.
_is_layer
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def _convert_to_spec_and_remove_singleton_batch_dim( parameters: distribution_utils.Params, outer_ndim: int ) -> distribution_utils.Params: """Convert a `Params` object of tensors to one containing unbatched specs. Note: The `Params` provided to this function are typically contain tensors generated by Layers...
Convert a `Params` object of tensors to one containing unbatched specs. Note: The `Params` provided to this function are typically contain tensors generated by Layers and therefore containing an outer singleton dimension. Since TF-Agents specs exclude batch and time prefixes, here we need to remove the single...
_convert_to_spec_and_remove_singleton_batch_dim
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def create_variables( module: typing.Union[Network, tf.keras.layers.Layer], input_spec: typing.Optional[types.NestedTensorSpec] = None, **kwargs: typing.Any, ) -> types.NestedTensorSpec: """Create variables in `module` given `input_spec`; return `output_spec`. Here `module` can be a `tf_agents.networks...
Create variables in `module` given `input_spec`; return `output_spec`. Here `module` can be a `tf_agents.networks.Network` or `Keras` layer. Args: module: The instance we would like to create layers on. input_spec: The input spec (excluding batch dimensions). **kwargs: Extra arguments to `module.__cal...
create_variables
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def _get_input_outer_ndim( layer: tf.keras.layers.Layer, input_spec: types.NestedTensorSpec ) -> int: """Calculate or guess the number of batch (outer) ndims in `layer`.""" if isinstance(layer, tf.keras.layers.RNN): raise TypeError( "Saw a tf.keras.layers.RNN layer nested inside e.g. a keras Sequent...
Calculate or guess the number of batch (outer) ndims in `layer`.
_get_input_outer_ndim
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def get_state_spec(layer: tf.keras.layers.Layer) -> types.NestedTensorSpec: """Extracts the state spec from a layer. Args: layer: The layer to extract from; can be a `Network`. Returns: The state spec. Raises: TypeError: If `layer` is a subclass of `tf.keras.layers.RNN` (it must be wrapped ...
Extracts the state spec from a layer. Args: layer: The layer to extract from; can be a `Network`. Returns: The state spec. Raises: TypeError: If `layer` is a subclass of `tf.keras.layers.RNN` (it must be wrapped by an `RNNWrapper` object). ValueError: If `layer` is a Keras layer and `crea...
get_state_spec
python
tensorflow/agents
tf_agents/networks/network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network.py
Apache-2.0
def test_summary_no_exception(self): """Tests that Network.summary() does not throw an exception.""" observation_spec = specs.TensorSpec([1], tf.float32, 'observation') action_spec = specs.TensorSpec([2], tf.float32, 'action') net = MockNetwork(observation_spec, action_spec) net.create_variables() ...
Tests that Network.summary() does not throw an exception.
test_summary_no_exception
python
tensorflow/agents
tf_agents/networks/network_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/network_test.py
Apache-2.0
def tanh_squash_to_spec(inputs, spec): """Maps inputs with arbitrary range to range defined by spec using `tanh`.""" means = (spec.maximum + spec.minimum) / 2.0 magnitudes = (spec.maximum - spec.minimum) / 2.0 return means + magnitudes * tf.tanh(inputs)
Maps inputs with arbitrary range to range defined by spec using `tanh`.
tanh_squash_to_spec
python
tensorflow/agents
tf_agents/networks/normal_projection_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/normal_projection_network.py
Apache-2.0
def __init__( self, sample_spec, activation_fn=None, init_means_output_factor=0.1, std_bias_initializer_value=0.0, mean_transform=tanh_squash_to_spec, std_transform=tf.nn.softplus, state_dependent_std=False, scale_distribution=False, seed=None, seed_stre...
Creates an instance of NormalProjectionNetwork. Args: sample_spec: A `tensor_spec.BoundedTensorSpec` detailing the shape and dtypes of samples pulled from the output distribution. activation_fn: Activation function to use in dense layer. init_means_output_factor: Output factor for initial...
__init__
python
tensorflow/agents
tf_agents/networks/normal_projection_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/normal_projection_network.py
Apache-2.0
def validate_specs(action_spec, observation_spec): """Validates the spec contains a single action.""" del observation_spec # not currently validated flat_action_spec = tf.nest.flatten(action_spec) if len(flat_action_spec) > 1: raise ValueError('Network only supports action_specs with a single action.') ...
Validates the spec contains a single action.
validate_specs
python
tensorflow/agents
tf_agents/networks/q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/q_network.py
Apache-2.0
def __init__( self, input_tensor_spec, action_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, fc_layer_params=(75, 40), dropout_layer_params=None, activation_fn=tf.keras.activations.relu, kernel_initializer=None, bat...
Creates an instance of `QNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input observations. action_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the actions. preprocessing_layers: (Optional.) A nest of `tf.keras.layers.Layer` ...
__init__
python
tensorflow/agents
tf_agents/networks/q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/q_network.py
Apache-2.0
def call(self, observation, step_type=None, network_state=(), training=False): """Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_s...
Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_state: A state tuple to pass to the network, mainly used by RNNs. training: Wheth...
call
python
tensorflow/agents
tf_agents/networks/q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/q_network.py
Apache-2.0
def __init__( self, input_tensor_spec, action_spec, preprocessing_layers=None, preprocessing_combiner=None, conv_layer_params=None, input_fc_layer_params=(75, 40), lstm_size=None, output_fc_layer_params=(75, 40), activation_fn=tf.keras.activations.relu, ...
Creates an instance of `QRnnNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input observations. action_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the actions. preprocessing_layers: (Optional.) A nest of `tf.keras.layers.Laye...
__init__
python
tensorflow/agents
tf_agents/networks/q_rnn_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/q_rnn_network.py
Apache-2.0
def _infer_state_specs( layers: Sequence[tf.keras.layers.Layer], ) -> Tuple[types.NestedTensorSpec, List[bool]]: """Infer the state spec of a sequence of keras Layers and Networks. Args: layers: A list of Keras layers and Network. Returns: A tuple with `state_spec`, a tuple of the state specs of len...
Infer the state spec of a sequence of keras Layers and Networks. Args: layers: A list of Keras layers and Network. Returns: A tuple with `state_spec`, a tuple of the state specs of length `len(layers)` and a list of bools indicating if the corresponding layer has lists in it's state.
_infer_state_specs
python
tensorflow/agents
tf_agents/networks/sequential.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/sequential.py
Apache-2.0
def __init__( self, layers: Sequence[tf.keras.layers.Layer], input_spec: Optional[types.NestedTensorSpec] = None, name: Optional[Text] = None, ): """Create a Sequential Network. Args: layers: A list or tuple of layers to compose. Any layers that are subclasses of `tf.ke...
Create a Sequential Network. Args: layers: A list or tuple of layers to compose. Any layers that are subclasses of `tf.keras.layers.{RNN,LSTM,GRU,...}` are wrapped in `tf_agents.keras_layers.RNNWrapper`. input_spec: (Optional.) A nest of `tf.TypeSpec` representing the input obs...
__init__
python
tensorflow/agents
tf_agents/networks/sequential.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/sequential.py
Apache-2.0
def copy(self, **kwargs) -> 'Sequential': """Make a copy of a `Sequential` instance. **NOTE** A copy of a `Sequential` instance always performs a deep copy of the underlying layers, so the new instance will not share weights with the original - but it will start with the same weights. Args: ...
Make a copy of a `Sequential` instance. **NOTE** A copy of a `Sequential` instance always performs a deep copy of the underlying layers, so the new instance will not share weights with the original - but it will start with the same weights. Args: **kwargs: Args to override when recreating this n...
copy
python
tensorflow/agents
tf_agents/networks/sequential.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/sequential.py
Apache-2.0
def __init__(self, batch_dims): """Create two tied ops to flatten and unflatten the front dimensions. Args: batch_dims: Number of batch dimensions the flatten/unflatten ops should handle. Raises: ValueError: if batch dims is negative. """ if batch_dims < 0: raise ValueErr...
Create two tied ops to flatten and unflatten the front dimensions. Args: batch_dims: Number of batch dimensions the flatten/unflatten ops should handle. Raises: ValueError: if batch dims is negative.
__init__
python
tensorflow/agents
tf_agents/networks/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/utils.py
Apache-2.0
def unflatten(self, tensor): """Unflattens the tensor's batch_dims using the cached shape.""" with tf.name_scope('batch_unflatten'): if self._batch_dims == 1: return tensor if self._original_tensor_shape is None: raise ValueError('Please call flatten before unflatten.') # pyf...
Unflattens the tensor's batch_dims using the cached shape.
unflatten
python
tensorflow/agents
tf_agents/networks/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/utils.py
Apache-2.0
def mlp_layers( conv_layer_params=None, fc_layer_params=None, dropout_layer_params=None, activation_fn=tf.keras.activations.relu, kernel_initializer=None, weight_decay_params=None, name=None, ): """Generates conv and fc layers to encode into a hidden state. Args: conv_layer_params: ...
Generates conv and fc layers to encode into a hidden state. Args: conv_layer_params: Optional list of convolution layers parameters, where each item is a length-three tuple indicating (filters, kernel_size, stride). fc_layer_params: Optional list of fully_connected parameters, where each it...
mlp_layers
python
tensorflow/agents
tf_agents/networks/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/networks/utils.py
Apache-2.0