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 call(self, trajectory): """Update the regret value. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining. """ baseline_reward = self._baseline_reward_fn(trajectory.observation) trajectory_reward = trajectory.reward if isinstance(traj...
Update the regret value. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining.
call
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py
Apache-2.0
def __init__( self, baseline_action_fn: Callable[[types.Tensor], types.Tensor], name: Optional[Text] = 'SuboptimalArmsMetric', dtype: float = tf.float32, ): """Computes the number of suboptimal arms with respect to a baseline. Args: baseline_action_fn: function that computes the...
Computes the number of suboptimal arms with respect to a baseline. Args: baseline_action_fn: function that computes the action used as a baseline for computing the metric. name: (str) name of the metric dtype: dtype of the metric value.
__init__
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py
Apache-2.0
def call(self, trajectory): """Update the metric value. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining. """ baseline_action = self._baseline_action_fn(trajectory.observation) disagreement = tf.cast( tf.not_equal(baseline_action...
Update the metric value. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining.
call
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py
Apache-2.0
def __init__( self, constraint: constraints.BaseConstraint, name: Optional[Text] = 'ConstraintViolationMetric', dtype: float = tf.float32, ): """Computes the constraint violations given an input constraint. Given a certain constraint, this metric computes how often the selected ac...
Computes the constraint violations given an input constraint. Given a certain constraint, this metric computes how often the selected actions in the trajectory violate the constraint. Args: constraint: an instance of `tf_agents.bandits.policies.BaseConstraint`. name: (str) name of the metric ...
__init__
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py
Apache-2.0
def call(self, trajectory): """Update the constraint violations metric. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining. """ feasibility_prob_all_actions = self._constraint(trajectory.observation) feasibility_prob_selected_actions = com...
Update the constraint violations metric. Args: trajectory: A tf_agents.trajectory.Trajectory Returns: The arguments, for easy chaining.
call
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py
Apache-2.0
def __init__( self, estimated_reward_fn: Callable[[types.Tensor], types.Tensor], name: Optional[Text] = 'DistanceFromGreedyMetric', dtype: float = tf.float32, ): """Init function for the metric. Args: estimated_reward_fn: A function that takes the observation as input and ...
Init function for the metric. Args: estimated_reward_fn: A function that takes the observation as input and computes the estimated rewards that the greedy policy uses. name: (str) name of the metric dtype: dtype of the metric value.
__init__
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics.py
Apache-2.0
def __call__(self, observation, actions=None): """Returns the probability of input actions being feasible.""" if actions is None: actions = tf.range( self._action_spec.minimum, self._action_spec.maximum + 1 ) actions = tf.reshape(actions, [1, -1]) actions = tf.tile(actions, [se...
Returns the probability of input actions being feasible.
__call__
python
tensorflow/agents
tf_agents/bandits/metrics/tf_metrics_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/metrics/tf_metrics_test.py
Apache-2.0
def _validate_scalarization_parameter_shape( multi_objectives: tf.Tensor, params: Dict[str, Union[Sequence[ScalarFloat], tf.Tensor]], ): """A private helper that validates the shapes of scalarization parameters. Every scalarization parameter in the input dictionary is either a 1-D tensor or `Sequence`, o...
A private helper that validates the shapes of scalarization parameters. Every scalarization parameter in the input dictionary is either a 1-D tensor or `Sequence`, or a tensor whose shape matches the shape of the input `multi_objectives` tensor. This is invoked by the `Scalarizer.call` method. Args: multi...
_validate_scalarization_parameter_shape
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def __init__(self, num_of_objectives: int): """Initialize the Scalarizer. Args: num_of_objectives: A non-negative integer indicating the number of objectives to scalarize. Raises: ValueError: if `not isinstance(num_of_objectives, int)`. ValueError: if `num_of_objectives < 2`. ...
Initialize the Scalarizer. Args: num_of_objectives: A non-negative integer indicating the number of objectives to scalarize. Raises: ValueError: if `not isinstance(num_of_objectives, int)`. ValueError: if `num_of_objectives < 2`.
__init__
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def __call__(self, multi_objectives: tf.Tensor) -> tf.Tensor: """Returns a single reward by scalarizing multiple objectives. Args: multi_objectives: A `Tensor` of shape [batch_size, number_of_objectives], where each column represents an objective. Returns: A `Tensor` of shape [batch_size] re...
Returns a single reward by scalarizing multiple objectives. Args: multi_objectives: A `Tensor` of shape [batch_size, number_of_objectives], where each column represents an objective. Returns: A `Tensor` of shape [batch_size] representing scalarized rewards. Raises: ValueError: if `mul...
__call__
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def _validate_scalarization_parameters(self, params: Dict[str, tf.Tensor]): """Validates the scalarization parameters. Each scalarization parameter in the input dictionary should be a rank-2 tensor, and the last dimension size should match `self._num_of_objectives`. Args: params: A dictionary fr...
Validates the scalarization parameters. Each scalarization parameter in the input dictionary should be a rank-2 tensor, and the last dimension size should match `self._num_of_objectives`. Args: params: A dictionary from parameter names to parameter tensors. Raises: ValueError: if any inpu...
_validate_scalarization_parameters
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def __init__( self, weights: Sequence[ScalarFloat], multi_objective_transform: Optional[ Callable[[tf.Tensor], tf.Tensor] ] = None, ): """Initialize the LinearScalarizer. Args: weights: A `Sequence` of weights for linearly combining the objectives. multi_objectiv...
Initialize the LinearScalarizer. Args: weights: A `Sequence` of weights for linearly combining the objectives. multi_objective_transform: A `Optional` `Callable` that takes in a `tf.Tensor` of multiple objective values and applies an arbitrary transform that returns a `tf.Tensor` of tra...
__init__
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def set_parameters(self, weights: tf.Tensor): # pytype: disable=signature-mismatch # overriding-parameter-count-checks """Set the scalarization parameter of the LinearScalarizer. Args: weights: A a rank-2 `tf.Tensor` of weights shaped as [batch_size, self._num_of_objectives], where `batch_size`...
Set the scalarization parameter of the LinearScalarizer. Args: weights: A a rank-2 `tf.Tensor` of weights shaped as [batch_size, self._num_of_objectives], where `batch_size` should match the batch size of the `multi_objectives` passed to the scalarizer call. Raises: ValueError: if ...
set_parameters
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def __init__( self, weights: Sequence[ScalarFloat], reference_point: Sequence[ScalarFloat], ): """Initialize the ChebyshevScalarizer. Args: weights: A `Sequence` of weights. reference_point: A `Sequence` of coordinates for the reference point. Raises: ValueError: if `...
Initialize the ChebyshevScalarizer. Args: weights: A `Sequence` of weights. reference_point: A `Sequence` of coordinates for the reference point. Raises: ValueError: if `len(weights) != len(reference_point)`.
__init__
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def set_parameters(self, weights: tf.Tensor, reference_point: tf.Tensor): # pytype: disable=signature-mismatch # overriding-parameter-count-checks """Set the scalarization parameters for the ChebyshevScalarizer. Args: weights: A rank-2 `tf.Tensor` of weights shaped as [batch_size, self._num_of_...
Set the scalarization parameters for the ChebyshevScalarizer. Args: weights: A rank-2 `tf.Tensor` of weights shaped as [batch_size, self._num_of_objectives], where `batch_size` should match the batch size of the `multi_objectives` passed to the scalarizer call. reference_point: A `tf.Te...
set_parameters
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def __init__( self, direction: Sequence[ScalarFloat], transform_params: Sequence[PARAMS], multi_objective_transform: Optional[ Callable[ [tf.Tensor, Sequence[ScalarFloat], Sequence[ScalarFloat]], tf.Tensor, ] ] = None, ): """Initialize ...
Initialize the HyperVolumeScalarizer. Args: direction: A `Sequence` representing a directional vector, which will be normalized to have unit length. Coordinates of the normalized direction whose absolute values are less than `HyperVolumeScalarizer.ALMOST_ZERO` will be considered zeros...
__init__
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def set_parameters( self, direction: tf.Tensor, # pytype: disable=signature-mismatch # overriding-parameter-count-checks transform_params: Dict[str, tf.Tensor], ): """Set the scalarization parameters for the HyperVolumeScalarizer. Args: direction: A `tf.Tensor` representing a direct...
Set the scalarization parameters for the HyperVolumeScalarizer. Args: direction: A `tf.Tensor` representing a directional vector, which will be normalized to have unit length. Coordinates of the normalized direction whose absolute values are less than `HyperVolumeScalarizer.ALMOST_ZERO` ...
set_parameters
python
tensorflow/agents
tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/multi_objective/multi_objective_scalarizer.py
Apache-2.0
def _remove_num_actions_dim_from_spec( observation_spec: types.NestedTensorSpec, ) -> types.NestedTensorSpec: """Removes the extra `num_actions` dimension from the observation spec.""" obs_spec_no_num_actions = { bandit_spec_utils.GLOBAL_FEATURE_KEY: observation_spec[ bandit_spec_utils.GLOBAL_FE...
Removes the extra `num_actions` dimension from the observation spec.
_remove_num_actions_dim_from_spec
python
tensorflow/agents
tf_agents/bandits/networks/global_and_arm_feature_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/global_and_arm_feature_network.py
Apache-2.0
def create_feed_forward_common_tower_network( observation_spec: types.NestedTensorSpec, global_layers: Sequence[int], arm_layers: Sequence[int], common_layers: Sequence[int], output_dim: int = 1, global_preprocessing_combiner: Optional[Callable[..., types.Tensor]] = None, arm_preprocessing_c...
Creates a common tower network with feedforward towers. The network produced by this function can be used either in `GreedyRewardPredictionPolicy`, or `NeuralLinUCBPolicy`. In the former case, the network must have `output_dim=1`, it is going to be an instance of `QNetwork`, and used in the policy as a reward ...
create_feed_forward_common_tower_network
python
tensorflow/agents
tf_agents/bandits/networks/global_and_arm_feature_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/global_and_arm_feature_network.py
Apache-2.0
def create_feed_forward_dot_product_network( observation_spec: types.NestedTensorSpec, global_layers: Sequence[int], arm_layers: Sequence[int], activation_fn: Callable[ [types.Tensor], types.Tensor ] = tf.keras.activations.relu, ) -> types.Network: """Creates a dot product network with fee...
Creates a dot product network with feedforward towers. Args: observation_spec: A nested tensor spec containing the specs for global as well as per-arm observations. global_layers: Iterable of ints. Specifies the layers of the global tower. arm_layers: Iterable of ints. Specifies the layers of the a...
create_feed_forward_dot_product_network
python
tensorflow/agents
tf_agents/bandits/networks/global_and_arm_feature_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/global_and_arm_feature_network.py
Apache-2.0
def __init__( self, observation_spec: types.NestedTensorSpec, global_network: types.Network, arm_network: types.Network, common_network: types.Network, name='GlobalAndArmCommonTowerNetwork', ) -> types.Network: """Initializes an instance of `GlobalAndArmCommonTowerNetwork`. ...
Initializes an instance of `GlobalAndArmCommonTowerNetwork`. The network architecture contains networks for both the global and the arm features. The outputs of these networks are concatenated and led through a third (common) network which in turn outputs reward estimates. Args: observation_spec...
__init__
python
tensorflow/agents
tf_agents/bandits/networks/global_and_arm_feature_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/global_and_arm_feature_network.py
Apache-2.0
def call(self, observation, step_type=None, network_state=()): """Runs the observation through the network.""" global_obs = observation[bandit_spec_utils.GLOBAL_FEATURE_KEY] arm_obs = observation[bandit_spec_utils.PER_ARM_FEATURE_KEY] arm_output, arm_state = self._arm_network( arm_obs, step_typ...
Runs the observation through the network.
call
python
tensorflow/agents
tf_agents/bandits/networks/global_and_arm_feature_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/global_and_arm_feature_network.py
Apache-2.0
def __init__( self, observation_spec: types.NestedTensorSpec, global_network: types.Network, arm_network: types.Network, name: Optional[Text] = 'GlobalAndArmDotProductNetwork', ): """Initializes an instance of `GlobalAndArmDotProductNetwork`. The network architecture contains ne...
Initializes an instance of `GlobalAndArmDotProductNetwork`. The network architecture contains networks for both the global and the arm features. The reward estimates will be the dot product of the global and per arm outputs. Args: observation_spec: The observation spec for the policy that uses t...
__init__
python
tensorflow/agents
tf_agents/bandits/networks/global_and_arm_feature_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/global_and_arm_feature_network.py
Apache-2.0
def __init__( self, input_tensor_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec, preprocessing_layers: Optional[Callable[..., types.Tensor]] = None, preprocessing_combiner: Optional[Callable[..., types.Tensor]] = None, conv_layer_params: Optional[Sequence[Any]] = N...
Creates an instance of `HeteroscedasticQNetwork`. Args: input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the input observations. action_spec: A nest of `tensor_spec.BoundedTensorSpec` representing the actions. preprocessing_layers: (Optional.) A nest of `tf.keras...
__init__
python
tensorflow/agents
tf_agents/bandits/networks/heteroscedastic_q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/heteroscedastic_q_network.py
Apache-2.0
def call(self, observation, step_type=None, network_state=()): """Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_state: A state tu...
Runs the given observation through the network. Args: observation: The observation to provide to the network. step_type: The step type for the given observation. See `StepType` in time_step.py. network_state: A state tuple to pass to the network, mainly used by RNNs. Returns: A...
call
python
tensorflow/agents
tf_agents/bandits/networks/heteroscedastic_q_network.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/heteroscedastic_q_network.py
Apache-2.0
def testVarianceBoundaryConditions(self): """Tests that min/max variance conditions are satisfied.""" batch_size = 3 num_state_dims = 5 min_variance = 1.0 max_variance = 2.0 eps = 0.0001 states = tf.random.uniform([batch_size, num_state_dims]) network = heteroscedastic_q_network.Heterosc...
Tests that min/max variance conditions are satisfied.
testVarianceBoundaryConditions
python
tensorflow/agents
tf_agents/bandits/networks/heteroscedastic_q_network_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/networks/heteroscedastic_q_network_test.py
Apache-2.0
def _distribution(self, time_step, policy_state): """Implementation of `distribution`. Returns a `Categorical` distribution. The returned `Categorical` distribution has (unnormalized) probabilities `exp(inverse_temperature * weights)`. Args: time_step: A `TimeStep` tuple corresponding to `time_s...
Implementation of `distribution`. Returns a `Categorical` distribution. The returned `Categorical` distribution has (unnormalized) probabilities `exp(inverse_temperature * weights)`. Args: time_step: A `TimeStep` tuple corresponding to `time_step_spec()`. policy_state: Unused in `CategoricalPo...
_distribution
python
tensorflow/agents
tf_agents/bandits/policies/categorical_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/categorical_policy.py
Apache-2.0
def testInverseTempUpdate(self, observation_shape, weights, seed): """Test that temperature updates perform as expected as it is increased.""" observation_spec = tensor_spec.TensorSpec( shape=observation_shape, dtype=tf.float32, name='observation_spec' ) time_step_spec = time_step.time_step_spec...
Test that temperature updates perform as expected as it is increased.
testInverseTempUpdate
python
tensorflow/agents
tf_agents/bandits/policies/categorical_policy_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/categorical_policy_test.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, name: Optional[Text] = None, ): """Initialization of the BaseConstraint class. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTenso...
Initialization of the BaseConstraint class. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. name: Python str name of this constraint.
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_network: Optional[types.Network], error_loss_fn: types.LossFn = tf.compat.v1.losses.mean_squared_error, name: Optional[Text] = 'NeuralConstraint', ): """Creates a trainable cons...
Creates a trainable constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide estimates of actio...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def compute_loss( self, observations: types.NestedTensor, actions: types.NestedTensor, rewards: types.Tensor, weights: Optional[types.Float] = None, training: bool = False, ) -> types.Tensor: """Computes loss for training the constraint network. Args: observations: A...
Computes loss for training the constraint network. Args: observations: A batch of observations. actions: A batch of actions. rewards: A batch of rewards. weights: Optional scalar or elementwise (per-batch-entry) importance weights. The output batch loss will be scaled by these weig...
compute_loss
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_network: types.Network, error_loss_fn: types.LossFn = tf.compat.v1.losses.mean_squared_error, comparator_fn: types.ComparatorFn = tf.greater, margin: float = 0.0, baseline...
Creates a trainable relative constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide estimates...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_network: types.Network, error_loss_fn: types.LossFn = tf.compat.v1.losses.mean_squared_error, comparator_fn: types.ComparatorFn = tf.greater, absolute_value: float = 0.0, ...
Creates a trainable absolute constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide estimates...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_network: types.Network, quantile: float = 0.5, comparator_fn: types.ComparatorFn = tf.greater, quantile_value: float = 0.0, name: Text = 'QuantileConstraint', ): """...
Creates a trainable quantile constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide estimates...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, constraint_network: types.Network, quantile: float = 0.5, comparator_fn: types.ComparatorFn = tf.greater, baseline_action_fn: Optional[ Callable[[types.Tensor], types.Tensor] ...
Creates a trainable relative quantile constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide ...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def __init__( self, time_step_spec: types.TimeStep, action_spec: types.BoundedTensorSpec, input_network: Optional[types.Network] = None, name: Optional[Text] = 'InputNetworkConstraint', ): """Creates a constraint using an input network. Args: time_step_spec: A `TimeStep` s...
Creates a constraint using an input network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. input_network: An instance of `tf_agents.network.Network` used to provide estimates of action feasibility. ...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def compute_feasibility_probability( observation: types.NestedTensor, constraints: Iterable[BaseConstraint], batch_size: types.Int, num_actions: int, action_mask: Optional[types.Tensor] = None, ) -> types.Float: """Helper function to compute the action feasibility probability.""" feasibility_pro...
Helper function to compute the action feasibility probability.
compute_feasibility_probability
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def construct_mask_from_multiple_sources( observation: types.NestedTensor, observation_and_action_constraint_splitter: types.Splitter, constraints: Iterable[BaseConstraint], max_num_actions: int, ) -> Optional[types.Tensor]: """Constructs an action mask from multiple sources. The sources include: ...
Constructs an action mask from multiple sources. The sources include: -- The action mask encoded in the observation, -- the `num_actions` feature restricting the number of actions per sample, -- the feasibility mask implied by constraints. The resulting mask disables all actions that are masked out in any o...
construct_mask_from_multiple_sources
python
tensorflow/agents
tf_agents/bandits/policies/constraints.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/constraints.py
Apache-2.0
def get_number_of_trainable_elements(network: types.Network) -> types.Float: """Gets the total # of elements in the network's trainable variables. Args: network: A `types.Network`. Returns: The total number of elements in the network's trainable variables. """ num_elements_list = [] for var in net...
Gets the total # of elements in the network's trainable variables. Args: network: A `types.Network`. Returns: The total number of elements in the network's trainable variables.
get_number_of_trainable_elements
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def _find_action_probabilities( greedy_action_prob: types.Tensor, other_actions_probs: types.Tensor, max_exploration_prob: float, ): """Finds action probabilities satisfying `max_exploration_prob`. Given action probabilities calculated by different values of the gamma parameter, this function attempt...
Finds action probabilities satisfying `max_exploration_prob`. Given action probabilities calculated by different values of the gamma parameter, this function attempts to find action probabilities at a specific gamma value such that non-greedy actions are chosen with at most `max_exploration_prob` probability. ...
_find_action_probabilities
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def _get_number_of_allowed_actions( self, mask: Optional[types.Tensor] ) -> types.Float: """Gets the number of allowed actions. Args: mask: An optional mask represented by a tensor shaped as [batch_size, num_actions]. Returns: The number of allowed actions. It can be either a s...
Gets the number of allowed actions. Args: mask: An optional mask represented by a tensor shaped as [batch_size, num_actions]. Returns: The number of allowed actions. It can be either a scalar (when `mask` is None), or a tensor shaped as [batch_size].
_get_number_of_allowed_actions
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def _compute_gamma( self, mask: Optional[types.Tensor], dtype: tf.DType, batch_size: int ) -> types.Float: """Computes the gamma parameter(s) in the sampling probability. This helper method implements a simple heuristic for computing the the gamma parameter in Step 2 of Algorithm 1 in the paper ...
Computes the gamma parameter(s) in the sampling probability. This helper method implements a simple heuristic for computing the the gamma parameter in Step 2 of Algorithm 1 in the paper https://arxiv.org/pdf/2003.12699.pdf. A higher gamma makes the action sampling distribution concentrate more on the g...
_compute_gamma
python
tensorflow/agents
tf_agents/bandits/policies/falcon_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/falcon_reward_prediction_policy.py
Apache-2.0
def scalarize_objectives( objectives_tensor: tf.Tensor, scalarizer: multi_objective_scalarizer.Scalarizer, ): """Scalarize a rank-3 objectives tensor into a rank-2 tensor. Scalarize an objective values tensor shaped as [batch_size, num_of_objectives, num_of_actions] along the second dimension into a ra...
Scalarize a rank-3 objectives tensor into a rank-2 tensor. Scalarize an objective values tensor shaped as [batch_size, num_of_objectives, num_of_actions] along the second dimension into a rank-2 tensor shaped as [batch_size, num_of_actions] Args: objectives_tensor: An objectives tensor to be scalarized. ...
scalarize_objectives
python
tensorflow/agents
tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
Apache-2.0
def _predict( self, observation: types.NestedSpecTensorOrArray, step_type: types.SpecTensorOrArray, policy_state: Sequence[types.TensorSpec], ) -> Tuple[tf.Tensor, List[types.TensorSpec]]: """Predict the objectives using the policy's objective networks. Args: observation: The ob...
Predict the objectives using the policy's objective networks. Args: observation: The observation whose objectives are to be predicted. step_type: The `tf_agents.trajectories.time_step.StepType` for the input observation. policy_state: The states for the policy's objective networks. R...
_predict
python
tensorflow/agents
tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_multi_objective_neural_policy.py
Apache-2.0
def _action_distribution(self, mask, predicted_rewards): """Returns the action with largest predicted reward.""" # Argmax. batch_size = tf.shape(predicted_rewards)[0] if mask is not None: actions = policy_utilities.masked_argmax( predicted_rewards, mask, output_type=self.action_spec.dtyp...
Returns the action with largest predicted reward.
_action_distribution
python
tensorflow/agents
tf_agents/bandits/policies/greedy_reward_prediction_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/greedy_reward_prediction_policy.py
Apache-2.0
def conjugate_gradient( a_mat: types.Tensor, b_mat: types.Tensor, tol: float = 1e-10 ) -> types.Float: """Returns `X` such that `A * X = B`. Implements the Conjugate Gradient method. https://en.wikipedia.org/wiki/Conjugate_gradient_method Args: a_mat: a Symmetric Positive Definite matrix, represented ...
Returns `X` such that `A * X = B`. Implements the Conjugate Gradient method. https://en.wikipedia.org/wiki/Conjugate_gradient_method Args: a_mat: a Symmetric Positive Definite matrix, represented as a `Tensor` of shape `[n, n]`. b_mat: a `Tensor` of shape `[n, k]`. tol: (float) desired toleran...
conjugate_gradient
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def while_exit_cond(i, x, p, r, rs_old, rs_new): """Exit the loop when n is reached or when the residual becomes small.""" del x # unused del p # unused del r # unused del rs_old # unused i_cond = tf.less(i, n) residual_cond = tf.greater(tf.reduce_max(tf.sqrt(rs_new)), tol) return tf...
Exit the loop when n is reached or when the residual becomes small.
while_exit_cond
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def simplified_woodbury_update( a_inv: types.Float, u: types.Float ) -> types.Float: """Returns `w` such that `inverse(a + u.T.dot(u)) = a_inv + w`. Makes use of the Woodbury matrix identity. See https://en.wikipedia.org/wiki/Woodbury_matrix_identity. **NOTE**: This implementation assumes that a_inv is sy...
Returns `w` such that `inverse(a + u.T.dot(u)) = a_inv + w`. Makes use of the Woodbury matrix identity. See https://en.wikipedia.org/wiki/Woodbury_matrix_identity. **NOTE**: This implementation assumes that a_inv is symmetric. Since it's too expensive to check symmetricity, the function silently outputs a wro...
simplified_woodbury_update
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def update_inverse(a_inv: types.Float, x: types.Float) -> types.Float: """Updates the inverse using the Woodbury matrix identity. Given a matrix `A` of size d-by-d and a matrix `X` of size k-by-d, this function computes the inverse of B = A + X^T X, assuming that the inverse of A is available. Reference: ...
Updates the inverse using the Woodbury matrix identity. Given a matrix `A` of size d-by-d and a matrix `X` of size k-by-d, this function computes the inverse of B = A + X^T X, assuming that the inverse of A is available. Reference: https://en.wikipedia.org/wiki/Woodbury_matrix_identity Args: a_inv: a...
update_inverse
python
tensorflow/agents
tf_agents/bandits/policies/linalg.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linalg.py
Apache-2.0
def _predict_mean_reward( self, theta: tf.Tensor, global_observation: tf.Tensor, arm_observations: Optional[tf.Tensor], ) -> tf.Tensor: """Predicts the mean reward using the theta vectors. Args: theta: A `tf.Tensor` of theta vectors, shaped as [num_models, overall_contex...
Predicts the mean reward using the theta vectors. Args: theta: A `tf.Tensor` of theta vectors, shaped as [num_models, overall_context_dim]. global_observation: A `tf.Tensor` shaped as [batch_size, self._global_context_dim]. arm_observations: An optional `tf.Tensor` shaped as [batc...
_predict_mean_reward
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def _predict_mean_reward_and_variance( self, global_observation: tf.Tensor, arm_observations: Optional[tf.Tensor] ) -> Tuple[tf.Tensor, tf.Tensor]: """Predicts mean reward and variance. Args: global_observation: A `tf.Tensor` shaped as [batch_size, self._global_context_dim]. arm_obs...
Predicts mean reward and variance. Args: global_observation: A `tf.Tensor` shaped as [batch_size, self._global_context_dim]. arm_observations: An optional `tf.Tensor` shaped as [batch_size, self._num_actions, self._arm_context_dim]. Expected to be supplied only when self._accept...
_predict_mean_reward_and_variance
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def _get_current_observation( self, global_observation, arm_observations, arm_index ): """Helper function to construct the observation for a specific arm. This function constructs the observation depending if the policy accepts per-arm features or not. If not, it simply returns the original observa...
Helper function to construct the observation for a specific arm. This function constructs the observation depending if the policy accepts per-arm features or not. If not, it simply returns the original observation. If yes, it concatenates the global observation with the observation of the arm indexed b...
_get_current_observation
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def _split_observation(self, observation): """Splits the observation into global and arm observations.""" if self._accepts_per_arm_features: global_observation = observation[bandit_spec_utils.GLOBAL_FEATURE_KEY] arm_observations = observation[bandit_spec_utils.PER_ARM_FEATURE_KEY] if not arm_o...
Splits the observation into global and arm observations.
_split_observation
python
tensorflow/agents
tf_agents/bandits/policies/linear_bandit_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/linear_bandit_policy.py
Apache-2.0
def pinball_loss( y_true: types.Tensor, y_pred: types.Tensor, weights: types.Float = 1.0, scope: Optional[Text] = None, loss_collection: tf.compat.v1.GraphKeys = tf.compat.v1.GraphKeys.LOSSES, reduction: tf.compat.v1.losses.Reduction = tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS, qu...
Adds a Pinball loss for quantile regression. ``` loss = quantile * (y_true - y_pred) if y_true > y_pred loss = (quantile - 1) * (y_true - y_pred) otherwise ``` See: https://en.wikipedia.org/wiki/Quantile_regression#Quantiles `weights` acts as a coefficient for the loss. If a scalar is provid...
pinball_loss
python
tensorflow/agents
tf_agents/bandits/policies/loss_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/loss_utils.py
Apache-2.0
def __init__( self, mixture_distribution: types.Distribution, policies: Sequence[tf_policy.TFPolicy], name: Optional[Text] = None, ): """Initializes an instance of `MixturePolicy`. Args: mixture_distribution: A `tfd.Categorical` distribution on the domain `[0, len(polici...
Initializes an instance of `MixturePolicy`. Args: mixture_distribution: A `tfd.Categorical` distribution on the domain `[0, len(policies) -1]`. This distribution is used by the mixture policy to choose which policy to listen to. policies: List of TF Policies. These are the policies that...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/mixture_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/mixture_policy.py
Apache-2.0
def _get_predicted_rewards_from_linucb(self, observation_numpy, batch_size): """Runs one step of LinUCB using numpy arrays.""" observation_numpy.reshape([batch_size, self._encoding_dim]) predicted_rewards = [] for k in range(self._num_actions): a_inv = np.linalg.inv(self._a_numpy[k] + np.eye(self...
Runs one step of LinUCB using numpy arrays.
_get_predicted_rewards_from_linucb
python
tensorflow/agents
tf_agents/bandits/policies/neural_linucb_policy_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/neural_linucb_policy_test.py
Apache-2.0
def __init__( self, features: types.Tensor, num_slots: int, logits: types.Tensor, penalty_mixture_coefficient: float = 1.0, ): """Initializes an instance of PenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots: The n...
Initializes an instance of PenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots: The number of slots to fill: this many items will be sampled. logits: Unnormalized log probabilities for the PlackettLuce distribution. Shape is `[num_items]...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def _penalizer_fn( self, logits: types.Float, slots: tf.Tensor, num_slotted: tf.Tensor, ): """Downscores items by their similarity to already selected items. Args: logits: The current logits of all items, shaped as [batch_size, num_items]. slots: A tensor of indice...
Downscores items by their similarity to already selected items. Args: logits: The current logits of all items, shaped as [batch_size, num_items]. slots: A tensor of indices of the selected items, shaped as [batch_size, num_slots]. Only the first `num_slotted` columns correspond to valid...
_penalizer_fn
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def __init__( self, features: types.Tensor, num_slots: int, logits: types.Tensor, penalty_mixture_coefficient: float = 1.0, ): """Initializes an instance of CosinePenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots:...
Initializes an instance of CosinePenalizedPlackettLuce. Args: features: Item features based on which similarity is calculated. num_slots: The number of slots to fill: this many items will be sampled. logits: Unnormalized log probabilities for the PlackettLuce distribution. Shape is `[num_...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def __init__( self, features: types.Tensor, num_slots: int, logits: types.Tensor, penalty_mixture_coefficient: float = 1.0, ): """Initializes an instance of NoPenaltyPlackettLuce. Args: features: Unused for this distribution. num_slots: The number of slots to fill: t...
Initializes an instance of NoPenaltyPlackettLuce. Args: features: Unused for this distribution. num_slots: The number of slots to fill: this many items will be sampled. logits: Unnormalized log probabilities for the PlackettLuce distribution. Shape is `[num_items]`. penalty_mixture_...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def __init__( self, num_items: int, num_slots: int, time_step_spec: types.TimeStep, network: types.Network, item_sampler: tfd.Distribution, penalty_mixture_coefficient: float = 1.0, logits_temperature: float = 1.0, name: Optional[Text] = None, ): """Initialize...
Initializes an instance of `RankingPolicy`. Args: num_items: The number of items the policy can choose from, to be slotted. num_slots: The number of recommendation slots presented to the user, i.e., chosen by the policy. time_step_spec: The time step spec. network: The network that ...
__init__
python
tensorflow/agents
tf_agents/bandits/policies/ranking_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/ranking_policy.py
Apache-2.0
def _action_distribution( self, mask: Optional[types.Tensor], predicted_rewards: types.Tensor ) -> Tuple[tfp.distributions.Distribution, types.Tensor]: """Returns an action distribution based on predicted rewards. Sub-classes are expected to implement this method. Args: mask: A 2-D tensor of...
Returns an action distribution based on predicted rewards. Sub-classes are expected to implement this method. Args: mask: A 2-D tensor of binary masks shaped as [batch_size, num_of_arms]. predicted_rewards: A 2-D tensor of predicted rewards shaped as [batch_size, num_of_arms]. Returns...
_action_distribution
python
tensorflow/agents
tf_agents/bandits/policies/reward_prediction_base_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/reward_prediction_base_policy.py
Apache-2.0
def _maybe_save_chosen_arm_features( self, time_step: ts.TimeStep, action: types.Tensor, step: policy_step.PolicyStep, ) -> policy_step.PolicyStep: """Extracts and saves the chosen arm features in the policy info. If the policy accepts arm features, this method extracts the arm featur...
Extracts and saves the chosen arm features in the policy info. If the policy accepts arm features, this method extracts the arm features from `time_step.observation` corresponding to the input `action` tensor, saves it in the policy info of the input `step` and returns the modified step. Otherwise, the...
_maybe_save_chosen_arm_features
python
tensorflow/agents
tf_agents/bandits/policies/reward_prediction_base_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/reward_prediction_base_policy.py
Apache-2.0
def _action( self, time_step: ts.TimeStep, policy_state: types.NestedTensor, seed: Optional[types.Seed] = None, ) -> policy_step.PolicyStep: """Implementation of `action`. Args: time_step: A `TimeStep` tuple corresponding to `time_step_spec()`. policy_state: A Tensor, or a...
Implementation of `action`. Args: time_step: A `TimeStep` tuple corresponding to `time_step_spec()`. policy_state: A Tensor, or a nested dict, list or tuple of Tensors representing the previous policy_state. seed: Seed to use if action performs sampling (optional). Returns: A `...
_action
python
tensorflow/agents
tf_agents/bandits/policies/reward_prediction_base_policy.py
https://github.com/tensorflow/agents/blob/master/tf_agents/bandits/policies/reward_prediction_base_policy.py
Apache-2.0
def get_distribution_strategy( distribution_strategy="default", num_gpus=0, num_packs=-1 ): """Return a DistributionStrategy for running the model. Args: distribution_strategy: a string specifying which distribution strategy to use. Accepted values are 'off', 'default', 'one_device', and 'mirrored' ...
Return a DistributionStrategy for running the model. Args: distribution_strategy: a string specifying which distribution strategy to use. Accepted values are 'off', 'default', 'one_device', and 'mirrored' case insensitive. 'off' means not to use Distribution Strategy; 'default' means to choose ...
get_distribution_strategy
python
tensorflow/agents
tf_agents/benchmark/distribution_strategy_utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/distribution_strategy_utils.py
Apache-2.0
def benchmark_pong_v0_at_3M(self): """Benchmarks to 3M Env steps. This is below the 12.5M train steps (50M frames) run by the paper to converge. Running 12.5M at the current throughput would take more than a week. 1-2 days is the max duration for a remotely usable test. 3M only confirms we have not...
Benchmarks to 3M Env steps. This is below the 12.5M train steps (50M frames) run by the paper to converge. Running 12.5M at the current throughput would take more than a week. 1-2 days is the max duration for a remotely usable test. 3M only confirms we have not regressed at 3M and does not gurantee con...
benchmark_pong_v0_at_3M
python
tensorflow/agents
tf_agents/benchmark/dqn_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/dqn_benchmark.py
Apache-2.0
def _run( self, strategy, batch_size=64, tf_function=True, replay_buffer_max_length=1000, train_steps=110, log_steps=10, ): """Runs Dqn CartPole environment. Args: strategy: Strategy to use, None is a valid value. batch_size: Total batch size to use for t...
Runs Dqn CartPole environment. Args: strategy: Strategy to use, None is a valid value. batch_size: Total batch size to use for the run. tf_function: If True tf.function is used. replay_buffer_max_length: Max length of the replay buffer. train_steps: Number of steps to run. log_s...
_run
python
tensorflow/agents
tf_agents/benchmark/dqn_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/dqn_benchmark_test.py
Apache-2.0
def run_and_report( self, train_step, strategy, batch_size, train_steps=110, log_steps=10, iterator=None, ): """Run function provided and report results per `tf.test.Benchmark`. Args: train_step: Function to execute on each step. strategy: Strategy to use...
Run function provided and report results per `tf.test.Benchmark`. Args: train_step: Function to execute on each step. strategy: Strategy to use, None is a valid value. batch_size: Total batch_size. train_steps: Number of steps to run. log_steps: How often to log step statistics, e.g. ...
run_and_report
python
tensorflow/agents
tf_agents/benchmark/dqn_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/dqn_benchmark_test.py
Apache-2.0
def __init__(self, output_dir=None): """Initialize class. Args: output_dir: Base directory to store all output for the test. """ # MLCompass sets this value, but PerfZero OSS passes it as an arg. if os.getenv('BENCHMARK_OUTPUT_DIR'): self.output_dir = os.getenv('BENCHMARK_OUTPUT_DIR') ...
Initialize class. Args: output_dir: Base directory to store all output for the test.
__init__
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark.py
Apache-2.0
def setUp(self): """Sets up and resets flags before each test.""" logging.set_verbosity(logging.INFO) if PerfZeroBenchmark.local_flags is None: # Loads flags to get defaults to then override. List cannot be empty. flags.FLAGS(['foo']) saved_flag_values = flagsaver.save_flag_values() ...
Sets up and resets flags before each test.
setUp
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark.py
Apache-2.0
def build_metric( self, name: str, value: Number, min_value: Optional[Number] = None, max_value: Optional[Number] = None, ): """Builds a dictionary representing the metric to record. Args: name: Name of the metric. value: Value of the metric. min_value: Lowest ...
Builds a dictionary representing the metric to record. Args: name: Name of the metric. value: Value of the metric. min_value: Lowest acceptable value. max_value: Highest acceptable value. Returns: Dictionary representing the metric.
build_metric
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark.py
Apache-2.0
def test_build_metric(self): """Tests building metric with only required values.""" bench = perfzero_benchmark.PerfZeroBenchmark() metric_name = 'metric_name' value = 25.93 expected_metric = {'name': metric_name, 'value': value} metric = bench.build_metric(metric_name, value) self.assertEqu...
Tests building metric with only required values.
test_build_metric
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark_test.py
Apache-2.0
def test_build_metric_min_max(self): """Tests building metric with min and max values.""" bench = perfzero_benchmark.PerfZeroBenchmark() metric_name = 'metric_name' value = 25.93 min_value = 0.004 max_value = 59783 expected_metric = { 'name': metric_name, 'value': value, ...
Tests building metric with min and max values.
test_build_metric_min_max
python
tensorflow/agents
tf_agents/benchmark/perfzero_benchmark_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/perfzero_benchmark_test.py
Apache-2.0
def run_benchmark(self, training_env, expected_min, expected_max): """Run benchmark for a given environment. In order to execute ~1M environment steps to match the paper, we run 489 iterations (num_iterations=489) which results in 1,001,472 environment steps. Each iteration results in 320 training step...
Run benchmark for a given environment. In order to execute ~1M environment steps to match the paper, we run 489 iterations (num_iterations=489) which results in 1,001,472 environment steps. Each iteration results in 320 training steps and 2,048 environment steps. Thus 489 * 2,048 = 1,001,472 environmen...
run_benchmark
python
tensorflow/agents
tf_agents/benchmark/ppo_benchmark.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/ppo_benchmark.py
Apache-2.0
def run_test( target_call, num_steps, strategy, batch_size=None, log_steps=100, num_steps_per_batch=1, iterator=None, ): """Run benchmark and return TimeHistory object with stats. Args: target_call: Call to execute for each step. num_steps: Number of steps to run. strategy: ...
Run benchmark and return TimeHistory object with stats. Args: target_call: Call to execute for each step. num_steps: Number of steps to run. strategy: None or tf.distribute.DistibutionStrategy object. batch_size: Total batch size. log_steps: Interval of steps between logging of stats. num_ste...
run_test
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def __init__(self, batch_size, log_steps, num_steps_per_batch=1): """Callback for logging performance. Args: batch_size: Total batch size. log_steps: Interval of steps between logging of stats. num_steps_per_batch: Number of steps per batch. """ self.batch_size = batch_size super(...
Callback for logging performance. Args: batch_size: Total batch size. log_steps: Interval of steps between logging of stats. num_steps_per_batch: Number of steps per batch.
__init__
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def on_batch_end(self): """Records elapse time of the batch and calculates examples per second.""" if self.global_steps % self.log_steps == 0: timestamp = time.time() elapsed_time = timestamp - self.start_time steps_per_second = self.log_steps / elapsed_time examples_per_second = steps_p...
Records elapse time of the batch and calculates examples per second.
on_batch_end
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def get_average_examples_per_second(self, warmup=True): """Returns average examples per second so far. Examples per second are defined by `batch_size` * `num_steps_per_batch` Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average ex...
Returns average examples per second so far. Examples per second are defined by `batch_size` * `num_steps_per_batch` Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average examples per second.
get_average_examples_per_second
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def get_average_step_time(self, warmup=True): """Returns average step time (seconds) so far. Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average step time in seconds. """ if warmup: if len(self.timestamp_log) < 3: ...
Returns average step time (seconds) so far. Args: warmup: If true ignore first set of steps executed as determined by `log_steps`. Returns: Average step time in seconds.
get_average_step_time
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def get_variable_value(agent, name): """Returns the value of the trainable variable with the given name.""" policy_vars = agent.policy.variables() tf_vars = [v for v in policy_vars if name in v.name] assert tf_vars, 'Variable "{}" does not exist. Found: {}'.format( name, policy_vars ) if tf.executing_...
Returns the value of the trainable variable with the given name.
get_variable_value
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def find_event_log( eventlog_dir: str, log_file_pattern: str = 'events.out.tfevents.*' ) -> str: """Find the event log in a given folder. Expects to find a single log file matching the pattern provided. Args: eventlog_dir: Event log directory to search. log_file_pattern: Pattern to use to find the e...
Find the event log in a given folder. Expects to find a single log file matching the pattern provided. Args: eventlog_dir: Event log directory to search. log_file_pattern: Pattern to use to find the event log. Returns: Path to the event log file that was found. Raises: FileNotFoundError: If ...
find_event_log
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def extract_event_log_values( event_file: str, event_tag: str, end_step: Optional[int] = None, start_step: Optional[int] = 0, ) -> Tuple[Dict[int, np.generic], float]: """Extracts the event values for the `event_tag` and total wall time. Args: event_file: Path to the event log. event_tag: E...
Extracts the event values for the `event_tag` and total wall time. Args: event_file: Path to the event log. event_tag: Event to extract from the logs. end_step: If set, processing of the event log ends on this step. start_step: First step to look for in event log, defaults to 0. Returns: Tuple...
extract_event_log_values
python
tensorflow/agents
tf_agents/benchmark/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils.py
Apache-2.0
def test_extract_value(self): """Tests extracting data from all steps in the event log.""" values, walltime = utils.extract_event_log_values( os.path.join(TEST_DATA, 'event_log_3m/events.out.tfevents.1599310762'), 'AverageReturn', ) # Verifies all (3M) records were examined 0-3M = 301. ...
Tests extracting data from all steps in the event log.
test_extract_value
python
tensorflow/agents
tf_agents/benchmark/utils_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils_test.py
Apache-2.0
def test_extract_value_1m_only(self): """Tests extracting data from the first 1M steps in the event log.""" values, walltime = utils.extract_event_log_values( os.path.join(TEST_DATA, 'event_log_3m/events.out.tfevents.1599310762'), 'AverageReturn', 1000000, ) # Verifies only 1M re...
Tests extracting data from the first 1M steps in the event log.
test_extract_value_1m_only
python
tensorflow/agents
tf_agents/benchmark/utils_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils_test.py
Apache-2.0
def test_extract_value_1m_only_start_at_1k(self): """Tests extracting data starting at step 1k.""" values, walltime = utils.extract_event_log_values( os.path.join(TEST_DATA, 'event_log_3m/events.out.tfevents.1599310762'), 'AverageReturn', 1000000, start_step=10000, ) # Ve...
Tests extracting data starting at step 1k.
test_extract_value_1m_only_start_at_1k
python
tensorflow/agents
tf_agents/benchmark/utils_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/benchmark/utils_test.py
Apache-2.0
def __init__( self, temperature, logits=None, probs=None, dtype=tf.int32, validate_args=False, allow_nan_stats=True, name='GumbelSoftmax', ): """Initialize GumbelSoftmax using class log-probabilities. Args: temperature: A `Tensor`, representing the temper...
Initialize GumbelSoftmax using class log-probabilities. Args: temperature: A `Tensor`, representing the temperature of one or more distributions. The temperature values must be positive, and the shape must broadcast against `(logits or probs)[..., 0]`. logits: An N-D `Tensor`, `N >= 1`,...
__init__
python
tensorflow/agents
tf_agents/distributions/gumbel_softmax.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/gumbel_softmax.py
Apache-2.0
def __init__( self, logits, mask, probs=None, dtype=tf.int32, validate_args=False, allow_nan_stats=True, neg_inf=-1e10, name='MaskedCategorical', ): """Initialize Categorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`...
Initialize Categorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a set of Categorical distributions. The first `N - 1` dimensions index into a batch of independent distributions and the last dimension re...
__init__
python
tensorflow/agents
tf_agents/distributions/masked.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/masked.py
Apache-2.0
def testCopy(self): """Confirm we can copy the distribution.""" distribution = masked.MaskedCategorical( [100.0, 100.0, 100.0], mask=[True, False, True] ) copy = distribution.copy() with self.cached_session() as s: probs_np = s.run(copy.probs_parameter()) logits_np = s.run(copy.l...
Confirm we can copy the distribution.
testCopy
python
tensorflow/agents
tf_agents/distributions/masked_test.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/masked_test.py
Apache-2.0
def sample(distribution, reparam=False, **kwargs): """Sample from distribution either with reparameterized sampling or regular sampling. Args: distribution: A `tfp.distributions.Distribution` instance. reparam: Whether to use reparameterized sampling. **kwargs: Parameters to be passed to distribution's...
Sample from distribution either with reparameterized sampling or regular sampling. Args: distribution: A `tfp.distributions.Distribution` instance. reparam: Whether to use reparameterized sampling. **kwargs: Parameters to be passed to distribution's sample() fucntion. Returns:
sample
python
tensorflow/agents
tf_agents/distributions/reparameterized_sampling.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/reparameterized_sampling.py
Apache-2.0
def __init__( self, logits=None, probs=None, dtype=tf.int32, force_probs_to_zero_outside_support=False, validate_args=False, allow_nan_stats=True, shift=None, name="ShiftedCategorical", ): """Initialize Categorical distributions using class log-probabilities. ...
Initialize Categorical distributions using class log-probabilities. Args: logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities of a set of Categorical distributions. The first `N - 1` dimensions index into a batch of independent distributions and the last dimension re...
__init__
python
tensorflow/agents
tf_agents/distributions/shifted_categorical.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/shifted_categorical.py
Apache-2.0
def sample(self, sample_shape=(), seed=None, name="sample", **kwargs): """Generate samples of the specified shape.""" sample = super(ShiftedCategorical, self).sample( sample_shape=sample_shape, seed=seed, name=name, **kwargs ) return sample + self._shift
Generate samples of the specified shape.
sample
python
tensorflow/agents
tf_agents/distributions/shifted_categorical.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/shifted_categorical.py
Apache-2.0
def __init__( self, distribution, spec, validate_args=False, name="SquashToSpecNormal" ): """Constructs a SquashToSpecNormal distribution. Args: distribution: input normal distribution with normalized mean and std dev spec: bounded action spec from which to compute action ranges valid...
Constructs a SquashToSpecNormal distribution. Args: distribution: input normal distribution with normalized mean and std dev spec: bounded action spec from which to compute action ranges validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for val...
__init__
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def kl_divergence(self, other, name="kl_divergence"): """Computes the KL Divergence between two SquashToSpecNormal distributions.""" if not isinstance(other, SquashToSpecNormal): raise ValueError( "other distribution should be of type " "SquashToSpecNormal, got {}".format(other) ...
Computes the KL Divergence between two SquashToSpecNormal distributions.
kl_divergence
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def mode(self, name="mode"): """Compute mean of the SquashToSpecNormal distribution.""" mean = ( self.action_magnitudes * tf.tanh(self.input_distribution.mode()) + self.action_means ) return mean
Compute mean of the SquashToSpecNormal distribution.
mode
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def get_parameters(value: Any) -> Params: """Creates a recursive `Params` object from `value`. The `Params` object can be converted back to an object of type `type(value)` with `make_from_parameters`. For more details, see the docstring of `Params`. Args: value: Typically a user provides `tfp.Distribut...
Creates a recursive `Params` object from `value`. The `Params` object can be converted back to an object of type `type(value)` with `make_from_parameters`. For more details, see the docstring of `Params`. Args: value: Typically a user provides `tfp.Distribution`, `tfp.Bijector`, or `tf.linalg.Linea...
get_parameters
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def make_from_parameters(value: Params) -> Any: """Creates an instance of type `value.type_` with the parameters in `value`. For more details, see the docstrings for `get_parameters` and `Params`. This function may raise strange errors if `value` is a `Params` created from a badly constructed object (one whic...
Creates an instance of type `value.type_` with the parameters in `value`. For more details, see the docstrings for `get_parameters` and `Params`. This function may raise strange errors if `value` is a `Params` created from a badly constructed object (one which does not set `self._parameters` properly). For e...
make_from_parameters
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def merge_to_parameters_from_dict( value: Params, params_dict: Mapping[Text, Any] ) -> Params: """Merges dict matching data of `parameters_to_dict(value)` to a new `Params`. For more details, see the example below and the documentation of `parameters_to_dict`. Example: ```python scale_matrix = tf.Var...
Merges dict matching data of `parameters_to_dict(value)` to a new `Params`. For more details, see the example below and the documentation of `parameters_to_dict`. Example: ```python scale_matrix = tf.Variable([[1.0, 2.0], [-1.0, 0.0]]) d = tfp.distributions.MultivariateNormalDiag( loc=[1.0, 1.0], s...
merge_to_parameters_from_dict
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def __init__( self, event_shape: tf.TensorShape, dtype: tf.DType, parameters: Params ): """Construct a `DistributionSpecV2` from a Distribution's properties. Note that the `parameters` used to create the spec should contain `tf.TypeSpec` objects instead of tensors. We check for this. Args: ...
Construct a `DistributionSpecV2` from a Distribution's properties. Note that the `parameters` used to create the spec should contain `tf.TypeSpec` objects instead of tensors. We check for this. Args: event_shape: The distribution's `event_shape`. This is the shape that `distribution.sample...
__init__
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def assert_specs_are_compatible( network_output_spec: types.NestedTensorSpec, spec: types.NestedTensorSpec, message_prefix: str, ): """Checks that the output of `network.create_variables` matches a spec. Args: network_output_spec: The output of `network.create_variables`. spec: The spec we are ...
Checks that the output of `network.create_variables` matches a spec. Args: network_output_spec: The output of `network.create_variables`. spec: The spec we are matching to. message_prefix: The message prefix for error messages, used when the specs don't match. Raises: ValueError: If the spec...
assert_specs_are_compatible
python
tensorflow/agents
tf_agents/distributions/utils.py
https://github.com/tensorflow/agents/blob/master/tf_agents/distributions/utils.py
Apache-2.0
def __init__( self, env, policy, observers=None, transition_observers=None, info_observers=None, ): """Creates a Driver. Args: env: An environment.Base environment. policy: A policy.Base policy. observers: A list of observers that are updated after the dr...
Creates a Driver. Args: env: An environment.Base environment. policy: A policy.Base policy. observers: A list of observers that are updated after the driver is run. Each observer is a callable(Trajectory) that returns the input. Trajectory.time_step is a stacked batch [N+1, batch_...
__init__
python
tensorflow/agents
tf_agents/drivers/driver.py
https://github.com/tensorflow/agents/blob/master/tf_agents/drivers/driver.py
Apache-2.0