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 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 |
def example_nested_spec(dtype):
"""Return an example nested array spec."""
return {
"array_spec_1": array_spec.ArraySpec((2, 3), dtype),
"bounded_spec_1": array_spec.BoundedArraySpec((2, 3), dtype, -10, 10),
"dict_spec": {
"array_spec_2": array_spec.ArraySpec((2, 3), dtype),
"b... | Return an example nested array spec. | example_nested_spec | python | tensorflow/agents | tf_agents/specs/array_spec_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/array_spec_test.py | Apache-2.0 |
def create_per_arm_observation_spec(
global_dim: int,
per_arm_dim: int,
max_num_actions: Optional[int] = None,
add_num_actions_feature: bool = False,
) -> types.NestedTensorSpec:
"""Creates an observation spec with per-arm features and possibly action mask.
Args:
global_dim: (int) The global fe... | Creates an observation spec with per-arm features and possibly action mask.
Args:
global_dim: (int) The global feature dimension.
per_arm_dim: (int) The per-arm feature dimension.
max_num_actions: If specified (int), this is the maximum number of actions
in any sample, and the num_actions dimension... | create_per_arm_observation_spec | python | tensorflow/agents | tf_agents/specs/bandit_spec_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/bandit_spec_utils.py | Apache-2.0 |
def get_context_dims_from_spec(
context_spec: types.NestedTensorSpec, accepts_per_arm_features: bool
) -> Tuple[int, int]:
"""Returns the global and per-arm context dimensions.
If the policy accepts per-arm features, this function returns the tuple of
the global and per-arm context dimension. Otherwise, it r... | Returns the global and per-arm context dimensions.
If the policy accepts per-arm features, this function returns the tuple of
the global and per-arm context dimension. Otherwise, it returns the (global)
context dim and zero.
Args:
context_spec: A nest of tensor specs, containing the observation spec.
... | get_context_dims_from_spec | python | tensorflow/agents | tf_agents/specs/bandit_spec_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/bandit_spec_utils.py | Apache-2.0 |
def drop_arm_observation(trajectory: types.Trajectory) -> types.Trajectory:
"""Drops the per-arm observation from a given trajectory/trajectory spec."""
transformed_trajectory = copy.deepcopy(trajectory)
del transformed_trajectory.observation[PER_ARM_FEATURE_KEY]
return transformed_trajectory | Drops the per-arm observation from a given trajectory/trajectory spec. | drop_arm_observation | python | tensorflow/agents | tf_agents/specs/bandit_spec_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/bandit_spec_utils.py | Apache-2.0 |
def __init__(
self, builder, input_params_spec, sample_spec, **distribution_parameters
):
"""Creates a DistributionSpec.
Args:
builder: Callable function(**params) which returns a Distribution
following the spec.
input_params_spec: Nest of tensor_specs describing the tensor paramete... | Creates a DistributionSpec.
Args:
builder: Callable function(**params) which returns a Distribution
following the spec.
input_params_spec: Nest of tensor_specs describing the tensor parameters
required for building the described distribution.
sample_spec: Data type of the output s... | __init__ | python | tensorflow/agents | tf_agents/specs/distribution_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/distribution_spec.py | Apache-2.0 |
def build_distribution(self, **distribution_parameters):
"""Creates an instance of the described distribution.
The spec's paramers are updated with the given ones.
Args:
**distribution_parameters: Kwargs update the spec's distribution
parameters.
Returns:
Distribution instance.
... | Creates an instance of the described distribution.
The spec's paramers are updated with the given ones.
Args:
**distribution_parameters: Kwargs update the spec's distribution
parameters.
Returns:
Distribution instance.
| build_distribution | python | tensorflow/agents | tf_agents/specs/distribution_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/distribution_spec.py | Apache-2.0 |
def nested_distributions_from_specs(specs, parameters):
"""Builds a nest of distributions from a nest of specs.
Args:
specs: A nest of distribution specs.
parameters: A nest of distribution kwargs.
Returns:
Nest of distribution instances with the same structure as the given specs.
"""
return nes... | Builds a nest of distributions from a nest of specs.
Args:
specs: A nest of distribution specs.
parameters: A nest of distribution kwargs.
Returns:
Nest of distribution instances with the same structure as the given specs.
| nested_distributions_from_specs | python | tensorflow/agents | tf_agents/specs/distribution_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/distribution_spec.py | Apache-2.0 |
def from_spec(spec):
"""Maps the given spec into corresponding TensorSpecs keeping bounds."""
def _convert_to_tensor_spec(s):
# Need to check bounded first as non bounded specs are base class.
if isinstance(s, tf.TypeSpec):
return s
if is_bounded(s):
return BoundedTensorSpec.from_spec(s)
... | Maps the given spec into corresponding TensorSpecs keeping bounds. | from_spec | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def to_placeholder(spec, outer_dims=()):
"""Creates a placeholder from TensorSpec.
Args:
spec: instance of TensorSpec
outer_dims: optional leading dimensions of the placeholder.
Returns:
An instance of tf.placeholder.
"""
ph_shape = list(outer_dims) + spec.shape.as_list()
return tf.compat.v1.p... | Creates a placeholder from TensorSpec.
Args:
spec: instance of TensorSpec
outer_dims: optional leading dimensions of the placeholder.
Returns:
An instance of tf.placeholder.
| to_placeholder | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def to_placeholder_with_default(default, spec, outer_dims=()):
"""Creates a placeholder from TensorSpec.
Args:
default: A constant value of output type dtype.
spec: Instance of TensorSpec
outer_dims: Optional leading dimensions of the placeholder.
Returns:
An instance of tf.placeholder.
"""
... | Creates a placeholder from TensorSpec.
Args:
default: A constant value of output type dtype.
spec: Instance of TensorSpec
outer_dims: Optional leading dimensions of the placeholder.
Returns:
An instance of tf.placeholder.
| to_placeholder_with_default | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def to_nest_placeholder(
nested_tensor_specs, default=None, name_scope="", outer_dims=()
):
"""Converts a nest of TensorSpecs to a nest of matching placeholders.
Args:
nested_tensor_specs: A nest of tensor specs.
default: Optional constant value to set as a default for the placeholder.
name_scope: ... | Converts a nest of TensorSpecs to a nest of matching placeholders.
Args:
nested_tensor_specs: A nest of tensor specs.
default: Optional constant value to set as a default for the placeholder.
name_scope: String name for the scope to create the placeholders in.
outer_dims: Optional leading dimensions ... | to_nest_placeholder | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def sample_bounded_spec(spec, seed=None, outer_dims=None):
"""Samples uniformily the given bounded spec.
Args:
spec: A BoundedSpec to sample.
seed: A seed used for sampling ops
outer_dims: An optional `Tensor` specifying outer dimensions to add to the
spec shape before sampling.
Returns:
A... | Samples uniformily the given bounded spec.
Args:
spec: A BoundedSpec to sample.
seed: A seed used for sampling ops
outer_dims: An optional `Tensor` specifying outer dimensions to add to the
spec shape before sampling.
Returns:
A Tensor sample of the requested spec.
| sample_bounded_spec | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def sample_spec_nest(
structure, seed=None, outer_dims=(), minimum=None, maximum=None
):
"""Samples the given nest of specs.
Args:
structure: A nest of `TensorSpec`.
seed: A seed used for sampling ops
outer_dims: An optional `Tensor` specifying outer dimensions to add to the
spec shape before... | Samples the given nest of specs.
Args:
structure: A nest of `TensorSpec`.
seed: A seed used for sampling ops
outer_dims: An optional `Tensor` specifying outer dimensions to add to the
spec shape before sampling.
minimum: An optional numeric value. If set, numeric specs within the nest
(bo... | sample_spec_nest | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def sample_fn(spec):
"""Return a composite tensor sample given `spec`.
Args:
spec: A TensorSpec, SparseTensorSpec, etc.
Returns:
A tensor or SparseTensor.
Raises:
NotImplementedError: If `outer_dims` is not statically known and a
SparseTensor is requested.
"""
if isi... | Return a composite tensor sample given `spec`.
Args:
spec: A TensorSpec, SparseTensorSpec, etc.
Returns:
A tensor or SparseTensor.
Raises:
NotImplementedError: If `outer_dims` is not statically known and a
SparseTensor is requested.
| sample_fn | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def zero_spec_nest(specs, outer_dims=None):
"""Create zero tensors for a given spec.
Args:
specs: A nest of `TensorSpec`.
outer_dims: An optional list of constants or `Tensor` specifying outer
dimensions to add to the spec shape before sampling.
Returns:
A nest of zero tensors matching `specs`... | Create zero tensors for a given spec.
Args:
specs: A nest of `TensorSpec`.
outer_dims: An optional list of constants or `Tensor` specifying outer
dimensions to add to the spec shape before sampling.
Returns:
A nest of zero tensors matching `specs`, with the optional outer
dimensions added.
... | zero_spec_nest | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def add_outer_dims_nest(specs, outer_dims):
"""Adds outer dimensions to the shape of input specs.
Args:
specs: Nested list/tuple/dict of TensorSpecs/ArraySpecs, describing the
shape of tensors.
outer_dims: a list or tuple, representing the outer shape to be added to the
TensorSpecs in specs.
... | Adds outer dimensions to the shape of input specs.
Args:
specs: Nested list/tuple/dict of TensorSpecs/ArraySpecs, describing the
shape of tensors.
outer_dims: a list or tuple, representing the outer shape to be added to the
TensorSpecs in specs.
Returns:
Nested TensorSpecs with outer dimen... | add_outer_dims_nest | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def with_dtype(specs, dtype):
"""Updates dtypes of all specs in the input spec.
Args:
specs: Nested list/tuple/dict of TensorSpecs/ArraySpecs, describing the
shape of tensors.
dtype: dtype to update the specs to.
Returns:
Nested TensorSpecs with the udpated dtype.
"""
def update_dtype(spe... | Updates dtypes of all specs in the input spec.
Args:
specs: Nested list/tuple/dict of TensorSpecs/ArraySpecs, describing the
shape of tensors.
dtype: dtype to update the specs to.
Returns:
Nested TensorSpecs with the udpated dtype.
| with_dtype | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def remove_outer_dims_nest(specs, num_outer_dims):
"""Removes the specified number of outer dimensions from the input spec nest.
Args:
specs: Nested list/tuple/dict of TensorSpecs/ArraySpecs, describing the
shape of tensors.
num_outer_dims: (int) Number of outer dimensions to remove.
Returns:
... | Removes the specified number of outer dimensions from the input spec nest.
Args:
specs: Nested list/tuple/dict of TensorSpecs/ArraySpecs, describing the
shape of tensors.
num_outer_dims: (int) Number of outer dimensions to remove.
Returns:
Nested TensorSpecs with outer dimensions removed from th... | remove_outer_dims_nest | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def to_proto(spec):
"""Encodes a nested spec into a struct_pb2.StructuredValue proto.
Args:
spec: Nested list/tuple or dict of TensorSpecs, describing the shape of the
non-batched Tensors.
Returns:
A `struct_pb2.StructuredValue` proto.
"""
# Make sure spec is a tensor_spec.
spec = from_spec(... | Encodes a nested spec into a struct_pb2.StructuredValue proto.
Args:
spec: Nested list/tuple or dict of TensorSpecs, describing the shape of the
non-batched Tensors.
Returns:
A `struct_pb2.StructuredValue` proto.
| to_proto | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def from_packed_proto(spec_packed_proto):
"""Decodes a packed Any proto containing the structured value for the spec."""
spec_proto = struct_pb2.StructuredValue()
spec_packed_proto.Unpack(spec_proto)
return from_proto(spec_proto) | Decodes a packed Any proto containing the structured value for the spec. | from_packed_proto | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def to_pbtxt_file(output_path, spec):
"""Saves a spec encoded as a struct_pb2.StructuredValue in a pbtxt file."""
spec_proto = to_proto(spec)
dir_path = os.path.split(output_path)[0]
tf.io.gfile.makedirs(dir_path)
with tf.io.gfile.GFile(output_path, "wb") as f:
f.write(text_format.MessageToString(spec_pro... | Saves a spec encoded as a struct_pb2.StructuredValue in a pbtxt file. | to_pbtxt_file | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def from_pbtxt_file(spec_path):
"""Loads a spec encoded as a struct_pb2.StructuredValue from a pbtxt file."""
spec_proto = struct_pb2.StructuredValue()
with tf.io.gfile.GFile(spec_path, "rb") as f:
text_format.MergeLines(f, spec_proto)
return from_proto(spec_proto) | Loads a spec encoded as a struct_pb2.StructuredValue from a pbtxt file. | from_pbtxt_file | python | tensorflow/agents | tf_agents/specs/tensor_spec.py | https://github.com/tensorflow/agents/blob/master/tf_agents/specs/tensor_spec.py | Apache-2.0 |
def get_context(method: Text = None) -> _multiprocessing.context.BaseContext:
"""Get a context: an object with the same API as multiprocessing module.
Args:
method: (Optional.) The method name; a Google-safe default is provided.
Returns:
A multiprocessing context.
Raises:
RuntimeError: If main() ... | Get a context: an object with the same API as multiprocessing module.
Args:
method: (Optional.) The method name; a Google-safe default is provided.
Returns:
A multiprocessing context.
Raises:
RuntimeError: If main() was not executed via handle_main().
| get_context | python | tensorflow/agents | tf_agents/system/system_multiprocessing.py | https://github.com/tensorflow/agents/blob/master/tf_agents/system/system_multiprocessing.py | Apache-2.0 |
def __init__(self, context, target):
"""Store target function and global state.
This function runs on the process that's creating subprocesses.
Args:
context: An instance of a multiprocessing BaseContext.
target: A callable that will be run in a subprocess.
"""
self._context = context
... | Store target function and global state.
This function runs on the process that's creating subprocesses.
Args:
context: An instance of a multiprocessing BaseContext.
target: A callable that will be run in a subprocess.
| __init__ | python | tensorflow/agents | tf_agents/system/system_multiprocessing.py | https://github.com/tensorflow/agents/blob/master/tf_agents/system/system_multiprocessing.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
"""Load global state and run target function.
This function runs on the subprocess.
Args:
*args: Arguments to target.
**kwargs: Keyword arguments to target.
Returns:
Return value of target.
Raises:
Reraises any exceptions by target.
... | Load global state and run target function.
This function runs on the subprocess.
Args:
*args: Arguments to target.
**kwargs: Keyword arguments to target.
Returns:
Return value of target.
Raises:
Reraises any exceptions by target.
| __call__ | python | tensorflow/agents | tf_agents/system/system_multiprocessing.py | https://github.com/tensorflow/agents/blob/master/tf_agents/system/system_multiprocessing.py | Apache-2.0 |
def handle_main(parent_main_fn, *args, **kwargs):
"""Function that wraps the main function in a multiprocessing-friendly way.
This function additionally accepts an `extra_state_savers` kwarg;
users can provide a list of `tf_agents.multiprocessing.StateSaver` instances,
where a `StateSaver` tells multiprocessin... | Function that wraps the main function in a multiprocessing-friendly way.
This function additionally accepts an `extra_state_savers` kwarg;
users can provide a list of `tf_agents.multiprocessing.StateSaver` instances,
where a `StateSaver` tells multiprocessing how to store some global state
and how to restore i... | handle_main | python | tensorflow/agents | tf_agents/system/default/multiprocessing_core.py | https://github.com/tensorflow/agents/blob/master/tf_agents/system/default/multiprocessing_core.py | Apache-2.0 |
def handle_test_main(parent_main_fn, *args, **kwargs):
"""Function that wraps the test main in a multiprocessing-friendly way.
This function additionally accepts an `extra_state_savers` kwarg;
users can provide a list of `tf_agents.multiprocessing.StateSaver` instances,
where a `StateSaver` tells multiprocessi... | Function that wraps the test main in a multiprocessing-friendly way.
This function additionally accepts an `extra_state_savers` kwarg;
users can provide a list of `tf_agents.multiprocessing.StateSaver` instances,
where a `StateSaver` tells multiprocessing how to store some global state
and how to restore it in... | handle_test_main | python | tensorflow/agents | tf_agents/system/default/multiprocessing_core.py | https://github.com/tensorflow/agents/blob/master/tf_agents/system/default/multiprocessing_core.py | Apache-2.0 |
def enable_interactive_mode(extra_state_savers=None):
"""Function that enables multiprocessing in interactive mode.
This function accepts an `extra_state_savers` argument;
users can provide a list of `tf_agents.multiprocessing.StateSaver` instances,
where a `StateSaver` tells multiprocessing how to store some ... | Function that enables multiprocessing in interactive mode.
This function accepts an `extra_state_savers` argument;
users can provide a list of `tf_agents.multiprocessing.StateSaver` instances,
where a `StateSaver` tells multiprocessing how to store some global state
and how to restore it in the subprocess.
... | enable_interactive_mode | python | tensorflow/agents | tf_agents/system/default/multiprocessing_core.py | https://github.com/tensorflow/agents/blob/master/tf_agents/system/default/multiprocessing_core.py | Apache-2.0 |
def __init__(
self,
env,
policy,
train_step,
steps_per_run=None,
episodes_per_run=None,
observers=None,
transition_observers=None,
info_observers=None,
metrics=None,
reference_metrics=None,
image_metrics=None,
summary_dir=None,
summary_... | Initializes an Actor.
Args:
env: An instance of either a tf or py environment. Note the policy, and
observers should match the tf/pyness of the env.
policy: An instance of a policy used to interact with the environment.
train_step: A scalar tf.int64 `tf.Variable` which will keep track of ... | __init__ | python | tensorflow/agents | tf_agents/train/actor.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/actor.py | Apache-2.0 |
def write_metric_summaries(self):
"""Generates scalar summaries for the actor metrics."""
if self._metrics is None:
return
with self._summary_writer.as_default(), common.soft_device_placement(), tf.summary.record_if(
lambda: True
):
# Generate summaries against the train_step
f... | Generates scalar summaries for the actor metrics. | write_metric_summaries | python | tensorflow/agents | tf_agents/train/actor.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/actor.py | Apache-2.0 |
def reset(self):
"""Reset the environment to the start and the policy state."""
self._time_step = self._env.reset()
self._policy_state = self._policy.get_initial_state(
self._env.batch_size or 1
) | Reset the environment to the start and the policy state. | reset | python | tensorflow/agents | tf_agents/train/actor.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/actor.py | Apache-2.0 |
def collect_metrics(buffer_size):
"""Utilitiy to create metrics often used during data collection."""
metrics = [
py_metrics.NumberOfEpisodes(),
py_metrics.EnvironmentSteps(),
py_metrics.AverageReturnMetric(buffer_size=buffer_size),
py_metrics.AverageEpisodeLengthMetric(buffer_size=buffer_si... | Utilitiy to create metrics often used during data collection. | collect_metrics | python | tensorflow/agents | tf_agents/train/actor.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/actor.py | Apache-2.0 |
def eval_metrics(buffer_size):
"""Utilitiy to create metrics often used during policy evaluation."""
return [
py_metrics.AverageReturnMetric(buffer_size=buffer_size),
py_metrics.AverageEpisodeLengthMetric(buffer_size=buffer_size),
] | Utilitiy to create metrics often used during policy evaluation. | eval_metrics | python | tensorflow/agents | tf_agents/train/actor.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/actor.py | Apache-2.0 |
def __init__(self, interval: int, fn: Callable[[], None], start: int = 0):
"""Constructs the IntervalTrigger.
Args:
interval: The triggering interval.
fn: callable with no arguments that gets triggered.
start: An initial value for the trigger.
"""
self._interval = interval
self._o... | Constructs the IntervalTrigger.
Args:
interval: The triggering interval.
fn: callable with no arguments that gets triggered.
start: An initial value for the trigger.
| __init__ | python | tensorflow/agents | tf_agents/train/interval_trigger.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/interval_trigger.py | Apache-2.0 |
def __call__(self, value: int, force_trigger: bool = False) -> None:
"""Maybe trigger the event based on the interval.
Args:
value: the value for triggering.
force_trigger: If True, the trigger will be forced triggered unless the
last trigger value is equal to `value`.
"""
if self._... | Maybe trigger the event based on the interval.
Args:
value: the value for triggering.
force_trigger: If True, the trigger will be forced triggered unless the
last trigger value is equal to `value`.
| __call__ | python | tensorflow/agents | tf_agents/train/interval_trigger.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/interval_trigger.py | Apache-2.0 |
def __init__(
self,
root_dir,
train_step,
agent,
experience_dataset_fn=None,
after_train_strategy_step_fn=None,
triggers=None,
checkpoint_interval=100000,
summary_interval=1000,
max_checkpoints_to_keep=3,
use_kwargs_in_agent_train=False,
strategy=N... | Initializes a Learner instance.
Args:
root_dir: Main directory path where checkpoints, saved_models, and
summaries (if summary_dir is not specified) will be written to.
train_step: a scalar tf.int64 `tf.Variable` which will keep track of the
number of train steps. This is used for artif... | __init__ | python | tensorflow/agents | tf_agents/train/learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/learner.py | Apache-2.0 |
def run(self, iterations=1, iterator=None, parallel_iterations=10):
"""Runs `iterations` iterations of training.
Args:
iterations: Number of train iterations to perform per call to run. The
iterations will be evaluated in a tf.while loop created by autograph.
Final aggregated losses will ... | Runs `iterations` iterations of training.
Args:
iterations: Number of train iterations to perform per call to run. The
iterations will be evaluated in a tf.while loop created by autograph.
Final aggregated losses will be returned.
iterator: The iterator to the dataset to use for trainin... | run | python | tensorflow/agents | tf_agents/train/learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/learner.py | Apache-2.0 |
def loss(
self,
experience_and_sample_info: Optional[ExperienceAndSampleInfo] = None,
reduce_op: tf.distribute.ReduceOp = tf.distribute.ReduceOp.SUM,
) -> tf_agent.LossInfo:
"""Computes loss for the experience.
Since this calls agent.loss() it does not update gradients or
increment the ... | Computes loss for the experience.
Since this calls agent.loss() it does not update gradients or
increment the train step counter. Networks are called with `training=False`
so statistics like batch norm are not updated.
Args:
experience_and_sample_info: A batch of experience and sample info. If n... | loss | python | tensorflow/agents | tf_agents/train/learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/learner.py | Apache-2.0 |
def __init__(
self,
root_dir: Text,
train_step: tf.Variable,
agent: ppo_agent.PPOAgent,
experience_dataset_fn: Callable[..., tf.data.Dataset],
normalization_dataset_fn: Callable[..., tf.data.Dataset],
num_samples: int,
num_epochs: int = 1,
minibatch_size: Optional[i... | Initializes a PPOLearner instance.
```python
agent = ppo_agent.PPOAgent(...,
compute_value_and_advantage_in_train=False,
# Skips updating normalizers in the agent, as it's handled in the learner.
update_normalizers_in_train=False)
# train_replay_buffer and normalization_replay_buffer poi... | __init__ | python | tensorflow/agents | tf_agents/train/ppo_learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner.py | Apache-2.0 |
def _create_datasets(self, strategy):
"""Create the training dataset and iterator."""
def _make_dataset(_):
train_dataset = self._experience_dataset_fn().take(self._num_samples)
# We take the current batches, repeat for `num_epochs` times and exhaust
# this data in the current learner run. T... | Create the training dataset and iterator. | _create_datasets | python | tensorflow/agents | tf_agents/train/ppo_learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner.py | Apache-2.0 |
def run(self, parallel_iterations=10):
"""Train `num_samples` batches repeating for `num_epochs` of iterations.
Args:
parallel_iterations: Maximum number of train iterations to allow running
in parallel. This value is forwarded directly to the training tf.while
loop.
Returns:
T... | Train `num_samples` batches repeating for `num_epochs` of iterations.
Args:
parallel_iterations: Maximum number of train iterations to allow running
in parallel. This value is forwarded directly to the training tf.while
loop.
Returns:
The total loss computed before running the fina... | run | python | tensorflow/agents | tf_agents/train/ppo_learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner.py | Apache-2.0 |
def _update_normalizers(self, iterator):
"""Update the normalizers and count the total number of frames."""
reward_spec = tensor_spec.TensorSpec(shape=[], dtype=tf.float32)
def _update(traj):
self._agent.update_observation_normalizer(traj.observation)
self._agent.update_reward_normalizer(traj.... | Update the normalizers and count the total number of frames. | _update_normalizers | python | tensorflow/agents | tf_agents/train/ppo_learner.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner.py | Apache-2.0 |
def _concat_and_flatten(traj, multiplier):
"""Concatenate tensors in the input trajectory by `multiplier` times.
Args:
traj: a `Trajectory` shaped [batch_size, num_steps, ...].
multiplier: the number of times to concatenate the input trajectory.
Returns:
a flattened `Trajectory` shaped [multiplier *... | Concatenate tensors in the input trajectory by `multiplier` times.
Args:
traj: a `Trajectory` shaped [batch_size, num_steps, ...].
multiplier: the number of times to concatenate the input trajectory.
Returns:
a flattened `Trajectory` shaped [multiplier * batch_size * num_steps, ...].
| _concat_and_flatten | python | tensorflow/agents | tf_agents/train/ppo_learner_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner_test.py | Apache-2.0 |
def _get_expected_minibatch(all_traj, minibatch_size, current_iteration):
"""Get the `Trajectory` containing the expected minibatch.
Args:
all_traj: a flattened `Trajectory` without the batch and time dimension.
minibatch_size: the number of steps included in each minibatch.
current_iteration: the indx... | Get the `Trajectory` containing the expected minibatch.
Args:
all_traj: a flattened `Trajectory` without the batch and time dimension.
minibatch_size: the number of steps included in each minibatch.
current_iteration: the indx of the current training iteration.
Returns:
The expected `Trajectory` s... | _get_expected_minibatch | python | tensorflow/agents | tf_agents/train/ppo_learner_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner_test.py | Apache-2.0 |
def create_trajectories(n_time_steps, batch_size):
"""Create an input trajectory of shape [batch_size, n_time_steps, ...]."""
# Observation looks like:
# [[ 0., 1., ... n_time_steps.],
# [10., 11., ... n_time_steps.],
# [20., 21., ... n_time_steps.],
# [ ... ],
# [10*batch_size... | Create an input trajectory of shape [batch_size, n_time_steps, ...]. | create_trajectories | python | tensorflow/agents | tf_agents/train/ppo_learner_test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/ppo_learner_test_utils.py | Apache-2.0 |
def __init__(self, step):
"""Creates an instance of the StepPerSecondTracker.
Args:
step: `tf.Variable` holding the current value for the number of train
steps.
"""
self.step = step
self.last_iteration = 0
self.last_time = 0
self.restart() | Creates an instance of the StepPerSecondTracker.
Args:
step: `tf.Variable` holding the current value for the number of train
steps.
| __init__ | python | tensorflow/agents | tf_agents/train/step_per_second_tracker.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/step_per_second_tracker.py | Apache-2.0 |
def __init__(
self,
saved_model_dir: Text,
agent: tf_agent.TFAgent,
train_step: tf.Variable,
interval: int,
async_saving: bool = False,
metadata_metrics: Optional[Mapping[Text, py_metric.PyMetric]] = None,
start: int = 0,
extra_concrete_functions: Optional[
... | Initializes a PolicySavedModelTrigger.
Args:
saved_model_dir: Base dir where checkpoints will be saved.
agent: Agent to extract policies from.
train_step: `tf.Variable` which keeps track of the number of train steps.
interval: How often, in train_steps, the trigger will save. Note that as
... | __init__ | python | tensorflow/agents | tf_agents/train/triggers.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/triggers.py | Apache-2.0 |
def __init__(
self, train_step: tf.Variable, interval: int, log_to_terminal: bool = True
):
"""Initializes a StepPerSecondLogTrigger.
Args:
train_step: `tf.Variable` which keeps track of the number of train steps.
interval: How often, in train_steps, the trigger will save. Note that as
... | Initializes a StepPerSecondLogTrigger.
Args:
train_step: `tf.Variable` which keeps track of the number of train steps.
interval: How often, in train_steps, the trigger will save. Note that as
long as the >= `interval` number of steps have passed since the last
trigger, the event gets tr... | __init__ | python | tensorflow/agents | tf_agents/train/triggers.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/triggers.py | Apache-2.0 |
def __init__(
self,
train_step: tf.Variable,
interval: int,
reverb_client: types.ReverbClient,
):
"""Initializes a StepPerSecondLogTrigger.
Args:
train_step: `tf.Variable` which keeps track of the number of train steps.
interval: How often, in train_steps, the trigger will... | Initializes a StepPerSecondLogTrigger.
Args:
train_step: `tf.Variable` which keeps track of the number of train steps.
interval: How often, in train_steps, the trigger will save. Note that as
long as the >= `interval` number of steps have passed since the last
trigger, the event gets tr... | __init__ | python | tensorflow/agents | tf_agents/train/triggers.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/triggers.py | Apache-2.0 |
def get_tensor_specs(env):
"""Returns observation, action and time step TensorSpecs from passed env.
Args:
env: environment instance used for collection.
"""
observation_tensor_spec = tensor_spec.from_spec(env.observation_spec())
action_tensor_spec = tensor_spec.from_spec(env.action_spec())
time_step_t... | Returns observation, action and time step TensorSpecs from passed env.
Args:
env: environment instance used for collection.
| get_tensor_specs | python | tensorflow/agents | tf_agents/train/utils/spec_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/spec_utils.py | Apache-2.0 |
def get_collect_data_spec_from_policy_and_env(env, policy):
"""Returns collect data spec from policy and environment.
Args:
env: instance of the environment used for collection
policy: policy for collection to get policy spec
Meant to be used for collection jobs (i.e. Actors) without having to
constru... | Returns collect data spec from policy and environment.
Args:
env: instance of the environment used for collection
policy: policy for collection to get policy spec
Meant to be used for collection jobs (i.e. Actors) without having to
construct an agent instance but directly from a policy (which can be loa... | get_collect_data_spec_from_policy_and_env | python | tensorflow/agents | tf_agents/train/utils/spec_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/spec_utils.py | Apache-2.0 |
def get_strategy(tpu, use_gpu):
"""Utility to create a `tf.DistributionStrategy` for TPU or GPU.
If neither is being used a DefaultStrategy is returned which allows executing
on CPU only.
Args:
tpu: BNS address of TPU to use. Note the flag and param are called TPU as
that is what the xmanager utilit... | Utility to create a `tf.DistributionStrategy` for TPU or GPU.
If neither is being used a DefaultStrategy is returned which allows executing
on CPU only.
Args:
tpu: BNS address of TPU to use. Note the flag and param are called TPU as
that is what the xmanager utilities call.
use_gpu: Whether a GPU ... | get_strategy | python | tensorflow/agents | tf_agents/train/utils/strategy_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/strategy_utils.py | Apache-2.0 |
def configure_logical_cpus():
"""Configures exactly 4 logical CPUs for the first physical CPU.
Assumes no logical configuration exists or it was configured the same way.
**Note**: The reason why the number of logical CPUs fixed is because
reconfiguring the number of logical CPUs once the underlying runtime ha... | Configures exactly 4 logical CPUs for the first physical CPU.
Assumes no logical configuration exists or it was configured the same way.
**Note**: The reason why the number of logical CPUs fixed is because
reconfiguring the number of logical CPUs once the underlying runtime has been
initialized is not support... | configure_logical_cpus | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def create_ppo_agent_and_dataset_fn(
action_spec, time_step_spec, train_step, batch_size
):
"""Builds and returns a dummy PPO Agent, dataset and dataset function."""
del action_spec # Unused.
del time_step_spec # Unused.
del batch_size # Unused.
# No arbitrary spec supported.
obs_spec = tensor_spec.... | Builds and returns a dummy PPO Agent, dataset and dataset function. | create_ppo_agent_and_dataset_fn | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def create_dqn_agent_and_dataset_fn(
action_spec, time_step_spec, train_step, batch_size
):
"""Builds and returns a dataset function for DQN Agent."""
q_net = build_dummy_sequential_net(
fc_layer_params=(100,), action_spec=action_spec
)
agent = dqn_agent.DqnAgent(
time_step_spec,
action_s... | Builds and returns a dataset function for DQN Agent. | create_dqn_agent_and_dataset_fn | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def get_actor_thread(test_case, reverb_server_port, num_iterations=10):
"""Returns a thread that runs an Actor."""
def build_and_run_actor():
root_dir = test_case.create_tempdir().full_path
env, action_tensor_spec, time_step_tensor_spec = (
get_cartpole_env_and_specs()
)
train_step = train... | Returns a thread that runs an Actor. | get_actor_thread | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def check_variables_different(test_case, old_vars_numpy, new_vars_numpy):
"""Tests whether the two sets of variables are different.
Useful for checking if variables were updated, i.e. a train step was run.
Args:
test_case: an instande of tf.test.TestCase for assertions
old_vars_numpy: numpy representati... | Tests whether the two sets of variables are different.
Useful for checking if variables were updated, i.e. a train step was run.
Args:
test_case: an instande of tf.test.TestCase for assertions
old_vars_numpy: numpy representation of old variables
new_vars_numpy: numpy representation of new variables
... | check_variables_different | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def check_variables_same(test_case, old_vars_numpy, new_vars_numpy):
"""Tests whether the two sets of variables are the same.
Useful for checking if variables were not updated, i.e. a loss step was run.
Args:
test_case: an instande of tf.test.TestCase for assertions
old_vars_numpy: numpy representation ... | Tests whether the two sets of variables are the same.
Useful for checking if variables were not updated, i.e. a loss step was run.
Args:
test_case: an instande of tf.test.TestCase for assertions
old_vars_numpy: numpy representation of old variables
new_vars_numpy: numpy representation of new variables... | check_variables_same | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def create_reverb_server_for_replay_buffer_and_variable_container(
collect_policy, train_step, replay_buffer_capacity, port
):
"""Sets up one reverb server for replay buffer and variable container."""
# Create the signature for the variable container holding the policy weights.
variables = {
reverb_vari... | Sets up one reverb server for replay buffer and variable container. | create_reverb_server_for_replay_buffer_and_variable_container | python | tensorflow/agents | tf_agents/train/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/test_utils.py | Apache-2.0 |
def create_staleness_metrics_after_train_step_fn(
train_step: tf.Variable, train_steps_per_policy_update: int = 1
) -> Callable[
[Tuple[types.NestedTensor, types.ReverbSampleInfo], tf_agent.LossInfo], None
]:
"""Creates an `after_train_step_fn` that computes staleness summaries.
Staleness, in this context,... | Creates an `after_train_step_fn` that computes staleness summaries.
Staleness, in this context, means that the observation was generated by a
policy that is older than the recently outputed policy.
Assume that observation train step is stored as Reverb priorities.
Args:
train_step: The current train step.... | create_staleness_metrics_after_train_step_fn | python | tensorflow/agents | tf_agents/train/utils/train_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils.py | Apache-2.0 |
def wait_for_policy(
policy_dir: Text,
sleep_time_secs: int = _WAIT_DEFAULT_SLEEP_TIME_SECS,
num_retries: int = _WAIT_DEFAULT_NUM_RETRIES,
**saved_model_policy_args
) -> py_tf_eager_policy.PyTFEagerPolicyBase:
"""Blocks until the policy in `policy_dir` becomes available.
The default setting allows ... | Blocks until the policy in `policy_dir` becomes available.
The default setting allows a fairly loose, but not infinite wait time of one
days for this function to block checking the `policy_dir` in every seconds.
Args:
policy_dir: The directory containing the policy files.
sleep_time_secs: Number of time... | wait_for_policy | python | tensorflow/agents | tf_agents/train/utils/train_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils.py | Apache-2.0 |
def wait_for_file(
file_path: Text,
sleep_time_secs: int = _WAIT_DEFAULT_SLEEP_TIME_SECS,
num_retries: int = _WAIT_DEFAULT_NUM_RETRIES,
) -> Text:
"""Blocks until the file at `file_path` becomes available.
The default setting allows a fairly loose, but not infinite wait time of one
days for this func... | Blocks until the file at `file_path` becomes available.
The default setting allows a fairly loose, but not infinite wait time of one
days for this function to block checking the `file_path` in every seconds.
Args:
file_path: The path to the file that we are waiting for.
sleep_time_secs: Number of time i... | wait_for_file | python | tensorflow/agents | tf_agents/train/utils/train_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils.py | Apache-2.0 |
def _is_file_missing(file_path=file_path):
"""Checks if the file is (still) missing, i.e. more wait is necessary."""
try:
stat = tf.io.gfile.stat(file_path)
except tf.errors.NotFoundError:
return True
found_file = stat.length <= 0
logging.info(
'Checking for file %s (%s)',
... | Checks if the file is (still) missing, i.e. more wait is necessary. | _is_file_missing | python | tensorflow/agents | tf_agents/train/utils/train_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils.py | Apache-2.0 |
def wait_for_predicate(
wait_predicate_fn: Callable[[], bool],
sleep_time_secs: int = _WAIT_DEFAULT_SLEEP_TIME_SECS,
num_retries: int = _WAIT_DEFAULT_NUM_RETRIES,
) -> None:
"""Blocks while `wait_predicate_fn` is returning `True`.
The callable `wait_predicate_fn` indicates if waiting is still needed by... | Blocks while `wait_predicate_fn` is returning `True`.
The callable `wait_predicate_fn` indicates if waiting is still needed by
returning `True`. Once the condition that we wanted to wait for met, the
callable should return `False` denoting that the execution can continue.
The default setting allows a fairly l... | wait_for_predicate | python | tensorflow/agents | tf_agents/train/utils/train_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils.py | Apache-2.0 |
def test_wait_for_predicate_instant_false(self):
"""Tests predicate returning False on first call."""
predicate_mock = mock.MagicMock(side_effect=[False])
# 10 retry limit to avoid a near infinite loop on an error.
train_utils.wait_for_predicate(predicate_mock, num_retries=10)
self.assertEqual(predi... | Tests predicate returning False on first call. | test_wait_for_predicate_instant_false | python | tensorflow/agents | tf_agents/train/utils/train_utils_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils_test.py | Apache-2.0 |
def test_wait_for_predicate_second_false(self):
"""Tests predicate returning False on second call."""
predicate_mock = mock.MagicMock(side_effect=[True, False])
# 10 retry limit to avoid a near infinite loop on an error.
train_utils.wait_for_predicate(predicate_mock, num_retries=10)
self.assertEqual... | Tests predicate returning False on second call. | test_wait_for_predicate_second_false | python | tensorflow/agents | tf_agents/train/utils/train_utils_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils_test.py | Apache-2.0 |
def test_wait_for_predicate_timeout(self):
"""Tests predicate returning True forever and then timing out."""
predicate_mock = mock.MagicMock(side_effect=[True, True, True])
with self.assertRaises(TimeoutError):
train_utils.wait_for_predicate(predicate_mock, num_retries=3) | Tests predicate returning True forever and then timing out. | test_wait_for_predicate_timeout | python | tensorflow/agents | tf_agents/train/utils/train_utils_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/train/utils/train_utils_test.py | Apache-2.0 |
def set_log_probability(
info: types.NestedTensorOrArray, log_probability: types.Float
) -> types.NestedTensorOrArray:
"""Sets the CommonFields.LOG_PROBABILITY on info to be log_probability."""
if info in ((), None):
return PolicyInfo(log_probability=log_probability)
return _maybe_set_value_namedtuple_or_... | Sets the CommonFields.LOG_PROBABILITY on info to be log_probability. | set_log_probability | python | tensorflow/agents | tf_agents/trajectories/policy_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/policy_step.py | Apache-2.0 |
def get_log_probability(
info: types.NestedTensorOrArray,
default_log_probability: Optional[types.Float] = None,
) -> types.Float:
"""Gets the CommonFields.LOG_PROBABILITY from info depending on type."""
return _maybe_get_value_namedtuple_or_dict(
info, CommonFields.LOG_PROBABILITY, default_log_probab... | Gets the CommonFields.LOG_PROBABILITY from info depending on type. | get_log_probability | python | tensorflow/agents | tf_agents/trajectories/policy_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/policy_step.py | Apache-2.0 |
def stacked_trajectory_from_transition(time_step, action_step, next_time_step):
"""Given transitions, returns a time stacked `Trajectory`.
The tensors of the produced `Trajectory` will have a time dimension added
(i.e., a shape of `[B, T, ...]` where T = 2 in this case). The `Trajectory`
can be used when calli... | Given transitions, returns a time stacked `Trajectory`.
The tensors of the produced `Trajectory` will have a time dimension added
(i.e., a shape of `[B, T, ...]` where T = 2 in this case). The `Trajectory`
can be used when calling `agent.train()` or passed directly to `to_transition`
without the need for a `ne... | stacked_trajectory_from_transition | python | tensorflow/agents | tf_agents/trajectories/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/test_utils.py | Apache-2.0 |
def __new__(cls, value):
"""Add ability to create StepType constants from a value."""
if value == cls.FIRST:
return cls.FIRST
if value == cls.MID:
return cls.MID
if value == cls.LAST:
return cls.LAST
raise ValueError('No known conversion for `%r` into a StepType' % value) | Add ability to create StepType constants from a value. | __new__ | python | tensorflow/agents | tf_agents/trajectories/time_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/time_step.py | Apache-2.0 |
def restart(
observation: types.NestedTensorOrArray,
batch_size: Optional[types.Int] = None,
reward_spec: Optional[types.NestedSpec] = None,
) -> TimeStep:
"""Returns a `TimeStep` with `step_type` set equal to `StepType.FIRST`.
Args:
observation: A NumPy array, tensor, or a nested dict, list or tup... | Returns a `TimeStep` with `step_type` set equal to `StepType.FIRST`.
Args:
observation: A NumPy array, tensor, or a nested dict, list or tuple of
arrays or tensors.
batch_size: (Optional) A python or tensorflow integer scalar. If not
provided, the environment will not be considered as a batched e... | restart | python | tensorflow/agents | tf_agents/trajectories/time_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/time_step.py | Apache-2.0 |
def transition(
observation: types.NestedTensorOrArray,
reward: types.NestedTensorOrArray,
discount: types.Float = 1.0,
outer_dims: Optional[types.Shape] = None,
) -> TimeStep:
"""Returns a `TimeStep` with `step_type` set equal to `StepType.MID`.
For TF transitions, the batch size is inferred from ... | Returns a `TimeStep` with `step_type` set equal to `StepType.MID`.
For TF transitions, the batch size is inferred from the shape of `reward`.
If `discount` is a scalar, and `observation` contains Tensors,
then `discount` will be broadcasted to match `reward.shape`.
Args:
observation: A NumPy array, tenso... | transition | python | tensorflow/agents | tf_agents/trajectories/time_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/time_step.py | Apache-2.0 |
def termination(
observation: types.NestedTensorOrArray,
reward: types.NestedTensorOrArray,
outer_dims: Optional[types.Shape] = None,
) -> TimeStep:
"""Returns a `TimeStep` with `step_type` set to `StepType.LAST`.
Args:
observation: A NumPy array, tensor, or a nested dict, list or tuple of
ar... | Returns a `TimeStep` with `step_type` set to `StepType.LAST`.
Args:
observation: A NumPy array, tensor, or a nested dict, list or tuple of
arrays or tensors.
reward: A NumPy array, tensor, or a nested dict, list or tuple of arrays or
tensors.
outer_dims: (optional) If provided, it will be use... | termination | python | tensorflow/agents | tf_agents/trajectories/time_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/time_step.py | Apache-2.0 |
def truncation(
observation: types.NestedTensorOrArray,
reward: types.NestedTensorOrArray,
discount: types.Float = 1.0,
outer_dims: Optional[types.Shape] = None,
) -> TimeStep:
"""Returns a `TimeStep` with `step_type` set to `StepType.LAST`.
If `discount` is a scalar, and `observation` contains Ten... | Returns a `TimeStep` with `step_type` set to `StepType.LAST`.
If `discount` is a scalar, and `observation` contains Tensors,
then `discount` will be broadcasted to match the outer dimensions.
Args:
observation: A NumPy array, tensor, or a nested dict, list or tuple of
arrays or tensors.
reward: A ... | truncation | python | tensorflow/agents | tf_agents/trajectories/time_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/time_step.py | Apache-2.0 |
def time_step_spec(
observation_spec: Optional[types.NestedSpec] = None,
reward_spec: Optional[types.NestedSpec] = None,
) -> TimeStep:
"""Returns a `TimeStep` spec given the observation_spec.
Args:
observation_spec: A nest of `tf.TypeSpec` or `ArraySpec` objects.
reward_spec: (Optional) A nest of ... | Returns a `TimeStep` spec given the observation_spec.
Args:
observation_spec: A nest of `tf.TypeSpec` or `ArraySpec` objects.
reward_spec: (Optional) A nest of `tf.TypeSpec` or `ArraySpec` objects.
Default - a scalar float32 of the same type (Tensor or Array) as
`observation_spec`.
Returns:
... | time_step_spec | python | tensorflow/agents | tf_agents/trajectories/time_step.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/time_step.py | Apache-2.0 |
def _create_trajectory(
observation,
action,
policy_info,
reward,
discount,
step_type,
next_step_type,
name_scope,
):
"""Create a Trajectory composed of either Tensors or numpy arrays.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to... | Create a Trajectory composed of either Tensors or numpy arrays.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to be a singleton array with scalar inner shape.
Args:
observation: (possibly nested tuple of) `Tensor` or `np.ndarray`; all shaped
`[B, ...]`, ... | _create_trajectory | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def first(
observation: types.NestedSpecTensorOrArray,
action: types.NestedSpecTensorOrArray,
policy_info: types.NestedSpecTensorOrArray,
reward: types.NestedSpecTensorOrArray,
discount: types.SpecTensorOrArray,
) -> Trajectory:
"""Create a Trajectory transitioning between StepTypes `FIRST` and `M... | Create a Trajectory transitioning between StepTypes `FIRST` and `MID`.
All inputs may be batched.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to be a singleton array with scalar inner shape.
Args:
observation: (possibly nested tuple of) `Tensor` or `np.nd... | first | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def mid(
observation: types.NestedSpecTensorOrArray,
action: types.NestedSpecTensorOrArray,
policy_info: types.NestedSpecTensorOrArray,
reward: types.NestedSpecTensorOrArray,
discount: types.SpecTensorOrArray,
) -> Trajectory:
"""Create a Trajectory transitioning between StepTypes `MID` and `MID`.... | Create a Trajectory transitioning between StepTypes `MID` and `MID`.
All inputs may be batched.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to be a singleton array with scalar inner shape.
Args:
observation: (possibly nested tuple of) `Tensor` or `np.ndar... | mid | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def last(
observation: types.NestedSpecTensorOrArray,
action: types.NestedSpecTensorOrArray,
policy_info: types.NestedSpecTensorOrArray,
reward: types.NestedSpecTensorOrArray,
discount: types.SpecTensorOrArray,
) -> Trajectory:
"""Create a Trajectory transitioning between StepTypes `MID` and `LAST... | Create a Trajectory transitioning between StepTypes `MID` and `LAST`.
All inputs may be batched.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to be a singleton array with scalar inner shape.
Args:
observation: (possibly nested tuple of) `Tensor` or `np.nda... | last | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def single_step(
observation: types.NestedSpecTensorOrArray,
action: types.NestedSpecTensorOrArray,
policy_info: types.NestedSpecTensorOrArray,
reward: types.NestedSpecTensorOrArray,
discount: types.SpecTensorOrArray,
) -> Trajectory:
"""Create a Trajectory transitioning between StepTypes `FIRST` ... | Create a Trajectory transitioning between StepTypes `FIRST` and `LAST`.
All inputs may be batched.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to be a singleton array with scalar inner shape.
Args:
observation: (possibly nested tuple of) `Tensor` or `np.n... | single_step | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def boundary(
observation: types.NestedSpecTensorOrArray,
action: types.NestedSpecTensorOrArray,
policy_info: types.NestedSpecTensorOrArray,
reward: types.NestedSpecTensorOrArray,
discount: types.SpecTensorOrArray,
) -> Trajectory:
"""Create a Trajectory transitioning between StepTypes `LAST` and ... | Create a Trajectory transitioning between StepTypes `LAST` and `FIRST`.
All inputs may be batched.
The input `discount` is used to infer the outer shape of the inputs,
as it is always expected to be a singleton array with scalar inner shape.
Args:
observation: (possibly nested tuple of) `Tensor` or `np.n... | boundary | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def _maybe_static_outer_dim(t):
"""Return the left-most dense shape dimension of `t`.
Args:
t: A `Tensor` or `CompositeTensor`.
Returns:
A python integer or `0-D` scalar tensor with type `int64`.
"""
assert tf.is_tensor(t), t
if isinstance(t, tf.SparseTensor):
static_shape = tf.get_static_valu... | Return the left-most dense shape dimension of `t`.
Args:
t: A `Tensor` or `CompositeTensor`.
Returns:
A python integer or `0-D` scalar tensor with type `int64`.
| _maybe_static_outer_dim | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def from_episode(
observation: types.NestedSpecTensorOrArray,
action: types.NestedSpecTensorOrArray,
policy_info: types.NestedSpecTensorOrArray,
reward: types.NestedSpecTensorOrArray,
discount: Optional[types.SpecTensorOrArray] = None,
) -> Trajectory:
"""Create a Trajectory from tensors represent... | Create a Trajectory from tensors representing a single episode.
If none of the inputs are tensors, then numpy arrays are generated instead.
If `discount` is not provided, the first entry in `reward` is used to estimate
`T`:
```
reward_0 = tf.nest.flatten(reward)[0]
T = shape(reward_0)[0]
```
In this... | from_episode | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def from_transition(
time_step: ts.TimeStep,
action_step: policy_step.PolicyStep,
next_time_step: ts.TimeStep,
) -> Trajectory:
"""Returns a `Trajectory` given transitions.
`from_transition` is used by a driver to convert sequence of transitions into
a `Trajectory` for efficient storage. Then an agen... | Returns a `Trajectory` given transitions.
`from_transition` is used by a driver to convert sequence of transitions into
a `Trajectory` for efficient storage. Then an agent (e.g.
`ppo_agent.PPOAgent`) converts it back to transitions by invoking
`to_transition`.
Note that this method does not add a time dimen... | from_transition | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def to_transition(
trajectory: Trajectory, next_trajectory: Optional[Trajectory] = None
) -> Transition:
"""Create a transition from a trajectory or two adjacent trajectories.
**NOTE** If `next_trajectory` is not provided, tensors of `trajectory` are
sliced along their *second* (`time`) dimension; for exampl... | Create a transition from a trajectory or two adjacent trajectories.
**NOTE** If `next_trajectory` is not provided, tensors of `trajectory` are
sliced along their *second* (`time`) dimension; for example:
```
time_steps.step_type = trajectory.step_type[:,:-1]
time_steps.observation = trajectory.observation[:... | to_transition | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def to_n_step_transition(
trajectory: Trajectory, gamma: types.Float
) -> Transition:
"""Create an n-step transition from a trajectory with `T=N + 1` frames.
**NOTE** Tensors of `trajectory` are sliced along their *second* (`time`)
dimension, to pull out the appropriate fields for the n-step transitions.
... | Create an n-step transition from a trajectory with `T=N + 1` frames.
**NOTE** Tensors of `trajectory` are sliced along their *second* (`time`)
dimension, to pull out the appropriate fields for the n-step transitions.
The output transition's `next_time_step.{reward, discount}` will contain
N-step discounted re... | to_n_step_transition | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def to_transition_spec(trajectory_spec: Trajectory) -> Transition:
"""Create a transition spec from a trajectory spec.
Note: since trajectories do not include the policy step's state (except
in special cases where the policy chooses to store this in the info field),
the returned `transition.action_spec.state` ... | Create a transition spec from a trajectory spec.
Note: since trajectories do not include the policy step's state (except
in special cases where the policy chooses to store this in the info field),
the returned `transition.action_spec.state` field will be an empty tuple.
Args:
trajectory_spec: An instance ... | to_transition_spec | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def _validate_rank(variable, min_rank, max_rank=None):
"""Validates if a variable has the correct rank.
Args:
variable: A `tf.Tensor` or `numpy.array`.
min_rank: An int representing the min expected rank of the variable.
max_rank: An int representing the max expected rank of the variable.
Raises:
... | Validates if a variable has the correct rank.
Args:
variable: A `tf.Tensor` or `numpy.array`.
min_rank: An int representing the min expected rank of the variable.
max_rank: An int representing the max expected rank of the variable.
Raises:
ValueError: if variable doesn't have expected rank.
| _validate_rank | python | tensorflow/agents | tf_agents/trajectories/trajectory.py | https://github.com/tensorflow/agents/blob/master/tf_agents/trajectories/trajectory.py | Apache-2.0 |
def check_tf1_allowed():
"""Raises an error if running in TF1 (non-eager) mode and this is disabled."""
if _TF1_MODE_ALLOWED:
return
if not tf2_checker.enabled():
raise RuntimeError(
'You are using TF1 or running TF with eager mode disabled. '
'TF-Agents no longer supports TF1 mode (excep... | Raises an error if running in TF1 (non-eager) mode and this is disabled. | check_tf1_allowed | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
def set_default_tf_function_parameters(*args, **kwargs):
"""Generates a decorator that sets default parameters for `tf.function`.
Args:
*args: default arguments for the `tf.function`.
**kwargs: default keyword arguments for the `tf.function`.
Returns:
Function decorator with preconfigured defaults f... | Generates a decorator that sets default parameters for `tf.function`.
Args:
*args: default arguments for the `tf.function`.
**kwargs: default keyword arguments for the `tf.function`.
Returns:
Function decorator with preconfigured defaults for `tf.function`.
| set_default_tf_function_parameters | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
def function(*args, **kwargs):
"""Wrapper for tf.function with TF Agents-specific customizations.
Example:
```python
@common.function()
def my_eager_code(x, y):
...
```
Args:
*args: Args for tf.function.
**kwargs: Keyword args for tf.function.
Returns:
A tf.function wrapper.
"""
... | Wrapper for tf.function with TF Agents-specific customizations.
Example:
```python
@common.function()
def my_eager_code(x, y):
...
```
Args:
*args: Args for tf.function.
**kwargs: Keyword args for tf.function.
Returns:
A tf.function wrapper.
| function | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
def function_in_tf1(*args, **kwargs):
"""Wrapper that returns common.function if using TF1.
This allows for code that assumes autodeps is available to be written once,
in the same way, for both TF1 and TF2.
Usage:
```python
train = function_in_tf1()(agent.train)
loss = train(experience)
```
Args:
... | Wrapper that returns common.function if using TF1.
This allows for code that assumes autodeps is available to be written once,
in the same way, for both TF1 and TF2.
Usage:
```python
train = function_in_tf1()(agent.train)
loss = train(experience)
```
Args:
*args: Arguments for common.function.
... | function_in_tf1 | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
def with_check_resource_vars(*fn_args, **fn_kwargs):
"""Helper function for calling common.function."""
check_tf1_allowed()
if has_eager_been_enabled():
# We're either in eager mode or in tf.function mode (no in-between); so
# autodep-like behavior is already expected of fn.
re... | Helper function for calling common.function. | with_check_resource_vars | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
def soft_variables_update(
source_variables,
target_variables,
tau=1.0,
tau_non_trainable=None,
sort_variables_by_name=False,
):
"""Performs a soft/hard update of variables from the source to the target.
Note: **when using this function with TF DistributionStrategy**, the
`strategy.extended.u... | Performs a soft/hard update of variables from the source to the target.
Note: **when using this function with TF DistributionStrategy**, the
`strategy.extended.update` call (below) needs to be done in a cross-replica
context, i.e. inside a merge_call. Please use the Periodically class above
that provides this ... | soft_variables_update | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
def join_scope(parent_scope, child_scope):
"""Joins a parent and child scope using `/`, checking for empty/none.
Args:
parent_scope: (string) parent/prefix scope.
child_scope: (string) child/suffix scope.
Returns:
joined scope: (string) parent and child scopes joined by /.
"""
if not parent_scop... | Joins a parent and child scope using `/`, checking for empty/none.
Args:
parent_scope: (string) parent/prefix scope.
child_scope: (string) child/suffix scope.
Returns:
joined scope: (string) parent and child scopes joined by /.
| join_scope | python | tensorflow/agents | tf_agents/utils/common.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/common.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.