2019-02-16 19:54:14 -08:00
|
|
|
from __future__ import absolute_import
|
|
|
|
from __future__ import division
|
|
|
|
from __future__ import print_function
|
|
|
|
|
|
|
|
import ray
|
2019-03-29 12:44:23 -07:00
|
|
|
from ray.rllib.evaluation.postprocessing import compute_advantages, \
|
|
|
|
Postprocessing
|
2019-05-20 16:46:05 -07:00
|
|
|
from ray.rllib.policy.sample_batch import SampleBatch
|
|
|
|
from ray.rllib.policy.torch_policy_template import build_torch_policy
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def pg_torch_loss(policy, model, dist_class, train_batch):
|
|
|
|
logits, _ = model.from_batch(train_batch)
|
|
|
|
action_dist = dist_class(logits, model)
|
|
|
|
log_probs = action_dist.logp(train_batch[SampleBatch.ACTIONS])
|
2019-05-18 00:23:11 -07:00
|
|
|
# save the error in the policy object
|
2019-08-23 02:21:11 -04:00
|
|
|
policy.pi_err = -train_batch[Postprocessing.ADVANTAGES].dot(
|
2019-05-18 00:23:11 -07:00
|
|
|
log_probs.reshape(-1))
|
|
|
|
return policy.pi_err
|
2019-03-29 12:44:23 -07:00
|
|
|
|
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
def postprocess_advantages(policy,
|
|
|
|
sample_batch,
|
|
|
|
other_agent_batches=None,
|
|
|
|
episode=None):
|
|
|
|
return compute_advantages(
|
|
|
|
sample_batch, 0.0, policy.config["gamma"], use_gae=False)
|
2019-02-16 19:54:14 -08:00
|
|
|
|
|
|
|
|
2019-08-23 02:21:11 -04:00
|
|
|
def pg_loss_stats(policy, train_batch):
|
2019-05-18 00:23:11 -07:00
|
|
|
# the error is recorded when computing the loss
|
|
|
|
return {"policy_loss": policy.pi_err.item()}
|
2019-04-12 11:39:14 -07:00
|
|
|
|
2019-02-16 19:54:14 -08:00
|
|
|
|
2019-05-18 00:23:11 -07:00
|
|
|
PGTorchPolicy = build_torch_policy(
|
|
|
|
name="PGTorchPolicy",
|
|
|
|
get_default_config=lambda: ray.rllib.agents.a3c.a3c.DEFAULT_CONFIG,
|
|
|
|
loss_fn=pg_torch_loss,
|
|
|
|
stats_fn=pg_loss_stats,
|
|
|
|
postprocess_fn=postprocess_advantages)
|