{"id":13492968,"url":"https://github.com/thu-ml/tianshou","last_synced_at":"2025-05-13T15:03:58.675Z","repository":{"id":37430819,"uuid":"129815042","full_name":"thu-ml/tianshou","owner":"thu-ml","description":"An elegant PyTorch deep reinforcement learning library.","archived":false,"fork":false,"pushed_at":"2025-05-03T10:56:09.000Z","size":48736,"stargazers_count":8448,"open_issues_count":152,"forks_count":1150,"subscribers_count":91,"default_branch":"master","last_synced_at":"2025-05-03T11:33:27.596Z","etag":null,"topics":["a2c","atari","bcq","cql","ddpg","double-dqn","dqn","drl","imitation-learning","mujoco","npg","policy-gradient","ppo","pytorch","rl","sac","td3","transferlab","trpo"],"latest_commit_sha":null,"homepage":"https://tianshou.org","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thu-ml.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-04-16T22:47:38.000Z","updated_at":"2025-05-03T11:06:44.000Z","dependencies_parsed_at":"2024-01-16T17:29:29.779Z","dependency_job_id":"a321e6e9-5499-4706-90d2-f2daabba6267","html_url":"https://github.com/thu-ml/tianshou","commit_stats":{"total_commits":376,"total_committers":63,"mean_commits":5.968253968253968,"dds":0.6622340425531915,"last_synced_commit":"1423eeb3b2828e1ffa03b0a2a2ae13473a82713a"},"previous_names":["aai-institute/tianshou","thu-ml/tianshou"],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thu-ml%2Ftianshou","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thu-ml%2Ftianshou/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thu-ml%2Ftianshou/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thu-ml%2Ftianshou/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thu-ml","download_url":"https://codeload.github.com/thu-ml/tianshou/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252187216,"owners_count":21708263,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["a2c","atari","bcq","cql","ddpg","double-dqn","dqn","drl","imitation-learning","mujoco","npg","policy-gradient","ppo","pytorch","rl","sac","td3","transferlab","trpo"],"created_at":"2024-07-31T19:01:10.918Z","updated_at":"2025-05-05T18:15:14.837Z","avatar_url":"https://github.com/thu-ml.png","language":"Python","funding_links":[],"categories":["Uncategorized","Reinforcement Learning (RL) and Deep Reinforcement Learning (DRL)","Python","时间序列","Reinforcement Learning","11. Specialized Domains"],"sub_categories":["Uncategorized","RL/DRL Algorithm Implementations and Software Frameworks","网络服务_其他","1.Basic for RL"],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"http://tianshou.readthedocs.io\"\u003e\u003cimg width=\"300px\" height=\"auto\" src=\"https://github.com/thu-ml/tianshou/raw/master/docs/_static/images/tianshou-logo.png\"\u003e\u003c/a\u003e\n\u003c/div\u003e\n\n---\n\n[![PyPI](https://img.shields.io/pypi/v/tianshou)](https://pypi.org/project/tianshou/) [![Conda](https://img.shields.io/conda/vn/conda-forge/tianshou)](https://github.com/conda-forge/tianshou-feedstock) [![Read the Docs](https://readthedocs.org/projects/tianshou/badge/?version=master)](https://tianshou.org/en/master/) [![Pytest](https://github.com/thu-ml/tianshou/actions/workflows/pytest.yml/badge.svg)](https://github.com/thu-ml/tianshou/actions) [![codecov](https://img.shields.io/codecov/c/gh/thu-ml/tianshou)](https://codecov.io/gh/thu-ml/tianshou) [![GitHub issues](https://img.shields.io/github/issues/thu-ml/tianshou)](https://github.com/thu-ml/tianshou/issues) [![GitHub stars](https://img.shields.io/github/stars/thu-ml/tianshou)](https://github.com/thu-ml/tianshou/stargazers) [![GitHub forks](https://img.shields.io/github/forks/thu-ml/tianshou)](https://github.com/thu-ml/tianshou/network) [![GitHub license](https://img.shields.io/github/license/thu-ml/tianshou)](https://github.com/thu-ml/tianshou/blob/master/LICENSE)\n\n**Tianshou** ([天授](https://baike.baidu.com/item/%E5%A4%A9%E6%8E%88)) is a reinforcement learning (RL) library based on pure PyTorch and [Gymnasium](http://github.com/Farama-Foundation/Gymnasium). Tianshou's main features at a glance are:\n\n1. Modular low-level interfaces for algorithm developers (RL researchers) that are both flexible, hackable and type-safe.\n1. Convenient high-level interfaces for applications of RL (training an implemented algorithm on a custom environment).\n1. Large scope: online (on- and off-policy) and offline RL, experimental support for multi-agent RL (MARL), experimental support for model-based RL, and more\n\n\nUnlike other reinforcement learning libraries, which may have complex codebases,\nunfriendly high-level APIs, or are not optimized for speed, Tianshou provides a high-performance, modularized framework\nand user-friendly interfaces for building deep reinforcement learning agents. One more aspect that sets Tianshou apart is its\ngenerality: it supports online and offline RL, multi-agent RL, and model-based algorithms.\n\nTianshou aims at enabling concise implementations, both for researchers and practitioners, without sacrificing flexibility.\n\nSupported algorithms include:\n\n- [Deep Q-Network (DQN)](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf)\n- [Double DQN](https://arxiv.org/pdf/1509.06461.pdf)\n- [Dueling DQN](https://arxiv.org/pdf/1511.06581.pdf)\n- [Branching DQN](https://arxiv.org/pdf/1711.08946.pdf)\n- [Categorical DQN (C51)](https://arxiv.org/pdf/1707.06887.pdf)\n- [Rainbow DQN (Rainbow)](https://arxiv.org/pdf/1710.02298.pdf)\n- [Quantile Regression DQN (QRDQN)](https://arxiv.org/pdf/1710.10044.pdf)\n- [Implicit Quantile Network (IQN)](https://arxiv.org/pdf/1806.06923.pdf)\n- [Fully-parameterized Quantile Function (FQF)](https://arxiv.org/pdf/1911.02140.pdf)\n- [Policy Gradient (PG)](https://papers.nips.cc/paper/1713-policy-gradient-methods-for-reinforcement-learning-with-function-approximation.pdf)\n- [Natural Policy Gradient (NPG)](https://proceedings.neurips.cc/paper/2001/file/4b86abe48d358ecf194c56c69108433e-Paper.pdf)\n- [Advantage Actor-Critic (A2C)](https://openai.com/blog/baselines-acktr-a2c/)\n- [Trust Region Policy Optimization (TRPO)](https://arxiv.org/pdf/1502.05477.pdf)\n- [Proximal Policy Optimization (PPO)](https://arxiv.org/pdf/1707.06347.pdf)\n- [Deep Deterministic Policy Gradient (DDPG)](https://arxiv.org/pdf/1509.02971.pdf)\n- [Twin Delayed DDPG (TD3)](https://arxiv.org/pdf/1802.09477.pdf)\n- [Soft Actor-Critic (SAC)](https://arxiv.org/pdf/1812.05905.pdf)\n- [Randomized Ensembled Double Q-Learning (REDQ)](https://arxiv.org/pdf/2101.05982.pdf)\n- [Discrete Soft Actor-Critic (SAC-Discrete)](https://arxiv.org/pdf/1910.07207.pdf)\n- [Vanilla Imitation Learning](https://en.wikipedia.org/wiki/Apprenticeship_learning)\n- [Batch-Constrained deep Q-Learning (BCQ)](https://arxiv.org/pdf/1812.02900.pdf)\n- [Conservative Q-Learning (CQL)](https://arxiv.org/pdf/2006.04779.pdf)\n- [Twin Delayed DDPG with Behavior Cloning (TD3+BC)](https://arxiv.org/pdf/2106.06860.pdf)\n- [Discrete Batch-Constrained deep Q-Learning (BCQ-Discrete)](https://arxiv.org/pdf/1910.01708.pdf)\n- [Discrete Conservative Q-Learning (CQL-Discrete)](https://arxiv.org/pdf/2006.04779.pdf)\n- [Discrete Critic Regularized Regression (CRR-Discrete)](https://arxiv.org/pdf/2006.15134.pdf)\n- [Generative Adversarial Imitation Learning (GAIL)](https://arxiv.org/pdf/1606.03476.pdf)\n- [Prioritized Experience Replay (PER)](https://arxiv.org/pdf/1511.05952.pdf)\n- [Generalized Advantage Estimator (GAE)](https://arxiv.org/pdf/1506.02438.pdf)\n- [Posterior Sampling Reinforcement Learning (PSRL)](https://www.ece.uvic.ca/~bctill/papers/learning/Strens_2000.pdf)\n- [Intrinsic Curiosity Module (ICM)](https://arxiv.org/pdf/1705.05363.pdf)\n- [Hindsight Experience Replay (HER)](https://arxiv.org/pdf/1707.01495.pdf)\n\nOther noteworthy features:\n\n- Elegant framework with dual APIs:\n  - Tianshou's high-level API maximizes ease of use for application development while still retaining a high degree\n    of flexibility.\n  - The fundamental procedural API provides a maximum of flexibility for algorithm development without being\n    overly verbose.\n- State-of-the-art results in [MuJoCo benchmarks](https://github.com/thu-ml/tianshou/tree/master/examples/mujoco) for REINFORCE/A2C/TRPO/PPO/DDPG/TD3/SAC algorithms\n- Support for vectorized environments (synchronous or asynchronous) for all algorithms (see [usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#parallel-sampling))\n- Support for super-fast vectorized environments based on [EnvPool](https://github.com/sail-sg/envpool/) for all algorithms (see [usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#envpool-integration))\n- Support for recurrent state representations in actor networks and critic networks (RNN-style training for POMDPs) (see [usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#rnn-style-training))\n- Support any type of environment state/action (e.g. a dict, a self-defined class, ...) [Usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#user-defined-environment-and-different-state-representation)\n- Support for customized training processes (see [usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#customize-training-process))\n- 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\n- Support for multi-agent RL (see [usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#multi-agent-reinforcement-learning))\n- Support for logging based on both [TensorBoard](https://www.tensorflow.org/tensorboard) and [W\u0026B](https://wandb.ai/)\n- Support for multi-GPU training (see [usage](https://tianshou.readthedocs.io/en/master/01_tutorials/07_cheatsheet.html#multi-gpu))\n- Comprehensive documentation, PEP8 code-style checking, type checking and thorough [tests](https://github.com/thu-ml/tianshou/actions)\n\nIn Chinese, Tianshou means divinely ordained, being derived to the gift of being born.\nTianshou is a reinforcement learning platform, and the nature of RL is not learn from humans.\nSo taking \"Tianshou\" means that there is no teacher to learn from, but rather to learn by oneself through constant interaction with the environment.\n\n“天授”意指上天所授，引申为与生具有的天赋。天授是强化学习平台，而强化学习算法并不是向人类学习的，所以取“天授”意思是没有老师来教，而是自己通过跟环境不断交互来进行学习。\n\n## Installation\n\nTianshou is currently hosted on [PyPI](https://pypi.org/project/tianshou/) and [conda-forge](https://github.com/conda-forge/tianshou-feedstock). It requires Python \u003e= 3.11.\n\nFor installing the most recent version of Tianshou, the best way is clone the repository and install it with [poetry](https://python-poetry.org/)\n(which you need to install on your system first)\n\n```bash\ngit clone git@github.com:thu-ml/tianshou.git\ncd tianshou\npoetry install\n```\n\nYou can also install the dev requirements by adding `--with dev` or the extras\nfor say mujoco and acceleration by [envpool](https://github.com/sail-sg/envpool)\nby adding `--extras \"mujoco envpool\"`\n\nIf 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.\nOr you may install all the following extras by adding `--all-extras`.\n\nAvailable extras are:\n\n- `atari` (for Atari environments)\n- `box2d` (for Box2D environments)\n- `classic_control` (for classic control (discrete) environments)\n- `mujoco` (for MuJoCo environments)\n- `mujoco-py` (for legacy mujoco-py environments[^1])\n- `pybullet` (for pybullet environments)\n- `robotics` (for gymnasium-robotics environments)\n- `vizdoom` (for ViZDoom environments)\n- `envpool` (for [envpool](https://github.com/sail-sg/envpool/) integration)\n- `argparse` (in order to be able to run the high level API examples)\n\n[^1]:\n    `mujoco-py` is a legacy package and is not recommended for new projects.\n    It is only included for compatibility with older projects.\n    Also note that there may be compatibility issues with macOS newer than\n    Monterey.\n\nOtherwise, you can install the latest release from PyPI (currently\nfar behind the master) with the following command:\n\n```bash\n$ pip install tianshou\n```\n\nIf you are using Anaconda or Miniconda, you can install Tianshou from conda-forge:\n\n```bash\n$ conda install tianshou -c conda-forge\n```\n\nAlternatively to the poetry install, you can also install the latest source version through GitHub:\n\n```bash\n$ pip install git+https://github.com/thu-ml/tianshou.git@master --upgrade\n```\n\nFinally, you may check the installation via your Python console as follows:\n\n```python\nimport tianshou\nprint(tianshou.__version__)\n```\n\nIf no errors are reported, you have successfully installed Tianshou.\n\n## Documentation\n\nTutorials and API documentation are hosted on [tianshou.readthedocs.io](https://tianshou.readthedocs.io/).\n\nFind example scripts in the [test/](https://github.com/thu-ml/tianshou/blob/master/test) and [examples/](https://github.com/thu-ml/tianshou/blob/master/examples) folders.\n\n## Why Tianshou?\n\n### Comprehensive Functionality\n\n### High Software Engineering Standards\n\n| RL Platform                                                        | Documentation                                                                                                                                                        | Code Coverage                                                                                                                                                | Type Hints         | Last Update                                                                                                       |\n| ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ----------------------------------------------------------------------------------------------------------------- |\n| [Stable-Baselines3](https://github.com/DLR-RM/stable-baselines3)   | [![Documentation Status](https://readthedocs.org/projects/stable-baselines/badge/?version=master)](https://stable-baselines3.readthedocs.io/en/master/?badge=master) | [![coverage report](https://gitlab.com/araffin/stable-baselines3/badges/master/coverage.svg)](https://gitlab.com/araffin/stable-baselines3/-/commits/master) | :heavy_check_mark: | ![GitHub last commit](https://img.shields.io/github/last-commit/DLR-RM/stable-baselines3?label=last%20update)     |\n| [Ray/RLlib](https://github.com/ray-project/ray/tree/master/rllib/) | [![](https://readthedocs.org/projects/ray/badge/?version=master)](http://docs.ray.io/en/master/rllib.html)                                                           | :heavy_minus_sign:\u003csup\u003e(1)\u003c/sup\u003e                                                                                                                             | :heavy_check_mark: | ![GitHub last commit](https://img.shields.io/github/last-commit/ray-project/ray?label=last%20update)              |\n| [SpinningUp](https://github.com/openai/spinningup)                 | [![](https://img.shields.io/readthedocs/spinningup)](https://spinningup.openai.com/)                                                                                 | :x:                                                                                                                                                          | :x:                | ![GitHub last commit](https://img.shields.io/github/last-commit/openai/spinningup?label=last%20update)            |\n| [Dopamine](https://github.com/google/dopamine)                     | [![](https://img.shields.io/badge/docs-passing-green)](https://github.com/google/dopamine/tree/master/docs)                                                          | :x:                                                                                                                                                          | :x:                | ![GitHub last commit](https://img.shields.io/github/last-commit/google/dopamine?label=last%20update)              |\n| [ACME](https://github.com/deepmind/acme)                           | [![](https://img.shields.io/badge/docs-passing-green)](https://github.com/deepmind/acme/blob/master/docs/index.md)                                                   | :heavy_minus_sign:\u003csup\u003e(1)\u003c/sup\u003e                                                                                                                             | :heavy_check_mark: | ![GitHub last commit](https://img.shields.io/github/last-commit/deepmind/acme?label=last%20update)                |\n| [Sample Factory](https://github.com/alex-petrenko/sample-factory)  | [:heavy_minus_sign:](https://arxiv.org/abs/2006.11751)                                                                                                               | [![codecov](https://codecov.io/gh/alex-petrenko/sample-factory/branch/master/graph/badge.svg)](https://codecov.io/gh/alex-petrenko/sample-factory)           | :x:                | ![GitHub last commit](https://img.shields.io/github/last-commit/alex-petrenko/sample-factory?label=last%20update) |\n|                                                                    |                                                                                                                                                                      |                                                                                                                                                              |                    |                                                                                                                   |\n| [Tianshou](https://github.com/thu-ml/tianshou)                     | [![Read the Docs](https://img.shields.io/readthedocs/tianshou)](https://tianshou.readthedocs.io/en/master)                                                           | [![codecov](https://img.shields.io/codecov/c/gh/thu-ml/tianshou)](https://codecov.io/gh/thu-ml/tianshou)                                                     | :heavy_check_mark: | ![GitHub last commit](https://img.shields.io/github/last-commit/thu-ml/tianshou?label=last%20update)              |\n\n\u003csup\u003e(1): it has continuous integration but the coverage rate is not available\u003c/sup\u003e\n\n### Reproducible, High-Quality Results\n\nTianshou 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.\nOur tests thus ensure reproducibility.\nCheck out the [GitHub Actions](https://github.com/thu-ml/tianshou/actions) page for more detail.\n\nAtari and MuJoCo benchmark results can be found in the [examples/atari/](examples/atari/) and [examples/mujoco/](examples/mujoco/) folders respectively. **Our MuJoCo results reach or exceed the level of performance of most existing benchmarks.**\n\n### Policy Interface\n\nAll algorithms implement the following, highly general API:\n\n- `__init__`: initialize the policy;\n- `forward`: compute actions based on given observations;\n- `process_buffer`: process initial buffer, which is useful for some offline learning algorithms\n- `process_fn`: preprocess data from the replay buffer (since we have reformulated _all_ algorithms to replay buffer-based algorithms);\n- `learn`: learn from a given batch of data;\n- `post_process_fn`: update the replay buffer from the learning process (e.g., prioritized replay buffer needs to update the weight);\n- `update`: the main interface for training, i.e., `process_fn -\u003e learn -\u003e post_process_fn`.\n\nThe implementation of this API suffices for a new algorithm to be applicable within Tianshou,\nmaking experimenation with new approaches particularly straightforward.\n\n## Quick Start\n\nTianshou provides two API levels:\n\n- the high-level interface, which provides ease of use for end users seeking to run deep reinforcement learning applications\n- the procedural interface, which provides a maximum of control, especially for very advanced users and developers of reinforcement learning algorithms.\n\nIn the following, let us consider an example application using the _CartPole_ gymnasium environment.\nWe shall apply the deep Q network (DQN) learning algorithm using both APIs.\n\n### High-Level API\n\nTo get started, we need some imports.\n\n```python\nfrom tianshou.highlevel.config import SamplingConfig\nfrom tianshou.highlevel.env import (\n    EnvFactoryRegistered,\n    VectorEnvType,\n)\nfrom tianshou.highlevel.experiment import DQNExperimentBuilder, ExperimentConfig\nfrom tianshou.highlevel.params.policy_params import DQNParams\nfrom tianshou.highlevel.trainer import (\n    EpochTestCallbackDQNSetEps,\n    EpochTrainCallbackDQNSetEps,\n    EpochStopCallbackRewardThreshold\n)\n```\n\nIn the high-level API, the basis for an RL experiment is an `ExperimentBuilder`\nwith which we can build the experiment we then seek to run.\nSince we want to use DQN, we use the specialization `DQNExperimentBuilder`.\nThe other imports serve to provide configuration options for our experiment.\n\nThe high-level API provides largely declarative semantics, i.e. the code is\nalmost exclusively concerned with configuration that controls what to do\n(rather than how to do it).\n\n```python\nexperiment = (\n    DQNExperimentBuilder(\n        EnvFactoryRegistered(task=\"CartPole-v1\", train_seed=0, test_seed=0, venv_type=VectorEnvType.DUMMY),\n        ExperimentConfig(\n            persistence_enabled=False,\n            watch=True,\n            watch_render=1 / 35,\n            watch_num_episodes=100,\n        ),\n        SamplingConfig(\n            num_epochs=10,\n            step_per_epoch=10000,\n            batch_size=64,\n            num_train_envs=10,\n            num_test_envs=100,\n            buffer_size=20000,\n            step_per_collect=10,\n            update_per_step=1 / 10,\n        ),\n    )\n    .with_dqn_params(\n        DQNParams(\n            lr=1e-3,\n            discount_factor=0.9,\n            estimation_step=3,\n            target_update_freq=320,\n        ),\n    )\n    .with_model_factory_default(hidden_sizes=(64, 64))\n    .with_epoch_train_callback(EpochTrainCallbackDQNSetEps(0.3))\n    .with_epoch_test_callback(EpochTestCallbackDQNSetEps(0.0))\n    .with_epoch_stop_callback(EpochStopCallbackRewardThreshold(195))\n    .build()\n)\nexperiment.run()\n```\n\nThe experiment builder takes three arguments:\n\n- the environment factory for the creation of environments. In this case,\n  we use an existing factory implementation for gymnasium environments.\n- the experiment configuration, which controls persistence and the overall\n  experiment flow. In this case, we have configured that we want to observe\n  the agent's behavior after it is trained (`watch=True`) for a number of\n  episodes (`watch_num_episodes=100`). We have disabled persistence, because\n  we do not want to save training logs, the agent or its configuration for\n  future use.\n- the sampling configuration, which controls fundamental training parameters,\n  such as the total number of epochs we run the experiment for (`num_epochs=10`)  \n  and the number of environment steps each epoch shall consist of\n  (`step_per_epoch=10000`).\n  Every epoch consists of a series of data collection (rollout) steps and\n  training steps.\n  The parameter `step_per_collect` controls the amount of data that is\n  collected in each collection step and after each collection step, we\n  perform a training step, applying a gradient-based update based on a sample\n  of data (`batch_size=64`) taken from the buffer of data that has been\n  collected. For further details, see the documentation of `SamplingConfig`.\n\nWe then proceed to configure some of the parameters of the DQN algorithm itself\nand of the neural network model we want to use.\nA DQN-specific detail is the use of callbacks to configure the algorithm's\nepsilon parameter for exploration. We want to use random exploration during rollouts\n(train callback), but we don't when evaluating the agent's performance in the test\nenvironments (test callback).\n\nFind the script in [examples/discrete/discrete_dqn_hl.py](examples/discrete/discrete_dqn_hl.py).\nHere's a run (with the training time cut short):\n\n\u003cp align=\"center\" style=\"text-algin:center\"\u003e\n  \u003cimg src=\"docs/_static/images/discrete_dqn_hl.gif\"\u003e\n\u003c/p\u003e\n\nFind many further applications of the high-level API in the `examples/` folder;\nlook for scripts ending with `_hl.py`.\nNote that most of these examples require the extra package `argparse`\n(install it by adding `--extras argparse` when invoking poetry).\n\n### Procedural API\n\nLet us now consider an analogous example in the procedural API.\nFind the full script in [examples/discrete/discrete_dqn.py](https://github.com/thu-ml/tianshou/blob/master/examples/discrete/discrete_dqn.py).\n\nFirst, import some relevant packages:\n\n```python\nimport gymnasium as gym\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nimport tianshou as ts\n```\n\nDefine some hyper-parameters:\n\n```python\ntask = 'CartPole-v1'\nlr, epoch, batch_size = 1e-3, 10, 64\ntrain_num, test_num = 10, 100\ngamma, n_step, target_freq = 0.9, 3, 320\nbuffer_size = 20000\neps_train, eps_test = 0.1, 0.05\nstep_per_epoch, step_per_collect = 10000, 10\n```\n\nInitialize the logger:\n\n```python\nlogger = ts.utils.TensorboardLogger(SummaryWriter('log/dqn'))\n# For other loggers, see https://tianshou.readthedocs.io/en/master/01_tutorials/05_logger.html\n```\n\nMake environments:\n\n```python\n# You can also try SubprocVectorEnv, which will use parallelization\ntrain_envs = ts.env.DummyVectorEnv([lambda: gym.make(task) for _ in range(train_num)])\ntest_envs = ts.env.DummyVectorEnv([lambda: gym.make(task) for _ in range(test_num)])\n```\n\nCreate the network as well as its optimizer:\n\n```python\nfrom tianshou.utils.net.common import Net\n\n# Note: You can easily define other networks.\n# See https://tianshou.readthedocs.io/en/master/01_tutorials/00_dqn.html#build-the-network\nenv = gym.make(task, render_mode=\"human\")\nstate_shape = env.observation_space.shape or env.observation_space.n\naction_shape = env.action_space.shape or env.action_space.n\nnet = Net(state_shape=state_shape, action_shape=action_shape, hidden_sizes=[128, 128, 128])\noptim = torch.optim.Adam(net.parameters(), lr=lr)\n```\n\nSet up the policy and collectors:\n\n```python\npolicy = ts.policy.DQNPolicy(\n    model=net,\n    optim=optim,\n    discount_factor=gamma,\n    action_space=env.action_space,\n    estimation_step=n_step,\n    target_update_freq=target_freq\n)\ntrain_collector = ts.data.Collector(policy, train_envs, ts.data.VectorReplayBuffer(buffer_size, train_num), exploration_noise=True)\ntest_collector = ts.data.Collector(policy, test_envs, exploration_noise=True)  # because DQN uses epsilon-greedy method\n```\n\nLet's train it:\n\n```python\nresult = ts.trainer.OffpolicyTrainer(\n    policy=policy,\n    train_collector=train_collector,\n    test_collector=test_collector,\n    max_epoch=epoch,\n    step_per_epoch=step_per_epoch,\n    step_per_collect=step_per_collect,\n    episode_per_test=test_num,\n    batch_size=batch_size,\n    update_per_step=1 / step_per_collect,\n    train_fn=lambda epoch, env_step: policy.set_eps(eps_train),\n    test_fn=lambda epoch, env_step: policy.set_eps(eps_test),\n    stop_fn=lambda mean_rewards: mean_rewards \u003e= env.spec.reward_threshold,\n    logger=logger,\n).run()\nprint(f\"Finished training in {result.timing.total_time} seconds\")\n```\n\nSave/load the trained policy (it's exactly the same as loading a `torch.nn.module`):\n\n```python\ntorch.save(policy.state_dict(), 'dqn.pth')\npolicy.load_state_dict(torch.load('dqn.pth'))\n```\n\nWatch the agent with 35 FPS:\n\n```python\npolicy.eval()\npolicy.set_eps(eps_test)\ncollector = ts.data.Collector(policy, env, exploration_noise=True)\ncollector.collect(n_episode=1, render=1 / 35)\n```\n\nInspect the data saved in TensorBoard:\n\n```bash\n$ tensorboard --logdir log/dqn\n```\n\nPlease read the [documentation](https://tianshou.readthedocs.io) for advanced usage.\n\n## Contributing\n\nTianshou is still under development.\nFurther algorithms and features are continuously being added, and we always welcome contributions to help make Tianshou better.\nIf you would like to contribute, please check out [this link](https://tianshou.org/en/master/04_contributing/04_contributing.html).\n\n## Citing Tianshou\n\nIf you find Tianshou useful, please cite it in your publications.\n\n```latex\n@article{tianshou,\n  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},\n  title   = {Tianshou: A Highly Modularized Deep Reinforcement Learning Library},\n  journal = {Journal of Machine Learning Research},\n  year    = {2022},\n  volume  = {23},\n  number  = {267},\n  pages   = {1--6},\n  url     = {http://jmlr.org/papers/v23/21-1127.html}\n}\n```\n\n## Acknowledgments\n\nTianshou is supported by [appliedAI Institute for Europe](https://www.appliedai-institute.de/en/),\nwho is committed to providing long-term support and development.\n\nTianshou was previously a reinforcement learning platform based on TensorFlow. You can check out the branch [`priv`](https://github.com/thu-ml/tianshou/tree/priv) for more detail. Many thanks to [Haosheng Zou](https://github.com/HaoshengZou)'s pioneering work for Tianshou before version 0.1.1.\n\nWe would like to thank [TSAIL](http://ml.cs.tsinghua.edu.cn/) and [Institute for Artificial Intelligence, Tsinghua University](http://ml.cs.tsinghua.edu.cn/thuai/) for providing such an excellent AI research platform.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthu-ml%2Ftianshou","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthu-ml%2Ftianshou","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthu-ml%2Ftianshou/lists"}