Skip to content

Commit 64af7ea

Browse files
authored
fix critical bugs in MAPolicy and docs update (#207)
- fix a bug in MAPolicy: `buffer.rew = Batch()` doesn't change `buffer.rew` (thanks mypy) - polish examples/box2d/bipedal_hardcore_sac.py - several docs update - format setup.py and bump version to 0.2.7
1 parent 380e9e9 commit 64af7ea

File tree

9 files changed

+41
-22
lines changed

9 files changed

+41
-22
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Here is Tianshou's other features:
3636
- Elegant framework, using only ~2000 lines of code
3737
- Support parallel environment simulation (synchronous or asynchronous) for all algorithms [Usage](https://tianshou.readthedocs.io/en/latest/tutorials/cheatsheet.html#parallel-sampling)
3838
- Support recurrent state representation in actor network and critic network (RNN-style training for POMDP) [Usage](https://tianshou.readthedocs.io/en/latest/tutorials/cheatsheet.html#rnn-style-training)
39-
- Support any type of environment state (e.g. a dict, a self-defined class, ...) [Usage](https://tianshou.readthedocs.io/en/latest/tutorials/cheatsheet.html#user-defined-environment-and-different-state-representation)
39+
- Support any type of environment state/action (e.g. a dict, a self-defined class, ...) [Usage](https://tianshou.readthedocs.io/en/latest/tutorials/cheatsheet.html#user-defined-environment-and-different-state-representation)
4040
- Support customized training process [Usage](https://tianshou.readthedocs.io/en/latest/tutorials/cheatsheet.html#customize-training-process)
4141
- Support n-step returns estimation and prioritized experience replay for all Q-learning based algorithms; GAE, nstep and PER are very fast thanks to numba jit function and vectorized numpy operation
4242
- Support multi-agent RL [Usage](https://tianshou.readthedocs.io/en/latest/tutorials/cheatsheet.html##multi-agent-reinforcement-learning)
@@ -74,8 +74,8 @@ $ pip install tianshou
7474
After installation, open your python console and type
7575

7676
```python
77-
import tianshou as ts
78-
print(ts.__version__)
77+
import tianshou
78+
print(tianshou.__version__)
7979
```
8080

8181
If no error occurs, you have successfully installed Tianshou.

docs/index.rst

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ Welcome to Tianshou!
2424
Here is Tianshou's other features:
2525

2626
* Elegant framework, using only ~2000 lines of code
27-
* Support parallel environment sampling for all algorithms: :ref:`parallel_sampling`
28-
* Support recurrent state representation in actor network and critic network (RNN-style training for POMDP): :ref:`rnn_training`
27+
* Support parallel environment simulation (synchronous or asynchronous) for all algorithms: :ref:`parallel_sampling`
28+
* Support recurrent state/action representation in actor network and critic network (RNN-style training for POMDP): :ref:`rnn_training`
2929
* Support any type of environment state (e.g. a dict, a self-defined class, ...): :ref:`self_defined_env`
3030
* Support customized training process: :ref:`customize_training`
31-
* Support n-step returns estimation :meth:`~tianshou.policy.BasePolicy.compute_nstep_return` and prioritized experience replay for all Q-learning based algorithms
31+
* Support n-step returns estimation :meth:`~tianshou.policy.BasePolicy.compute_nstep_return` and prioritized experience replay :class:`~tianshou.data.PrioritizedReplayBuffer` for all Q-learning based algorithms; GAE, nstep and PER are very fast thanks to numba jit function and vectorized numpy operation
3232
* Support multi-agent RL: :doc:`/tutorials/tictactoe`
3333

3434
中文文档位于 `https://tianshou.readthedocs.io/zh/latest/ <https://tianshou.readthedocs.io/zh/latest/>`_
@@ -63,8 +63,8 @@ If you use Anaconda or Miniconda, you can install Tianshou through the following
6363
After installation, open your python console and type
6464
::
6565

66-
import tianshou as ts
67-
print(ts.__version__)
66+
import tianshou
67+
print(tianshou.__version__)
6868

6969
If no error occurs, you have successfully installed Tianshou.
7070

examples/box2d/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Bipedal-Hardcore-SAC
2+
3+
- Our default choice: remove the done flag penalty, will soon converge to \~250 reward within 100 epochs (10M env steps, 3~4 hours, see the image below)
4+
- If the done penalty is not removed, it converges much slower than before, about 200 epochs (20M env steps) to reach the same performance (\~200 reward)
5+
- Action noise is only necessary in the beginning. It is a negative impact at the end of the training. Removing it can reach \~255 (our best result under the original env, no done penalty removed).
6+
7+
![](results/sac/BipedalHardcore.png)

examples/box2d/bipedal_hardcore_sac.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@ def get_args():
2424
parser.add_argument('--gamma', type=float, default=0.99)
2525
parser.add_argument('--tau', type=float, default=0.005)
2626
parser.add_argument('--alpha', type=float, default=0.1)
27-
parser.add_argument('--epoch', type=int, default=1000)
28-
parser.add_argument('--step-per-epoch', type=int, default=2400)
27+
parser.add_argument('--epoch', type=int, default=100)
28+
parser.add_argument('--step-per-epoch', type=int, default=10000)
2929
parser.add_argument('--collect-per-step', type=int, default=10)
3030
parser.add_argument('--batch-size', type=int, default=128)
3131
parser.add_argument('--layer-num', type=int, default=1)
3232
parser.add_argument('--training-num', type=int, default=8)
33-
parser.add_argument('--test-num', type=int, default=8)
33+
parser.add_argument('--test-num', type=int, default=100)
3434
parser.add_argument('--logdir', type=str, default='log')
3535
parser.add_argument('--render', type=float, default=0.)
3636
parser.add_argument('--rew-norm', type=int, default=0)
@@ -39,14 +39,14 @@ def get_args():
3939
parser.add_argument(
4040
'--device', type=str,
4141
default='cuda' if torch.cuda.is_available() else 'cpu')
42+
parser.add_argument('--resume_path', type=str, default=None)
4243
return parser.parse_args()
4344

4445

4546
class EnvWrapper(object):
4647
"""Env wrapper for reward scale, action repeat and action noise"""
4748

48-
def __init__(self, task, action_repeat=3,
49-
reward_scale=5, act_noise=0.3):
49+
def __init__(self, task, action_repeat=3, reward_scale=5, act_noise=0.3):
5050
self._env = gym.make(task)
5151
self.action_repeat = action_repeat
5252
self.reward_scale = reward_scale
@@ -70,8 +70,6 @@ def step(self, action):
7070

7171

7272
def test_sac_bipedal(args=get_args()):
73-
torch.set_num_threads(1) # we just need only one thread for NN
74-
7573
env = EnvWrapper(args.task)
7674

7775
def IsStop(reward):
@@ -118,6 +116,10 @@ def IsStop(reward):
118116
reward_normalization=args.rew_norm,
119117
ignore_done=args.ignore_done,
120118
estimation_step=args.n_step)
119+
# load a previous policy
120+
if args.resume_path:
121+
policy.load_state_dict(torch.load(args.resume_path))
122+
print("Loaded agent from: ", args.resume_path)
121123

122124
# collector
123125
train_collector = Collector(
@@ -135,7 +137,8 @@ def save_fn(policy):
135137
result = offpolicy_trainer(
136138
policy, train_collector, test_collector, args.epoch,
137139
args.step_per_epoch, args.collect_per_step, args.test_num,
138-
args.batch_size, stop_fn=IsStop, save_fn=save_fn, writer=writer)
140+
args.batch_size, stop_fn=IsStop, save_fn=save_fn, writer=writer,
141+
test_in_train=False)
139142

140143
if __name__ == '__main__':
141144
pprint.pprint(result)
39.8 KB
Loading

setup.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,19 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4+
import os
45
from setuptools import setup, find_packages
56

67

8+
def get_version() -> str:
9+
# https://packaging.python.org/guides/single-sourcing-package-version/
10+
init = open(os.path.join("tianshou", "__init__.py"), "r").read().split()
11+
return init[init.index("__version__") + 2][1:-1]
12+
13+
714
setup(
815
name='tianshou',
9-
version='0.2.6',
16+
version=get_version(),
1017
description='A Library for Deep Reinforcement Learning',
1118
long_description=open('README.md', encoding='utf8').read(),
1219
long_description_content_type='text/markdown',

tianshou/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
utils.pre_compile()
66

77

8-
__version__ = '0.2.6'
8+
__version__ = '0.2.7'
99

1010
__all__ = [
1111
'env',

tianshou/policy/imitation/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99

1010
class ImitationPolicy(BasePolicy):
11-
"""Implementation of vanilla imitation learning (for continuous action space).
11+
"""Implementation of vanilla imitation learning.
1212
1313
:param torch.nn.Module model: a model following the rules in
1414
:class:`~tianshou.policy.BasePolicy`. (s -> a)

tianshou/policy/multiagent/mapolicy.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def process_fn(self, batch: Batch, buffer: ReplayBuffer,
3636
# reward can be empty Batch (after initial reset) or nparray.
3737
has_rew = isinstance(buffer.rew, np.ndarray)
3838
if has_rew: # save the original reward in save_rew
39-
save_rew, buffer.rew = buffer.rew, Batch()
39+
# Since we do not override buffer.__setattr__, here we use _meta to
40+
# change buffer.rew, otherwise buffer.rew = Batch() has no effect.
41+
save_rew, buffer._meta.rew = buffer.rew, Batch()
4042
for policy in self.policies:
4143
agent_index = np.nonzero(batch.obs.agent_id == policy.agent_id)[0]
4244
if len(agent_index) == 0:
@@ -45,11 +47,11 @@ def process_fn(self, batch: Batch, buffer: ReplayBuffer,
4547
tmp_batch, tmp_indice = batch[agent_index], indice[agent_index]
4648
if has_rew:
4749
tmp_batch.rew = tmp_batch.rew[:, policy.agent_id - 1]
48-
buffer.rew = save_rew[:, policy.agent_id - 1]
50+
buffer._meta.rew = save_rew[:, policy.agent_id - 1]
4951
results[f'agent_{policy.agent_id}'] = \
5052
policy.process_fn(tmp_batch, buffer, tmp_indice)
5153
if has_rew: # restore from save_rew
52-
buffer.rew = save_rew
54+
buffer._meta.rew = save_rew
5355
return Batch(results)
5456

5557
def forward(self, batch: Batch,

0 commit comments

Comments
 (0)