2023-10-08 17:57:03 +02:00
|
|
|
from typing import Any, Literal, Self, cast
|
2022-01-16 05:30:21 +08:00
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
import gymnasium as gym
|
2022-01-16 05:30:21 +08:00
|
|
|
import numpy as np
|
|
|
|
import torch
|
|
|
|
import torch.nn.functional as F
|
2023-10-03 07:54:34 +02:00
|
|
|
from overrides import override
|
2022-01-16 05:30:21 +08:00
|
|
|
from torch.nn.utils import clip_grad_norm_
|
|
|
|
|
|
|
|
from tianshou.data import Batch, ReplayBuffer, to_torch
|
2023-10-03 07:54:34 +02:00
|
|
|
from tianshou.data.buffer.base import TBuffer
|
Improved typing and reduced duplication (#912)
# Goals of the PR
The PR introduces **no changes to functionality**, apart from improved
input validation here and there. The main goals are to reduce some
complexity of the code, to improve types and IDE completions, and to
extend documentation and block comments where appropriate. Because of
the change to the trainer interfaces, many files are affected (more
details below), but still the overall changes are "small" in a certain
sense.
## Major Change 1 - BatchProtocol
**TL;DR:** One can now annotate which fields the batch is expected to
have on input params and which fields a returned batch has. Should be
useful for reading the code. getting meaningful IDE support, and
catching bugs with mypy. This annotation strategy will continue to work
if Batch is replaced by TensorDict or by something else.
**In more detail:** Batch itself has no fields and using it for
annotations is of limited informational power. Batches with fields are
not separate classes but instead instances of Batch directly, so there
is no type that could be used for annotation. Fortunately, python
`Protocol` is here for the rescue. With these changes we can now do
things like
```python
class ActionBatchProtocol(BatchProtocol):
logits: Sequence[Union[tuple, torch.Tensor]]
dist: torch.distributions.Distribution
act: torch.Tensor
state: Optional[torch.Tensor]
class RolloutBatchProtocol(BatchProtocol):
obs: torch.Tensor
obs_next: torch.Tensor
info: Dict[str, Any]
rew: torch.Tensor
terminated: torch.Tensor
truncated: torch.Tensor
class PGPolicy(BasePolicy):
...
def forward(
self,
batch: RolloutBatchProtocol,
state: Optional[Union[dict, Batch, np.ndarray]] = None,
**kwargs: Any,
) -> ActionBatchProtocol:
```
The IDE and mypy are now very helpful in finding errors and in
auto-completion, whereas before the tools couldn't assist in that at
all.
## Major Change 2 - remove duplication in trainer package
**TL;DR:** There was a lot of duplication between `BaseTrainer` and its
subclasses. Even worse, it was almost-duplication. There was also
interface fragmentation through things like `onpolicy_trainer`. Now this
duplication is gone and all downstream code was adjusted.
**In more detail:** Since this change affects a lot of code, I would
like to explain why I thought it to be necessary.
1. The subclasses of `BaseTrainer` just duplicated docstrings and
constructors. What's worse, they changed the order of args there, even
turning some kwargs of BaseTrainer into args. They also had the arg
`learning_type` which was passed as kwarg to the base class and was
unused there. This made things difficult to maintain, and in fact some
errors were already present in the duplicated docstrings.
2. The "functions" a la `onpolicy_trainer`, which just called the
`OnpolicyTrainer.run`, not only introduced interface fragmentation but
also completely obfuscated the docstring and interfaces. They themselves
had no dosctring and the interface was just `*args, **kwargs`, which
makes it impossible to understand what they do and which things can be
passed without reading their implementation, then reading the docstring
of the associated class, etc. Needless to say, mypy and IDEs provide no
support with such functions. Nevertheless, they were used everywhere in
the code-base. I didn't find the sacrifices in clarity and complexity
justified just for the sake of not having to write `.run()` after
instantiating a trainer.
3. The trainers are all very similar to each other. As for my
application I needed a new trainer, I wanted to understand their
structure. The similarity, however, was hard to discover since they were
all in separate modules and there was so much duplication. I kept
staring at the constructors for a while until I figured out that
essentially no changes to the superclass were introduced. Now they are
all in the same module and the similarities/differences between them are
much easier to grasp (in my opinion)
4. Because of (1), I had to manually change and check a lot of code,
which was very tedious and boring. This kind of work won't be necessary
in the future, since now IDEs can be used for changing signatures,
renaming args and kwargs, changing class names and so on.
I have some more reasons, but maybe the above ones are convincing
enough.
## Minor changes: improved input validation and types
I added input validation for things like `state` and `action_scaling`
(which only makes sense for continuous envs). After adding this, some
tests failed to pass this validation. There I added
`action_scaling=isinstance(env.action_space, Box)`, after which tests
were green. I don't know why the tests were green before, since action
scaling doesn't make sense for discrete actions. I guess some aspect was
not tested and didn't crash.
I also added Literal in some places, in particular for
`action_bound_method`. Now it is no longer allowed to pass an empty
string, instead one should pass `None`. Also here there is input
validation with clear error messages.
@Trinkle23897 The functional tests are green. I didn't want to fix the
formatting, since it will change in the next PR that will solve #914
anyway. I also found a whole bunch of code in `docs/_static`, which I
just deleted (shouldn't it be copied from the sources during docs build
instead of committed?). I also haven't adjusted the documentation yet,
which atm still mentions the trainers of the type
`onpolicy_trainer(...)` instead of `OnpolicyTrainer(...).run()`
## Breaking Changes
The adjustments to the trainer package introduce breaking changes as
duplicated interfaces are deleted. However, it should be very easy for
users to adjust to them
---------
Co-authored-by: Michael Panchenko <m.panchenko@appliedai.de>
2023-08-22 18:54:46 +02:00
|
|
|
from tianshou.data.types import RolloutBatchProtocol
|
2023-10-08 17:57:03 +02:00
|
|
|
from tianshou.exploration import BaseNoise
|
2022-01-16 05:30:21 +08:00
|
|
|
from tianshou.policy import SACPolicy
|
2023-10-08 17:57:03 +02:00
|
|
|
from tianshou.policy.base import TLearningRateScheduler
|
2022-01-16 05:30:21 +08:00
|
|
|
from tianshou.utils.net.continuous import ActorProb
|
|
|
|
|
|
|
|
|
|
|
|
class CQLPolicy(SACPolicy):
|
|
|
|
"""Implementation of CQL algorithm. arXiv:2006.04779.
|
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
:param actor: the actor network following the rules in
|
2022-01-16 05:30:21 +08:00
|
|
|
:class:`~tianshou.policy.BasePolicy`. (s -> a)
|
2023-10-08 17:57:03 +02:00
|
|
|
:param actor_optim: The optimizer for actor network.
|
|
|
|
:param critic: The first critic network.
|
|
|
|
:param critic_optim: The optimizer for the first critic network.
|
|
|
|
:param action_space: Env's action space.
|
|
|
|
:param critic2: the second critic network. (s, a -> Q(s, a)).
|
|
|
|
If None, use the same network as critic (via deepcopy).
|
|
|
|
:param critic2_optim: the optimizer for the second critic network.
|
|
|
|
If None, clone critic_optim to use for critic2.parameters().
|
|
|
|
:param cql_alpha_lr: The learning rate of cql_log_alpha.
|
|
|
|
:param cql_weight:
|
|
|
|
:param tau: Parameter for soft update of the target network.
|
|
|
|
:param gamma: Discount factor, in [0, 1].
|
|
|
|
:param alpha: Entropy regularization coefficient or a tuple
|
|
|
|
(target_entropy, log_alpha, alpha_optim) for automatic tuning.
|
|
|
|
:param temperature:
|
|
|
|
:param with_lagrange: Whether to use Lagrange.
|
|
|
|
TODO: extend documentation - what does this mean?
|
|
|
|
:param lagrange_threshold: The value of tau in CQL(Lagrange).
|
|
|
|
:param min_action: The minimum value of each dimension of action.
|
|
|
|
:param max_action: The maximum value of each dimension of action.
|
|
|
|
:param num_repeat_actions: The number of times the action is repeated when calculating log-sum-exp.
|
|
|
|
:param alpha_min: Lower bound for clipping cql_alpha.
|
|
|
|
:param alpha_max: Upper bound for clipping cql_alpha.
|
|
|
|
:param clip_grad: Clip_grad for updating critic network.
|
|
|
|
:param calibrated: calibrate Q-values as in CalQL paper `arXiv:2303.05479`.
|
2023-10-03 07:54:34 +02:00
|
|
|
Useful for offline pre-training followed by online training,
|
|
|
|
and also was observed to achieve better results than vanilla cql.
|
2023-10-08 17:57:03 +02:00
|
|
|
:param device: Which device to create this model on.
|
|
|
|
:param estimation_step: Estimation steps.
|
|
|
|
:param exploration_noise: Type of exploration noise.
|
|
|
|
:param deterministic_eval: Flag for deterministic evaluation.
|
|
|
|
:param action_scaling: Flag for action scaling.
|
|
|
|
:param action_bound_method: Method for action bounding. Only used if the
|
|
|
|
action_space is continuous.
|
|
|
|
:param observation_space: Env's Observation space.
|
2022-04-17 08:52:30 -07:00
|
|
|
:param lr_scheduler: a learning rate scheduler that adjusts the learning rate in
|
2023-10-08 17:57:03 +02:00
|
|
|
optimizer in each policy.update().
|
2022-01-16 05:30:21 +08:00
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed
|
|
|
|
explanation.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2023-10-08 17:57:03 +02:00
|
|
|
*,
|
2022-01-16 05:30:21 +08:00
|
|
|
actor: ActorProb,
|
|
|
|
actor_optim: torch.optim.Optimizer,
|
2023-10-08 17:57:03 +02:00
|
|
|
critic: torch.nn.Module,
|
|
|
|
critic_optim: torch.optim.Optimizer,
|
|
|
|
action_space: gym.spaces.Box,
|
|
|
|
critic2: torch.nn.Module | None = None,
|
|
|
|
critic2_optim: torch.optim.Optimizer | None = None,
|
2022-01-16 05:30:21 +08:00
|
|
|
cql_alpha_lr: float = 1e-4,
|
|
|
|
cql_weight: float = 1.0,
|
|
|
|
tau: float = 0.005,
|
|
|
|
gamma: float = 0.99,
|
2023-09-05 23:34:23 +02:00
|
|
|
alpha: float | tuple[float, torch.Tensor, torch.optim.Optimizer] = 0.2,
|
2022-01-16 05:30:21 +08:00
|
|
|
temperature: float = 1.0,
|
|
|
|
with_lagrange: bool = True,
|
|
|
|
lagrange_threshold: float = 10.0,
|
|
|
|
min_action: float = -1.0,
|
|
|
|
max_action: float = 1.0,
|
|
|
|
num_repeat_actions: int = 10,
|
|
|
|
alpha_min: float = 0.0,
|
|
|
|
alpha_max: float = 1e6,
|
|
|
|
clip_grad: float = 1.0,
|
2023-10-03 07:54:34 +02:00
|
|
|
calibrated: bool = True,
|
2023-10-08 17:57:03 +02:00
|
|
|
# TODO: why does this one have device? Almost no other policies have it
|
2023-09-05 23:34:23 +02:00
|
|
|
device: str | torch.device = "cpu",
|
2023-10-08 17:57:03 +02:00
|
|
|
estimation_step: int = 1,
|
|
|
|
exploration_noise: BaseNoise | Literal["default"] | None = None,
|
|
|
|
deterministic_eval: bool = True,
|
|
|
|
action_scaling: bool = True,
|
|
|
|
action_bound_method: Literal["clip"] | None = "clip",
|
|
|
|
observation_space: gym.Space | None = None,
|
|
|
|
lr_scheduler: TLearningRateScheduler | None = None,
|
2022-01-16 05:30:21 +08:00
|
|
|
) -> None:
|
|
|
|
super().__init__(
|
2023-10-08 17:57:03 +02:00
|
|
|
actor=actor,
|
|
|
|
actor_optim=actor_optim,
|
|
|
|
critic=critic,
|
|
|
|
critic_optim=critic_optim,
|
|
|
|
action_space=action_space,
|
|
|
|
critic2=critic2,
|
|
|
|
critic2_optim=critic2_optim,
|
|
|
|
tau=tau,
|
|
|
|
gamma=gamma,
|
|
|
|
deterministic_eval=deterministic_eval,
|
|
|
|
alpha=alpha,
|
|
|
|
exploration_noise=exploration_noise,
|
|
|
|
estimation_step=estimation_step,
|
|
|
|
action_scaling=action_scaling,
|
|
|
|
action_bound_method=action_bound_method,
|
|
|
|
observation_space=observation_space,
|
|
|
|
lr_scheduler=lr_scheduler,
|
2022-01-16 05:30:21 +08:00
|
|
|
)
|
|
|
|
# There are _target_entropy, _log_alpha, _alpha_optim in SACPolicy.
|
|
|
|
self.device = device
|
|
|
|
self.temperature = temperature
|
|
|
|
self.with_lagrange = with_lagrange
|
|
|
|
self.lagrange_threshold = lagrange_threshold
|
|
|
|
|
|
|
|
self.cql_weight = cql_weight
|
|
|
|
|
|
|
|
self.cql_log_alpha = torch.tensor([0.0], requires_grad=True)
|
|
|
|
self.cql_alpha_optim = torch.optim.Adam([self.cql_log_alpha], lr=cql_alpha_lr)
|
|
|
|
self.cql_log_alpha = self.cql_log_alpha.to(device)
|
|
|
|
|
|
|
|
self.min_action = min_action
|
|
|
|
self.max_action = max_action
|
|
|
|
|
|
|
|
self.num_repeat_actions = num_repeat_actions
|
|
|
|
|
|
|
|
self.alpha_min = alpha_min
|
|
|
|
self.alpha_max = alpha_max
|
|
|
|
self.clip_grad = clip_grad
|
|
|
|
|
2023-10-03 07:54:34 +02:00
|
|
|
self.calibrated = calibrated
|
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
def train(self, mode: bool = True) -> Self:
|
2022-01-16 05:30:21 +08:00
|
|
|
"""Set the module in training mode, except for the target network."""
|
|
|
|
self.training = mode
|
|
|
|
self.actor.train(mode)
|
2023-10-08 17:57:03 +02:00
|
|
|
self.critic.train(mode)
|
2022-01-16 05:30:21 +08:00
|
|
|
self.critic2.train(mode)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def sync_weight(self) -> None:
|
|
|
|
"""Soft-update the weight for the target network."""
|
2023-10-08 17:57:03 +02:00
|
|
|
self.soft_update(self.critic_old, self.critic, self.tau)
|
2022-01-30 00:53:56 +08:00
|
|
|
self.soft_update(self.critic2_old, self.critic2, self.tau)
|
2022-01-16 05:30:21 +08:00
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
def actor_pred(self, obs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
2022-01-16 05:30:21 +08:00
|
|
|
batch = Batch(obs=obs, info=None)
|
|
|
|
obs_result = self(batch)
|
|
|
|
return obs_result.act, obs_result.log_prob
|
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
def calc_actor_loss(self, obs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
2022-01-16 05:30:21 +08:00
|
|
|
act_pred, log_pi = self.actor_pred(obs)
|
2023-10-08 17:57:03 +02:00
|
|
|
q1 = self.critic(obs, act_pred)
|
2022-01-16 05:30:21 +08:00
|
|
|
q2 = self.critic2(obs, act_pred)
|
|
|
|
min_Q = torch.min(q1, q2)
|
2023-10-08 17:57:03 +02:00
|
|
|
# self.alpha: float | torch.Tensor
|
|
|
|
actor_loss = (self.alpha * log_pi - min_Q).mean()
|
2022-01-16 05:30:21 +08:00
|
|
|
# actor_loss.shape: (), log_pi.shape: (batch_size, 1)
|
|
|
|
return actor_loss, log_pi
|
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
def calc_pi_values(
|
|
|
|
self,
|
|
|
|
obs_pi: torch.Tensor,
|
|
|
|
obs_to_pred: torch.Tensor,
|
|
|
|
) -> tuple[torch.Tensor, torch.Tensor]:
|
2022-01-16 05:30:21 +08:00
|
|
|
act_pred, log_pi = self.actor_pred(obs_pi)
|
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
q1 = self.critic(obs_to_pred, act_pred)
|
2022-01-16 05:30:21 +08:00
|
|
|
q2 = self.critic2(obs_to_pred, act_pred)
|
|
|
|
|
|
|
|
return q1 - log_pi.detach(), q2 - log_pi.detach()
|
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
def calc_random_values(
|
|
|
|
self,
|
|
|
|
obs: torch.Tensor,
|
|
|
|
act: torch.Tensor,
|
|
|
|
) -> tuple[torch.Tensor, torch.Tensor]:
|
2023-10-08 17:57:03 +02:00
|
|
|
random_value1 = self.critic(obs, act)
|
2023-08-25 23:40:56 +02:00
|
|
|
random_log_prob1 = np.log(0.5 ** act.shape[-1])
|
2022-01-16 05:30:21 +08:00
|
|
|
|
|
|
|
random_value2 = self.critic2(obs, act)
|
2023-08-25 23:40:56 +02:00
|
|
|
random_log_prob2 = np.log(0.5 ** act.shape[-1])
|
2022-01-16 05:30:21 +08:00
|
|
|
|
|
|
|
return random_value1 - random_log_prob1, random_value2 - random_log_prob2
|
|
|
|
|
2023-10-03 07:54:34 +02:00
|
|
|
@override
|
|
|
|
def process_buffer(self, buffer: TBuffer) -> TBuffer:
|
|
|
|
"""If `self.calibrated = True`, adds `calibration_returns` to buffer._meta.
|
|
|
|
|
|
|
|
:param buffer:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
if self.calibrated:
|
|
|
|
# otherwise _meta hack cannot work
|
|
|
|
assert isinstance(buffer, ReplayBuffer)
|
|
|
|
batch, indices = buffer.sample(0)
|
|
|
|
returns, _ = self.compute_episodic_return(
|
|
|
|
batch=batch,
|
|
|
|
buffer=buffer,
|
|
|
|
indices=indices,
|
2023-10-08 17:57:03 +02:00
|
|
|
gamma=self.gamma,
|
2023-10-03 07:54:34 +02:00
|
|
|
gae_lambda=1.0,
|
|
|
|
)
|
|
|
|
# TODO: don't access _meta directly
|
|
|
|
buffer._meta = cast(
|
|
|
|
RolloutBatchProtocol,
|
|
|
|
Batch(**buffer._meta.__dict__, calibration_returns=returns),
|
|
|
|
)
|
|
|
|
return buffer
|
|
|
|
|
2022-01-16 05:30:21 +08:00
|
|
|
def process_fn(
|
2023-08-25 23:40:56 +02:00
|
|
|
self,
|
|
|
|
batch: RolloutBatchProtocol,
|
|
|
|
buffer: ReplayBuffer,
|
|
|
|
indices: np.ndarray,
|
Improved typing and reduced duplication (#912)
# Goals of the PR
The PR introduces **no changes to functionality**, apart from improved
input validation here and there. The main goals are to reduce some
complexity of the code, to improve types and IDE completions, and to
extend documentation and block comments where appropriate. Because of
the change to the trainer interfaces, many files are affected (more
details below), but still the overall changes are "small" in a certain
sense.
## Major Change 1 - BatchProtocol
**TL;DR:** One can now annotate which fields the batch is expected to
have on input params and which fields a returned batch has. Should be
useful for reading the code. getting meaningful IDE support, and
catching bugs with mypy. This annotation strategy will continue to work
if Batch is replaced by TensorDict or by something else.
**In more detail:** Batch itself has no fields and using it for
annotations is of limited informational power. Batches with fields are
not separate classes but instead instances of Batch directly, so there
is no type that could be used for annotation. Fortunately, python
`Protocol` is here for the rescue. With these changes we can now do
things like
```python
class ActionBatchProtocol(BatchProtocol):
logits: Sequence[Union[tuple, torch.Tensor]]
dist: torch.distributions.Distribution
act: torch.Tensor
state: Optional[torch.Tensor]
class RolloutBatchProtocol(BatchProtocol):
obs: torch.Tensor
obs_next: torch.Tensor
info: Dict[str, Any]
rew: torch.Tensor
terminated: torch.Tensor
truncated: torch.Tensor
class PGPolicy(BasePolicy):
...
def forward(
self,
batch: RolloutBatchProtocol,
state: Optional[Union[dict, Batch, np.ndarray]] = None,
**kwargs: Any,
) -> ActionBatchProtocol:
```
The IDE and mypy are now very helpful in finding errors and in
auto-completion, whereas before the tools couldn't assist in that at
all.
## Major Change 2 - remove duplication in trainer package
**TL;DR:** There was a lot of duplication between `BaseTrainer` and its
subclasses. Even worse, it was almost-duplication. There was also
interface fragmentation through things like `onpolicy_trainer`. Now this
duplication is gone and all downstream code was adjusted.
**In more detail:** Since this change affects a lot of code, I would
like to explain why I thought it to be necessary.
1. The subclasses of `BaseTrainer` just duplicated docstrings and
constructors. What's worse, they changed the order of args there, even
turning some kwargs of BaseTrainer into args. They also had the arg
`learning_type` which was passed as kwarg to the base class and was
unused there. This made things difficult to maintain, and in fact some
errors were already present in the duplicated docstrings.
2. The "functions" a la `onpolicy_trainer`, which just called the
`OnpolicyTrainer.run`, not only introduced interface fragmentation but
also completely obfuscated the docstring and interfaces. They themselves
had no dosctring and the interface was just `*args, **kwargs`, which
makes it impossible to understand what they do and which things can be
passed without reading their implementation, then reading the docstring
of the associated class, etc. Needless to say, mypy and IDEs provide no
support with such functions. Nevertheless, they were used everywhere in
the code-base. I didn't find the sacrifices in clarity and complexity
justified just for the sake of not having to write `.run()` after
instantiating a trainer.
3. The trainers are all very similar to each other. As for my
application I needed a new trainer, I wanted to understand their
structure. The similarity, however, was hard to discover since they were
all in separate modules and there was so much duplication. I kept
staring at the constructors for a while until I figured out that
essentially no changes to the superclass were introduced. Now they are
all in the same module and the similarities/differences between them are
much easier to grasp (in my opinion)
4. Because of (1), I had to manually change and check a lot of code,
which was very tedious and boring. This kind of work won't be necessary
in the future, since now IDEs can be used for changing signatures,
renaming args and kwargs, changing class names and so on.
I have some more reasons, but maybe the above ones are convincing
enough.
## Minor changes: improved input validation and types
I added input validation for things like `state` and `action_scaling`
(which only makes sense for continuous envs). After adding this, some
tests failed to pass this validation. There I added
`action_scaling=isinstance(env.action_space, Box)`, after which tests
were green. I don't know why the tests were green before, since action
scaling doesn't make sense for discrete actions. I guess some aspect was
not tested and didn't crash.
I also added Literal in some places, in particular for
`action_bound_method`. Now it is no longer allowed to pass an empty
string, instead one should pass `None`. Also here there is input
validation with clear error messages.
@Trinkle23897 The functional tests are green. I didn't want to fix the
formatting, since it will change in the next PR that will solve #914
anyway. I also found a whole bunch of code in `docs/_static`, which I
just deleted (shouldn't it be copied from the sources during docs build
instead of committed?). I also haven't adjusted the documentation yet,
which atm still mentions the trainers of the type
`onpolicy_trainer(...)` instead of `OnpolicyTrainer(...).run()`
## Breaking Changes
The adjustments to the trainer package introduce breaking changes as
duplicated interfaces are deleted. However, it should be very easy for
users to adjust to them
---------
Co-authored-by: Michael Panchenko <m.panchenko@appliedai.de>
2023-08-22 18:54:46 +02:00
|
|
|
) -> RolloutBatchProtocol:
|
|
|
|
# TODO: mypy rightly complains here b/c the design violates
|
|
|
|
# Liskov Substitution Principle
|
|
|
|
# DDPGPolicy.process_fn() results in a batch with returns but
|
|
|
|
# CQLPolicy.process_fn() doesn't add the returns.
|
|
|
|
# Should probably be fixed!
|
2022-01-16 05:30:21 +08:00
|
|
|
return batch
|
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
def learn(self, batch: RolloutBatchProtocol, *args: Any, **kwargs: Any) -> dict[str, float]:
|
2022-05-15 15:40:32 +02:00
|
|
|
batch: Batch = to_torch(batch, dtype=torch.float, device=self.device)
|
2022-01-16 05:30:21 +08:00
|
|
|
obs, act, rew, obs_next = batch.obs, batch.act, batch.rew, batch.obs_next
|
|
|
|
batch_size = obs.shape[0]
|
|
|
|
|
|
|
|
# compute actor loss and update actor
|
|
|
|
actor_loss, log_pi = self.calc_actor_loss(obs)
|
|
|
|
self.actor_optim.zero_grad()
|
|
|
|
actor_loss.backward()
|
|
|
|
self.actor_optim.step()
|
|
|
|
|
|
|
|
# compute alpha loss
|
2023-10-08 17:57:03 +02:00
|
|
|
if self.is_auto_alpha:
|
|
|
|
log_pi = log_pi + self.target_entropy
|
|
|
|
alpha_loss = -(self.log_alpha * log_pi.detach()).mean()
|
|
|
|
self.alpha_optim.zero_grad()
|
2022-01-16 05:30:21 +08:00
|
|
|
# update log_alpha
|
|
|
|
alpha_loss.backward()
|
2023-10-08 17:57:03 +02:00
|
|
|
self.alpha_optim.step()
|
2022-01-16 05:30:21 +08:00
|
|
|
# update alpha
|
2023-10-08 17:57:03 +02:00
|
|
|
# TODO: it's probably a bad idea to track both alpha and log_alpha in different fields
|
|
|
|
self.alpha = self.log_alpha.detach().exp()
|
2022-01-16 05:30:21 +08:00
|
|
|
|
|
|
|
# compute target_Q
|
|
|
|
with torch.no_grad():
|
|
|
|
act_next, new_log_pi = self.actor_pred(obs_next)
|
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
target_Q1 = self.critic_old(obs_next, act_next)
|
2022-01-16 05:30:21 +08:00
|
|
|
target_Q2 = self.critic2_old(obs_next, act_next)
|
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
target_Q = torch.min(target_Q1, target_Q2) - self.alpha * new_log_pi
|
2022-01-16 05:30:21 +08:00
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
target_Q = rew + self.gamma * (1 - batch.done) * target_Q.flatten()
|
2022-01-16 05:30:21 +08:00
|
|
|
# shape: (batch_size)
|
|
|
|
|
|
|
|
# compute critic loss
|
2023-10-08 17:57:03 +02:00
|
|
|
current_Q1 = self.critic(obs, act).flatten()
|
2022-01-16 05:30:21 +08:00
|
|
|
current_Q2 = self.critic2(obs, act).flatten()
|
|
|
|
# shape: (batch_size)
|
|
|
|
|
|
|
|
critic1_loss = F.mse_loss(current_Q1, target_Q)
|
|
|
|
critic2_loss = F.mse_loss(current_Q2, target_Q)
|
|
|
|
|
|
|
|
# CQL
|
2023-08-25 23:40:56 +02:00
|
|
|
random_actions = (
|
|
|
|
torch.FloatTensor(batch_size * self.num_repeat_actions, act.shape[-1])
|
|
|
|
.uniform_(-self.min_action, self.max_action)
|
|
|
|
.to(self.device)
|
|
|
|
)
|
2022-05-15 15:40:32 +02:00
|
|
|
|
|
|
|
obs_len = len(obs.shape)
|
|
|
|
repeat_size = [1, self.num_repeat_actions] + [1] * (obs_len - 1)
|
2023-08-25 23:40:56 +02:00
|
|
|
view_size = [batch_size * self.num_repeat_actions, *list(obs.shape[1:])]
|
2022-05-15 15:40:32 +02:00
|
|
|
tmp_obs = obs.unsqueeze(1).repeat(*repeat_size).view(*view_size)
|
|
|
|
tmp_obs_next = obs_next.unsqueeze(1).repeat(*repeat_size).view(*view_size)
|
2022-01-16 05:30:21 +08:00
|
|
|
# tmp_obs & tmp_obs_next: (batch_size * num_repeat, state_dim)
|
|
|
|
|
|
|
|
current_pi_value1, current_pi_value2 = self.calc_pi_values(tmp_obs, tmp_obs)
|
|
|
|
next_pi_value1, next_pi_value2 = self.calc_pi_values(tmp_obs_next, tmp_obs)
|
|
|
|
|
|
|
|
random_value1, random_value2 = self.calc_random_values(tmp_obs, random_actions)
|
|
|
|
|
|
|
|
for value in [
|
2023-08-25 23:40:56 +02:00
|
|
|
current_pi_value1,
|
|
|
|
current_pi_value2,
|
|
|
|
next_pi_value1,
|
|
|
|
next_pi_value2,
|
|
|
|
random_value1,
|
|
|
|
random_value2,
|
2022-01-16 05:30:21 +08:00
|
|
|
]:
|
|
|
|
value.reshape(batch_size, self.num_repeat_actions, 1)
|
|
|
|
|
2023-10-03 07:54:34 +02:00
|
|
|
if self.calibrated:
|
|
|
|
returns = (
|
|
|
|
batch.calibration_returns.unsqueeze(1)
|
|
|
|
.repeat(
|
|
|
|
(1, self.num_repeat_actions),
|
|
|
|
)
|
|
|
|
.view(-1, 1)
|
|
|
|
)
|
|
|
|
random_value1 = torch.max(random_value1, returns)
|
|
|
|
random_value2 = torch.max(random_value2, returns)
|
|
|
|
|
|
|
|
current_pi_value1 = torch.max(current_pi_value1, returns)
|
|
|
|
current_pi_value2 = torch.max(current_pi_value2, returns)
|
|
|
|
|
|
|
|
next_pi_value1 = torch.max(next_pi_value1, returns)
|
|
|
|
next_pi_value2 = torch.max(next_pi_value2, returns)
|
|
|
|
|
2022-01-16 05:30:21 +08:00
|
|
|
# cat q values
|
|
|
|
cat_q1 = torch.cat([random_value1, current_pi_value1, next_pi_value1], 1)
|
|
|
|
cat_q2 = torch.cat([random_value2, current_pi_value2, next_pi_value2], 1)
|
|
|
|
# shape: (batch_size, 3 * num_repeat, 1)
|
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
cql1_scaled_loss = (
|
|
|
|
torch.logsumexp(cat_q1 / self.temperature, dim=1).mean()
|
|
|
|
* self.cql_weight
|
|
|
|
* self.temperature
|
|
|
|
- current_Q1.mean() * self.cql_weight
|
|
|
|
)
|
|
|
|
cql2_scaled_loss = (
|
|
|
|
torch.logsumexp(cat_q2 / self.temperature, dim=1).mean()
|
|
|
|
* self.cql_weight
|
|
|
|
* self.temperature
|
|
|
|
- current_Q2.mean() * self.cql_weight
|
|
|
|
)
|
2022-01-16 05:30:21 +08:00
|
|
|
# shape: (1)
|
|
|
|
|
|
|
|
if self.with_lagrange:
|
|
|
|
cql_alpha = torch.clamp(
|
|
|
|
self.cql_log_alpha.exp(),
|
|
|
|
self.alpha_min,
|
|
|
|
self.alpha_max,
|
|
|
|
)
|
2023-08-25 23:40:56 +02:00
|
|
|
cql1_scaled_loss = cql_alpha * (cql1_scaled_loss - self.lagrange_threshold)
|
|
|
|
cql2_scaled_loss = cql_alpha * (cql2_scaled_loss - self.lagrange_threshold)
|
2022-01-16 05:30:21 +08:00
|
|
|
|
|
|
|
self.cql_alpha_optim.zero_grad()
|
|
|
|
cql_alpha_loss = -(cql1_scaled_loss + cql2_scaled_loss) * 0.5
|
|
|
|
cql_alpha_loss.backward(retain_graph=True)
|
|
|
|
self.cql_alpha_optim.step()
|
|
|
|
|
|
|
|
critic1_loss = critic1_loss + cql1_scaled_loss
|
|
|
|
critic2_loss = critic2_loss + cql2_scaled_loss
|
|
|
|
|
|
|
|
# update critic
|
2023-10-08 17:57:03 +02:00
|
|
|
self.critic_optim.zero_grad()
|
2022-01-16 05:30:21 +08:00
|
|
|
critic1_loss.backward(retain_graph=True)
|
|
|
|
# clip grad, prevent the vanishing gradient problem
|
|
|
|
# It doesn't seem necessary
|
2023-10-08 17:57:03 +02:00
|
|
|
clip_grad_norm_(self.critic.parameters(), self.clip_grad)
|
|
|
|
self.critic_optim.step()
|
2022-01-16 05:30:21 +08:00
|
|
|
|
|
|
|
self.critic2_optim.zero_grad()
|
|
|
|
critic2_loss.backward()
|
|
|
|
clip_grad_norm_(self.critic2.parameters(), self.clip_grad)
|
|
|
|
self.critic2_optim.step()
|
|
|
|
|
|
|
|
self.sync_weight()
|
|
|
|
|
|
|
|
result = {
|
|
|
|
"loss/actor": actor_loss.item(),
|
|
|
|
"loss/critic1": critic1_loss.item(),
|
|
|
|
"loss/critic2": critic2_loss.item(),
|
|
|
|
}
|
2023-10-08 17:57:03 +02:00
|
|
|
if self.is_auto_alpha:
|
|
|
|
self.alpha = cast(torch.Tensor, self.alpha)
|
2022-01-16 05:30:21 +08:00
|
|
|
result["loss/alpha"] = alpha_loss.item()
|
2023-10-08 17:57:03 +02:00
|
|
|
result["alpha"] = self.alpha.item()
|
2022-01-16 05:30:21 +08:00
|
|
|
if self.with_lagrange:
|
|
|
|
result["loss/cql_alpha"] = cql_alpha_loss.item()
|
|
|
|
result["cql_alpha"] = cql_alpha.item()
|
|
|
|
return result
|