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 via_iterator():
"""If total_length > 0, create a dataset iterator to concat episodes."""
valid_episodes = tf.range(min_val, max_val)
ds = tf.data.Dataset.from_tensor_slices(valid_episodes)
if self._completed_only:
# Filter out incomplete episodes.
def check_completed(id_):
... | If total_length > 0, create a dataset iterator to concat episodes. | via_iterator | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _clear(self, clear_all_variables=False):
"""Clears the replay buffer.
Args:
clear_all_variables: Boolean to indicate whether to clear all variables or
just the data table and episode lengths (i.e. keep the current episode
ids that are in flight in the buffer).
Returns:
An o... | Clears the replay buffer.
Args:
clear_all_variables: Boolean to indicate whether to clear all variables or
just the data table and episode lengths (i.e. keep the current episode
ids that are in flight in the buffer).
Returns:
An op to clear the buffer.
| _clear | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _completed_episodes(self):
"""Get a list of completed episode ids in the replay buffer.
Returns:
An int64 vector of length at most `capacity`.
"""
def _completed_episodes():
completed_mask = tf.equal(self._episode_completed, 1)
return tf.boolean_mask(
tensor=self._episo... | Get a list of completed episode ids in the replay buffer.
Returns:
An int64 vector of length at most `capacity`.
| _completed_episodes | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _get_episode(self, episode_id):
"""Gets the current steps of the episode_id.
Args:
episode_id: A Tensor with the episode_id.
Returns:
A nested tuple/list of Tensors with all the items/steps of the episode.
Each Tensor has shape `(episode_length,) + TensorSpec.shape`.
Raises:
... | Gets the current steps of the episode_id.
Args:
episode_id: A Tensor with the episode_id.
Returns:
A nested tuple/list of Tensors with all the items/steps of the episode.
Each Tensor has shape `(episode_length,) + TensorSpec.shape`.
Raises:
InvalidArgumentException: (at runtime) i... | _get_episode | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _maybe_end_episode(self, episode_id, end_episode=False):
"""Mark episode ID as complete when end_episode is True.
Args:
episode_id: A Tensor containing the current episode_id.
end_episode: A Boolean Tensor whether should end the episode_id.
Returns:
A Boolean Tensor whether the episo... | Mark episode ID as complete when end_episode is True.
Args:
episode_id: A Tensor containing the current episode_id.
end_episode: A Boolean Tensor whether should end the episode_id.
Returns:
A Boolean Tensor whether the episode was marked as complete.
| _maybe_end_episode | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _maybe_end_batch_episodes(self, batch_episode_ids, end_episode=False):
"""Mark episode ID as complete when end_episode is True.
Args:
batch_episode_ids: A Tensor int64 with a batch of episode_ids with shape
`(batch_size,)`.
end_episode: A Boolean Tensor whether should end all batch_epis... | Mark episode ID as complete when end_episode is True.
Args:
batch_episode_ids: A Tensor int64 with a batch of episode_ids with shape
`(batch_size,)`.
end_episode: A Boolean Tensor whether should end all batch_episode_ids, or
Tensor with shape `(batch_size,)` to mark which ones to end.
... | _maybe_end_batch_episodes | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _get_episode_id(self, episode_id, begin_episode=False, end_episode=False):
"""Increments the episode_id when begin_episode is True.
Args:
episode_id: A Tensor containing the current episode_id.
begin_episode: A Boolean Tensor whether should increment the episode_id.
end_episode: A Boolean... | Increments the episode_id when begin_episode is True.
Args:
episode_id: A Tensor containing the current episode_id.
begin_episode: A Boolean Tensor whether should increment the episode_id.
end_episode: A Boolean Tensor whether should end the episode_id.
Returns:
An updated episode id v... | _get_episode_id | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _get_batch_episode_ids(
self, batch_episode_ids, begin_episode=False, end_episode=False, mask=None
):
"""Increments the episode_id of the elements that have begin_episode True.
Mark as completed those that have end_episode True.
Args:
batch_episode_ids: A tf.int64 tensor with shape `(num... | Increments the episode_id of the elements that have begin_episode True.
Mark as completed those that have end_episode True.
Args:
batch_episode_ids: A tf.int64 tensor with shape `(num_episodes,)`
containing a one or more episodes IDs.
begin_episode: A Boolean Tensor whether should incremen... | _get_batch_episode_ids | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _sample_episode_ids(
self, shape, weigh_by_episode_length=False, seed=None
):
"""Samples episode ids from the replay buffer."""
last_id = self._get_last_episode_id()
assert_nonempty = tf.compat.v1.assert_non_negative(
last_id,
message=(
'EpisodicReplayBuffer is empty.... | Samples episode ids from the replay buffer. | _sample_episode_ids | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _increment_episode_length_locked(self, episode_id, increment=1):
"""Increments the length of episode_id in a thread safe manner.
NOTE: This method should only be called inside a critical section.
Args:
episode_id: int64 scalar of vector. ID(s) of the episode(s) for which we
will increase... | Increments the length of episode_id in a thread safe manner.
NOTE: This method should only be called inside a critical section.
Args:
episode_id: int64 scalar of vector. ID(s) of the episode(s) for which we
will increase the length.
increment: Amount to increment episode_length by.
Re... | _increment_episode_length_locked | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _get_valid_ids_mask_locked(self, episode_ids):
"""Returns a mask of whether the given IDs are valid. Caller must lock."""
episode_locations = self._get_episode_id_location(episode_ids)
location_matches_id = tf.equal(
episode_ids, self._episodes_loc_to_id_map.sparse_read(episode_locations)
)
... | Returns a mask of whether the given IDs are valid. Caller must lock. | _get_valid_ids_mask_locked | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def get_valid_ids_mask(self, episode_ids):
"""Returns a mask of whether the given IDs are valid."""
with tf.device(self._device):
with tf.name_scope('get_valid_ids_mask'):
return self._add_episode_critical_section.execute(
lambda: self._get_valid_ids_mask_locked(episode_ids)
) | Returns a mask of whether the given IDs are valid. | get_valid_ids_mask | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def extract(self, locations, clear_data=False):
"""Extracts Episodes with the given IDs.
Args:
locations: A `1-D` Tensor of locations to extract from (note, this is NOT
the same as an episode ids variable). It's up to the user to ensure
that only valid episode locations are requested (i.... | Extracts Episodes with the given IDs.
Args:
locations: A `1-D` Tensor of locations to extract from (note, this is NOT
the same as an episode ids variable). It's up to the user to ensure
that only valid episode locations are requested (i.e., values should be
between `0` and `self.capa... | extract | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _extract_locked():
"""Does the above within the buffer's critical section."""
episodes = Episodes(
length=self._episode_lengths.sparse_read(locations),
completed=self._episode_completed.sparse_read(locations),
tensor_lists=self._data_table.get_episode_lists(locations),
... | Does the above within the buffer's critical section. | _extract_locked | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def extend_episodes(self, episode_ids, episode_ids_indices, episodes):
"""Extends a batch of episodes in this buffer.
Args:
episode_ids: A int64 vector containing the ids of the episodes the items
are being added to. Shaped `(max_num_episodes,)`.
episode_ids_indices: An int64 vector contai... | Extends a batch of episodes in this buffer.
Args:
episode_ids: A int64 vector containing the ids of the episodes the items
are being added to. Shaped `(max_num_episodes,)`.
episode_ids_indices: An int64 vector containing the locations in
`episode_ids` that are being extended. Shaped `... | extend_episodes | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _extend_locked(episode_ids, expanded_episode_ids):
"""Does the above within the buffer's critical section."""
episode_locations = self._get_episode_id_location(episode_ids)
episode_valid = tf.equal(
self._episodes_loc_to_id_map.sparse_read(episode_locations),
episode_ids,
... | Does the above within the buffer's critical section. | _extend_locked | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def __init__(self, replay_buffer, num_episodes=None):
"""Create a `StatefulEpisodicReplayBuffer` for `num_episodes` batches.
Args:
replay_buffer: An instance of `EpisodicReplayBuffer`.
num_episodes: (Optional) integer, number of episode IDs to create. If
`None`, a scalar ID variable is retu... | Create a `StatefulEpisodicReplayBuffer` for `num_episodes` batches.
Args:
replay_buffer: An instance of `EpisodicReplayBuffer`.
num_episodes: (Optional) integer, number of episode IDs to create. If
`None`, a scalar ID variable is returned.
Raises:
TypeError: If `replay_buffer` is not... | __init__ | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def add_batch(self, items):
"""Adds a batch of single steps for the corresponding episodes IDs.
Args:
items: A batch of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an extra outer dimension `(num_epi... | Adds a batch of single steps for the corresponding episodes IDs.
Args:
items: A batch of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an extra outer dimension `(num_episodes, ...)` in addition to
... | add_batch | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def add_sequence(self, items):
"""Adds a sequence of items to the replay buffer for the selected episode.
Args:
items: A sequence of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an outer sequence dim... | Adds a sequence of items to the replay buffer for the selected episode.
Args:
items: A sequence of items to be added to the buffer. Items will have the
same structure as the data_spec of this class, but the tensors in items
will have an outer sequence dimension in addition to the correspondin... | add_sequence | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def extend_episodes(self, episode_ids_indices, episodes):
"""Extends a batch of episodes in this buffer.
Args:
episode_ids_indices: An int64 vector containing the locations in
`self.episode_ids` that are being extended. Shaped `(num_episodes,)`,
where `num_episodes <= max_num_episodes`. ... | Extends a batch of episodes in this buffer.
Args:
episode_ids_indices: An int64 vector containing the locations in
`self.episode_ids` that are being extended. Shaped `(num_episodes,)`,
where `num_episodes <= max_num_episodes`. Rows in `episodes` and
`begin_episode` correspond to loc... | extend_episodes | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def _valid_range_ids(last_id, capacity):
"""Returns the [min_val, max_val) range of ids.
Args:
last_id: A tensor that indicates the last id stored in the replay buffer.
capacity: The maximum number of elements that the replay buffer can hold.
Returns:
A tuple (min_id, max_id) for the range [min_id, ... | Returns the [min_val, max_val) range of ids.
Args:
last_id: A tensor that indicates the last id stored in the replay buffer.
capacity: The maximum number of elements that the replay buffer can hold.
Returns:
A tuple (min_id, max_id) for the range [min_id, max_id) of valid ids.
| _valid_range_ids | python | tensorflow/agents | tf_agents/replay_buffers/episodic_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_replay_buffer.py | Apache-2.0 |
def __init__(self, tensor_spec, capacity, name_prefix='EpisodicTable'):
"""Creates a table.
Args:
tensor_spec: A nest of TensorSpec representing each value that can be
stored in the table.
capacity: Maximum number of values the table can store.
name_prefix: optional name prefix for va... | Creates a table.
Args:
tensor_spec: A nest of TensorSpec representing each value that can be
stored in the table.
capacity: Maximum number of values the table can store.
name_prefix: optional name prefix for variable names.
Raises:
ValueError: If the names in tensor_spec are em... | __init__ | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def _stack_tensor_list(self, slot, tensor_list):
"""Stacks a slot list, restoring dtype and shape information.
Going through the Variable loses all TensorList dtype and
static element shape info. Setting dtype, shape, and adding batch
dimension for the length of the list.
Args:
slot: The sl... | Stacks a slot list, restoring dtype and shape information.
Going through the Variable loses all TensorList dtype and
static element shape info. Setting dtype, shape, and adding batch
dimension for the length of the list.
Args:
slot: The slot corresponding to tensor_list
tensor_list: Tenso... | _stack_tensor_list | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def get_episode_lists(self, rows=None):
"""Returns episodes as TensorLists.
Args:
rows: A list/tensor of location(s) to retrieve. If not specified, all
episodes are returned.
Returns:
Episodes as TensorLists, stored in nested Tensors.
"""
if rows is None:
rows = tf.range(... | Returns episodes as TensorLists.
Args:
rows: A list/tensor of location(s) to retrieve. If not specified, all
episodes are returned.
Returns:
Episodes as TensorLists, stored in nested Tensors.
| get_episode_lists | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def get_episode_values(self, row):
"""Returns all values for the given row.
Args:
row: A scalar tensor of location to read values from. A batch of values
will be returned with each Tensor having an extra first dimension equal
to the length of rows.
Returns:
Stacked values at gi... | Returns all values for the given row.
Args:
row: A scalar tensor of location to read values from. A batch of values
will be returned with each Tensor having an extra first dimension equal
to the length of rows.
Returns:
Stacked values at given row.
| get_episode_values | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def append(self, row, values):
"""Returns ops for appending multiple time values at the given row.
Args:
row: A scalar location at which to append values.
values: A nest of Tensors to append. The outermost dimension of each
tensor is treated as a time axis, and these must all be equal.
... | Returns ops for appending multiple time values at the given row.
Args:
row: A scalar location at which to append values.
values: A nest of Tensors to append. The outermost dimension of each
tensor is treated as a time axis, and these must all be equal.
Returns:
Ops for appending val... | append | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def add(self, rows, values):
"""Returns ops for appending a single frame value to the given rows.
This operation is batch-aware.
Args:
rows: A list/tensor of location(s) to write values at.
values: A nest of Tensors to write. If rows has more than one element,
values can have an extra ... | Returns ops for appending a single frame value to the given rows.
This operation is batch-aware.
Args:
rows: A list/tensor of location(s) to write values at.
values: A nest of Tensors to write. If rows has more than one element,
values can have an extra first dimension representing the bat... | add | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def extend(self, rows, episode_lists):
"""Returns ops for extending a set of rows by the given TensorLists.
Args:
rows: A batch of row locations to extend.
episode_lists: Nested batch of TensorLists, must have the same batch
dimension as rows.
Returns:
Ops for extending the table... | Returns ops for extending a set of rows by the given TensorLists.
Args:
rows: A batch of row locations to extend.
episode_lists: Nested batch of TensorLists, must have the same batch
dimension as rows.
Returns:
Ops for extending the table.
| extend | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def clear(self):
"""Returns op for clearing the table and removing all the episodes.
Returns:
Op for clearing the table.
"""
clear_ops = []
for slot in self._flattened_slots:
clear_ops.append(
self._slot2variable_map[slot].erase(
tf.range(self._capacity, dtype=tf... | Returns op for clearing the table and removing all the episodes.
Returns:
Op for clearing the table.
| clear | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def clear_rows(self, rows):
"""Returns ops for clearing all the values at the given rows.
Args:
rows: A list/tensor of location(s) to clear values.
Returns:
Ops for clearing the values at rows.
"""
rows = tf.convert_to_tensor(value=rows, dtype=tf.int64)
clear_ops = []
for spec,... | Returns ops for clearing all the values at the given rows.
Args:
rows: A list/tensor of location(s) to clear values.
Returns:
Ops for clearing the values at rows.
| clear_rows | python | tensorflow/agents | tf_agents/replay_buffers/episodic_table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/episodic_table.py | Apache-2.0 |
def add_frame(self, frame):
"""Add a frame to the buffer.
Args:
frame: Numpy array.
Returns:
A deduplicated frame.
"""
h = hash(frame.tobytes())
if h in self._frames:
_, refcount = self._frames[h]
self._frames[h] = (frame, refcount + 1)
return h
self._frames[h... | Add a frame to the buffer.
Args:
frame: Numpy array.
Returns:
A deduplicated frame.
| add_frame | python | tensorflow/agents | tf_agents/replay_buffers/py_hashed_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/py_hashed_replay_buffer.py | Apache-2.0 |
def _encode(self, traj):
"""Encodes a trajectory for efficient storage.
The observations in this trajectory are replaced by a compressed
version of the observations: each frame is only stored exactly once.
Args:
traj: The original trajectory.
Returns:
The same trajectory where frames ... | Encodes a trajectory for efficient storage.
The observations in this trajectory are replaced by a compressed
version of the observations: each frame is only stored exactly once.
Args:
traj: The original trajectory.
Returns:
The same trajectory where frames in the observation have been
... | _encode | python | tensorflow/agents | tf_agents/replay_buffers/py_hashed_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/py_hashed_replay_buffer.py | Apache-2.0 |
def next_dataset_element(test_case, dataset):
"""Utility function to iterate over tf.data.Datasets in both TF 1.x and 2.x.
TensorFlow 1.x and 2.x have different mechanisms for iterating over elements
of a tf.data.Dataset. TensorFlow 1.x would require something like:
itr = tf.data.Dataset.range(10).make_one_sh... | Utility function to iterate over tf.data.Datasets in both TF 1.x and 2.x.
TensorFlow 1.x and 2.x have different mechanisms for iterating over elements
of a tf.data.Dataset. TensorFlow 1.x would require something like:
itr = tf.data.Dataset.range(10).make_one_shot_iterator()
get_next = itr.get_next()
with tf... | next_dataset_element | python | tensorflow/agents | tf_agents/replay_buffers/py_replay_buffers_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/py_replay_buffers_test.py | Apache-2.0 |
def __init__(self, data_spec, capacity):
"""Creates a PyUniformReplayBuffer.
Args:
data_spec: An ArraySpec or a list/tuple/nest of ArraySpecs describing a
single item that can be stored in this buffer.
capacity: The maximum number of items that can be stored in the buffer.
"""
super... | Creates a PyUniformReplayBuffer.
Args:
data_spec: An ArraySpec or a list/tuple/nest of ArraySpecs describing a
single item that can be stored in this buffer.
capacity: The maximum number of items that can be stored in the buffer.
| __init__ | python | tensorflow/agents | tf_agents/replay_buffers/py_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/py_uniform_replay_buffer.py | Apache-2.0 |
def get_single():
"""Gets a single item from the replay buffer."""
with self._lock:
if self._np_state.size <= 0:
def empty_item(spec):
return np.empty(spec.shape, dtype=spec.dtype)
if num_steps is not None:
item = [
tf.nest.map_structure(... | Gets a single item from the replay buffer. | get_single | python | tensorflow/agents | tf_agents/replay_buffers/py_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/py_uniform_replay_buffer.py | Apache-2.0 |
def __init__(self, data_spec, capacity, stateful_dataset=False):
"""Initializes the replay buffer.
Args:
data_spec: A spec or a list/tuple/nest of specs describing a single item
that can be stored in this buffer
capacity: number of elements that the replay buffer can hold.
stateful_da... | Initializes the replay buffer.
Args:
data_spec: A spec or a list/tuple/nest of specs describing a single item
that can be stored in this buffer
capacity: number of elements that the replay buffer can hold.
stateful_dataset: whether the dataset contains stateful ops or not.
| __init__ | python | tensorflow/agents | tf_agents/replay_buffers/replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/replay_buffer.py | Apache-2.0 |
def as_dataset(
self,
sample_batch_size=None,
num_steps=None,
num_parallel_calls=None,
sequence_preprocess_fn=None,
single_deterministic_pass=False,
):
"""Creates and returns a dataset that returns entries from the buffer.
A single entry from the dataset is the result of t... | Creates and returns a dataset that returns entries from the buffer.
A single entry from the dataset is the result of the following pipeline:
* Sample sequences from the underlying data store
* (optionally) Process them with `sequence_preprocess_fn`,
* (optionally) Split them into subsequences of... | as_dataset | python | tensorflow/agents | tf_agents/replay_buffers/replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/replay_buffer.py | Apache-2.0 |
def _as_dataset(
self,
sample_batch_size,
num_steps,
sequence_preprocess_fn,
num_parallel_calls,
):
"""Creates and returns a dataset that returns entries from the buffer."""
raise NotImplementedError | Creates and returns a dataset that returns entries from the buffer. | _as_dataset | python | tensorflow/agents | tf_agents/replay_buffers/replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/replay_buffer.py | Apache-2.0 |
def _single_deterministic_pass_dataset(
self,
sample_batch_size,
num_steps,
sequence_preprocess_fn,
num_parallel_calls,
):
"""Creates and returns a dataset that returns entries from the buffer."""
raise NotImplementedError | Creates and returns a dataset that returns entries from the buffer. | _single_deterministic_pass_dataset | python | tensorflow/agents | tf_agents/replay_buffers/replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/replay_buffer.py | Apache-2.0 |
def add_batch(self, items):
"""Adds a batch of items to the replay buffer.
***Warning***: `ReverbReplayBuffer` does not support `add_batch`. See
`reverb_utils.ReverbObserver` for more information on how to add data
to the buffer.
Args:
items: Ignored.
Returns:
Nothing.
Raises... | Adds a batch of items to the replay buffer.
***Warning***: `ReverbReplayBuffer` does not support `add_batch`. See
`reverb_utils.ReverbObserver` for more information on how to add data
to the buffer.
Args:
items: Ignored.
Returns:
Nothing.
Raises: NotImplementedError
| add_batch | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer.py | Apache-2.0 |
def _as_dataset(
self,
sample_batch_size,
num_steps,
sequence_preprocess_fn,
num_parallel_calls,
):
"""Creates and returns a dataset that returns entries from the buffer.
*NOTE*: If `num_steps` does not match the `sequence_length` used in the
observer (or if `sequence_length... | Creates and returns a dataset that returns entries from the buffer.
*NOTE*: If `num_steps` does not match the `sequence_length` used in the
observer (or if `sequence_length is None` varies from episode to episode),
then individual sequences will be truncated to the highest possible multiple
of `num_ste... | _as_dataset | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer.py | Apache-2.0 |
def _single_deterministic_pass_dataset(
self,
sample_batch_size=None,
num_steps=None,
sequence_preprocess_fn=None,
num_parallel_calls=None,
):
"""Creates and returns a dataset that returns entries from the buffer.
*NOTE*: If `num_steps` does not match the `sequence_length` used ... | Creates and returns a dataset that returns entries from the buffer.
*NOTE*: If `num_steps` does not match the `sequence_length` used in the
observer (or if `sequence_length is None` varies from episode to episode),
then individual sequences will be truncated to the highest possible multiple
of `num_ste... | _single_deterministic_pass_dataset | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer.py | Apache-2.0 |
def gather_all(self):
"""Returns all the items in buffer.
***Warning***: `ReverbReplayBuffer` does not support `gather_all`. See
`reverb_utils.ReverbObserver` for more information on how to retrieve data
from the buffer.
Returns:
Nothing.
Raises:
NotImplementedError
"""
ra... | Returns all the items in buffer.
***Warning***: `ReverbReplayBuffer` does not support `gather_all`. See
`reverb_utils.ReverbObserver` for more information on how to retrieve data
from the buffer.
Returns:
Nothing.
Raises:
NotImplementedError
| gather_all | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer.py | Apache-2.0 |
def update_priorities(self, keys, priorities):
"""Updates the priorities for the given keys."""
# TODO(b/144858635): Return ops here and support v1.
self._tf_client.update_priorities(self._table_name, keys, priorities) | Updates the priorities for the given keys. | update_priorities | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer.py | Apache-2.0 |
def truncate_reshape_rows_by_num_steps(sample, num_steps):
"""Reshapes tensors in `sample` to have shape `[rows, num_steps, ...]`.
This function takes a structure `sample` and for each tensor `t`, it truncates
the tensor's outer dimension to be the highest possible multiple of
`num_steps`.
This is done by f... | Reshapes tensors in `sample` to have shape `[rows, num_steps, ...]`.
This function takes a structure `sample` and for each tensor `t`, it truncates
the tensor's outer dimension to be the highest possible multiple of
`num_steps`.
This is done by first calculating `rows = tf.shape(t[0]) // num_steps`, then
tr... | truncate_reshape_rows_by_num_steps | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer.py | Apache-2.0 |
def _insert_random_data(
self, env, num_steps, sequence_length=2, additional_observers=None
):
"""Insert `num_step` random observations into Reverb server."""
observers = [] if additional_observers is None else additional_observers
traj_obs = reverb_utils.ReverbAddTrajectoryObserver(
self._p... | Insert `num_step` random observations into Reverb server. | _insert_random_data | python | tensorflow/agents | tf_agents/replay_buffers/reverb_replay_buffer_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_replay_buffer_test.py | Apache-2.0 |
def __call__(self, trajectory: trajectory_lib.Trajectory) -> None:
"""Cache the single step trajectory to be written into Reverb.
Allows trajectory to be a flattened trajectory. No batch dimension allowed.
Args:
trajectory: The trajectory to be written which could be (possibly nested)
trajec... | Cache the single step trajectory to be written into Reverb.
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
the... | __call__ | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def _write_cached_steps(self) -> None:
"""Writes the cached steps into the writer.
**Note**: The method does not clear the cache.
"""
# Only writes to Reverb when the writer has cached trajectories.
if self._writer_has_data:
# No need to truncate since the truncation is done in the class.
... | Writes the cached steps into the writer.
**Note**: The method does not clear the cache.
| _write_cached_steps | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def reset(self, write_cached_steps: bool = True) -> None:
"""Resets the state of the observer.
**Note**: Reset should be called only after all collection has finished
in a standard workflow. No need to manually call reset between episodes.
Args:
write_cached_steps: By default, if there is remain... | Resets the state of the observer.
**Note**: Reset should be called only after all collection has finished
in a standard workflow. No need to manually call reset between episodes.
Args:
write_cached_steps: By default, if there is remaining data in the cache,
write them to Reverb before cleari... | reset | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def open(self) -> None:
"""Open the writer of the observer. This is a no-op if it's already open."""
if self._writer is None:
self._writer = self._py_client.trajectory_writer(
num_keep_alive_refs=self._max_sequence_length + 1,
validate_items=False,
) | Open the writer of the observer. This is a no-op if it's already open. | open | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def close(self) -> None:
"""Closes the writer of the observer.
**Note**: Using the observer after it is closed (and not reopened) is not
supported.
"""
if self._writer is not None:
self._writer.end_episode()
self._writer.close()
self._writer = None
self._writer_has_data =... | Closes the writer of the observer.
**Note**: Using the observer after it is closed (and not reopened) is not
supported.
| close | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def __init__(
self,
py_client: types.ReverbClient,
table_name: Union[Text, Sequence[Text]],
sequence_length: int,
stride_length: int = 1,
priority: Union[float, int] = 1,
pad_end_of_episodes: bool = False,
tile_end_of_episodes: bool = False,
):
"""Creates an instanc... | Creates an instance of the ReverbAddTrajectoryObserver.
If multiple table_names and sequence lengths are provided data will only be
stored once but be available for sampling with multiple sequence lengths
from the respective reverb tables.
**Note**: This observer is designed to work with py_drivers on... | __init__ | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def __call__(self, trajectory: trajectory_lib.Trajectory) -> None:
"""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)
trajector... | 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/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def _sequence_lengths_reached(self) -> bool:
"""Whether the cache has sufficient steps to write a new item into Reverb."""
return (self._cached_steps >= self._sequence_length) and (
self._cached_steps - self._sequence_length
) % self._stride_length == 0 | Whether the cache has sufficient steps to write a new item into Reverb. | _sequence_lengths_reached | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def _write_cached_steps(self) -> None:
"""Writes the cached steps iff there is enough data in the cache.
**Note**: The method does *not* clear the cache after writing.
"""
if self._sequence_lengths_reached():
trajectory = tf.nest.map_structure(
lambda d: d[-self._sequence_length :], se... | Writes the cached steps iff there is enough data in the cache.
**Note**: The method does *not* clear the cache after writing.
| _write_cached_steps | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def _get_padding_step(
self, example_trajectory: trajectory_lib.Trajectory
) -> trajectory_lib.Trajectory:
"""Get the padding step to append to the cache."""
zero_step = trajectory_lib.boundary(
tf.nest.map_structure(tf.zeros_like, example_trajectory.observation),
tf.nest.map_structure(t... | Get the padding step to append to the cache. | _get_padding_step | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def reset(self, write_cached_steps: bool = True) -> None:
"""Resets the state of the observer.
**Note**: Reset should be called only after all collection has finished
in a standard workflow. No need to manually call reset between episodes.
Args:
write_cached_steps: boolean flag indicating whethe... | Resets the state of the observer.
**Note**: Reset should be called only after all collection has finished
in a standard workflow. No need to manually call reset between episodes.
Args:
write_cached_steps: boolean flag indicating whether we want to write the
cached trajectory. When this argum... | reset | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def open(self) -> None:
"""Open the writer of the observer."""
if self._writer is None:
self._writer = self._py_client.trajectory_writer(
num_keep_alive_refs=self._sequence_length + 1, validate_items=False
)
self._cached_steps = 0 | Open the writer of the observer. | open | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def close(self) -> None:
"""Closes the writer of the observer.
**Note**: Using the observer after it is closed (and not reopened) is not
supported.
"""
if self._writer is not None:
self._writer.end_episode()
self._writer.close()
self._writer = None | Closes the writer of the observer.
**Note**: Using the observer after it is closed (and not reopened) is not
supported.
| close | python | tensorflow/agents | tf_agents/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def __call__(self, trajectory: trajectory_lib.Trajectory) -> None:
"""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)
trajector... | 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/replay_buffers/reverb_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/reverb_utils.py | Apache-2.0 |
def get_rlds_step_features() -> List[str]:
"""Returns a list representing features in an RLDS step."""
return [
rlds.OBSERVATION,
rlds.ACTION,
rlds.REWARD,
rlds.DISCOUNT,
rlds.IS_FIRST,
rlds.IS_LAST,
rlds.IS_TERMINAL,
] | Returns a list representing features in an RLDS step. | get_rlds_step_features | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def _validate_rlds_episode_spec(rlds_data: tf.data.Dataset) -> None:
"""Validates the dataset of RLDS data.
Validates that rlds_data has RLDS steps.
Args:
rlds_data: An RLDS dataset is tf.data.Dataset of RLDS episodes, where each
episode contains a tf.data.Dataset of RLDS steps. An RLDS step is a
... | Validates the dataset of RLDS data.
Validates that rlds_data has RLDS steps.
Args:
rlds_data: An RLDS dataset is tf.data.Dataset of RLDS episodes, where each
episode contains a tf.data.Dataset of RLDS steps. An RLDS step is a
dictionary of tensors containing is_first, is_last, observation, action,... | _validate_rlds_episode_spec | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def _validate_rlds_step_spec(
rlds_step_spec: tf.data.Dataset.element_spec,
) -> None:
"""Validates the RLDS step spec.
Validates that rlds_step_spec is correct spec for RLDS steps.
Args:
rlds_step_spec: An element spec to be validated as correct RLDS steps spec.
Raises:
ValueError: If RLDS step ... | Validates the RLDS step spec.
Validates that rlds_step_spec is correct spec for RLDS steps.
Args:
rlds_step_spec: An element spec to be validated as correct RLDS steps spec.
Raises:
ValueError: If RLDS step spec is not valid.
| _validate_rlds_step_spec | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def create_trajectory_data_spec(
rlds_data: tf.data.Dataset,
) -> trajectory.Trajectory:
"""Creates data spec for initializing Reverb server and Reverb Replay Buffer.
Creates a data spec for the corresponding trajectory dataset that can be
created using the rlds_data provided as input. This data spec is nece... | Creates data spec for initializing Reverb server and Reverb Replay Buffer.
Creates a data spec for the corresponding trajectory dataset that can be
created using the rlds_data provided as input. This data spec is necessary for
initializing Reverb server and Reverb Replay Buffer.
Args:
rlds_data: An RLDS d... | create_trajectory_data_spec | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def convert_rlds_to_trajectories(
rlds_data: tf.data.Dataset, policy_info_fn: _PolicyFnType = None
) -> tf.data.Dataset:
"""Converts the RLDS data to a dataset of trajectories.
Converts the rlds_data provided to a dataset of TF Agents trajectories by
flattening and converting it into batches and then tuples ... | Converts the RLDS data to a dataset of trajectories.
Converts the rlds_data provided to a dataset of TF Agents trajectories by
flattening and converting it into batches and then tuples of overlapping pairs
of adjacent RLDS steps.
An end step of first step type is padded to the RLDS data to ensure that the
t... | convert_rlds_to_trajectories | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def _pair_to_tuple(
pair: Dict[str, tf.Tensor]
) -> Tuple[Dict[str, tf.Tensor], Dict[str, tf.Tensor]]:
"""Converts a batch of two adjacent RLDS steps to a Tuple of RLDS steps."""
current_step = {}
next_step = {}
for key, value in pair.items():
if isinstance(value, dict):
current_st... | Converts a batch of two adjacent RLDS steps to a Tuple of RLDS steps. | _pair_to_tuple | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def _get_discount(step: Dict[str, tf.Tensor]) -> tf.Tensor:
"""Returns 0 for complete episode, else returns the current discount."""
return (
tf.constant(0.0, dtype=tf.float32)
if _is_complete(step)
else step[rlds.DISCOUNT]
) | Returns 0 for complete episode, else returns the current discount. | _get_discount | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def _validate_step(
current_step: Dict[str, tf.Tensor], next_step: Dict[str, tf.Tensor]
) -> None:
"""Validates a tuple of adjacent RLDS steps."""
# This check validates any incorrectly terminated episodes in RLDS data.
if current_step[rlds.IS_TERMINAL]:
tf.Assert(
current_step[rlds... | Validates a tuple of adjacent RLDS steps. | _validate_step | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def _to_trajectory(
current_step: Dict[str, tf.Tensor], next_step: Dict[str, tf.Tensor]
) -> trajectory.Trajectory:
"""Converts a tuple of adjacent RLDS steps to a trajectory."""
_validate_step(current_step, next_step)
step_type = _get_step_type(current_step)
next_step_type = _get_step_type(next... | Converts a tuple of adjacent RLDS steps to a trajectory. | _to_trajectory | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def push_rlds_to_reverb(
rlds_data: tf.data.Dataset,
reverb_observer: Union[
reverb_utils.ReverbAddEpisodeObserver,
reverb_utils.ReverbAddTrajectoryObserver,
],
policy_info_fn: _PolicyFnType = None,
) -> int:
"""Pushes the RLDS data to Reverb server as TF Agents trajectories.
Pushes... | Pushes the RLDS data to Reverb server as TF Agents trajectories.
Pushes the rlds_data provided to Reverb server using reverb_observer after
converting it to TF Agents trajectories.
Please note that the data spec used to initialize replay buffer and reverb
server for creating the reverb_observer must match th... | push_rlds_to_reverb | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb.py | Apache-2.0 |
def generate_valid_episodes() -> (
Dict[str, Tuple[tf.data.Dataset, List[trajectory.Trajectory]]]
):
"""Get test data for valid RLDS datasets to be used across differrent tests.
Returns:
A dict representing all valid cases as keys and tuples of valid input RLDS
and expected TF-Agents trajectories as va... | Get test data for valid RLDS datasets to be used across differrent tests.
Returns:
A dict representing all valid cases as keys and tuples of valid input RLDS
and expected TF-Agents trajectories as values.
| generate_valid_episodes | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb_test.py | Apache-2.0 |
def generate_invalid_episodes() -> Dict[str, Tuple[tf.data.Dataset, str]]:
"""Get test data for invalid RLDS datasets to be used across differrent tests.
Returns:
A dict representing all invalid cases as keys and tuples of invalid input
RLDS and expected error messages as values.
"""
return {
'in... | Get test data for invalid RLDS datasets to be used across differrent tests.
Returns:
A dict representing all invalid cases as keys and tuples of invalid input
RLDS and expected error messages as values.
| generate_invalid_episodes | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb_test.py | Apache-2.0 |
def get_policy_info_test_fn(
current_step: Dict[str, tf.Tensor], next_step: Dict[str, tf.Tensor]
) -> Dict[str, tf.Tensor]:
"""Returns policy info for test function for policy info tests."""
del next_step # unused
return {rlds_types.ACTION: current_step[rlds_types.ACTION]} | Returns policy info for test function for policy info tests. | get_policy_info_test_fn | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb_test.py | Apache-2.0 |
def get_policy_with_extra_param_test_fn(
current_step: Dict[str, tf.Tensor], next_step: Dict[str, tf.Tensor]
) -> Dict[str, tf.Tensor]:
"""Returns policy info for test function with extra parameter."""
del next_step
return {
rlds_types.ACTION: current_step[rlds_types.ACTION],
_EXTRA_PARAM: current... | Returns policy info for test function with extra parameter. | get_policy_with_extra_param_test_fn | python | tensorflow/agents | tf_agents/replay_buffers/rlds_to_reverb_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/rlds_to_reverb_test.py | Apache-2.0 |
def __init__(self, tensor_spec, capacity, scope='Table'):
"""Creates a table.
Args:
tensor_spec: A nest of TensorSpec representing each value that can be
stored in the table.
capacity: Maximum number of values the table can store.
scope: Variable scope for the Table.
Raises:
... | Creates a table.
Args:
tensor_spec: A nest of TensorSpec representing each value that can be
stored in the table.
capacity: Maximum number of values the table can store.
scope: Variable scope for the Table.
Raises:
ValueError: If the names in tensor_spec are empty or not unique... | __init__ | python | tensorflow/agents | tf_agents/replay_buffers/table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/table.py | Apache-2.0 |
def _create_storage(spec, slot_name):
"""Create storage for a slot, track it."""
shape = [self._capacity] + spec.shape.as_list()
new_storage = common.create_variable(
name=slot_name,
initializer=tf.zeros(shape, dtype=spec.dtype),
shape=None,
dtype=spec.dtype,
... | Create storage for a slot, track it. | _create_storage | python | tensorflow/agents | tf_agents/replay_buffers/table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/table.py | Apache-2.0 |
def read(self, rows, slots=None):
"""Returns values for the given rows.
Args:
rows: A scalar/list/tensor of location(s) to read values from. If rows is
a scalar, a single value is returned without a batch dimension. If rows
is a list of integers or a rank-1 int Tensor a batch of values wi... | Returns values for the given rows.
Args:
rows: A scalar/list/tensor of location(s) to read values from. If rows is
a scalar, a single value is returned without a batch dimension. If rows
is a list of integers or a rank-1 int Tensor a batch of values will be
returned with each Tensor h... | read | python | tensorflow/agents | tf_agents/replay_buffers/table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/table.py | Apache-2.0 |
def write(self, rows, values, slots=None):
"""Returns ops for writing values at the given rows.
Args:
rows: A scalar/list/tensor of location(s) to write values at.
values: A nest of Tensors to write. If rows has more than one element,
values can have an extra first dimension representing th... | Returns ops for writing values at the given rows.
Args:
rows: A scalar/list/tensor of location(s) to write values at.
values: A nest of Tensors to write. If rows has more than one element,
values can have an extra first dimension representing the batch size.
Values must have the same st... | write | python | tensorflow/agents | tf_agents/replay_buffers/table.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/table.py | Apache-2.0 |
def __init__(
self,
data_spec,
batch_size,
max_length=1000,
scope='TFUniformReplayBuffer',
device='cpu:*',
table_fn=table.Table,
dataset_drop_remainder=False,
dataset_window_shift=None,
stateful_dataset=False,
):
"""Creates a TFUniformReplayBuffer.
... | Creates a TFUniformReplayBuffer.
The TFUniformReplayBuffer stores episodes in `B == batch_size` blocks of
size `L == max_length`, with total frame capacity
`C == L * B`. Storage looks like:
```
block1 ep1 frame1
frame2
...
ep2 frame1
frame2
... | __init__ | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _add_batch(self, items):
"""Adds a batch of items to the replay buffer.
Args:
items: A tensor or list/tuple/nest of tensors representing a batch of
items to be added to the replay buffer. Each element of `items` must
match the data_spec of this class. Should be shape [batch_size,
... | Adds a batch of items to the replay buffer.
Args:
items: A tensor or list/tuple/nest of tensors representing a batch of
items to be added to the replay buffer. Each element of `items` must
match the data_spec of this class. Should be shape [batch_size,
data_spec, ...]
Returns:
... | _add_batch | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _get_next(
self, sample_batch_size=None, num_steps=None, time_stacked=True
):
"""Returns an item or batch of items sampled uniformly from the buffer.
Sample transitions uniformly from replay buffer. When sub-episodes are
desired, specify num_steps, although note that for the returned items to
... | Returns an item or batch of items sampled uniformly from the buffer.
Sample transitions uniformly from replay buffer. When sub-episodes are
desired, specify num_steps, although note that for the returned items to
truly be sub-episodes also requires that experience collection be
single-threaded.
Ar... | _get_next | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _as_dataset(
self,
sample_batch_size=None,
num_steps=None,
sequence_preprocess_fn=None,
num_parallel_calls=None,
):
"""Creates a dataset that returns entries from the buffer in shuffled order.
Args:
sample_batch_size: (Optional.) An optional batch_size to specify the
... | Creates a dataset that returns entries from the buffer in shuffled order.
Args:
sample_batch_size: (Optional.) An optional batch_size to specify the
number of items to return. See as_dataset() documentation.
num_steps: (Optional.) Optional way to specify that sub-episodes are
desired. ... | _as_dataset | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _single_deterministic_pass_dataset(
self,
sample_batch_size=None,
num_steps=None,
sequence_preprocess_fn=None,
num_parallel_calls=None,
):
"""Creates a dataset that returns entries from the buffer in fixed order.
Args:
sample_batch_size: (Optional.) An optional batch_s... | Creates a dataset that returns entries from the buffer in fixed order.
Args:
sample_batch_size: (Optional.) An optional batch_size to specify the
number of items to return. See as_dataset() documentation.
num_steps: (Optional.) Optional way to specify that sub-episodes are
desired. See... | _single_deterministic_pass_dataset | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def get_row_ids(_):
"""Passed to Dataset.range(self._batch_size).flat_map(.), gets row ids."""
with tf.device(self._device), tf.name_scope(self._scope):
with tf.name_scope('single_deterministic_pass_dataset'):
# Here we pass num_steps=None because _valid_range_ids uses
# num_step... | Passed to Dataset.range(self._batch_size).flat_map(.), gets row ids. | get_row_ids | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _gather_all(self):
"""Returns all the items in buffer, shape [batch_size, timestep, ...].
Returns:
All the items currently in the buffer.
"""
with tf.device(self._device), tf.name_scope(self._scope):
with tf.name_scope('gather_all'):
# Make ids, repeated over batch_size. Shape [... | Returns all the items in buffer, shape [batch_size, timestep, ...].
Returns:
All the items currently in the buffer.
| _gather_all | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _clear(self, clear_all_variables=False):
"""Return op that resets the contents of replay buffer.
Args:
clear_all_variables: boolean indicating if all variables should be
cleared. By default, table contents will be unlinked from replay buffer,
but values are unmodified for efficiency. ... | Return op that resets the contents of replay buffer.
Args:
clear_all_variables: boolean indicating if all variables should be
cleared. By default, table contents will be unlinked from replay buffer,
but values are unmodified for efficiency. Set `clear_all_variables=True`
to reset all ... | _clear | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _increment_last_id(self, increment=1):
"""Increments the last_id in a thread safe manner.
Args:
increment: amount to increment last_id by.
Returns:
An op that increments the last_id.
"""
def _assign_add():
return self._last_id.assign_add(increment).value()
return self._... | Increments the last_id in a thread safe manner.
Args:
increment: amount to increment last_id by.
Returns:
An op that increments the last_id.
| _increment_last_id | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _get_rows_for_id(self, id_):
"""Make a batch_size length list of tensors, with row ids for write."""
id_mod = tf.math.mod(id_, self._max_length)
rows = self._batch_offsets + id_mod
return rows | Make a batch_size length list of tensors, with row ids for write. | _get_rows_for_id | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _valid_range_ids(last_id, max_length, num_steps=None):
"""Returns the [min_val, max_val) range of ids.
When num_steps is provided, [min_val, max_val+num_steps) are also valid ids.
Args:
last_id: The last id added to the buffer.
max_length: The max length of each batch segment in the buffer.
num_... | Returns the [min_val, max_val) range of ids.
When num_steps is provided, [min_val, max_val+num_steps) are also valid ids.
Args:
last_id: The last id added to the buffer.
max_length: The max length of each batch segment in the buffer.
num_steps: Optional way to specify that how many ids need to be vali... | _valid_range_ids | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer.py | Apache-2.0 |
def _create_collect_rb_dataset(
self,
max_length,
buffer_batch_size,
num_adds,
sample_batch_size,
num_steps=None,
):
"""Create a replay buffer, add items to it, and collect from its dataset."""
spec = specs.TensorSpec([], tf.int32, 'action')
replay_buffer = tf_uniform_r... | Create a replay buffer, add items to it, and collect from its dataset. | _create_collect_rb_dataset | python | tensorflow/agents | tf_agents/replay_buffers/tf_uniform_replay_buffer_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/replay_buffers/tf_uniform_replay_buffer_test.py | Apache-2.0 |
def sample_bounded_spec(spec, rng):
"""Samples the given bounded spec.
Args:
spec: A BoundedSpec to sample.
rng: A numpy RandomState to use for the sampling.
Returns:
An np.array sample of the requested spec.
"""
tf_dtype = tf.as_dtype(spec.dtype)
low = spec.minimum
high = spec.maximum
if... | Samples the given bounded spec.
Args:
spec: A BoundedSpec to sample.
rng: A numpy RandomState to use for the sampling.
Returns:
An np.array sample of the requested spec.
| sample_bounded_spec | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def sample_spec_nest(structure, rng, outer_dims=()):
"""Samples the given nest of specs.
Args:
structure: An `ArraySpec`, or a nested dict, list or tuple of `ArraySpec`s.
rng: A numpy RandomState to use for the sampling.
outer_dims: An optional list/tuple specifying outer dimensions to add to the
... | Samples the given nest of specs.
Args:
structure: An `ArraySpec`, or a nested dict, list or tuple of `ArraySpec`s.
rng: A numpy RandomState to use for the sampling.
outer_dims: An optional list/tuple specifying outer dimensions to add to the
spec shape before sampling.
Returns:
A nest of sam... | sample_spec_nest | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def check_arrays_nest(arrays, spec):
"""Check that the arrays conform to the spec.
Args:
arrays: A NumPy array, or a nested dict, list or tuple of arrays.
spec: An `ArraySpec`, or a nested dict, list or tuple of `ArraySpec`s.
Returns:
True if the arrays conforms to the spec, False otherwise.
"""
... | Check that the arrays conform to the spec.
Args:
arrays: A NumPy array, or a nested dict, list or tuple of arrays.
spec: An `ArraySpec`, or a nested dict, list or tuple of `ArraySpec`s.
Returns:
True if the arrays conforms to the spec, False otherwise.
| check_arrays_nest | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def assert_arrays_spec_nest(arrays, spec):
"""Check that the arrays conform to the spec.
Args:
arrays: A NumPy array, or a nested dict, list or tuple of arrays.
spec: An `ArraySpec`, or a nested dict, list or tuple of `ArraySpec`s.
Raise:
A TypeError or ValueError describing the mismatch.
"""
tf... | Check that the arrays conform to the spec.
Args:
arrays: A NumPy array, or a nested dict, list or tuple of arrays.
spec: An `ArraySpec`, or a nested dict, list or tuple of `ArraySpec`s.
Raise:
A TypeError or ValueError describing the mismatch.
| assert_arrays_spec_nest | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def __init__(self, shape, dtype, name=None):
"""Initializes a new `ArraySpec`.
Args:
shape: An iterable specifying the array shape.
dtype: numpy dtype or string specifying the array dtype.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`... | Initializes a new `ArraySpec`.
Args:
shape: An iterable specifying the array shape.
dtype: numpy dtype or string specifying the array dtype.
name: Optional string containing a semantic name for the corresponding
array. Defaults to `None`.
Raises:
TypeError: If the shape is not ... | __init__ | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def __eq__(self, other):
"""Checks if the shape and dtype of two specs are equal."""
if not isinstance(other, ArraySpec):
return False
return self.shape == other.shape and self.dtype == other.dtype | Checks if the shape and dtype of two specs are equal. | __eq__ | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def check_array(self, array):
"""Return whether the given NumPy array conforms to the spec.
Args:
array: A NumPy array or a scalar. Tuples and lists will not be converted
to a NumPy array automatically; they will cause this function to return
false, even if a conversion to a conforming ar... | Return whether the given NumPy array conforms to the spec.
Args:
array: A NumPy array or a scalar. Tuples and lists will not be converted
to a NumPy array automatically; they will cause this function to return
false, even if a conversion to a conforming array is trivial.
Returns:
T... | check_array | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def from_array(array, name=None):
"""Construct a spec from the given array or number."""
if isinstance(array, np.ndarray):
return ArraySpec(array.shape, array.dtype, name)
elif isinstance(array, numbers.Number):
return ArraySpec(tuple(), type(array), name)
else:
raise ValueError('Array... | Construct a spec from the given array or number. | from_array | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def num_values(self):
"""Returns the number of values for discrete BoundedArraySpec."""
if is_discrete(self):
return (
np.broadcast_to(self.maximum, shape=self.shape)
- np.broadcast_to(self.minimum, shape=self.shape)
+ 1
) | Returns the number of values for discrete BoundedArraySpec. | num_values | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
def check_array(self, array):
"""Return true if the given array conforms to the spec."""
return (
super(BoundedArraySpec, self).check_array(array)
and np.all(array >= self.minimum)
and np.all(array <= self.maximum)
) | Return true if the given array conforms to the spec. | check_array | python | tensorflow/agents | tf_agents/specs/array_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.