tf_agents.agents.PPOAgent

A PPO Agent.

Inherits From: TFAgent

time_step_spec A TimeStep spec of the expected time_steps.
action_spec A nest of BoundedTensorSpec representing the actions.
optimizer Optimizer to use for the agent, default to using tf.compat.v1.train.AdamOptimizer.
actor_net A network.DistributionNetwork which maps observations to action distributions. Commonly, it is set to actor_distribution_network.ActorDistributionNetwork.
value_net A Network which returns the value prediction for input states, with call(observation, step_type, network_state). Commonly, it is set to value_network.ValueNetwork.
importance_ratio_clipping Epsilon in clipped, surrogate PPO objective. For more detail, see explanation at the top of the doc.
lambda_value Lambda parameter for TD-lambda computation.
discount_factor Discount factor for return computation. Default to 0.99 which is the value used for all environments from (Schulman, 2017).
entropy_regularization Coefficient for entropy regularization loss term. Default to 0.0 because no entropy bonus was used in (Schulman, 2017).
policy_l2_reg Coefficient for L2 regularization of unshared actor_net weights. Default to 0.0 because no L2 regularization was applied on the policy network weights in (Schulman, 2017).
value_function_l2_reg Coefficient for l2 regularization of unshared value function weights. Default to 0.0 because no L2 regularization was applied on the policy network weights in (Schulman, 2017).
shared_vars_l2_reg Coefficient for l2 regularization of weights shared between actor_net and value_net. Default to 0.0 because no L2 regularization was applied on the policy network or value network weights in (Schulman, 2017).
value_pred_loss_coef Multiplier for value prediction loss to balance with policy gradient loss. Default to 0.5, which was used for all environments in the OpenAI baseline implementation. This parameters is irrelevant unless you are sharing part of actor_net and value_net. In that case, you would want to tune this coeeficient, whose value depends on the network architecture of your choice.
num_epochs Number of epochs for computing policy updates. (Schulman,2017) sets this to 10 for Mujoco, 15 for Roboschool and 3 for Atari.
use_gae If True (default False), uses generalized advantage estimation for computing per-timestep advantage. Else, just subtracts value predictions from empirical return.
use_td_lambda_return If True (default False), uses td_lambda_return for training value function; here: td_lambda_return = gae_advantage + value_predictions. use_gae must be set to True as well to enable TD -lambda returns. If use_td_lambda_return is set to True while use_gae is False, the empirical return will be used and a warning will be logged.
normalize_rewards If true, keeps moving variance of rewards and normalizes incoming rewards. While not mentioned directly in (Schulman, 2017), reward normalization was implemented in OpenAI baselines and (Ilyas et al., 2018) pointed out that it largely improves performance. You may refer to Figure 1 of https://arxiv.org/pdf/1811.02553.pdf for a comparison with and without reward scaling.
reward_norm_clipping Value above and below to clip normalized reward. Additional optimization proposed in (Ilyas et al., 2018) set to 5 or 10.
normalize_observations If True, keeps moving mean and variance of observations and normalizes incoming observations. Additional optimization proposed in (Ilyas et al., 2018). If true, and the observation spec is not tf.float32 (such as Atari), please manually convert the observation spec received from the environment to tf.float32 before creating the networks. Otherwise, the normalized input to the network (float32) will have a different dtype as what the network expects, resulting in a mismatch error.

Example usage:

observation_tensor_spec, action_spec, time_step_tensor_spec = (
spec_utils.get_tensor_specs(env))
normalized_observation_tensor_spec = tf.nest.map_structure(
lambda s: tf.TensorSpec(
dtype=tf.float32, shape=s.shape, name=s.name
),
observation_tensor_spec
)

actor_net = actor_distribution_network.ActorDistributionNetwork(
normalized_observation_tensor_spec, ...)
value_net = value_network.ValueNetwork(
normalized_observation_tensor_spec, ...)
# Note that the agent still uses the original time_step_tensor_spec
# from the environment.
agent = ppo_clip_agent.PPOClipAgent(
time_step_tensor_spec, action_spec, actor_net, value_net, ...)
</td>
</tr><tr>
<td>
`log_prob_clipping`
</td>
<td>
+/- value for clipping log probs to prevent inf / NaN
values.  Default: no clipping.
</td>
</tr><tr>
<td>
`kl_cutoff_factor`
</td>
<td>
Only meaningful when `kl_cutoff_coef > 0.0`. A multipler
used for calculating the KL cutoff ( =
`kl_cutoff_factor * adaptive_kl_target`). If policy KL averaged across
the batch changes more than the cutoff, a squared cutoff loss would
be added to the loss function.
</td>
</tr><tr>
<td>
`kl_cutoff_coef`
</td>
<td>
kl_cutoff_coef and kl_cutoff_factor are additional params
if one wants to use a KL cutoff loss term in addition to the adaptive KL
loss term. Default to 0.0 to disable the KL cutoff loss term as this was
not used in the paper.  kl_cutoff_coef is the coefficient to mulitply by
the KL cutoff loss term, before adding to the total loss function.
</td>
</tr><tr>
<td>
`initial_adaptive_kl_beta`
</td>
<td>
Initial value for beta coefficient of adaptive
KL penalty. This initial value is not important in practice because the
algorithm quickly adjusts to it. A common default is 1.0.
</td>
</tr><tr>
<td>
`adaptive_kl_target`
</td>
<td>
Desired KL target for policy updates. If actual KL is
far from this target, adaptive_kl_beta will be updated. You should tune
this for your environment. 0.01 was found to perform well for Mujoco.
</td>
</tr><tr>
<td>
`adaptive_kl_tolerance`
</td>
<td>
A tolerance for adaptive_kl_beta. Mean KL above
`(1 + tol) * adaptive_kl_target`, or below
`(1 - tol) * adaptive_kl_target`,
will cause `adaptive_kl_beta` to be updated. `0.5` was chosen
heuristically in the paper, but the algorithm is not very
sensitive to it.
</td>
</tr><tr>
<td>
`gradient_clipping`
</td>
<td>
Norm length to clip gradients.  Default: no clipping.
</td>
</tr><tr>
<td>
`value_clipping`
</td>
<td>
Difference between new and old value predictions are
clipped to this threshold. Value clipping could be helpful when training
very deep networks. Default: no clipping.
</td>
</tr><tr>
<td>
`check_numerics`
</td>
<td>
If true, adds `tf.debugging.check_numerics` to help find
NaN / Inf values. For debugging only.
</td>
</tr><tr>
<td>
`compute_value_and_advantage_in_train`
</td>
<td>
A bool to indicate where value
prediction and advantage calculation happen.  If True, both happen in
agent.train(). If False, value prediction is computed during data
collection. This argument must be set to `False` if mini batch learning
is enabled.
</td>
</tr><tr>
<td>
`update_normalizers_in_train`
</td>
<td>
A bool to indicate whether normalizers are
updated at the end of the `train` method. Set to `False` if mini batch
learning is enabled, or if `train` is called on multiple iterations of
the same trajectories. In that case, you would need to call the
`update_reward_normalizer` and `update_observation_normalizer` methods
after all iterations of the same trajectory are done. This ensures that
normalizers are updated in the same way as (Schulman, 2017).
</td>
</tr><tr>
<td>
`debug_summaries`
</td>
<td>
A bool to gather debug summaries.
</td>
</tr><tr>
<td>
`summarize_grads_and_vars`
</td>
<td>
If true, gradient summaries will be written.
</td>
</tr><tr>
<td>
`train_step_counter`
</td>
<td>
An optional counter to increment every time the train
op is run.  Defaults to the global_step.
</td>
</tr><tr>
<td>
`name`
</td>
<td>
The name of this agent. All variables in this module will fall under
that name. Defaults to the class name.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2"><h2 class="add-link">Raises</h2></th></tr>

<tr>
<td>
`ValueError`
</td>
<td>
If the actor_net is not a DistributionNetwork or value_net is
not a Network.
</td>
</tr>
</table>





<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2"><h2 class="add-link">Attributes</h2></th></tr>

<tr>
<td>
`action_spec`
</td>
<td>
TensorSpec describing the action produced by the agent.
</td>
</tr><tr>
<td>
`actor_net`
</td>
<td>
Returns actor_net TensorFlow template function.
</td>
</tr><tr>
<td>
`collect_data_spec`
</td>
<td>
Returns a `Trajectory` spec, as expected by the `collect_policy`.
</td>
</tr><tr>
<td>
`collect_policy`
</td>
<td>
Return a policy that can be used to collect data from the environment.
</td>
</tr><tr>
<td>
`data_context`
</td>
<td>

</td>
</tr><tr>
<td>
`debug_summaries`
</td>
<td>

</td>
</tr><tr>
<td>
`policy`
</td>
<td>
Return the current policy held by the agent.
</td>
</tr><tr>
<td>
`summaries_enabled`
</td>
<td>

</td>
</tr><tr>
<td>
`summarize_grads_and_vars`
</td>
<td>

</td>
</tr><tr>
<td>
`time_step_spec`
</td>
<td>
Describes the `TimeStep` tensors expected by the agent.
</td>
</tr><tr>
<td>
`train_argspec`
</td>
<td>
TensorSpec describing extra supported `kwargs` to `train()`.
</td>
</tr><tr>
<td>
`train_sequence_length`
</td>
<td>
The number of time steps needed in experience tensors passed to `train`.

Train requires experience to be a `Trajectory` containing tensors shaped
`[B, T, ...]`.  This argument describes the value of `T` required.

For example, for non-RNN DQN training, `T=2` because DQN requires single
transitions.

If this value is `None`, then `train` can handle an unknown `T` (it can be
determined at runtime from the data).  Most RNN-based agents fall into
this category.
</td>
</tr><tr>
<td>
`train_step_counter`
</td>
<td>

</td>
</tr><tr>
<td>
`training_data_spec`
</td>
<td>
Returns a trajectory spec, as expected by the train() function.
</td>
</tr><tr>
<td>
`validate_args`
</td>
<td>
Whether `train` & `preprocess_sequence` validate input & output args.
</td>
</tr>
</table>



## Methods

<h3 id="adaptive_kl_loss"><code>adaptive_kl_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L1290-L1306">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>adaptive_kl_loss(
    kl_divergence: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    debug_summaries: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>




<h3 id="compute_advantages"><code>compute_advantages</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L410-L448">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>compute_advantages(
    rewards: <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>,
    returns: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    discounts: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    value_preds: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>

Compute advantages, optionally using GAE.

Based on baselines ppo1 implementation. Removes final timestep, as it needs
to use this timestep for next-step value prediction for TD error
computation.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`rewards`
</td>
<td>
Tensor of per-timestep rewards.
</td>
</tr><tr>
<td>
`returns`
</td>
<td>
Tensor of per-timestep returns.
</td>
</tr><tr>
<td>
`discounts`
</td>
<td>
Tensor of per-timestep discounts. Zero for terminal timesteps.
</td>
</tr><tr>
<td>
`value_preds`
</td>
<td>
Cached value estimates from the data-collection policy.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>

<tr>
<td>
`advantages`
</td>
<td>
Tensor of length (len(rewards) - 1), because the final
timestep is just used for next-step value prediction.
</td>
</tr>
</table>



<h3 id="compute_return_and_advantage"><code>compute_return_and_advantage</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L555-L642">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>compute_return_and_advantage(
    next_time_steps: <a href="../../tf_agents/trajectories/time_step/TimeStep"><code>tf_agents.trajectories.time_step.TimeStep</code></a>,
    value_preds: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
) -> Tuple[<a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>, <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>]
</code></pre>

Compute the Monte Carlo return and advantage.

Normalazation will be applied to the computed returns and advantages if
it's enabled.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`next_time_steps`
</td>
<td>
batched tensor of TimeStep tuples after action is taken.
</td>
</tr><tr>
<td>
`value_preds`
</td>
<td>
Batched value prediction tensor. Should have one more entry
in time index than time_steps, with the final value corresponding to the
value prediction of the final state.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
tuple of (return, normalized_advantage), both are batched tensors.
</td>
</tr>

</table>



<h3 id="entropy_regularization_loss"><code>entropy_regularization_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L992-L1023">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>entropy_regularization_loss(
    time_steps: <a href="../../tf_agents/trajectories/time_step/TimeStep"><code>tf_agents.trajectories.time_step.TimeStep</code></a>,
    current_policy_distribution: <a href="../../tf_agents/typing/types/NestedDistribution"><code>tf_agents.typing.types.NestedDistribution</code></a>,
    weights: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    debug_summaries: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>

Create regularization loss tensor based on agent parameters.


<h3 id="get_loss"><code>get_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L450-L553">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>get_loss(
    time_steps: <a href="../../tf_agents/trajectories/time_step/TimeStep"><code>tf_agents.trajectories.time_step.TimeStep</code></a>,
    actions: <a href="../../tf_agents/typing/types/NestedTensorSpec"><code>tf_agents.typing.types.NestedTensorSpec</code></a>,
    act_log_probs: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    returns: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    normalized_advantages: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    action_distribution_parameters: <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>,
    weights: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    train_step: tf.Variable,
    debug_summaries: bool,
    old_value_predictions: Optional[types.Tensor] = None,
    training: bool = False
) -> <a href="../../tf_agents/agents/tf_agent/LossInfo"><code>tf_agents.agents.tf_agent.LossInfo</code></a>
</code></pre>

Compute the loss and create optimization op for one training epoch.

All tensors should have a single batch dimension.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`time_steps`
</td>
<td>
A minibatch of TimeStep tuples.
</td>
</tr><tr>
<td>
`actions`
</td>
<td>
A minibatch of actions.
</td>
</tr><tr>
<td>
`act_log_probs`
</td>
<td>
A minibatch of action probabilities (probability under the
sampling policy).
</td>
</tr><tr>
<td>
`returns`
</td>
<td>
A minibatch of per-timestep returns.
</td>
</tr><tr>
<td>
`normalized_advantages`
</td>
<td>
A minibatch of normalized per-timestep advantages.
</td>
</tr><tr>
<td>
`action_distribution_parameters`
</td>
<td>
Parameters of data-collecting action
distribution. Needed for KL computation.
</td>
</tr><tr>
<td>
`weights`
</td>
<td>
Optional scalar or element-wise (per-batch-entry) importance
weights.  Includes a mask for invalid timesteps.
</td>
</tr><tr>
<td>
`train_step`
</td>
<td>
A train_step variable to increment for each train step.
Typically the global_step.
</td>
</tr><tr>
<td>
`debug_summaries`
</td>
<td>
True if debug summaries should be created.
</td>
</tr><tr>
<td>
`old_value_predictions`
</td>
<td>
(Optional) The saved value predictions, used
for calculating the value estimation loss when value clipping is
performed.
</td>
</tr><tr>
<td>
`training`
</td>
<td>
Whether this loss is being used for training.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
A tf_agent.LossInfo named tuple with the total_loss and all intermediate
losses in the extra field contained in a PPOLossInfo named tuple.
</td>
</tr>

</table>



<h3 id="initialize"><code>initialize</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/tf_agent.py#L323-L340">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>initialize() -> Optional[tf.Operation]
</code></pre>

Initializes the agent.


<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
An operation that can be used to initialize the agent.
</td>
</tr>

</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Raises</th></tr>

<tr>
<td>
`RuntimeError`
</td>
<td>
If the class was not initialized properly (`super.__init__`
was not called).
</td>
</tr>
</table>



<h3 id="kl_cutoff_loss"><code>kl_cutoff_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L1266-L1288">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>kl_cutoff_loss(
    kl_divergence: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    debug_summaries: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>




<h3 id="kl_penalty_loss"><code>kl_penalty_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L1323-L1365">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>kl_penalty_loss(
    time_steps: <a href="../../tf_agents/trajectories/time_step/TimeStep"><code>tf_agents.trajectories.time_step.TimeStep</code></a>,
    action_distribution_parameters: <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>,
    current_policy_distribution: <a href="../../tf_agents/typing/types/NestedDistribution"><code>tf_agents.typing.types.NestedDistribution</code></a>,
    weights: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    debug_summaries: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>

Compute a loss that penalizes policy steps with high KL.

Based on KL divergence from old (data-collection) policy to new (updated)
policy.

All tensors should have a single batch dimension.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`time_steps`
</td>
<td>
TimeStep tuples with observations for each timestep. Used for
computing new action distributions.
</td>
</tr><tr>
<td>
`action_distribution_parameters`
</td>
<td>
Action distribution params of the data
collection policy, used for reconstruction old action distributions.
</td>
</tr><tr>
<td>
`current_policy_distribution`
</td>
<td>
The policy distribution, evaluated on all
time_steps.
</td>
</tr><tr>
<td>
`weights`
</td>
<td>
Optional scalar or element-wise (per-batch-entry) importance
weights.  Inlcudes a mask for invalid timesteps.
</td>
</tr><tr>
<td>
`debug_summaries`
</td>
<td>
True if debug summaries should be created.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>

<tr>
<td>
`kl_penalty_loss`
</td>
<td>
The sum of a squared penalty for KL over a constant
threshold, plus an adaptive penalty that encourages updates toward a
target KL divergence.
</td>
</tr>
</table>



<h3 id="l2_regularization_loss"><code>l2_regularization_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L941-L990">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>l2_regularization_loss(
    debug_summaries: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>




<h3 id="policy_gradient_loss"><code>policy_gradient_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L1120-L1264">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>policy_gradient_loss(
    time_steps: <a href="../../tf_agents/trajectories/time_step/TimeStep"><code>tf_agents.trajectories.time_step.TimeStep</code></a>,
    actions: <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>,
    sample_action_log_probs: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    advantages: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    current_policy_distribution: <a href="../../tf_agents/typing/types/NestedDistribution"><code>tf_agents.typing.types.NestedDistribution</code></a>,
    weights: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    debug_summaries: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>

Create tensor for policy gradient loss.

All tensors should have a single batch dimension.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`time_steps`
</td>
<td>
TimeSteps with observations for each timestep.
</td>
</tr><tr>
<td>
`actions`
</td>
<td>
Tensor of actions for timesteps, aligned on index.
</td>
</tr><tr>
<td>
`sample_action_log_probs`
</td>
<td>
Tensor of sample probability of each action.
</td>
</tr><tr>
<td>
`advantages`
</td>
<td>
Tensor of advantage estimate for each timestep, aligned on
index. Works better when advantage estimates are normalized.
</td>
</tr><tr>
<td>
`current_policy_distribution`
</td>
<td>
The policy distribution, evaluated on all
time_steps.
</td>
</tr><tr>
<td>
`weights`
</td>
<td>
Optional scalar or element-wise (per-batch-entry) importance
weights.  Includes a mask for invalid timesteps.
</td>
</tr><tr>
<td>
`debug_summaries`
</td>
<td>
True if debug summaries should be created.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>

<tr>
<td>
`policy_gradient_loss`
</td>
<td>
A tensor that will contain policy gradient loss for
the on-policy experience.
</td>
</tr>
</table>



<h3 id="preprocess_sequence"><code>preprocess_sequence</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/tf_agent.py#L342-L379">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>preprocess_sequence(
    experience: <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>
) -> <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>
</code></pre>

Defines preprocess_sequence function to be fed into replay buffers.

This defines how we preprocess the collected data before training.
Defaults to pass through for most agents.
Structure of `experience` must match that of `self.collect_data_spec`.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`experience`
</td>
<td>
a `Trajectory` shaped [batch, time, ...] or [time, ...] which
represents the collected experience data.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
A post processed `Trajectory` with the same shape as the input.
</td>
</tr>

</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Raises</th></tr>

<tr>
<td>
`TypeError`
</td>
<td>
If experience does not match `self.collect_data_spec` structure
types.
</td>
</tr>
</table>



<h3 id="train"><code>train</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/tf_agent.py#L450-L514">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>train(
    experience: <a href="../../tf_agents/typing/types/NestedTensor"><code>tf_agents.typing.types.NestedTensor</code></a>,
    weights: Optional[types.Tensor] = None,
    **kwargs
) -> <a href="../../tf_agents/agents/tf_agent/LossInfo"><code>tf_agents.agents.tf_agent.LossInfo</code></a>
</code></pre>

Trains the agent.


<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`experience`
</td>
<td>
A batch of experience data in the form of a `Trajectory`. The
structure of `experience` must match that of `self.training_data_spec`.
All tensors in `experience` must be shaped `[batch, time, ...]` where
`time` must be equal to `self.train_step_length` if that
property is not `None`.
</td>
</tr><tr>
<td>
`weights`
</td>
<td>
(optional).  A `Tensor`, either `0-D` or shaped `[batch]`,
containing weights to be used when calculating the total train loss.
Weights are typically multiplied elementwise against the per-batch loss,
but the implementation is up to the Agent.
</td>
</tr><tr>
<td>
`**kwargs`
</td>
<td>
Any additional data as declared by `self.train_argspec`.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>
<tr class="alt">
<td colspan="2">
A `LossInfo` loss tuple containing loss and info tensors.

- In eager mode, the loss values are first calculated, then a train step
is performed before they are returned.
- In graph mode, executing any or all of the loss tensors
will first calculate the loss value(s), then perform a train step,
and return the pre-train-step `LossInfo`.
</td>
</tr>

</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Raises</th></tr>

<tr>
<td>
`TypeError`
</td>
<td>
If `validate_args is True` and: Experience is not type
`Trajectory`; or if `experience`  does not match
`self.training_data_spec` structure types.
</td>
</tr><tr>
<td>
`ValueError`
</td>
<td>
If `validate_args is True` and: Experience tensors' time axes
are not compatible with `self.train_sequence_length`; or if experience
does not match `self.training_data_spec` structure.
</td>
</tr><tr>
<td>
`ValueError`
</td>
<td>
If `validate_args is True` and the user does not pass
`**kwargs` matching `self.train_argspec`.
</td>
</tr><tr>
<td>
`RuntimeError`
</td>
<td>
If the class was not initialized properly (`super.__init__`
was not called).
</td>
</tr>
</table>



<h3 id="update_adaptive_kl_beta"><code>update_adaptive_kl_beta</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L1367-L1415">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>update_adaptive_kl_beta(
    kl_divergence: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
) -> Optional[tf.Operation]
</code></pre>

Create update op for adaptive KL penalty coefficient.


<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`kl_divergence`
</td>
<td>
KL divergence of old policy to new policy for all
timesteps.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>

<tr>
<td>
`update_op`
</td>
<td>
An op which runs the update for the adaptive kl penalty term.
</td>
</tr>
</table>



<h3 id="update_observation_normalizer"><code>update_observation_normalizer</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L932-L935">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>update_observation_normalizer(
    batched_observations
)
</code></pre>




<h3 id="update_reward_normalizer"><code>update_reward_normalizer</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L937-L939">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>update_reward_normalizer(
    batched_rewards
)
</code></pre>




<h3 id="value_estimation_loss"><code>value_estimation_loss</code></h3>

<a target="_blank" href="https://github.com/tensorflow/agents/blob/v0.6.0/tf_agents/agents/ppo/ppo_agent.py#L1025-L1118">View source</a>

<pre class="devsite-click-to-copy prettyprint lang-py tfo-signature-link">
<code>value_estimation_loss(
    time_steps: <a href="../../tf_agents/trajectories/time_step/TimeStep"><code>tf_agents.trajectories.time_step.TimeStep</code></a>,
    returns: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    weights: <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>,
    old_value_predictions: Optional[types.Tensor] = None,
    debug_summaries: bool = False,
    training: bool = False
) -> <a href="../../tf_agents/typing/types/Tensor"><code>tf_agents.typing.types.Tensor</code></a>
</code></pre>

Computes the value estimation loss for actor-critic training.

All tensors should have a single batch dimension.

<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Args</th></tr>

<tr>
<td>
`time_steps`
</td>
<td>
A batch of timesteps.
</td>
</tr><tr>
<td>
`returns`
</td>
<td>
Per-timestep returns for value function to predict. (Should come
from TD-lambda computation.)
</td>
</tr><tr>
<td>
`weights`
</td>
<td>
Optional scalar or element-wise (per-batch-entry) importance
weights.  Includes a mask for invalid timesteps.
</td>
</tr><tr>
<td>
`old_value_predictions`
</td>
<td>
(Optional) The saved value predictions from
policy_info, required when self._value_clipping > 0.
</td>
</tr><tr>
<td>
`debug_summaries`
</td>
<td>
True if debug summaries should be created.
</td>
</tr><tr>
<td>
`training`
</td>
<td>
Whether this loss is going to be used for training.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Returns</th></tr>

<tr>
<td>
`value_estimation_loss`
</td>
<td>
A scalar value_estimation_loss loss.
</td>
</tr>
</table>



<!-- Tabular view -->
 <table class="responsive fixed orange">
<colgroup><col width="214px"><col></colgroup>
<tr><th colspan="2">Raises</th></tr>

<tr>
<td>
`ValueError`
</td>
<td>
If old_value_predictions was not passed in, but value clipping
was performed.
</td>
</tr>
</table>