2019-05-20 16:46:05 -07:00
|
|
|
"""Adapted from VTraceTFPolicy to use the PPO surrogate loss.
|
2019-03-29 12:44:23 -07:00
|
|
|
|
2019-05-20 16:46:05 -07:00
|
|
|
Keep in sync with changes to VTraceTFPolicy."""
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
import logging
|
|
|
|
import gym
|
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
from ray.rllib.agents.a3c.a3c_torch_policy import apply_grad_clipping
|
|
|
|
import ray.rllib.agents.impala.vtrace_torch as vtrace
|
|
|
|
from ray.rllib.agents.impala.vtrace_torch_policy import make_time_major, \
|
|
|
|
choose_optimizer
|
|
|
|
from ray.rllib.agents.ppo.appo_tf_policy import build_appo_model, \
|
|
|
|
postprocess_trajectory
|
|
|
|
from ray.rllib.agents.ppo.ppo_torch_policy import ValueNetworkMixin, \
|
|
|
|
KLCoeffMixin
|
2019-05-18 00:23:11 -07:00
|
|
|
from ray.rllib.evaluation.postprocessing import Postprocessing
|
2020-04-23 09:11:12 +02:00
|
|
|
from ray.rllib.models.torch.torch_action_dist import TorchCategorical
|
2019-05-20 16:46:05 -07:00
|
|
|
from ray.rllib.policy.sample_batch import SampleBatch
|
2020-04-23 09:11:12 +02:00
|
|
|
from ray.rllib.policy.torch_policy import LearningRateSchedule
|
|
|
|
from ray.rllib.policy.torch_policy_template import build_torch_policy
|
2019-07-29 15:02:32 -07:00
|
|
|
from ray.rllib.utils.explained_variance import explained_variance
|
2020-04-23 09:11:12 +02:00
|
|
|
from ray.rllib.utils.framework import try_import_torch
|
|
|
|
from ray.rllib.utils.torch_ops import global_norm, sequence_mask
|
2019-05-10 20:36:18 -07:00
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
torch, nn = try_import_torch()
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2019-03-29 12:44:23 -07:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class PPOSurrogateLoss:
|
2019-03-29 12:44:23 -07:00
|
|
|
"""Loss used when V-trace is disabled.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
prev_actions_logp: A float32 tensor of shape [T, B].
|
|
|
|
actions_logp: A float32 tensor of shape [T, B].
|
|
|
|
action_kl: A float32 tensor of shape [T, B].
|
|
|
|
actions_entropy: A float32 tensor of shape [T, B].
|
|
|
|
values: A float32 tensor of shape [T, B].
|
|
|
|
valid_mask: A bool tensor of valid RNN input elements (#2992).
|
|
|
|
advantages: A float32 tensor of shape [T, B].
|
|
|
|
value_targets: A float32 tensor of shape [T, B].
|
2019-07-29 15:02:32 -07:00
|
|
|
vf_loss_coeff (float): Coefficient of the value function loss.
|
|
|
|
entropy_coeff (float): Coefficient of the entropy regularizer.
|
|
|
|
clip_param (float): Clip parameter.
|
|
|
|
cur_kl_coeff (float): Coefficient for KL loss.
|
|
|
|
use_kl_loss (bool): If true, use KL loss.
|
2019-03-29 12:44:23 -07:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self,
|
|
|
|
prev_actions_logp,
|
|
|
|
actions_logp,
|
|
|
|
action_kl,
|
|
|
|
actions_entropy,
|
|
|
|
values,
|
|
|
|
valid_mask,
|
|
|
|
advantages,
|
|
|
|
value_targets,
|
|
|
|
vf_loss_coeff=0.5,
|
|
|
|
entropy_coeff=0.01,
|
2019-07-29 15:02:32 -07:00
|
|
|
clip_param=0.3,
|
|
|
|
cur_kl_coeff=None,
|
|
|
|
use_kl_loss=False):
|
2019-03-29 12:44:23 -07:00
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
if valid_mask is not None:
|
|
|
|
num_valid = torch.sum(valid_mask)
|
|
|
|
|
|
|
|
def reduce_mean_valid(t):
|
|
|
|
return torch.sum(t * valid_mask) / num_valid
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
def reduce_mean_valid(t):
|
|
|
|
return torch.mean(t)
|
2019-03-29 12:44:23 -07:00
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
logp_ratio = torch.exp(actions_logp - prev_actions_logp)
|
|
|
|
|
|
|
|
surrogate_loss = torch.min(
|
2019-03-29 12:44:23 -07:00
|
|
|
advantages * logp_ratio,
|
2020-04-23 09:11:12 +02:00
|
|
|
advantages * torch.clamp(logp_ratio, 1 - clip_param,
|
|
|
|
1 + clip_param))
|
2019-03-29 12:44:23 -07:00
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
self.mean_kl = reduce_mean_valid(action_kl)
|
|
|
|
self.pi_loss = -reduce_mean_valid(surrogate_loss)
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
# The baseline loss
|
2019-07-29 15:02:32 -07:00
|
|
|
delta = values - value_targets
|
2019-03-29 12:44:23 -07:00
|
|
|
self.value_targets = value_targets
|
2020-04-23 09:11:12 +02:00
|
|
|
self.vf_loss = 0.5 * reduce_mean_valid(torch.pow(delta, 2.0))
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
# The entropy loss
|
2019-07-29 15:02:32 -07:00
|
|
|
self.entropy = reduce_mean_valid(actions_entropy)
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
# The summed weighted loss
|
|
|
|
self.total_loss = (self.pi_loss + self.vf_loss * vf_loss_coeff -
|
|
|
|
self.entropy * entropy_coeff)
|
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
# Optional additional KL Loss
|
|
|
|
if use_kl_loss:
|
|
|
|
self.total_loss += cur_kl_coeff * self.mean_kl
|
|
|
|
|
2019-03-29 12:44:23 -07:00
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class VTraceSurrogateLoss:
|
2019-03-29 12:44:23 -07:00
|
|
|
def __init__(self,
|
|
|
|
actions,
|
|
|
|
prev_actions_logp,
|
|
|
|
actions_logp,
|
2019-07-29 15:02:32 -07:00
|
|
|
old_policy_actions_logp,
|
2019-03-29 12:44:23 -07:00
|
|
|
action_kl,
|
|
|
|
actions_entropy,
|
|
|
|
dones,
|
|
|
|
behaviour_logits,
|
2019-07-29 15:02:32 -07:00
|
|
|
old_policy_behaviour_logits,
|
2019-03-29 12:44:23 -07:00
|
|
|
target_logits,
|
|
|
|
discount,
|
|
|
|
rewards,
|
|
|
|
values,
|
|
|
|
bootstrap_value,
|
2019-05-16 22:05:07 -07:00
|
|
|
dist_class,
|
2019-08-10 14:05:12 -07:00
|
|
|
model,
|
2019-03-29 12:44:23 -07:00
|
|
|
valid_mask,
|
|
|
|
vf_loss_coeff=0.5,
|
|
|
|
entropy_coeff=0.01,
|
|
|
|
clip_rho_threshold=1.0,
|
|
|
|
clip_pg_rho_threshold=1.0,
|
2019-07-29 15:02:32 -07:00
|
|
|
clip_param=0.3,
|
|
|
|
cur_kl_coeff=None,
|
|
|
|
use_kl_loss=False):
|
|
|
|
"""APPO Loss, with IS modifications and V-trace for Advantage Estimation
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
VTraceLoss takes tensors of shape [T, B, ...], where `B` is the
|
|
|
|
batch_size. The reason we need to know `B` is for V-trace to properly
|
|
|
|
handle episode cut boundaries.
|
|
|
|
|
|
|
|
Arguments:
|
2019-05-16 22:05:07 -07:00
|
|
|
actions: An int|float32 tensor of shape [T, B, logit_dim].
|
2019-03-29 12:44:23 -07:00
|
|
|
prev_actions_logp: A float32 tensor of shape [T, B].
|
|
|
|
actions_logp: A float32 tensor of shape [T, B].
|
2019-07-29 15:02:32 -07:00
|
|
|
old_policy_actions_logp: A float32 tensor of shape [T, B].
|
2019-03-29 12:44:23 -07:00
|
|
|
action_kl: A float32 tensor of shape [T, B].
|
|
|
|
actions_entropy: A float32 tensor of shape [T, B].
|
|
|
|
dones: A bool tensor of shape [T, B].
|
2019-05-16 22:05:07 -07:00
|
|
|
behaviour_logits: A float32 tensor of shape [T, B, logit_dim].
|
2019-07-29 15:02:32 -07:00
|
|
|
old_policy_behaviour_logits: A float32 tensor of shape
|
|
|
|
[T, B, logit_dim].
|
2019-05-16 22:05:07 -07:00
|
|
|
target_logits: A float32 tensor of shape [T, B, logit_dim].
|
2019-03-29 12:44:23 -07:00
|
|
|
discount: A float32 scalar.
|
|
|
|
rewards: A float32 tensor of shape [T, B].
|
|
|
|
values: A float32 tensor of shape [T, B].
|
|
|
|
bootstrap_value: A float32 tensor of shape [B].
|
2019-05-16 22:05:07 -07:00
|
|
|
dist_class: action distribution class for logits.
|
2019-08-10 14:05:12 -07:00
|
|
|
model: backing ModelV2 instance
|
2019-03-29 12:44:23 -07:00
|
|
|
valid_mask: A bool tensor of valid RNN input elements (#2992).
|
2019-07-29 15:02:32 -07:00
|
|
|
vf_loss_coeff (float): Coefficient of the value function loss.
|
|
|
|
entropy_coeff (float): Coefficient of the entropy regularizer.
|
|
|
|
clip_param (float): Clip parameter.
|
|
|
|
cur_kl_coeff (float): Coefficient for KL loss.
|
|
|
|
use_kl_loss (bool): If true, use KL loss.
|
2019-03-29 12:44:23 -07:00
|
|
|
"""
|
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
if valid_mask is not None:
|
|
|
|
num_valid = torch.sum(valid_mask)
|
|
|
|
|
|
|
|
def reduce_mean_valid(t):
|
|
|
|
return torch.sum(t * valid_mask) / num_valid
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
def reduce_mean_valid(t):
|
|
|
|
return torch.mean(t)
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2019-03-29 12:44:23 -07:00
|
|
|
# Compute vtrace on the CPU for better perf.
|
2020-04-23 09:11:12 +02:00
|
|
|
self.vtrace_returns = vtrace.multi_from_logits(
|
|
|
|
behaviour_policy_logits=behaviour_logits,
|
|
|
|
target_policy_logits=old_policy_behaviour_logits,
|
|
|
|
actions=torch.unbind(actions, dim=2),
|
|
|
|
discounts=(1.0 - dones.float()) * discount,
|
|
|
|
rewards=rewards,
|
|
|
|
values=values,
|
|
|
|
bootstrap_value=bootstrap_value,
|
|
|
|
dist_class=dist_class,
|
|
|
|
model=model,
|
|
|
|
clip_rho_threshold=clip_rho_threshold,
|
|
|
|
clip_pg_rho_threshold=clip_pg_rho_threshold)
|
|
|
|
|
|
|
|
self.is_ratio = torch.clamp(
|
|
|
|
torch.exp(prev_actions_logp - old_policy_actions_logp), 0.0, 2.0)
|
|
|
|
logp_ratio = self.is_ratio * torch.exp(actions_logp -
|
|
|
|
prev_actions_logp)
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
advantages = self.vtrace_returns.pg_advantages
|
2020-04-23 09:11:12 +02:00
|
|
|
surrogate_loss = torch.min(
|
2019-03-29 12:44:23 -07:00
|
|
|
advantages * logp_ratio,
|
2020-04-23 09:11:12 +02:00
|
|
|
advantages * torch.clamp(logp_ratio, 1 - clip_param,
|
|
|
|
1 + clip_param))
|
2019-03-29 12:44:23 -07:00
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
self.mean_kl = reduce_mean_valid(action_kl)
|
|
|
|
self.pi_loss = -reduce_mean_valid(surrogate_loss)
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
# The baseline loss
|
2019-07-29 15:02:32 -07:00
|
|
|
delta = values - self.vtrace_returns.vs
|
2019-03-29 12:44:23 -07:00
|
|
|
self.value_targets = self.vtrace_returns.vs
|
2020-04-23 09:11:12 +02:00
|
|
|
self.vf_loss = 0.5 * reduce_mean_valid(torch.pow(delta, 2.0))
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
# The entropy loss
|
2019-07-29 15:02:32 -07:00
|
|
|
self.entropy = reduce_mean_valid(actions_entropy)
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
# The summed weighted loss
|
|
|
|
self.total_loss = (self.pi_loss + self.vf_loss * vf_loss_coeff -
|
|
|
|
self.entropy * entropy_coeff)
|
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
# Optional additional KL Loss
|
|
|
|
if use_kl_loss:
|
|
|
|
self.total_loss += cur_kl_coeff * self.mean_kl
|
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def build_appo_surrogate_loss(policy, model, dist_class, train_batch):
|
|
|
|
model_out, _ = model.from_batch(train_batch)
|
|
|
|
action_dist = dist_class(model_out, model)
|
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
if isinstance(policy.action_space, gym.spaces.Discrete):
|
|
|
|
is_multidiscrete = False
|
|
|
|
output_hidden_shape = [policy.action_space.n]
|
|
|
|
elif isinstance(policy.action_space,
|
|
|
|
gym.spaces.multi_discrete.MultiDiscrete):
|
|
|
|
is_multidiscrete = True
|
|
|
|
output_hidden_shape = policy.action_space.nvec.astype(np.int32)
|
|
|
|
else:
|
|
|
|
is_multidiscrete = False
|
|
|
|
output_hidden_shape = 1
|
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
def _make_time_major(*args, **kw):
|
|
|
|
return make_time_major(policy, train_batch.get("seq_lens"), *args,
|
|
|
|
**kw)
|
2019-05-18 00:23:11 -07:00
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
actions = train_batch[SampleBatch.ACTIONS]
|
|
|
|
dones = train_batch[SampleBatch.DONES]
|
|
|
|
rewards = train_batch[SampleBatch.REWARDS]
|
2020-04-01 09:43:21 +02:00
|
|
|
behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS]
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
target_model_out, _ = policy.target_model.from_batch(train_batch)
|
2020-04-23 09:11:12 +02:00
|
|
|
old_policy_behaviour_logits = target_model_out.detach()
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2020-05-27 16:19:13 +02:00
|
|
|
if isinstance(output_hidden_shape, (list, tuple, np.ndarray)):
|
|
|
|
unpacked_behaviour_logits = torch.split(
|
|
|
|
behaviour_logits, list(output_hidden_shape), dim=1)
|
|
|
|
unpacked_old_policy_behaviour_logits = torch.split(
|
|
|
|
old_policy_behaviour_logits, list(output_hidden_shape), dim=1)
|
|
|
|
unpacked_outputs = torch.split(
|
|
|
|
model_out, list(output_hidden_shape), dim=1)
|
|
|
|
else:
|
|
|
|
unpacked_behaviour_logits = torch.chunk(
|
|
|
|
behaviour_logits, output_hidden_shape, dim=1)
|
|
|
|
unpacked_old_policy_behaviour_logits = torch.chunk(
|
|
|
|
old_policy_behaviour_logits, output_hidden_shape, dim=1)
|
|
|
|
unpacked_outputs = torch.chunk(model_out, output_hidden_shape, dim=1)
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
old_policy_action_dist = dist_class(old_policy_behaviour_logits, model)
|
|
|
|
prev_action_dist = dist_class(behaviour_logits, policy.model)
|
|
|
|
values = policy.model.value_function()
|
2019-05-18 00:23:11 -07:00
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
policy.model_vars = policy.model.variables()
|
|
|
|
policy.target_model_vars = policy.target_model.variables()
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
if policy.is_recurrent():
|
2020-04-23 09:11:12 +02:00
|
|
|
max_seq_len = torch.max(train_batch["seq_lens"]) - 1
|
|
|
|
mask = sequence_mask(train_batch["seq_lens"], max_seq_len)
|
|
|
|
mask = torch.reshape(mask, [-1])
|
2019-05-18 00:23:11 -07:00
|
|
|
else:
|
2020-04-23 09:11:12 +02:00
|
|
|
mask = torch.ones_like(rewards)
|
2019-05-18 00:23:11 -07:00
|
|
|
|
|
|
|
if policy.config["vtrace"]:
|
2019-08-23 02:21:11 -04:00
|
|
|
logger.debug("Using V-Trace surrogate loss (vtrace=True)")
|
2019-05-18 00:23:11 -07:00
|
|
|
|
|
|
|
# Prepare actions for loss
|
2020-04-23 09:11:12 +02:00
|
|
|
loss_actions = actions if is_multidiscrete else torch.unsqueeze(
|
|
|
|
actions, dim=1)
|
2019-05-18 00:23:11 -07:00
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
# Prepare KL for Loss
|
2020-04-23 09:11:12 +02:00
|
|
|
mean_kl = _make_time_major(
|
2020-05-27 16:19:13 +02:00
|
|
|
old_policy_action_dist.kl(action_dist), drop_last=True)
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
policy.loss = VTraceSurrogateLoss(
|
2020-04-23 09:11:12 +02:00
|
|
|
actions=_make_time_major(loss_actions, drop_last=True),
|
|
|
|
prev_actions_logp=_make_time_major(
|
2019-05-18 00:23:11 -07:00
|
|
|
prev_action_dist.logp(actions), drop_last=True),
|
2020-04-23 09:11:12 +02:00
|
|
|
actions_logp=_make_time_major(
|
2019-05-18 00:23:11 -07:00
|
|
|
action_dist.logp(actions), drop_last=True),
|
2020-04-23 09:11:12 +02:00
|
|
|
old_policy_actions_logp=_make_time_major(
|
2019-07-29 15:02:32 -07:00
|
|
|
old_policy_action_dist.logp(actions), drop_last=True),
|
2020-05-27 16:19:13 +02:00
|
|
|
action_kl=mean_kl,
|
2020-04-23 09:11:12 +02:00
|
|
|
actions_entropy=_make_time_major(
|
2020-05-27 16:19:13 +02:00
|
|
|
action_dist.entropy(), drop_last=True),
|
2020-04-23 09:11:12 +02:00
|
|
|
dones=_make_time_major(dones, drop_last=True),
|
|
|
|
behaviour_logits=_make_time_major(
|
2019-05-18 00:23:11 -07:00
|
|
|
unpacked_behaviour_logits, drop_last=True),
|
2020-04-23 09:11:12 +02:00
|
|
|
old_policy_behaviour_logits=_make_time_major(
|
2019-07-29 15:02:32 -07:00
|
|
|
unpacked_old_policy_behaviour_logits, drop_last=True),
|
2020-04-23 09:11:12 +02:00
|
|
|
target_logits=_make_time_major(unpacked_outputs, drop_last=True),
|
2019-05-18 00:23:11 -07:00
|
|
|
discount=policy.config["gamma"],
|
2020-04-23 09:11:12 +02:00
|
|
|
rewards=_make_time_major(rewards, drop_last=True),
|
|
|
|
values=_make_time_major(values, drop_last=True),
|
|
|
|
bootstrap_value=_make_time_major(values)[-1],
|
|
|
|
dist_class=TorchCategorical if is_multidiscrete else dist_class,
|
2019-08-10 14:05:12 -07:00
|
|
|
model=policy.model,
|
2020-04-23 09:11:12 +02:00
|
|
|
valid_mask=_make_time_major(mask, drop_last=True),
|
2019-05-18 00:23:11 -07:00
|
|
|
vf_loss_coeff=policy.config["vf_loss_coeff"],
|
2019-07-29 15:02:32 -07:00
|
|
|
entropy_coeff=policy.config["entropy_coeff"],
|
2019-05-18 00:23:11 -07:00
|
|
|
clip_rho_threshold=policy.config["vtrace_clip_rho_threshold"],
|
|
|
|
clip_pg_rho_threshold=policy.config[
|
|
|
|
"vtrace_clip_pg_rho_threshold"],
|
2019-07-29 15:02:32 -07:00
|
|
|
clip_param=policy.config["clip_param"],
|
|
|
|
cur_kl_coeff=policy.kl_coeff,
|
|
|
|
use_kl_loss=policy.config["use_kl_loss"])
|
2019-05-18 00:23:11 -07:00
|
|
|
else:
|
2019-08-23 02:21:11 -04:00
|
|
|
logger.debug("Using PPO surrogate loss (vtrace=False)")
|
2019-07-29 15:02:32 -07:00
|
|
|
|
|
|
|
# Prepare KL for Loss
|
2020-05-27 16:19:13 +02:00
|
|
|
mean_kl = _make_time_major(prev_action_dist.kl(action_dist))
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
policy.loss = PPOSurrogateLoss(
|
2020-04-23 09:11:12 +02:00
|
|
|
prev_actions_logp=_make_time_major(prev_action_dist.logp(actions)),
|
|
|
|
actions_logp=_make_time_major(action_dist.logp(actions)),
|
2020-05-27 16:19:13 +02:00
|
|
|
action_kl=mean_kl,
|
|
|
|
actions_entropy=_make_time_major(action_dist.entropy()),
|
2020-04-23 09:11:12 +02:00
|
|
|
values=_make_time_major(values),
|
|
|
|
valid_mask=_make_time_major(mask),
|
|
|
|
advantages=_make_time_major(
|
|
|
|
train_batch[Postprocessing.ADVANTAGES]),
|
|
|
|
value_targets=_make_time_major(
|
2019-08-23 02:21:11 -04:00
|
|
|
train_batch[Postprocessing.VALUE_TARGETS]),
|
2019-05-18 00:23:11 -07:00
|
|
|
vf_loss_coeff=policy.config["vf_loss_coeff"],
|
2019-07-29 15:02:32 -07:00
|
|
|
entropy_coeff=policy.config["entropy_coeff"],
|
|
|
|
clip_param=policy.config["clip_param"],
|
|
|
|
cur_kl_coeff=policy.kl_coeff,
|
|
|
|
use_kl_loss=policy.config["use_kl_loss"])
|
2019-05-18 00:23:11 -07:00
|
|
|
|
|
|
|
return policy.loss.total_loss
|
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def stats(policy, train_batch):
|
2020-04-23 09:11:12 +02:00
|
|
|
values_batched = make_time_major(
|
2019-08-23 02:21:11 -04:00
|
|
|
policy,
|
|
|
|
train_batch.get("seq_lens"),
|
|
|
|
policy.model.value_function(),
|
|
|
|
drop_last=policy.config["vtrace"])
|
2019-07-29 15:02:32 -07:00
|
|
|
|
|
|
|
stats_dict = {
|
2020-04-23 09:11:12 +02:00
|
|
|
"cur_lr": policy.cur_lr,
|
2019-07-29 15:02:32 -07:00
|
|
|
"policy_loss": policy.loss.pi_loss,
|
|
|
|
"entropy": policy.loss.entropy,
|
2020-04-23 09:11:12 +02:00
|
|
|
"var_gnorm": global_norm(policy.model.trainable_variables()),
|
2019-07-29 15:02:32 -07:00
|
|
|
"vf_loss": policy.loss.vf_loss,
|
|
|
|
"vf_explained_var": explained_variance(
|
2020-04-23 09:11:12 +02:00
|
|
|
torch.reshape(policy.loss.value_targets, [-1]),
|
|
|
|
torch.reshape(values_batched, [-1]),
|
|
|
|
framework="torch"),
|
2019-07-29 15:02:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
if policy.config["vtrace"]:
|
2020-04-23 09:11:12 +02:00
|
|
|
is_stat_mean = torch.mean(policy.loss.is_ratio, [0, 1])
|
|
|
|
is_stat_var = torch.var(policy.loss.is_ratio, [0, 1])
|
2019-07-29 15:02:32 -07:00
|
|
|
stats_dict.update({"mean_IS": is_stat_mean})
|
|
|
|
stats_dict.update({"var_IS": is_stat_var})
|
|
|
|
|
|
|
|
if policy.config["use_kl_loss"]:
|
|
|
|
stats_dict.update({"kl": policy.loss.mean_kl})
|
|
|
|
stats_dict.update({"KL_Coeff": policy.kl_coeff})
|
|
|
|
|
|
|
|
return stats_dict
|
|
|
|
|
|
|
|
|
2020-01-02 17:42:13 -08:00
|
|
|
class TargetNetworkMixin:
|
2019-07-29 15:02:32 -07:00
|
|
|
def __init__(self, obs_space, action_space, config):
|
2019-08-23 02:21:11 -04:00
|
|
|
def do_update():
|
2020-04-23 09:11:12 +02:00
|
|
|
# Update_target_fn will be called periodically to copy Q network to
|
|
|
|
# target Q network.
|
|
|
|
assert len(self.model_variables) == \
|
|
|
|
len(self.target_model_variables), \
|
|
|
|
(self.model_variables, self.target_model_variables)
|
|
|
|
self.target_model.load_state_dict(self.model.state_dict())
|
2019-08-23 02:21:11 -04:00
|
|
|
|
|
|
|
self.update_target = do_update
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
|
|
|
|
def add_values(policy, input_dict, state_batches, model, action_dist):
|
|
|
|
out = {}
|
|
|
|
if not policy.config["vtrace"]:
|
|
|
|
out[SampleBatch.VF_PREDS] = policy.model.value_function()
|
|
|
|
return out
|
2019-10-31 15:16:02 -07:00
|
|
|
|
2019-07-29 15:02:32 -07:00
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
def setup_early_mixins(policy, obs_space, action_space, config):
|
2019-07-29 15:02:32 -07:00
|
|
|
LearningRateSchedule.__init__(policy, config["lr"], config["lr_schedule"])
|
|
|
|
|
|
|
|
|
|
|
|
def setup_late_mixins(policy, obs_space, action_space, config):
|
2020-04-23 09:11:12 +02:00
|
|
|
KLCoeffMixin.__init__(policy, config)
|
|
|
|
ValueNetworkMixin.__init__(policy, obs_space, action_space, config)
|
2019-07-29 15:02:32 -07:00
|
|
|
TargetNetworkMixin.__init__(policy, obs_space, action_space, config)
|
|
|
|
|
|
|
|
|
2020-04-23 09:11:12 +02:00
|
|
|
AsyncPPOTorchPolicy = build_torch_policy(
|
|
|
|
name="AsyncPPOTorchPolicy",
|
2019-05-18 00:23:11 -07:00
|
|
|
loss_fn=build_appo_surrogate_loss,
|
2019-07-29 15:02:32 -07:00
|
|
|
stats_fn=stats,
|
2019-05-18 00:23:11 -07:00
|
|
|
postprocess_fn=postprocess_trajectory,
|
2020-04-23 09:11:12 +02:00
|
|
|
extra_action_out_fn=add_values,
|
|
|
|
extra_grad_process_fn=apply_grad_clipping,
|
2019-07-29 15:02:32 -07:00
|
|
|
optimizer_fn=choose_optimizer,
|
2020-04-23 09:11:12 +02:00
|
|
|
before_init=setup_early_mixins,
|
2019-07-29 15:02:32 -07:00
|
|
|
after_init=setup_late_mixins,
|
2020-04-23 09:11:12 +02:00
|
|
|
make_model=build_appo_model,
|
2019-07-29 15:02:32 -07:00
|
|
|
mixins=[
|
|
|
|
LearningRateSchedule, KLCoeffMixin, TargetNetworkMixin,
|
|
|
|
ValueNetworkMixin
|
|
|
|
],
|
2020-03-14 12:05:04 -07:00
|
|
|
get_batch_divisibility_req=lambda p: p.config["rollout_fragment_length"])
|