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-05-18 00:23:11 -07:00
|
|
|
def pg_torch_loss(policy, batch_tensors):
|
2019-07-25 11:02:53 -07:00
|
|
|
logits, _ = policy.model({
|
2019-05-18 00:23:11 -07:00
|
|
|
SampleBatch.CUR_OBS: batch_tensors[SampleBatch.CUR_OBS]
|
2019-07-25 11:02:53 -07:00
|
|
|
})
|
2019-05-18 00:23:11 -07:00
|
|
|
action_dist = policy.dist_class(logits)
|
|
|
|
log_probs = action_dist.logp(batch_tensors[SampleBatch.ACTIONS])
|
|
|
|
# save the error in the policy object
|
|
|
|
policy.pi_err = -batch_tensors[Postprocessing.ADVANTAGES].dot(
|
|
|
|
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-05-18 00:23:11 -07:00
|
|
|
def pg_loss_stats(policy, batch_tensors):
|
|
|
|
# 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)
|