Bumps [pillow](https://github.com/python-pillow/Pillow) from 10.0.1 to 10.2.0. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/python-pillow/Pillow/releases">pillow's releases</a>.</em></p> <blockquote> <h2>10.2.0</h2> <p><a href="https://pillow.readthedocs.io/en/stable/releasenotes/10.2.0.html">https://pillow.readthedocs.io/en/stable/releasenotes/10.2.0.html</a></p> <h2>Changes</h2> <ul> <li>Add <code>keep_rgb</code> option when saving JPEG to prevent conversion of RGB colorspace <a href="https://redirect.github.com/python-pillow/Pillow/issues/7553">#7553</a> [<a href="https://github.com/bgilbert"><code>@bgilbert</code></a>]</li> <li>Trim negative glyph offsets in ImageFont.getmask() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7672">#7672</a> [<a href="https://github.com/nulano"><code>@nulano</code></a>]</li> <li>Removed unnecessary "pragma: no cover" <a href="https://redirect.github.com/python-pillow/Pillow/issues/7668">#7668</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Trim glyph size in ImageFont.getmask() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7669">#7669</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Fix loading IPTC images and update test <a href="https://redirect.github.com/python-pillow/Pillow/issues/7667">#7667</a> [<a href="https://github.com/nulano"><code>@nulano</code></a>]</li> <li>Allow uncompressed TIFF images to be saved in chunks <a href="https://redirect.github.com/python-pillow/Pillow/issues/7650">#7650</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Concatenate multiple JPEG EXIF markers <a href="https://redirect.github.com/python-pillow/Pillow/issues/7496">#7496</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Changed IPTC tile tuple to match other plugins <a href="https://redirect.github.com/python-pillow/Pillow/issues/7661">#7661</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Do not assign new fp attribute when exiting context manager <a href="https://redirect.github.com/python-pillow/Pillow/issues/7566">#7566</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Support arbitrary masks for uncompressed RGB DDS images <a href="https://redirect.github.com/python-pillow/Pillow/issues/7589">#7589</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Support setting ROWSPERSTRIP tag <a href="https://redirect.github.com/python-pillow/Pillow/issues/7654">#7654</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Apply ImageFont.MAX_STRING_LENGTH to ImageFont.getmask() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7662">#7662</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Optimise <code>ImageColor</code> using <code>functools.lru_cache</code> <a href="https://redirect.github.com/python-pillow/Pillow/issues/7657">#7657</a> [<a href="https://github.com/hugovk"><code>@hugovk</code></a>]</li> <li>Restricted environment keys for ImageMath.eval() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7655">#7655</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Optimise <code>ImageMode.getmode</code> using <code>functools.lru_cache</code> <a href="https://redirect.github.com/python-pillow/Pillow/issues/7641">#7641</a> [<a href="https://github.com/hugovk"><code>@hugovk</code></a>]</li> <li>Added trusted PyPI publishing <a href="https://redirect.github.com/python-pillow/Pillow/issues/7616">#7616</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Compile FriBiDi for Windows ARM64 <a href="https://redirect.github.com/python-pillow/Pillow/issues/7629">#7629</a> [<a href="https://github.com/nulano"><code>@nulano</code></a>]</li> <li>Fix incorrect color blending for overlapping glyphs <a href="https://redirect.github.com/python-pillow/Pillow/issues/7497">#7497</a> [<a href="https://github.com/ZachNagengast"><code>@ZachNagengast</code></a>]</li> <li>Add .git-blame-ignore-revs file <a href="https://redirect.github.com/python-pillow/Pillow/issues/7528">#7528</a> [<a href="https://github.com/akx"><code>@akx</code></a>]</li> <li>Attempt memory mapping when tile args is a string <a href="https://redirect.github.com/python-pillow/Pillow/issues/7565">#7565</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Fill identical pixels with transparency in subsequent frames when saving GIF <a href="https://redirect.github.com/python-pillow/Pillow/issues/7568">#7568</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Removed unnecessary string length check <a href="https://redirect.github.com/python-pillow/Pillow/issues/7560">#7560</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Determine mask mode in Python instead of C <a href="https://redirect.github.com/python-pillow/Pillow/issues/7548">#7548</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Corrected duration when combining multiple GIF frames into single frame <a href="https://redirect.github.com/python-pillow/Pillow/issues/7521">#7521</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Handle disposing GIF background from outside palette <a href="https://redirect.github.com/python-pillow/Pillow/issues/7515">#7515</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Seek past the data when skipping a PSD layer <a href="https://redirect.github.com/python-pillow/Pillow/issues/7483">#7483</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>ImageMath: Inline <code>isinstance</code> check <a href="https://redirect.github.com/python-pillow/Pillow/issues/7623">#7623</a> [<a href="https://github.com/hugovk"><code>@hugovk</code></a>]</li> <li>Update actions/upload-artifact action to v4 <a href="https://redirect.github.com/python-pillow/Pillow/issues/7619">#7619</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Import plugins relative to the module <a href="https://redirect.github.com/python-pillow/Pillow/issues/7576">#7576</a> [<a href="https://github.com/deliangyang"><code>@deliangyang</code></a>]</li> <li>Translate encoder error codes to strings; deprecate <code>ImageFile.raise_oserror()</code> <a href="https://redirect.github.com/python-pillow/Pillow/issues/7609">#7609</a> [<a href="https://github.com/bgilbert"><code>@bgilbert</code></a>]</li> <li>Updated readthedocs to latest version of Python <a href="https://redirect.github.com/python-pillow/Pillow/issues/7611">#7611</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Support reading BC4U and DX10 BC1 images <a href="https://redirect.github.com/python-pillow/Pillow/issues/6486">#6486</a> [<a href="https://github.com/REDxEYE"><code>@REDxEYE</code></a>]</li> <li>Optimize ImageStat.Stat.extrema <a href="https://redirect.github.com/python-pillow/Pillow/issues/7593">#7593</a> [<a href="https://github.com/florath"><code>@florath</code></a>]</li> <li>Handle pathlib.Path in FreeTypeFont <a href="https://redirect.github.com/python-pillow/Pillow/issues/7578">#7578</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Use list comprehensions to create transformed lists <a href="https://redirect.github.com/python-pillow/Pillow/issues/7597">#7597</a> [<a href="https://github.com/hugovk"><code>@hugovk</code></a>]</li> <li>Added support for reading DX10 BC4 DDS images <a href="https://redirect.github.com/python-pillow/Pillow/issues/7603">#7603</a> [<a href="https://github.com/sambvfx"><code>@sambvfx</code></a>]</li> <li>Optimized ImageStat.Stat.count <a href="https://redirect.github.com/python-pillow/Pillow/issues/7599">#7599</a> [<a href="https://github.com/florath"><code>@florath</code></a>]</li> <li>Moved error from truetype() to FreeTypeFont <a href="https://redirect.github.com/python-pillow/Pillow/issues/7587">#7587</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Correct PDF palette size when saving <a href="https://redirect.github.com/python-pillow/Pillow/issues/7555">#7555</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>Fixed closing file pointer with olefile 0.47 <a href="https://redirect.github.com/python-pillow/Pillow/issues/7594">#7594</a> [<a href="https://github.com/radarhere"><code>@radarhere</code></a>]</li> <li>ruff: Minor optimizations of list comprehensions, x in set, etc. <a href="https://redirect.github.com/python-pillow/Pillow/issues/7524">#7524</a> [<a href="https://github.com/cclauss"><code>@cclauss</code></a>]</li> <li>Build Windows wheels using cibuildwheel <a href="https://redirect.github.com/python-pillow/Pillow/issues/7580">#7580</a> [<a href="https://github.com/nulano"><code>@nulano</code></a>]</li> <li>Raise ValueError when TrueType font size is zero or less <a href="https://redirect.github.com/python-pillow/Pillow/issues/7584">#7584</a> [<a href="https://github.com/akx"><code>@akx</code></a>]</li> <li>Install cibuildwheel from requirements file <a href="https://redirect.github.com/python-pillow/Pillow/issues/7581">#7581</a> [<a href="https://github.com/hugovk"><code>@hugovk</code></a>]</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst">pillow's changelog</a>.</em></p> <blockquote> <h2>10.2.0 (2024-01-02)</h2> <ul> <li> <p>Add <code>keep_rgb</code> option when saving JPEG to prevent conversion of RGB colorspace <a href="https://redirect.github.com/python-pillow/Pillow/issues/7553">#7553</a> [bgilbert, radarhere]</p> </li> <li> <p>Trim glyph size in ImageFont.getmask() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7669">#7669</a>, <a href="https://redirect.github.com/python-pillow/Pillow/issues/7672">#7672</a> [radarhere, nulano]</p> </li> <li> <p>Deprecate IptcImagePlugin helpers <a href="https://redirect.github.com/python-pillow/Pillow/issues/7664">#7664</a> [nulano, hugovk, radarhere]</p> </li> <li> <p>Allow uncompressed TIFF images to be saved in chunks <a href="https://redirect.github.com/python-pillow/Pillow/issues/7650">#7650</a> [radarhere]</p> </li> <li> <p>Concatenate multiple JPEG EXIF markers <a href="https://redirect.github.com/python-pillow/Pillow/issues/7496">#7496</a> [radarhere]</p> </li> <li> <p>Changed IPTC tile tuple to match other plugins <a href="https://redirect.github.com/python-pillow/Pillow/issues/7661">#7661</a> [radarhere]</p> </li> <li> <p>Do not assign new fp attribute when exiting context manager <a href="https://redirect.github.com/python-pillow/Pillow/issues/7566">#7566</a> [radarhere]</p> </li> <li> <p>Support arbitrary masks for uncompressed RGB DDS images <a href="https://redirect.github.com/python-pillow/Pillow/issues/7589">#7589</a> [radarhere, akx]</p> </li> <li> <p>Support setting ROWSPERSTRIP tag <a href="https://redirect.github.com/python-pillow/Pillow/issues/7654">#7654</a> [radarhere]</p> </li> <li> <p>Apply ImageFont.MAX_STRING_LENGTH to ImageFont.getmask() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7662">#7662</a> [radarhere]</p> </li> <li> <p>Optimise <code>ImageColor</code> using <code>functools.lru_cache</code> <a href="https://redirect.github.com/python-pillow/Pillow/issues/7657">#7657</a> [hugovk]</p> </li> <li> <p>Restricted environment keys for ImageMath.eval() <a href="https://redirect.github.com/python-pillow/Pillow/issues/7655">#7655</a> [wiredfool, radarhere]</p> </li> <li> <p>Optimise <code>ImageMode.getmode</code> using <code>functools.lru_cache</code> <a href="https://redirect.github.com/python-pillow/Pillow/issues/7641">#7641</a> [hugovk, radarhere]</p> </li> <li> <p>Fix incorrect color blending for overlapping glyphs <a href="https://redirect.github.com/python-pillow/Pillow/issues/7497">#7497</a> [ZachNagengast, nulano, radarhere]</p> </li> <li> <p>Attempt memory mapping when tile args is a string <a href="https://redirect.github.com/python-pillow/Pillow/issues/7565">#7565</a> [radarhere]</p> </li> <li> <p>Fill identical pixels with transparency in subsequent frames when saving GIF <a href="https://redirect.github.com/python-pillow/Pillow/issues/7568">#7568</a> [radarhere]</p> </li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="6956d0b285
"><code>6956d0b</code></a> 10.2.0 version bump</li> <li><a href="31c8dacdc7
"><code>31c8dac</code></a> Merge pull request <a href="https://redirect.github.com/python-pillow/Pillow/issues/7675">#7675</a> from python-pillow/pre-commit-ci-update-config</li> <li><a href="40a3f91af2
"><code>40a3f91</code></a> Merge pull request <a href="https://redirect.github.com/python-pillow/Pillow/issues/7674">#7674</a> from nulano/url-example</li> <li><a href="cb41b0cc78
"><code>cb41b0c</code></a> [pre-commit.ci] pre-commit autoupdate</li> <li><a href="de62b25ed3
"><code>de62b25</code></a> fix image url in "Reading from URL" example</li> <li><a href="7c526a6c6b
"><code>7c526a6</code></a> Update CHANGES.rst [ci skip]</li> <li><a href="d93a5ad70b
"><code>d93a5ad</code></a> Merge pull request <a href="https://redirect.github.com/python-pillow/Pillow/issues/7553">#7553</a> from bgilbert/jpeg-rgb</li> <li><a href="aed764fe84
"><code>aed764f</code></a> Update CHANGES.rst [ci skip]</li> <li><a href="f8df5303fa
"><code>f8df530</code></a> Merge pull request <a href="https://redirect.github.com/python-pillow/Pillow/issues/7672">#7672</a> from nulano/imagefont-negative-crop</li> <li><a href="24e9485e6b
"><code>24e9485</code></a> Merge pull request <a href="https://redirect.github.com/python-pillow/Pillow/issues/7671">#7671</a> from radarhere/imagetransform</li> <li>Additional commits viewable in <a href="https://github.com/python-pillow/Pillow/compare/10.0.1...10.2.0">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>
⚠️️ Dropped support of Gym: Tianshou no longer supports
gym
, and we recommend that you transition to Gymnasium. If you absolutely have to use gym, you can try using Shimmy (the compatibility layer), but Tianshou provides no guarantees that things will work then.
⚠️️ Current Status: the Tianshou master branch is currently under heavy development, moving towards more features, improved interfaces, more documentation. You can view the relevant issues in the corresponding milestone Stay tuned! (and expect breaking changes until the release is done)
Tianshou (天授) is a reinforcement learning platform based on pure PyTorch. Unlike other reinforcement learning libraries, which are partly based on TensorFlow, have unfriendly APIs ot are not optimized for speed, Tianshou provides a high-performance, modularized framework and user-friendly APIs for building deep reinforcement learning agents, enabling concise implementations without sacrificing flexibility.
The set of supported algorithms includes the following:
- 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.
You can simply install Tianshou from PyPI 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, 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.
中文文档位于 https://tianshou.readthedocs.io/zh/master/。
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 quality software engineering standard
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 (
TrainerEpochCallbackTestDQNSetEps,
TrainerEpochCallbackTrainDQNSetEps,
)
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(
EnvFactoryGymnasium(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):
Procedural API
Let us now consider an analogous example in the procedural API. Find the full script from which the snippets below were derived at test/discrete/test_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
logger = ts.utils.TensorboardLogger(SummaryWriter('log/dqn')) # TensorBoard is supported!
# For other loggers: https://tianshou.readthedocs.io/en/master/tutorials/logger.html
Make environments:
# you can also try with SubprocVectorEnv
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)])
Define the network:
from tianshou.utils.net.common import Net
# you can define other net by following the API:
# https://tianshou.readthedocs.io/en/master/tutorials/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)
Setup 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 PyTorch nn.module
):
torch.save(policy.state_dict(), 'dqn.pth')
policy.load_state_dict(torch.load('dqn.pth'))
Watch the performance 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)
Look at the result saved in tensorboard: (with bash script in your terminal)
$ tensorboard --logdir log/dqn
You can check out 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.