This PR adds strict typing to the output of `update` and `learn` in all
policies. This will likely be the last large refactoring PR before the
next release (0.6.0, not 1.0.0), so it requires some attention. Several
difficulties were encountered on the path to that goal:
1. The policy hierarchy is actually "broken" in the sense that the keys
of dicts that were output by `learn` did not follow the same enhancement
(inheritance) pattern as the policies. This is a real problem and should
be addressed in the near future. Generally, several aspects of the
policy design and hierarchy might deserve a dedicated discussion.
2. Each policy needs to be generic in the stats return type, because one
might want to extend it at some point and then also extend the stats.
Even within the source code base this pattern is necessary in many
places.
3. The interaction between learn and update is a bit quirky, we
currently handle it by having update modify special field inside
TrainingStats, whereas all other fields are handled by learn.
4. The IQM module is a policy wrapper and required a
TrainingStatsWrapper. The latter relies on a bunch of black magic.
They were addressed by:
1. Live with the broken hierarchy, which is now made visible by bounds
in generics. We use type: ignore where appropriate.
2. Make all policies generic with bounds following the policy
inheritance hierarchy (which is incorrect, see above). We experimented a
bit with nested TrainingStats classes, but that seemed to add more
complexity and be harder to understand. Unfortunately, mypy thinks that
the code below is wrong, wherefore we have to add `type: ignore` to the
return of each `learn`
```python
T = TypeVar("T", bound=int)
def f() -> T:
return 3
```
3. See above
4. Write representative tests for the `TrainingStatsWrapper`. Still, the
black magic might cause nasty surprises down the line (I am not proud of
it)...
Closes #933
---------
Co-authored-by: Maximilian Huettenrauch <m.huettenrauch@appliedai.de>
Co-authored-by: Michael Panchenko <m.panchenko@appliedai.de>
176 lines
5.8 KiB
Python
176 lines
5.8 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
import datetime
|
|
import os
|
|
import pickle
|
|
import pprint
|
|
import sys
|
|
|
|
import numpy as np
|
|
import torch
|
|
from torch.utils.tensorboard import SummaryWriter
|
|
|
|
from examples.atari.atari_network import DQN
|
|
from examples.atari.atari_wrapper import make_atari_env
|
|
from examples.offline.utils import load_buffer
|
|
from tianshou.data import Collector, VectorReplayBuffer
|
|
from tianshou.policy import ImitationPolicy
|
|
from tianshou.trainer import OfflineTrainer
|
|
from tianshou.utils import TensorboardLogger, WandbLogger
|
|
|
|
|
|
def get_args():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--task", type=str, default="PongNoFrameskip-v4")
|
|
parser.add_argument("--seed", type=int, default=1626)
|
|
parser.add_argument("--lr", type=float, default=0.0001)
|
|
parser.add_argument("--epoch", type=int, default=100)
|
|
parser.add_argument("--update-per-epoch", type=int, default=10000)
|
|
parser.add_argument("--batch-size", type=int, default=32)
|
|
parser.add_argument("--test-num", type=int, default=10)
|
|
parser.add_argument("--frames-stack", type=int, default=4)
|
|
parser.add_argument("--scale-obs", type=int, default=0)
|
|
parser.add_argument("--logdir", type=str, default="log")
|
|
parser.add_argument("--render", type=float, default=0.0)
|
|
parser.add_argument("--resume-path", type=str, default=None)
|
|
parser.add_argument("--resume-id", type=str, default=None)
|
|
parser.add_argument(
|
|
"--logger",
|
|
type=str,
|
|
default="tensorboard",
|
|
choices=["tensorboard", "wandb"],
|
|
)
|
|
parser.add_argument("--wandb-project", type=str, default="offline_atari.benchmark")
|
|
parser.add_argument(
|
|
"--watch",
|
|
default=False,
|
|
action="store_true",
|
|
help="watch the play of pre-trained policy only",
|
|
)
|
|
parser.add_argument("--log-interval", type=int, default=100)
|
|
parser.add_argument(
|
|
"--load-buffer-name",
|
|
type=str,
|
|
default="./expert_DQN_PongNoFrameskip-v4.hdf5",
|
|
)
|
|
parser.add_argument("--buffer-from-rl-unplugged", action="store_true", default=False)
|
|
parser.add_argument(
|
|
"--device",
|
|
type=str,
|
|
default="cuda" if torch.cuda.is_available() else "cpu",
|
|
)
|
|
return parser.parse_known_args()[0]
|
|
|
|
|
|
def test_il(args=get_args()):
|
|
# envs
|
|
env, _, test_envs = make_atari_env(
|
|
args.task,
|
|
args.seed,
|
|
1,
|
|
args.test_num,
|
|
scale=args.scale_obs,
|
|
frame_stack=args.frames_stack,
|
|
)
|
|
args.state_shape = env.observation_space.shape or env.observation_space.n
|
|
args.action_shape = env.action_space.shape or env.action_space.n
|
|
# should be N_FRAMES x H x W
|
|
print("Observations shape:", args.state_shape)
|
|
print("Actions shape:", args.action_shape)
|
|
# seed
|
|
np.random.seed(args.seed)
|
|
torch.manual_seed(args.seed)
|
|
# model
|
|
net = DQN(*args.state_shape, args.action_shape, device=args.device).to(args.device)
|
|
optim = torch.optim.Adam(net.parameters(), lr=args.lr)
|
|
# define policy
|
|
policy = ImitationPolicy(actor=net, optim=optim, action_space=env.action_space)
|
|
# load a previous policy
|
|
if args.resume_path:
|
|
policy.load_state_dict(torch.load(args.resume_path, map_location=args.device))
|
|
print("Loaded agent from: ", args.resume_path)
|
|
# buffer
|
|
if args.buffer_from_rl_unplugged:
|
|
buffer = load_buffer(args.load_buffer_name)
|
|
else:
|
|
assert os.path.exists(
|
|
args.load_buffer_name,
|
|
), "Please run atari_dqn.py first to get expert's data buffer."
|
|
if args.load_buffer_name.endswith(".pkl"):
|
|
with open(args.load_buffer_name, "rb") as f:
|
|
buffer = pickle.load(f)
|
|
elif args.load_buffer_name.endswith(".hdf5"):
|
|
buffer = VectorReplayBuffer.load_hdf5(args.load_buffer_name)
|
|
else:
|
|
print(f"Unknown buffer format: {args.load_buffer_name}")
|
|
sys.exit(0)
|
|
print("Replay buffer size:", len(buffer), flush=True)
|
|
|
|
# collector
|
|
test_collector = Collector(policy, test_envs, exploration_noise=True)
|
|
|
|
# log
|
|
now = datetime.datetime.now().strftime("%y%m%d-%H%M%S")
|
|
args.algo_name = "il"
|
|
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,
|
|
)
|
|
writer = SummaryWriter(log_path)
|
|
writer.add_text("args", str(args))
|
|
if args.logger == "tensorboard":
|
|
logger = TensorboardLogger(writer)
|
|
else: # wandb
|
|
logger.load(writer)
|
|
|
|
def save_best_fn(policy):
|
|
torch.save(policy.state_dict(), os.path.join(log_path, "policy.pth"))
|
|
|
|
def stop_fn(mean_rewards):
|
|
return False
|
|
|
|
# watch agent's performance
|
|
def watch():
|
|
print("Setup test envs ...")
|
|
policy.eval()
|
|
test_envs.seed(args.seed)
|
|
print("Testing agent ...")
|
|
test_collector.reset()
|
|
result = test_collector.collect(n_episode=args.test_num, render=args.render)
|
|
pprint.pprint(result)
|
|
rew = result.returns_stat.mean
|
|
print(f"Mean reward (over {result.n_collected_episodes} episodes): {rew}")
|
|
|
|
if args.watch:
|
|
watch()
|
|
sys.exit(0)
|
|
|
|
result = OfflineTrainer(
|
|
policy=policy,
|
|
buffer=buffer,
|
|
test_collector=test_collector,
|
|
max_epoch=args.epoch,
|
|
step_per_epoch=args.update_per_epoch,
|
|
episode_per_test=args.test_num,
|
|
batch_size=args.batch_size,
|
|
stop_fn=stop_fn,
|
|
save_best_fn=save_best_fn,
|
|
logger=logger,
|
|
).run()
|
|
|
|
pprint.pprint(result)
|
|
watch()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
test_il(get_args())
|