Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add offline trainer and discrete BCQ algorithm #263

Merged
merged 29 commits into from
Jan 20, 2021
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
1cdc203
work
zhujl1991 Dec 15, 2020
ae8c12e
removing_comments
zhujl1991 Dec 15, 2020
b5eba6c
removing_comments
zhujl1991 Dec 15, 2020
5e6873e
format
zhujl1991 Dec 15, 2020
8035e8b
cleaning
zhujl1991 Dec 15, 2020
5c52a18
almost
zhujl1991 Dec 15, 2020
9bf02be
feedback
zhujl1991 Jan 5, 2021
288c154
lint
zhujl1991 Jan 5, 2021
6bc7ac7
Merge branch 'master' into work
Trinkle23897 Jan 6, 2021
7919fc6
Merge branch 'master' into work
Trinkle23897 Jan 6, 2021
48f0012
.
zhujl1991 Jan 6, 2021
9f76425
Merge branch 'work' of github.com:zhujl1991/tianshou into work
zhujl1991 Jan 6, 2021
f4b9aa6
resolve #269, #270
Trinkle23897 Jan 12, 2021
36a137c
update BCQPolicy and BCQN
Trinkle23897 Jan 12, 2021
2e22daf
runnable
Trinkle23897 Jan 13, 2021
e63cb50
polish
Trinkle23897 Jan 13, 2021
21705b7
fix unacessary relu layer in network
Trinkle23897 Jan 14, 2021
d8be9ed
final
Trinkle23897 Jan 14, 2021
8489d17
fix
Trinkle23897 Jan 14, 2021
c2cf972
add atari_bcq, still need check
Trinkle23897 Jan 15, 2021
a3b51a2
update examples
Trinkle23897 Jan 16, 2021
1d34109
Merge branch 'master' into work
Trinkle23897 Jan 16, 2021
667b2f8
tune eps code
Trinkle23897 Jan 16, 2021
04b1379
Merge branch 'work' of github.com:zhujl1991/tianshou into work
Trinkle23897 Jan 16, 2021
151fd0b
fix eps mask
Trinkle23897 Jan 16, 2021
705a919
Merge branch 'master' into work
Trinkle23897 Jan 20, 2021
5ef0c4c
fix test
Trinkle23897 Jan 20, 2021
a37a542
update readme
Trinkle23897 Jan 20, 2021
0b291de
trailing comma
Trinkle23897 Jan 20, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,4 @@ MUJOCO_LOG.TXT
*.zip
*.pstats
*.swp
*.pkl
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
- [Soft Actor-Critic (SAC)](https://arxiv.org/pdf/1812.05905.pdf)
- [Discrete Soft Actor-Critic (SAC-Discrete)](https://arxiv.org/pdf/1910.07207.pdf)
- Vanilla Imitation Learning
- [Discrete Batch-Constrained deep Q-Learning (BCQ-Discrete)](https://arxiv.org/pdf/1910.01708.pdf)
- [Prioritized Experience Replay (PER)](https://arxiv.org/pdf/1511.05952.pdf)
- [Generalized Advantage Estimator (GAE)](https://arxiv.org/pdf/1506.02438.pdf)
- [Posterior Sampling Reinforcement Learning (PSRL)](https://www.ece.uvic.ca/~bctill/papers/learning/Strens_2000.pdf)
Expand Down
3 changes: 2 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ Welcome to Tianshou!
* :class:`~tianshou.policy.TD3Policy` `Twin Delayed DDPG <https://arxiv.org/pdf/1802.09477.pdf>`_
* :class:`~tianshou.policy.SACPolicy` `Soft Actor-Critic <https://arxiv.org/pdf/1812.05905.pdf>`_
* :class:`~tianshou.policy.DiscreteSACPolicy` `Discrete Soft Actor-Critic <https://arxiv.org/pdf/1910.07207.pdf>`_
* :class:`~tianshou.policy.PSRLPolicy` `Posterior Sampling Reinforcement Learning <https://www.ece.uvic.ca/~bctill/papers/learning/Strens_2000.pdf>`_
* :class:`~tianshou.policy.ImitationPolicy` Imitation Learning
* :class:`~tianshou.policy.DiscreteBCQPolicy` `Discrete Batch-Constrained deep Q-Learning <https://arxiv.org/pdf/1910.01708.pdf>`_
* :class:`~tianshou.policy.PSRLPolicy` `Posterior Sampling Reinforcement Learning <https://www.ece.uvic.ca/~bctill/papers/learning/Strens_2000.pdf>`_
* :class:`~tianshou.data.PrioritizedReplayBuffer` `Prioritized Experience Replay <https://arxiv.org/pdf/1511.05952.pdf>`_
* :meth:`~tianshou.policy.BasePolicy.compute_episodic_return` `Generalized Advantage Estimator <https://arxiv.org/pdf/1506.02438.pdf>`_

Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/concepts.rst
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ Trainer

Once you have a collector and a policy, you can start writing the training method for your RL agent. Trainer, to be honest, is a simple wrapper. It helps you save energy for writing the training loop. You can also construct your own trainer: :ref:`customized_trainer`.

Tianshou has two types of trainer: :func:`~tianshou.trainer.onpolicy_trainer` and :func:`~tianshou.trainer.offpolicy_trainer`, corresponding to on-policy algorithms (such as Policy Gradient) and off-policy algorithms (such as DQN). Please check out :doc:`/api/tianshou.trainer` for the usage.
Tianshou has three types of trainer: :func:`~tianshou.trainer.onpolicy_trainer` for on-policy algorithms such as Policy Gradient, :func:`~tianshou.trainer.offpolicy_trainer` for off-policy algorithms such as DQN, and :func:`~tianshou.trainer.offline_trainer` for offline algorithms such as BCQ. Please check out :doc:`/api/tianshou.trainer` for the usage.


.. _pseudocode:
Expand Down
4 changes: 2 additions & 2 deletions docs/tutorials/dqn.rst
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ In each step, the collector will let the policy perform (at least) a specified n
Train Policy with a Trainer
---------------------------

Tianshou provides :class:`~tianshou.trainer.onpolicy_trainer` and :class:`~tianshou.trainer.offpolicy_trainer`. The trainer will automatically stop training when the policy reach the stop condition ``stop_fn`` on test collector. Since DQN is an off-policy algorithm, we use the :class:`~tianshou.trainer.offpolicy_trainer` as follows:
Tianshou provides :func:`~tianshou.trainer.onpolicy_trainer`, :func:`~tianshou.trainer.offpolicy_trainer`, and :func:`~tianshou.trainer.offline_trainer`. The trainer will automatically stop training when the policy reach the stop condition ``stop_fn`` on test collector. Since DQN is an off-policy algorithm, we use the :func:`~tianshou.trainer.offpolicy_trainer` as follows:
::

result = ts.trainer.offpolicy_trainer(
Expand All @@ -133,7 +133,7 @@ Tianshou provides :class:`~tianshou.trainer.onpolicy_trainer` and :class:`~tians
writer=None)
print(f'Finished training! Use {result["duration"]}')

The meaning of each parameter is as follows (full description can be found at :meth:`~tianshou.trainer.offpolicy_trainer`):
The meaning of each parameter is as follows (full description can be found at :func:`~tianshou.trainer.offpolicy_trainer`):

* ``max_epoch``: The maximum of epochs for training. The training process might be finished before reaching the ``max_epoch``;
* ``step_per_epoch``: The number of step for updating policy network in one epoch;
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def get_version() -> str:
"tensorboard",
"torch>=1.4.0",
"numba>=0.51.0",
"h5py>=3.1.0"
"h5py>=2.10.0", # to match tensorflow's minimal requirements
],
extras_require={
"dev": [
Expand Down
11 changes: 11 additions & 0 deletions test/discrete/test_dqn.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import gym
import torch
import pickle
import pprint
import argparse
import numpy as np
Expand Down Expand Up @@ -36,6 +37,9 @@ def get_args():
parser.add_argument('--prioritized-replay', type=int, default=0)
parser.add_argument('--alpha', type=float, default=0.6)
parser.add_argument('--beta', type=float, default=0.4)
parser.add_argument(
'--save-buffer-name', type=str,
default="./expert_DQN_CartPole-v0.pkl")
parser.add_argument(
'--device', type=str,
default='cuda' if torch.cuda.is_available() else 'cpu')
Expand Down Expand Up @@ -110,6 +114,7 @@ def test_fn(epoch, env_step):
stop_fn=stop_fn, save_fn=save_fn, writer=writer)

assert stop_fn(result['best_reward'])

if __name__ == '__main__':
pprint.pprint(result)
# Let's watch its performance!
Expand All @@ -120,6 +125,12 @@ def test_fn(epoch, env_step):
result = collector.collect(n_episode=1, render=args.render)
print(f'Final reward: {result["rew"]}, length: {result["len"]}')

# save buffer in pickle format, for imitation learning unittest
buf = ReplayBuffer(args.buffer_size)
collector = Collector(policy, test_envs, buf)
collector.collect(n_step=args.buffer_size)
pickle.dump(buf, open(args.save_buffer_name, "wb"))


def test_pdqn(args=get_args()):
args.prioritized_replay = 1
Expand Down
114 changes: 114 additions & 0 deletions test/discrete/test_il_bcq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import os
import gym
import torch
import pickle
import pprint
import argparse
import numpy as np
from torch.utils.tensorboard import SummaryWriter

from tianshou.data import Collector
from tianshou.env import DummyVectorEnv
from tianshou.utils.net.common import Net
from tianshou.trainer import offline_trainer
from tianshou.policy import DiscreteBCQPolicy


def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--task", type=str, default="CartPole-v0")
parser.add_argument("--seed", type=int, default=1626)
parser.add_argument("--eps-test", type=float, default=0.001)
parser.add_argument("--lr", type=float, default=3e-4)
parser.add_argument("--gamma", type=float, default=0.9)
parser.add_argument("--n-step", type=int, default=3)
parser.add_argument("--target-update-freq", type=int, default=320)
parser.add_argument("--unlikely-action-threshold", type=float, default=0.3)
parser.add_argument("--imitation-logits-penalty", type=float, default=0.01)
parser.add_argument("--epoch", type=int, default=5)
parser.add_argument("--step-per-epoch", type=int, default=1000)
zhujl1991 marked this conversation as resolved.
Show resolved Hide resolved
parser.add_argument("--batch-size", type=int, default=64)
parser.add_argument("--layer-num", type=int, default=2)
parser.add_argument("--hidden-layer-size", type=int, default=128)
parser.add_argument("--test-num", type=int, default=100)
parser.add_argument("--logdir", type=str, default="log")
parser.add_argument("--render", type=float, default=0.)
parser.add_argument(
"--load-buffer-name", type=str,
default="./expert_DQN_CartPole-v0.pkl",
)
parser.add_argument(
"--device", type=str,
default="cuda" if torch.cuda.is_available() else "cpu",
)
args = parser.parse_known_args()[0]
return args


def test_discrete_bcq(args=get_args()):
# envs
env = gym.make(args.task)
args.state_shape = env.observation_space.shape or env.observation_space.n
args.action_shape = env.action_space.shape or env.action_space.n
test_envs = DummyVectorEnv(
[lambda: gym.make(args.task) for _ in range(args.test_num)])
# seed
np.random.seed(args.seed)
torch.manual_seed(args.seed)
test_envs.seed(args.seed)
# model
policy_net = Net(
args.layer_num, args.state_shape, args.action_shape, args.device,
hidden_layer_size=args.hidden_layer_size,
).to(args.device)
imitation_net = Net(
args.layer_num, args.state_shape, args.action_shape, args.device,
hidden_layer_size=args.hidden_layer_size,
).to(args.device)
optim = torch.optim.Adam(
list(policy_net.parameters()) + list(imitation_net.parameters()),
lr=args.lr
)

policy = DiscreteBCQPolicy(
policy_net, imitation_net, optim, args.gamma, args.n_step,
args.target_update_freq, args.eps_test,
args.unlikely_action_threshold, args.imitation_logits_penalty,
)
# buffer
assert os.path.exists(args.load_buffer_name), \
"Please run test_dqn.py first to get expert's data buffer."
buffer = pickle.load(open(args.load_buffer_name, "rb"))

# collector
test_collector = Collector(policy, test_envs)

log_path = os.path.join(args.logdir, args.task, 'discrete_bcq')
writer = SummaryWriter(log_path)

def save_fn(policy):
torch.save(policy.state_dict(), os.path.join(log_path, 'policy.pth'))

def stop_fn(mean_rewards):
return mean_rewards >= env.spec.reward_threshold

result = offline_trainer(
policy, buffer, test_collector,
args.epoch, args.step_per_epoch, args.test_num, args.batch_size,
stop_fn=stop_fn, save_fn=save_fn, writer=writer,
Trinkle23897 marked this conversation as resolved.
Show resolved Hide resolved
)
assert stop_fn(result['best_reward'])

if __name__ == '__main__':
pprint.pprint(result)
# Let's watch its performance!
env = gym.make(args.task)
policy.eval()
policy.set_eps(args.eps_test)
collector = Collector(policy, env)
result = collector.collect(n_episode=1, render=args.render)
print(f'Final reward: {result["rew"]}, length: {result["len"]}')


if __name__ == "__main__":
test_discrete_bcq(get_args())
2 changes: 1 addition & 1 deletion tianshou/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from tianshou import data, env, utils, policy, trainer, exploration


__version__ = "0.3.0"
__version__ = "0.3.1"

__all__ = [
"env",
Expand Down
2 changes: 2 additions & 0 deletions tianshou/policy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from tianshou.policy.modelfree.td3 import TD3Policy
from tianshou.policy.modelfree.sac import SACPolicy
from tianshou.policy.modelfree.discrete_sac import DiscreteSACPolicy
from tianshou.policy.imitation.discrete_bcq import DiscreteBCQPolicy
from tianshou.policy.modelbase.psrl import PSRLPolicy
from tianshou.policy.multiagent.mapolicy import MultiAgentPolicyManager

Expand All @@ -27,6 +28,7 @@
"TD3Policy",
"SACPolicy",
"DiscreteSACPolicy",
"DiscreteBCQPolicy",
"PSRLPolicy",
"MultiAgentPolicyManager",
]
2 changes: 1 addition & 1 deletion tianshou/policy/imitation/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, float]:
a_ = to_torch(batch.act, dtype=torch.float32, device=a.device)
loss = F.mse_loss(a, a_) # type: ignore
elif self.mode == "discrete": # classification
a = self(batch).logits
a = F.log_softmax(self(batch).logits, dim=-1)
a_ = to_torch(batch.act, dtype=torch.long, device=a.device)
loss = F.nll_loss(a, a_) # type: ignore
loss.backward()
Expand Down
133 changes: 133 additions & 0 deletions tianshou/policy/imitation/discrete_bcq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import math
import torch
import numpy as np
import torch.nn.functional as F
from typing import Any, Dict, Union, Optional

from tianshou.policy import DQNPolicy
from tianshou.data import Batch, ReplayBuffer, to_torch


class DiscreteBCQPolicy(DQNPolicy):
"""Implementation of discrete BCQ algorithm. arXiv:1910.01708.

:param torch.nn.Module model: a model following the rules in
:class:`~tianshou.policy.BasePolicy`. (s -> q_value)
:param torch.nn.Module imitator: a model following the rules in
:class:`~tianshou.policy.BasePolicy`. (s -> imtation_logits)
:param torch.optim.Optimizer optim: a torch.optim for optimizing the model.
:param float discount_factor: in [0, 1].
:param int estimation_step: greater than 1, the number of steps to look
ahead.
:param int target_update_freq: the target network update frequency.
:param float eval_eps: the epsilon-greedy noise added in evaluation.
:param float unlikely_action_threshold: the threshold (tau) for unlikely
actions, as shown in Equ. (17) in the paper, defaults to 0.3.
:param float imitation_logits_penalty: reguralization weight for imitation
logits, defaults to 1e-2.
:param bool reward_normalization: normalize the reward to Normal(0, 1),
defaults to False.

.. seealso::

Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed
explanation.
"""

def __init__(
self,
model: torch.nn.Module,
imitator: torch.nn.Module,
optim: torch.optim.Optimizer,
discount_factor: float = 0.99,
estimation_step: int = 1,
target_update_freq: int = 8000,
eval_eps: float = 1e-3,
unlikely_action_threshold: float = 0.3,
imitation_logits_penalty: float = 1e-2,
reward_normalization: bool = False,
**kwargs: Any,
) -> None:
super().__init__(model, optim, discount_factor, estimation_step,
target_update_freq, reward_normalization, **kwargs)
assert target_update_freq > 0, "BCQ needs target network setting."
self.imitator = imitator
assert (
0.0 <= unlikely_action_threshold < 1.0
), "unlikely_action_threshold should be in [0, 1)"
self._log_tau = math.log(unlikely_action_threshold)
assert 0.0 <= eval_eps < 1.0
self._eps = eval_eps
Trinkle23897 marked this conversation as resolved.
Show resolved Hide resolved
self._weight_reg = imitation_logits_penalty

def train(self, mode: bool = True) -> "DiscreteBCQPolicy":
self.training = mode
self.model.train(mode)
self.imitator.train(mode)
return self

def _target_q(
self, buffer: ReplayBuffer, indice: np.ndarray
) -> torch.Tensor:
batch = buffer[indice] # batch.obs_next: s_{t+n}
# target_Q = Q_old(s_, argmax(Q_new(s_, *)))
with torch.no_grad():
act = self(batch, input="obs_next", eps=0.0).act
target_q, _ = self.model_old(batch.obs_next)
target_q = target_q[np.arange(len(act)), act]
return target_q

def forward( # type: ignore
self,
batch: Batch,
state: Optional[Union[dict, Batch, np.ndarray]] = None,
input: str = "obs",
eps: Optional[float] = None,
**kwargs: Any,
) -> Batch:
if eps is None:
eps = self._eps
obs = batch[input]
q_value, state = self.model(obs, state=state, info=batch.info)
imitation_logits, _ = self.imitator(obs, state=state, info=batch.info)

# mask actions for argmax
ratio = imitation_logits - imitation_logits.max(
dim=-1, keepdim=True).values
mask = (ratio < self._log_tau).float()
action = (q_value - np.inf * mask).argmax(dim=-1)

# add eps to act
if not np.isclose(eps, 0.0) and np.random.rand() < eps:
bsz, action_num = q_value.shape
action = np.random.randint(action_num, size=bsz)

return Batch(act=action, state=state, q_value=q_value,
imitation_logits=imitation_logits)

def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, float]:
if self._iter % self._freq == 0:
self.sync_weight()
self._iter += 1

target_q = batch.returns.flatten()
result = self(batch, eps=0.0)
imitation_logits = result.imitation_logits
current_q = result.q_value[np.arange(len(target_q)), batch.act]
act = to_torch(batch.act, dtype=torch.long, device=target_q.device)
q_loss = F.smooth_l1_loss(current_q, target_q)
i_loss = F.nll_loss(
F.log_softmax(imitation_logits, dim=-1), act) # type: ignore
reg_loss = imitation_logits.pow(2).mean()
loss = q_loss + i_loss + self._weight_reg * reg_loss

self.optim.zero_grad()
loss.backward()
self.optim.step()

return {
"loss": loss.item(),
"q_loss": q_loss.item(),
"i_loss": i_loss.item(),
"reg_loss": reg_loss.item(),
}
Loading