2021-03-30 11:50:35 +08:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
2021-09-03 05:05:04 +08:00
|
|
|
import argparse
|
|
|
|
import datetime
|
2021-03-30 11:50:35 +08:00
|
|
|
import os
|
|
|
|
import pprint
|
2021-09-03 05:05:04 +08:00
|
|
|
|
2021-03-30 11:50:35 +08:00
|
|
|
import numpy as np
|
2021-09-03 05:05:04 +08:00
|
|
|
import torch
|
2022-05-05 07:55:15 -04:00
|
|
|
from mujoco_env import make_mujoco_env
|
2021-03-30 11:50:35 +08:00
|
|
|
from torch import nn
|
2021-09-03 05:05:04 +08:00
|
|
|
from torch.distributions import Independent, Normal
|
2021-03-30 11:50:35 +08:00
|
|
|
from torch.optim.lr_scheduler import LambdaLR
|
|
|
|
from torch.utils.tensorboard import SummaryWriter
|
|
|
|
|
2021-09-03 05:05:04 +08:00
|
|
|
from tianshou.data import Collector, ReplayBuffer, VectorReplayBuffer
|
2021-03-30 11:50:35 +08:00
|
|
|
from tianshou.policy import PPOPolicy
|
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.trainer import OnpolicyTrainer
|
2022-05-05 07:55:15 -04:00
|
|
|
from tianshou.utils import TensorboardLogger, WandbLogger
|
2023-04-29 06:43:22 +02:00
|
|
|
from tianshou.utils.net.common import ActorCritic, Net
|
2021-03-30 11:50:35 +08:00
|
|
|
from tianshou.utils.net.continuous import ActorProb, Critic
|
|
|
|
|
|
|
|
|
|
|
|
def get_args():
|
|
|
|
parser = argparse.ArgumentParser()
|
2022-05-05 07:55:15 -04:00
|
|
|
parser.add_argument("--task", type=str, default="Ant-v3")
|
|
|
|
parser.add_argument("--seed", type=int, default=0)
|
|
|
|
parser.add_argument("--buffer-size", type=int, default=4096)
|
|
|
|
parser.add_argument("--hidden-sizes", type=int, nargs="*", default=[64, 64])
|
|
|
|
parser.add_argument("--lr", type=float, default=3e-4)
|
|
|
|
parser.add_argument("--gamma", type=float, default=0.99)
|
|
|
|
parser.add_argument("--epoch", type=int, default=100)
|
|
|
|
parser.add_argument("--step-per-epoch", type=int, default=30000)
|
|
|
|
parser.add_argument("--step-per-collect", type=int, default=2048)
|
|
|
|
parser.add_argument("--repeat-per-collect", type=int, default=10)
|
|
|
|
parser.add_argument("--batch-size", type=int, default=64)
|
|
|
|
parser.add_argument("--training-num", type=int, default=64)
|
|
|
|
parser.add_argument("--test-num", type=int, default=10)
|
2021-03-30 11:50:35 +08:00
|
|
|
# ppo special
|
2022-05-05 07:55:15 -04:00
|
|
|
parser.add_argument("--rew-norm", type=int, default=True)
|
2021-03-30 11:50:35 +08:00
|
|
|
# In theory, `vf-coef` will not make any difference if using Adam optimizer.
|
2022-05-05 07:55:15 -04:00
|
|
|
parser.add_argument("--vf-coef", type=float, default=0.25)
|
|
|
|
parser.add_argument("--ent-coef", type=float, default=0.0)
|
|
|
|
parser.add_argument("--gae-lambda", type=float, default=0.95)
|
|
|
|
parser.add_argument("--bound-action-method", type=str, default="clip")
|
|
|
|
parser.add_argument("--lr-decay", type=int, default=True)
|
|
|
|
parser.add_argument("--max-grad-norm", type=float, default=0.5)
|
|
|
|
parser.add_argument("--eps-clip", type=float, default=0.2)
|
|
|
|
parser.add_argument("--dual-clip", type=float, default=None)
|
|
|
|
parser.add_argument("--value-clip", type=int, default=0)
|
|
|
|
parser.add_argument("--norm-adv", type=int, default=0)
|
|
|
|
parser.add_argument("--recompute-adv", type=int, default=1)
|
|
|
|
parser.add_argument("--logdir", type=str, default="log")
|
2023-08-25 23:40:56 +02:00
|
|
|
parser.add_argument("--render", type=float, default=0.0)
|
2021-03-30 11:50:35 +08:00
|
|
|
parser.add_argument(
|
2023-08-25 23:40:56 +02:00
|
|
|
"--device",
|
|
|
|
type=str,
|
|
|
|
default="cuda" if torch.cuda.is_available() else "cpu",
|
2021-09-03 05:05:04 +08:00
|
|
|
)
|
2022-05-05 07:55:15 -04:00
|
|
|
parser.add_argument("--resume-path", type=str, default=None)
|
|
|
|
parser.add_argument("--resume-id", type=str, default=None)
|
2021-09-03 05:05:04 +08:00
|
|
|
parser.add_argument(
|
2022-05-05 07:55:15 -04:00
|
|
|
"--logger",
|
|
|
|
type=str,
|
|
|
|
default="tensorboard",
|
|
|
|
choices=["tensorboard", "wandb"],
|
|
|
|
)
|
|
|
|
parser.add_argument("--wandb-project", type=str, default="mujoco.benchmark")
|
|
|
|
parser.add_argument(
|
|
|
|
"--watch",
|
2021-09-03 05:05:04 +08:00
|
|
|
default=False,
|
2022-05-05 07:55:15 -04:00
|
|
|
action="store_true",
|
|
|
|
help="watch the play of pre-trained policy only",
|
2021-09-03 05:05:04 +08:00
|
|
|
)
|
2021-03-30 11:50:35 +08:00
|
|
|
return parser.parse_args()
|
|
|
|
|
|
|
|
|
|
|
|
def test_ppo(args=get_args()):
|
2022-05-05 07:55:15 -04:00
|
|
|
env, train_envs, test_envs = make_mujoco_env(
|
2023-08-25 23:40:56 +02:00
|
|
|
args.task,
|
|
|
|
args.seed,
|
|
|
|
args.training_num,
|
|
|
|
args.test_num,
|
|
|
|
obs_norm=True,
|
2022-05-05 07:55:15 -04:00
|
|
|
)
|
2021-03-30 11:50:35 +08:00
|
|
|
args.state_shape = env.observation_space.shape or env.observation_space.n
|
|
|
|
args.action_shape = env.action_space.shape or env.action_space.n
|
|
|
|
args.max_action = env.action_space.high[0]
|
|
|
|
print("Observations shape:", args.state_shape)
|
|
|
|
print("Actions shape:", args.action_shape)
|
2021-09-03 05:05:04 +08:00
|
|
|
print("Action range:", np.min(env.action_space.low), np.max(env.action_space.high))
|
2021-03-30 11:50:35 +08:00
|
|
|
# seed
|
|
|
|
np.random.seed(args.seed)
|
|
|
|
torch.manual_seed(args.seed)
|
|
|
|
# model
|
2021-09-03 05:05:04 +08:00
|
|
|
net_a = Net(
|
|
|
|
args.state_shape,
|
|
|
|
hidden_sizes=args.hidden_sizes,
|
|
|
|
activation=nn.Tanh,
|
2022-05-05 07:55:15 -04:00
|
|
|
device=args.device,
|
2021-09-03 05:05:04 +08:00
|
|
|
)
|
|
|
|
actor = ActorProb(
|
|
|
|
net_a,
|
|
|
|
args.action_shape,
|
|
|
|
unbounded=True,
|
2022-05-05 07:55:15 -04:00
|
|
|
device=args.device,
|
2021-09-03 05:05:04 +08:00
|
|
|
).to(args.device)
|
|
|
|
net_c = Net(
|
|
|
|
args.state_shape,
|
|
|
|
hidden_sizes=args.hidden_sizes,
|
|
|
|
activation=nn.Tanh,
|
2022-05-05 07:55:15 -04:00
|
|
|
device=args.device,
|
2021-09-03 05:05:04 +08:00
|
|
|
)
|
2021-03-30 11:50:35 +08:00
|
|
|
critic = Critic(net_c, device=args.device).to(args.device)
|
2023-04-29 06:43:22 +02:00
|
|
|
actor_critic = ActorCritic(actor, critic)
|
|
|
|
|
2021-03-30 11:50:35 +08:00
|
|
|
torch.nn.init.constant_(actor.sigma_param, -0.5)
|
2023-04-29 06:43:22 +02:00
|
|
|
for m in actor_critic.modules():
|
2021-03-30 11:50:35 +08:00
|
|
|
if isinstance(m, torch.nn.Linear):
|
|
|
|
# orthogonal initialization
|
|
|
|
torch.nn.init.orthogonal_(m.weight, gain=np.sqrt(2))
|
|
|
|
torch.nn.init.zeros_(m.bias)
|
|
|
|
# do last policy layer scaling, this will make initial actions have (close to)
|
|
|
|
# 0 mean and std, and will help boost performances,
|
|
|
|
# see https://arxiv.org/abs/2006.05990, Fig.24 for details
|
|
|
|
for m in actor.mu.modules():
|
|
|
|
if isinstance(m, torch.nn.Linear):
|
|
|
|
torch.nn.init.zeros_(m.bias)
|
|
|
|
m.weight.data.copy_(0.01 * m.weight.data)
|
|
|
|
|
2023-04-29 06:43:22 +02:00
|
|
|
optim = torch.optim.Adam(actor_critic.parameters(), lr=args.lr)
|
2021-03-30 11:50:35 +08:00
|
|
|
|
|
|
|
lr_scheduler = None
|
|
|
|
if args.lr_decay:
|
|
|
|
# decay learning rate to 0 linearly
|
2023-08-25 23:40:56 +02:00
|
|
|
max_update_num = np.ceil(args.step_per_epoch / args.step_per_collect) * args.epoch
|
2021-03-30 11:50:35 +08:00
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
lr_scheduler = LambdaLR(optim, lr_lambda=lambda epoch: 1 - epoch / max_update_num)
|
2021-03-30 11:50:35 +08:00
|
|
|
|
|
|
|
def dist(*logits):
|
|
|
|
return Independent(Normal(*logits), 1)
|
|
|
|
|
2021-09-03 05:05:04 +08:00
|
|
|
policy = PPOPolicy(
|
2023-10-08 17:57:03 +02:00
|
|
|
actor=actor,
|
|
|
|
critic=critic,
|
|
|
|
optim=optim,
|
|
|
|
dist_fn=dist,
|
2021-09-03 05:05:04 +08:00
|
|
|
discount_factor=args.gamma,
|
|
|
|
gae_lambda=args.gae_lambda,
|
|
|
|
max_grad_norm=args.max_grad_norm,
|
|
|
|
vf_coef=args.vf_coef,
|
|
|
|
ent_coef=args.ent_coef,
|
|
|
|
reward_normalization=args.rew_norm,
|
|
|
|
action_scaling=True,
|
|
|
|
action_bound_method=args.bound_action_method,
|
|
|
|
lr_scheduler=lr_scheduler,
|
|
|
|
action_space=env.action_space,
|
|
|
|
eps_clip=args.eps_clip,
|
|
|
|
value_clip=args.value_clip,
|
|
|
|
dual_clip=args.dual_clip,
|
|
|
|
advantage_normalization=args.norm_adv,
|
2022-05-05 07:55:15 -04:00
|
|
|
recompute_advantage=args.recompute_adv,
|
2021-09-03 05:05:04 +08:00
|
|
|
)
|
2021-03-30 11:50:35 +08:00
|
|
|
|
|
|
|
# load a previous policy
|
|
|
|
if args.resume_path:
|
2022-05-05 07:55:15 -04:00
|
|
|
ckpt = torch.load(args.resume_path, map_location=args.device)
|
|
|
|
policy.load_state_dict(ckpt["model"])
|
|
|
|
train_envs.set_obs_rms(ckpt["obs_rms"])
|
|
|
|
test_envs.set_obs_rms(ckpt["obs_rms"])
|
2021-03-30 11:50:35 +08:00
|
|
|
print("Loaded agent from: ", args.resume_path)
|
|
|
|
|
|
|
|
# collector
|
|
|
|
if args.training_num > 1:
|
|
|
|
buffer = VectorReplayBuffer(args.buffer_size, len(train_envs))
|
|
|
|
else:
|
|
|
|
buffer = ReplayBuffer(args.buffer_size)
|
|
|
|
train_collector = Collector(policy, train_envs, buffer, exploration_noise=True)
|
|
|
|
test_collector = Collector(policy, test_envs)
|
2022-05-05 07:55:15 -04:00
|
|
|
|
2021-03-30 11:50:35 +08:00
|
|
|
# log
|
2022-05-05 07:55:15 -04:00
|
|
|
now = datetime.datetime.now().strftime("%y%m%d-%H%M%S")
|
|
|
|
args.algo_name = "ppo"
|
|
|
|
log_name = os.path.join(args.task, args.algo_name, str(args.seed), now)
|
|
|
|
log_path = os.path.join(args.logdir, log_name)
|
|
|
|
|
|
|
|
# logger
|
|
|
|
if args.logger == "wandb":
|
|
|
|
logger = WandbLogger(
|
|
|
|
save_interval=1,
|
|
|
|
name=log_name.replace(os.path.sep, "__"),
|
|
|
|
run_id=args.resume_id,
|
|
|
|
config=args,
|
|
|
|
project=args.wandb_project,
|
|
|
|
)
|
2021-03-30 11:50:35 +08:00
|
|
|
writer = SummaryWriter(log_path)
|
|
|
|
writer.add_text("args", str(args))
|
2022-05-05 07:55:15 -04:00
|
|
|
if args.logger == "tensorboard":
|
|
|
|
logger = TensorboardLogger(writer)
|
|
|
|
else: # wandb
|
|
|
|
logger.load(writer)
|
2021-03-30 11:50:35 +08:00
|
|
|
|
2022-03-21 16:29:27 -04:00
|
|
|
def save_best_fn(policy):
|
2022-05-05 07:55:15 -04:00
|
|
|
state = {"model": policy.state_dict(), "obs_rms": train_envs.get_obs_rms()}
|
|
|
|
torch.save(state, os.path.join(log_path, "policy.pth"))
|
2021-03-30 11:50:35 +08:00
|
|
|
|
|
|
|
if not args.watch:
|
|
|
|
# trainer
|
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
|
|
|
result = OnpolicyTrainer(
|
|
|
|
policy=policy,
|
|
|
|
train_collector=train_collector,
|
|
|
|
test_collector=test_collector,
|
|
|
|
max_epoch=args.epoch,
|
|
|
|
step_per_epoch=args.step_per_epoch,
|
|
|
|
repeat_per_collect=args.repeat_per_collect,
|
|
|
|
episode_per_test=args.test_num,
|
|
|
|
batch_size=args.batch_size,
|
2021-09-03 05:05:04 +08:00
|
|
|
step_per_collect=args.step_per_collect,
|
2022-03-21 16:29:27 -04:00
|
|
|
save_best_fn=save_best_fn,
|
2021-09-03 05:05:04 +08:00
|
|
|
logger=logger,
|
2022-05-05 07:55:15 -04:00
|
|
|
test_in_train=False,
|
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
|
|
|
).run()
|
2021-03-30 11:50:35 +08:00
|
|
|
pprint.pprint(result)
|
|
|
|
|
|
|
|
# Let's watch its performance!
|
|
|
|
policy.eval()
|
|
|
|
test_envs.seed(args.seed)
|
|
|
|
test_collector.reset()
|
|
|
|
result = test_collector.collect(n_episode=args.test_num, render=args.render)
|
|
|
|
print(f'Final reward: {result["rews"].mean()}, length: {result["lens"].mean()}')
|
|
|
|
|
|
|
|
|
2022-05-05 07:55:15 -04:00
|
|
|
if __name__ == "__main__":
|
2021-03-30 11:50:35 +08:00
|
|
|
test_ppo()
|