Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.1.0 to 2.2.2. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/urllib3/urllib3/releases">urllib3's releases</a>.</em></p> <blockquote> <h2>2.2.2</h2> <h2>🚀 urllib3 is fundraising for HTTP/2 support</h2> <p><a href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3 is raising ~$40,000 USD</a> to release HTTP/2 support and ensure long-term sustainable maintenance of the project after a sharp decline in financial support for 2023. If your company or organization uses Python and would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and thousands of other projects <a href="https://opencollective.com/urllib3">please consider contributing financially</a> to ensure HTTP/2 support is developed sustainably and maintained for the long-haul.</p> <p>Thank you for your support.</p> <h2>Changes</h2> <ul> <li>Added the <code>Proxy-Authorization</code> header to the list of headers to strip from requests when redirecting to a different host. As before, different headers can be set via <code>Retry.remove_headers_on_redirect</code>.</li> <li>Allowed passing negative integers as <code>amt</code> to read methods of <code>http.client.HTTPResponse</code> as an alternative to <code>None</code>. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3122">#3122</a>)</li> <li>Fixed return types representing copying actions to use <code>typing.Self</code>. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3363">#3363</a>)</li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/urllib3/urllib3/compare/2.2.1...2.2.2">https://github.com/urllib3/urllib3/compare/2.2.1...2.2.2</a></p> <h2>2.2.1</h2> <h2>🚀 urllib3 is fundraising for HTTP/2 support</h2> <p><a href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3 is raising ~$40,000 USD</a> to release HTTP/2 support and ensure long-term sustainable maintenance of the project after a sharp decline in financial support for 2023. If your company or organization uses Python and would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and thousands of other projects <a href="https://opencollective.com/urllib3">please consider contributing financially</a> to ensure HTTP/2 support is developed sustainably and maintained for the long-haul.</p> <p>Thank you for your support.</p> <h2>Changes</h2> <ul> <li>Fixed issue where <code>InsecureRequestWarning</code> was emitted for HTTPS connections when using Emscripten. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3331">#3331</a>)</li> <li>Fixed <code>HTTPConnectionPool.urlopen</code> to stop automatically casting non-proxy headers to <code>HTTPHeaderDict</code>. This change was premature as it did not apply to proxy headers and <code>HTTPHeaderDict</code> does not handle byte header values correctly yet. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3343">#3343</a>)</li> <li>Changed <code>ProtocolError</code> to <code>InvalidChunkLength</code> when response terminates before the chunk length is sent. (<a href="https://redirect.github.com/urllib3/urllib3/issues/2860">#2860</a>)</li> <li>Changed <code>ProtocolError</code> to be more verbose on incomplete reads with excess content. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3261">#3261</a>)</li> </ul> <h2>2.2.0</h2> <h2>🖥️ urllib3 now works in the browser</h2> <p>🎉 <strong>This release adds experimental support for <a href="https://urllib3.readthedocs.io/en/stable/reference/contrib/emscripten.html">using urllib3 in the browser with Pyodide</a>!</strong> 🎉</p> <p>Thanks to Joe Marshall (<a href="https://github.com/joemarshall"><code>@joemarshall</code></a>) for contributing this feature. This change was possible thanks to work done in urllib3 v2.0 to detach our API from <code>http.client</code>. Please report all bugs to the <a href="https://github.com/urllib3/urllib3/issues">urllib3 issue tracker</a>.</p> <h2>🚀 urllib3 is fundraising for HTTP/2 support</h2> <p><a href="https://sethmlarson.dev/urllib3-is-fundraising-for-http2-support">urllib3 is raising ~$40,000 USD</a> to release HTTP/2 support and ensure long-term sustainable maintenance of the project after a sharp decline in financial support for 2023. If your company or organization uses Python and would benefit from HTTP/2 support in Requests, pip, cloud SDKs, and thousands of other projects <a href="https://opencollective.com/urllib3">please consider contributing financially</a> to ensure HTTP/2 support is developed sustainably and maintained for the long-haul.</p> <p>Thank you for your support.</p> <h2>Changes</h2> <ul> <li>Added support for <a href="https://urllib3.readthedocs.io/en/latest/reference/contrib/emscripten.html">Emscripten and Pyodide</a>, including streaming support in cross-origin isolated browser environments where threading is enabled. (<a href="https://redirect.github.com/urllib3/urllib3/issues/2951">#2951</a>)</li> <li>Added support for <code>HTTPResponse.read1()</code> method. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3186">#3186</a>)</li> <li>Added rudimentary support for HTTP/2. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3284">#3284</a>)</li> <li>Fixed issue where requests against urls with trailing dots were failing due to SSL errors when using proxy. (<a href="https://redirect.github.com/urllib3/urllib3/issues/2244">#2244</a>)</li> <li>Fixed <code>HTTPConnection.proxy_is_verified</code> and <code>HTTPSConnection.proxy_is_verified</code> to be always set to a boolean after connecting to a proxy. It could be <code>None</code> in some cases previously. (<a href="https://redirect.github.com/urllib3/urllib3/issues/3130">#3130</a>)</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/urllib3/urllib3/blob/main/CHANGES.rst">urllib3's changelog</a>.</em></p> <blockquote> <h1>2.2.2 (2024-06-17)</h1> <ul> <li>Added the <code>Proxy-Authorization</code> header to the list of headers to strip from requests when redirecting to a different host. As before, different headers can be set via <code>Retry.remove_headers_on_redirect</code>.</li> <li>Allowed passing negative integers as <code>amt</code> to read methods of <code>http.client.HTTPResponse</code> as an alternative to <code>None</code>. (<code>[#3122](https://github.com/urllib3/urllib3/issues/3122) <https://github.com/urllib3/urllib3/issues/3122></code>__)</li> <li>Fixed return types representing copying actions to use <code>typing.Self</code>. (<code>[#3363](https://github.com/urllib3/urllib3/issues/3363) <https://github.com/urllib3/urllib3/issues/3363></code>__)</li> </ul> <h1>2.2.1 (2024-02-16)</h1> <ul> <li>Fixed issue where <code>InsecureRequestWarning</code> was emitted for HTTPS connections when using Emscripten. (<code>[#3331](https://github.com/urllib3/urllib3/issues/3331) <https://github.com/urllib3/urllib3/issues/3331></code>__)</li> <li>Fixed <code>HTTPConnectionPool.urlopen</code> to stop automatically casting non-proxy headers to <code>HTTPHeaderDict</code>. This change was premature as it did not apply to proxy headers and <code>HTTPHeaderDict</code> does not handle byte header values correctly yet. (<code>[#3343](https://github.com/urllib3/urllib3/issues/3343) <https://github.com/urllib3/urllib3/issues/3343></code>__)</li> <li>Changed <code>InvalidChunkLength</code> to <code>ProtocolError</code> when response terminates before the chunk length is sent. (<code>[#2860](https://github.com/urllib3/urllib3/issues/2860) <https://github.com/urllib3/urllib3/issues/2860></code>__)</li> <li>Changed <code>ProtocolError</code> to be more verbose on incomplete reads with excess content. (<code>[#3261](https://github.com/urllib3/urllib3/issues/3261) <https://github.com/urllib3/urllib3/issues/3261></code>__)</li> </ul> <h1>2.2.0 (2024-01-30)</h1> <ul> <li>Added support for <code>Emscripten and Pyodide <https://urllib3.readthedocs.io/en/latest/reference/contrib/emscripten.html></code><strong>, including streaming support in cross-origin isolated browser environments where threading is enabled. (<code>[#2951](https://github.com/urllib3/urllib3/issues/2951) <https://github.com/urllib3/urllib3/issues/2951></code></strong>)</li> <li>Added support for <code>HTTPResponse.read1()</code> method. (<code>[#3186](https://github.com/urllib3/urllib3/issues/3186) <https://github.com/urllib3/urllib3/issues/3186></code>__)</li> <li>Added rudimentary support for HTTP/2. (<code>[#3284](https://github.com/urllib3/urllib3/issues/3284) <https://github.com/urllib3/urllib3/issues/3284></code>__)</li> <li>Fixed issue where requests against urls with trailing dots were failing due to SSL errors when using proxy. (<code>[#2244](https://github.com/urllib3/urllib3/issues/2244) <https://github.com/urllib3/urllib3/issues/2244></code>__)</li> <li>Fixed <code>HTTPConnection.proxy_is_verified</code> and <code>HTTPSConnection.proxy_is_verified</code> to be always set to a boolean after connecting to a proxy. It could be <code>None</code> in some cases previously. (<code>[#3130](https://github.com/urllib3/urllib3/issues/3130) <https://github.com/urllib3/urllib3/issues/3130></code>__)</li> <li>Fixed an issue where <code>headers</code> passed in a request with <code>json=</code> would be mutated (<code>[#3203](https://github.com/urllib3/urllib3/issues/3203) <https://github.com/urllib3/urllib3/issues/3203></code>__)</li> <li>Fixed <code>HTTPSConnection.is_verified</code> to be set to <code>False</code> when connecting from a HTTPS proxy to an HTTP target. It was set to <code>True</code> previously. (<code>[#3267](https://github.com/urllib3/urllib3/issues/3267) <https://github.com/urllib3/urllib3/issues/3267></code>__)</li> <li>Fixed handling of new error message from OpenSSL 3.2.0 when configuring an HTTP proxy as HTTPS (<code>[#3268](https://github.com/urllib3/urllib3/issues/3268) <https://github.com/urllib3/urllib3/issues/3268></code>__)</li> <li>Fixed TLS 1.3 post-handshake auth when the server certificate validation is disabled (<code>[#3325](https://github.com/urllib3/urllib3/issues/3325) <https://github.com/urllib3/urllib3/issues/3325></code>__)</li> <li>Note for downstream distributors: To run integration tests, you now need to run the tests a second time with the <code>--integration</code> pytest flag. (<code>[#3181](https://github.com/urllib3/urllib3/issues/3181) <https://github.com/urllib3/urllib3/issues/3181></code>__)</li> </ul> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="27e2a5c5a7
"><code>27e2a5c</code></a> Release 2.2.2 (<a href="https://redirect.github.com/urllib3/urllib3/issues/3406">#3406</a>)</li> <li><a href="accff72ecc
"><code>accff72</code></a> Merge pull request from GHSA-34jh-p97f-mpxf</li> <li><a href="34be4a57e5
"><code>34be4a5</code></a> Pin CFFI to a new release candidate instead of a Git commit (<a href="https://redirect.github.com/urllib3/urllib3/issues/3398">#3398</a>)</li> <li><a href="da410581b6
"><code>da41058</code></a> Bump browser-actions/setup-chrome from 1.6.0 to 1.7.1 (<a href="https://redirect.github.com/urllib3/urllib3/issues/3399">#3399</a>)</li> <li><a href="b07a669bd9
"><code>b07a669</code></a> Bump github/codeql-action from 2.13.4 to 3.25.6 (<a href="https://redirect.github.com/urllib3/urllib3/issues/3396">#3396</a>)</li> <li><a href="b8589ec9f8
"><code>b8589ec</code></a> Measure coverage with v4 of artifact actions (<a href="https://redirect.github.com/urllib3/urllib3/issues/3394">#3394</a>)</li> <li><a href="f3bdc55851
"><code>f3bdc55</code></a> Allow triggering CI manually (<a href="https://redirect.github.com/urllib3/urllib3/issues/3391">#3391</a>)</li> <li><a href="52392654b3
"><code>5239265</code></a> Fix HTTP version in debug log (<a href="https://redirect.github.com/urllib3/urllib3/issues/3316">#3316</a>)</li> <li><a href="b34619f94e
"><code>b34619f</code></a> Bump actions/checkout to 4.1.4 (<a href="https://redirect.github.com/urllib3/urllib3/issues/3387">#3387</a>)</li> <li><a href="9961d14de7
"><code>9961d14</code></a> Bump browser-actions/setup-chrome from 1.5.0 to 1.6.0 (<a href="https://redirect.github.com/urllib3/urllib3/issues/3386">#3386</a>)</li> <li>Additional commits viewable in <a href="https://github.com/urllib3/urllib3/compare/2.1.0...2.2.2">compare view</a></li> </ul> </details> <br /> [](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/thu-ml/tianshou/network/alerts). </details> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Tianshou (天授) is a reinforcement learning platform based on pure PyTorch and Gymnasium. Unlike other reinforcement learning libraries, which may have complex codebases, unfriendly high-level APIs, or are not optimized for speed, Tianshou provides a high-performance, modularized framework and user-friendly interfaces for building deep reinforcement learning agents. One more aspect that sets Tianshou apart is its generality: it supports online and offline RL, multi-agent RL, and model-based algorithms.
Tianshou aims at enabling concise implementations, both for researchers and practitioners, without sacrificing flexibility.
Supported algorithms include:
- Deep Q-Network (DQN)
- Double DQN
- Dueling DQN
- Branching DQN
- Categorical DQN (C51)
- Rainbow DQN (Rainbow)
- Quantile Regression DQN (QRDQN)
- Implicit Quantile Network (IQN)
- Fully-parameterized Quantile Function (FQF)
- Policy Gradient (PG)
- Natural Policy Gradient (NPG)
- Advantage Actor-Critic (A2C)
- Trust Region Policy Optimization (TRPO)
- Proximal Policy Optimization (PPO)
- Deep Deterministic Policy Gradient (DDPG)
- Twin Delayed DDPG (TD3)
- Soft Actor-Critic (SAC)
- Randomized Ensembled Double Q-Learning (REDQ)
- Discrete Soft Actor-Critic (SAC-Discrete)
- Vanilla Imitation Learning
- Batch-Constrained deep Q-Learning (BCQ)
- Conservative Q-Learning (CQL)
- Twin Delayed DDPG with Behavior Cloning (TD3+BC)
- Discrete Batch-Constrained deep Q-Learning (BCQ-Discrete)
- Discrete Conservative Q-Learning (CQL-Discrete)
- Discrete Critic Regularized Regression (CRR-Discrete)
- Generative Adversarial Imitation Learning (GAIL)
- Prioritized Experience Replay (PER)
- Generalized Advantage Estimator (GAE)
- Posterior Sampling Reinforcement Learning (PSRL)
- Intrinsic Curiosity Module (ICM)
- Hindsight Experience Replay (HER)
Other noteworthy features:
- Elegant framework with dual APIs:
- Tianshou's high-level API maximizes ease of use for application development while still retaining a high degree of flexibility.
- The fundamental procedural API provides a maximum of flexibility for algorithm development without being overly verbose.
- State-of-the-art results in MuJoCo benchmarks for REINFORCE/A2C/TRPO/PPO/DDPG/TD3/SAC algorithms
- Support for vectorized environments (synchronous or asynchronous) for all algorithms (see usage)
- Support for super-fast vectorized environments based on EnvPool for all algorithms (see usage)
- Support for recurrent state representations in actor networks and critic networks (RNN-style training for POMDPs) (see usage)
- Support any type of environment state/action (e.g. a dict, a self-defined class, ...) Usage
- Support for customized training processes (see usage)
- Support n-step returns estimation and prioritized experience replay for all Q-learning based algorithms; GAE, nstep and PER are highly optimized thanks to numba's just-in-time compilation and vectorized numpy operations
- Support for multi-agent RL (see usage)
- Support for logging based on both TensorBoard and W&B
- Support for multi-GPU training (see usage)
- Comprehensive documentation, PEP8 code-style checking, type checking and thorough tests
In Chinese, Tianshou means divinely ordained, being derived to the gift of being born. Tianshou is a reinforcement learning platform, and the nature of RL is not learn from humans. So taking "Tianshou" means that there is no teacher to learn from, but rather to learn by oneself through constant interaction with the environment.
“天授”意指上天所授,引申为与生具有的天赋。天授是强化学习平台,而强化学习算法并不是向人类学习的,所以取“天授”意思是没有老师来教,而是自己通过跟环境不断交互来进行学习。
Installation
Tianshou is currently hosted on PyPI and conda-forge. It requires Python >= 3.11.
For installing the most recent version of Tianshou, the best way is clone the repository and install it with poetry (which you need to install on your system first)
git clone git@github.com:thu-ml/tianshou.git
cd tianshou
poetry install
You can also install the dev requirements by adding --with dev
or the extras
for say mujoco and acceleration by envpool
by adding --extras "mujoco envpool"
If you wish to install multiple extras, ensure that you include them in a single command. Sequential calls to poetry install --extras xxx
will overwrite prior installations, leaving only the last specified extras installed.
Or you may install all the following extras by adding --all-extras
.
Available extras are:
atari
(for Atari environments)box2d
(for Box2D environments)classic_control
(for classic control (discrete) environments)mujoco
(for MuJoCo environments)mujoco-py
(for legacy mujoco-py environments1)pybullet
(for pybullet environments)robotics
(for gymnasium-robotics environments)vizdoom
(for ViZDoom environments)envpool
(for envpool integration)argparse
(in order to be able to run the high level API examples)
Otherwise, you can install the latest release from PyPI (currently far behind the master) with the following command:
$ pip install tianshou
If you are using Anaconda or Miniconda, you can install Tianshou from conda-forge:
$ conda install tianshou -c conda-forge
Alternatively to the poetry install, you can also install the latest source version through GitHub:
$ pip install git+https://github.com/thu-ml/tianshou.git@master --upgrade
Finally, you may check the installation via your Python console as follows:
import tianshou
print(tianshou.__version__)
If no errors are reported, you have successfully installed Tianshou.
Documentation
Tutorials and API documentation are hosted on tianshou.readthedocs.io.
Find example scripts in the test/ and examples/ folders.
Why Tianshou?
Comprehensive Functionality
RL Platform | GitHub Stars | # of Alg. (1) | Custom Env | Batch Training | RNN Support | Nested Observation | Backend |
---|---|---|---|---|---|---|---|
Baselines | 9 | ✔️ (gym) | ➖ (2) | ✔️ | ❌ | TF1 | |
Stable-Baselines | 11 | ✔️ (gym) | ➖ (2) | ✔️ | ❌ | TF1 | |
Stable-Baselines3 | 7 (3) | ✔️ (gym) | ➖ (2) | ❌ | ✔️ | PyTorch | |
Ray/RLlib | 16 | ✔️ | ✔️ | ✔️ | ✔️ | TF/PyTorch | |
SpinningUp | 6 | ✔️ (gym) | ➖ (2) | ❌ | ❌ | PyTorch | |
Dopamine | 7 | ❌ | ❌ | ❌ | ❌ | TF/JAX | |
ACME | 14 | ✔️ (dm_env) | ✔️ | ✔️ | ✔️ | TF/JAX | |
keras-rl | 7 | ✔️ (gym) | ❌ | ❌ | ❌ | Keras | |
rlpyt | 11 | ❌ | ✔️ | ✔️ | ✔️ | PyTorch | |
ChainerRL | 18 | ✔️ (gym) | ✔️ | ✔️ | ❌ | Chainer | |
Sample Factory | 1 (4) | ✔️ (gym) | ✔️ | ✔️ | ✔️ | PyTorch | |
Tianshou | 20 | ✔️ (Gymnasium) | ✔️ | ✔️ | ✔️ | PyTorch |
(1): access date: 2021-08-08
(2): not all algorithms support this feature
(3): TQC and QR-DQN in sb3-contrib instead of main repo
(4): super fast APPO!
High Software Engineering Standards
RL Platform | Documentation | Code Coverage | Type Hints | Last Update |
---|---|---|---|---|
Baselines | ❌ | ❌ | ❌ | |
Stable-Baselines | ❌ | |||
Stable-Baselines3 | ✔️ | |||
Ray/RLlib | ➖(1) | ✔️ | ||
SpinningUp | ❌ | ❌ | ||
Dopamine | ❌ | ❌ | ||
ACME | ➖(1) | ✔️ | ||
keras-rl | ➖(1) | ❌ | ||
rlpyt | ❌ | |||
ChainerRL | ❌ | |||
Sample Factory | ➖ | ❌ | ||
Tianshou | ✔️ |
(1): it has continuous integration but the coverage rate is not available
Reproducible, High-Quality Results
Tianshou is rigorously tested. In contrast to other RL platforms, our tests include the full agent training procedure for all of the implemented algorithms. Our tests would fail once if any of the agents failed to achieve a consistent level of performance on limited epochs. Our tests thus ensure reproducibility. Check out the GitHub Actions page for more detail.
Atari and MuJoCo benchmark results can be found in the examples/atari/ and examples/mujoco/ folders respectively. Our MuJoCo results reach or exceed the level of performance of most existing benchmarks.
Policy Interface
All algorithms implement the following, highly general API:
__init__
: initialize the policy;forward
: compute actions based on given observations;process_buffer
: process initial buffer, which is useful for some offline learning algorithmsprocess_fn
: preprocess data from the replay buffer (since we have reformulated all algorithms to replay buffer-based algorithms);learn
: learn from a given batch of data;post_process_fn
: update the replay buffer from the learning process (e.g., prioritized replay buffer needs to update the weight);update
: the main interface for training, i.e.,process_fn -> learn -> post_process_fn
.
The implementation of this API suffices for a new algorithm to be applicable within Tianshou, making experimenation with new approaches particularly straightforward.
Quick Start
Tianshou provides two API levels:
- the high-level interface, which provides ease of use for end users seeking to run deep reinforcement learning applications
- the procedural interface, which provides a maximum of control, especially for very advanced users and developers of reinforcement learning algorithms.
In the following, let us consider an example application using the CartPole gymnasium environment. We shall apply the deep Q network (DQN) learning algorithm using both APIs.
High-Level API
To get started, we need some imports.
from tianshou.highlevel.config import SamplingConfig
from tianshou.highlevel.env import (
EnvFactoryRegistered,
VectorEnvType,
)
from tianshou.highlevel.experiment import DQNExperimentBuilder, ExperimentConfig
from tianshou.highlevel.params.policy_params import DQNParams
from tianshou.highlevel.trainer import (
EpochTestCallbackDQNSetEps,
EpochTrainCallbackDQNSetEps,
EpochStopCallbackRewardThreshold
)
In the high-level API, the basis for an RL experiment is an ExperimentBuilder
with which we can build the experiment we then seek to run.
Since we want to use DQN, we use the specialization DQNExperimentBuilder
.
The other imports serve to provide configuration options for our experiment.
The high-level API provides largely declarative semantics, i.e. the code is almost exclusively concerned with configuration that controls what to do (rather than how to do it).
experiment = (
DQNExperimentBuilder(
EnvFactoryRegistered(task="CartPole-v1", seed=0, venv_type=VectorEnvType.DUMMY),
ExperimentConfig(
persistence_enabled=False,
watch=True,
watch_render=1 / 35,
watch_num_episodes=100,
),
SamplingConfig(
num_epochs=10,
step_per_epoch=10000,
batch_size=64,
num_train_envs=10,
num_test_envs=100,
buffer_size=20000,
step_per_collect=10,
update_per_step=1 / 10,
),
)
.with_dqn_params(
DQNParams(
lr=1e-3,
discount_factor=0.9,
estimation_step=3,
target_update_freq=320,
),
)
.with_model_factory_default(hidden_sizes=(64, 64))
.with_epoch_train_callback(EpochTrainCallbackDQNSetEps(0.3))
.with_epoch_test_callback(EpochTestCallbackDQNSetEps(0.0))
.with_epoch_stop_callback(EpochStopCallbackRewardThreshold(195))
.build()
)
experiment.run()
The experiment builder takes three arguments:
- the environment factory for the creation of environments. In this case, we use an existing factory implementation for gymnasium environments.
- the experiment configuration, which controls persistence and the overall
experiment flow. In this case, we have configured that we want to observe
the agent's behavior after it is trained (
watch=True
) for a number of episodes (watch_num_episodes=100
). We have disabled persistence, because we do not want to save training logs, the agent or its configuration for future use. - the sampling configuration, which controls fundamental training parameters,
such as the total number of epochs we run the experiment for (
num_epochs=10
)
and the number of environment steps each epoch shall consist of (step_per_epoch=10000
). Every epoch consists of a series of data collection (rollout) steps and training steps. The parameterstep_per_collect
controls the amount of data that is collected in each collection step and after each collection step, we perform a training step, applying a gradient-based update based on a sample of data (batch_size=64
) taken from the buffer of data that has been collected. For further details, see the documentation ofSamplingConfig
.
We then proceed to configure some of the parameters of the DQN algorithm itself and of the neural network model we want to use. A DQN-specific detail is the use of callbacks to configure the algorithm's epsilon parameter for exploration. We want to use random exploration during rollouts (train callback), but we don't when evaluating the agent's performance in the test environments (test callback).
Find the script in examples/discrete/discrete_dqn_hl.py. Here's a run (with the training time cut short):
Find many further applications of the high-level API in the examples/
folder;
look for scripts ending with _hl.py
.
Note that most of these examples require the extra package argparse
(install it by adding --extras argparse
when invoking poetry).
Procedural API
Let us now consider an analogous example in the procedural API. Find the full script in examples/discrete/discrete_dqn.py.
First, import some relevant packages:
import gymnasium as gym
import torch
from torch.utils.tensorboard import SummaryWriter
import tianshou as ts
Define some hyper-parameters:
task = 'CartPole-v1'
lr, epoch, batch_size = 1e-3, 10, 64
train_num, test_num = 10, 100
gamma, n_step, target_freq = 0.9, 3, 320
buffer_size = 20000
eps_train, eps_test = 0.1, 0.05
step_per_epoch, step_per_collect = 10000, 10
Initialize the logger:
logger = ts.utils.TensorboardLogger(SummaryWriter('log/dqn'))
# For other loggers, see https://tianshou.readthedocs.io/en/master/01_tutorials/05_logger.html
Make environments:
# You can also try SubprocVectorEnv, which will use parallelization
train_envs = ts.env.DummyVectorEnv([lambda: gym.make(task) for _ in range(train_num)])
test_envs = ts.env.DummyVectorEnv([lambda: gym.make(task) for _ in range(test_num)])
Create the network as well as its optimizer:
from tianshou.utils.net.common import Net
# Note: You can easily define other networks.
# See https://tianshou.readthedocs.io/en/master/01_tutorials/00_dqn.html#build-the-network
env = gym.make(task, render_mode="human")
state_shape = env.observation_space.shape or env.observation_space.n
action_shape = env.action_space.shape or env.action_space.n
net = Net(state_shape=state_shape, action_shape=action_shape, hidden_sizes=[128, 128, 128])
optim = torch.optim.Adam(net.parameters(), lr=lr)
Set up the policy and collectors:
policy = ts.policy.DQNPolicy(
model=net,
optim=optim,
discount_factor=gamma,
action_space=env.action_space,
estimation_step=n_step,
target_update_freq=target_freq
)
train_collector = ts.data.Collector(policy, train_envs, ts.data.VectorReplayBuffer(buffer_size, train_num), exploration_noise=True)
test_collector = ts.data.Collector(policy, test_envs, exploration_noise=True) # because DQN uses epsilon-greedy method
Let's train it:
result = ts.trainer.OffpolicyTrainer(
policy=policy,
train_collector=train_collector,
test_collector=test_collector,
max_epoch=epoch,
step_per_epoch=step_per_epoch,
step_per_collect=step_per_collect,
episode_per_test=test_num,
batch_size=batch_size,
update_per_step=1 / step_per_collect,
train_fn=lambda epoch, env_step: policy.set_eps(eps_train),
test_fn=lambda epoch, env_step: policy.set_eps(eps_test),
stop_fn=lambda mean_rewards: mean_rewards >= env.spec.reward_threshold,
logger=logger,
).run()
print(f"Finished training in {result.timing.total_time} seconds")
Save/load the trained policy (it's exactly the same as loading a torch.nn.module
):
torch.save(policy.state_dict(), 'dqn.pth')
policy.load_state_dict(torch.load('dqn.pth'))
Watch the agent with 35 FPS:
policy.eval()
policy.set_eps(eps_test)
collector = ts.data.Collector(policy, env, exploration_noise=True)
collector.collect(n_episode=1, render=1 / 35)
Inspect the data saved in TensorBoard:
$ tensorboard --logdir log/dqn
Please read the documentation for advanced usage.
Contributing
Tianshou is still under development. Further algorithms and features are continuously being added, and we always welcome contributions to help make Tianshou better. If you would like to contribute, please check out this link.
Citing Tianshou
If you find Tianshou useful, please cite it in your publications.
@article{tianshou,
author = {Jiayi Weng and Huayu Chen and Dong Yan and Kaichao You and Alexis Duburcq and Minghao Zhang and Yi Su and Hang Su and Jun Zhu},
title = {Tianshou: A Highly Modularized Deep Reinforcement Learning Library},
journal = {Journal of Machine Learning Research},
year = {2022},
volume = {23},
number = {267},
pages = {1--6},
url = {http://jmlr.org/papers/v23/21-1127.html}
}
Acknowledgments
Tianshou is supported by appliedAI Institute for Europe, who is committed to providing long-term support and development.
Tianshou was previously a reinforcement learning platform based on TensorFlow. You can check out the branch priv
for more detail. Many thanks to Haosheng Zou's pioneering work for Tianshou before version 0.1.1.
We would like to thank TSAIL and Institute for Artificial Intelligence, Tsinghua University for providing such an excellent AI research platform.
-
mujoco-py
is a legacy package and is not recommended for new projects. It is only included for compatibility with older projects. Also note that there may be compatibility issues with macOS newer than Monterey. ↩︎