2023-10-17 10:28:24 +02:00
{
2023-10-17 13:59:37 +02:00
"cells": [
{
2023-10-26 16:27:59 +02:00
"cell_type": "markdown",
2023-10-17 13:59:37 +02:00
"metadata": {
2023-10-26 16:27:59 +02:00
"id": "M98bqxdMsTXK"
2023-10-17 13:59:37 +02:00
},
"source": [
2023-10-26 16:27:59 +02:00
"# Collector\n",
2023-11-09 13:36:23 +01:00
"From its literal meaning, we can easily know that the Collector in Tianshou is used to collect training data. More specifically, the Collector controls the interaction between Policy (agent) and the environment. It also helps save the interaction data into the ReplayBuffer and returns episode statistics.\n",
2023-10-17 13:59:37 +02:00
"\n",
"<center>\n",
2023-11-17 11:33:44 +01:00
"<img src=../_static/images/structure.svg></img>\n",
2023-10-17 13:59:37 +02:00
"</center>\n",
"\n"
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
2023-10-26 16:27:59 +02:00
"metadata": {
"id": "OX5cayLv4Ziu"
},
2023-10-17 13:59:37 +02:00
"source": [
2023-11-09 13:36:23 +01:00
"## Usages\n",
2023-10-17 13:59:37 +02:00
"Collector can be used both for training (data collecting) and evaluation in Tianshou."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
2023-10-26 16:27:59 +02:00
"metadata": {
"id": "Z6XKbj28u8Ze"
},
2023-10-17 13:59:37 +02:00
"source": [
2023-11-09 13:36:23 +01:00
"### Policy evaluation\n",
2023-10-17 13:59:37 +02:00
"We need to evaluate our trained policy from time to time in DRL experiments. Collector can help us with this.\n",
"\n",
2023-11-09 13:36:23 +01:00
"First we have to initialize a Collector with an (vectorized) environment and a given policy (agent)."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "code",
2023-10-26 16:27:59 +02:00
"execution_count": null,
"metadata": {
"editable": true,
"id": "w8t9ubO7u69J",
"slideshow": {
"slide_type": ""
},
"tags": [
"hide-cell",
"remove-output"
]
},
"outputs": [],
2023-10-17 13:59:37 +02:00
"source": [
2024-02-07 17:28:16 +01:00
"%%capture\n",
"\n",
2023-10-26 16:27:59 +02:00
"import gymnasium as gym\n",
2023-10-17 13:59:37 +02:00
"import torch\n",
"\n",
2024-02-07 17:28:16 +01:00
"from tianshou.data import Collector, VectorReplayBuffer\n",
2023-10-17 13:59:37 +02:00
"from tianshou.env import DummyVectorEnv\n",
2024-04-03 18:07:51 +02:00
"from tianshou.policy import PGPolicy\n",
2023-10-17 13:59:37 +02:00
"from tianshou.utils.net.common import Net\n",
2024-02-07 17:28:16 +01:00
"from tianshou.utils.net.discrete import Actor"
2023-10-26 16:27:59 +02:00
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"env = gym.make(\"CartPole-v1\")\n",
"test_envs = DummyVectorEnv([lambda: gym.make(\"CartPole-v1\") for _ in range(2)])\n",
2023-10-17 13:59:37 +02:00
"\n",
"# model\n",
2024-02-07 17:28:16 +01:00
"assert env.observation_space.shape is not None # for mypy\n",
2023-10-26 16:27:59 +02:00
"net = Net(\n",
" env.observation_space.shape,\n",
" hidden_sizes=[\n",
" 16,\n",
" ],\n",
")\n",
2024-02-07 17:28:16 +01:00
"\n",
"assert isinstance(env.action_space, gym.spaces.Discrete) # for mypy\n",
"actor = Actor(net, env.action_space.n)\n",
2023-10-17 13:59:37 +02:00
"optim = torch.optim.Adam(actor.parameters(), lr=0.0003)\n",
"\n",
2024-04-03 18:07:51 +02:00
"policy: PGPolicy = PGPolicy(\n",
2023-10-26 16:27:59 +02:00
" actor=actor,\n",
" optim=optim,\n",
" dist_fn=torch.distributions.Categorical,\n",
" action_space=env.action_space,\n",
" action_scaling=False,\n",
")\n",
2023-10-17 13:59:37 +02:00
"test_collector = Collector(policy, test_envs)"
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "wmt8vuwpzQdR"
2023-10-26 16:27:59 +02:00
},
"source": [
2023-11-09 13:36:23 +01:00
"Now we would like to collect 9 episodes of data to test how our initialized Policy performs."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "code",
2023-10-26 16:27:59 +02:00
"execution_count": null,
2023-10-17 13:59:37 +02:00
"metadata": {
2023-10-17 10:28:24 +02:00
"colab": {
2023-10-17 13:59:37 +02:00
"base_uri": "https://localhost:8080/"
2023-10-17 10:28:24 +02:00
},
2023-10-17 13:59:37 +02:00
"id": "9SuT6MClyjyH",
"outputId": "1e48f13b-c1fe-4fc2-ca1b-669485efdcae"
},
2023-10-26 16:27:59 +02:00
"outputs": [],
"source": [
2024-03-28 18:02:31 +01:00
"collect_result = test_collector.collect(reset_before_collect=True, n_episode=9)\n",
2024-02-07 17:28:16 +01:00
"\n",
"collect_result.pprint_asdict()"
2023-10-26 16:27:59 +02:00
]
2023-10-17 10:28:24 +02:00
},
2023-10-17 13:59:37 +02:00
{
"cell_type": "markdown",
"metadata": {
"id": "zX9AQY0M0R3C"
2023-10-26 16:27:59 +02:00
},
"source": [
"Now we wonder what is the performance of a random policy."
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "code",
2023-10-26 16:27:59 +02:00
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "UEcs8P8P0RLt",
"outputId": "85f02f9d-b79b-48b2-99c6-36a1602f0884"
},
"outputs": [],
2023-10-17 13:59:37 +02:00
"source": [
"# Reset the collector\n",
2024-03-28 18:02:31 +01:00
"collect_result = test_collector.collect(reset_before_collect=True, n_episode=9, random=True)\n",
2024-02-07 17:28:16 +01:00
"\n",
"collect_result.pprint_asdict()"
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "sKQRTiG10ljU"
2023-10-26 16:27:59 +02:00
},
"source": [
Feature/dataclasses (#996)
This PR adds strict typing to the output of `update` and `learn` in all
policies. This will likely be the last large refactoring PR before the
next release (0.6.0, not 1.0.0), so it requires some attention. Several
difficulties were encountered on the path to that goal:
1. The policy hierarchy is actually "broken" in the sense that the keys
of dicts that were output by `learn` did not follow the same enhancement
(inheritance) pattern as the policies. This is a real problem and should
be addressed in the near future. Generally, several aspects of the
policy design and hierarchy might deserve a dedicated discussion.
2. Each policy needs to be generic in the stats return type, because one
might want to extend it at some point and then also extend the stats.
Even within the source code base this pattern is necessary in many
places.
3. The interaction between learn and update is a bit quirky, we
currently handle it by having update modify special field inside
TrainingStats, whereas all other fields are handled by learn.
4. The IQM module is a policy wrapper and required a
TrainingStatsWrapper. The latter relies on a bunch of black magic.
They were addressed by:
1. Live with the broken hierarchy, which is now made visible by bounds
in generics. We use type: ignore where appropriate.
2. Make all policies generic with bounds following the policy
inheritance hierarchy (which is incorrect, see above). We experimented a
bit with nested TrainingStats classes, but that seemed to add more
complexity and be harder to understand. Unfortunately, mypy thinks that
the code below is wrong, wherefore we have to add `type: ignore` to the
return of each `learn`
```python
T = TypeVar("T", bound=int)
def f() -> T:
return 3
```
3. See above
4. Write representative tests for the `TrainingStatsWrapper`. Still, the
black magic might cause nasty surprises down the line (I am not proud of
it)...
Closes #933
---------
Co-authored-by: Maximilian Huettenrauch <m.huettenrauch@appliedai.de>
Co-authored-by: Michael Panchenko <m.panchenko@appliedai.de>
2023-12-30 11:09:03 +01:00
"It seems like an initialized policy performs even worse than a random policy without any training."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
2023-10-26 16:27:59 +02:00
"metadata": {
"id": "8RKmHIoG1A1k"
},
2023-10-17 13:59:37 +02:00
"source": [
2023-11-09 13:36:23 +01:00
"### Data Collecting\n",
2023-10-17 13:59:37 +02:00
"Data collecting is mostly used during training, when we need to store the collected data in a ReplayBuffer."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "code",
2023-10-26 16:27:59 +02:00
"execution_count": null,
"metadata": {
"editable": true,
"id": "CB9XB9bF1YPC",
"slideshow": {
"slide_type": ""
},
"tags": []
},
"outputs": [],
2023-10-17 13:59:37 +02:00
"source": [
"train_env_num = 4\n",
"buffer_size = 100\n",
2023-10-26 16:27:59 +02:00
"train_envs = DummyVectorEnv([lambda: gym.make(\"CartPole-v1\") for _ in range(train_env_num)])\n",
2024-02-07 17:28:16 +01:00
"replayBuffer = VectorReplayBuffer(buffer_size, train_env_num)\n",
2023-10-17 13:59:37 +02:00
"\n",
2024-02-07 17:28:16 +01:00
"train_collector = Collector(policy, train_envs, replayBuffer)"
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "rWKDazA42IUQ"
2023-10-26 16:27:59 +02:00
},
"source": [
"Now we can collect 50 steps of data, which will be automatically saved in the replay buffer. You can still choose to collect a certain number of episodes rather than steps. Try it yourself."
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "code",
2023-10-26 16:27:59 +02:00
"execution_count": null,
2023-10-17 13:59:37 +02:00
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
2023-10-17 10:28:24 +02:00
},
2023-10-17 13:59:37 +02:00
"id": "-fUtQOnM2Yi1",
"outputId": "dceee987-433e-4b75-ed9e-823c20a9e1c2"
},
2023-10-26 16:27:59 +02:00
"outputs": [],
"source": [
2024-02-07 17:28:16 +01:00
"train_collector.reset()\n",
"replayBuffer.reset()\n",
"\n",
"print(f\"Replay buffer before collecting is empty, and has length={len(replayBuffer)} \\n\")\n",
"n_step = 50\n",
"collect_result = train_collector.collect(n_step=n_step)\n",
"print(\n",
" f\"Replay buffer after collecting {n_step} steps has length={len(replayBuffer)}.\\n\"\n",
" f\"This may exceed n_step when it is not a multiple of train_env_num because of vectorization.\\n\",\n",
")\n",
"collect_result.pprint_asdict()"
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
2024-02-07 17:28:16 +01:00
"cell_type": "markdown",
"metadata": {},
2023-10-26 16:27:59 +02:00
"source": [
2024-02-07 17:28:16 +01:00
"Sample some data from the replay buffer."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "code",
2023-10-26 16:27:59 +02:00
"execution_count": null,
2024-02-07 17:28:16 +01:00
"metadata": {},
2023-10-26 16:27:59 +02:00
"outputs": [],
"source": [
2024-02-07 17:28:16 +01:00
"replayBuffer.sample(10)"
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
},
{
"cell_type": "markdown",
2023-10-26 16:27:59 +02:00
"metadata": {
"id": "8NP7lOBU3-VS"
},
2023-10-17 13:59:37 +02:00
"source": [
2023-11-09 13:36:23 +01:00
"## Further Reading\n",
2023-10-17 13:59:37 +02:00
"The above collector actually collects 52 data at a time because 52 % 4 = 0. There is one asynchronous collector which allows you collect exactly 50 steps. Check the [documentation](https://tianshou.readthedocs.io/en/master/api/tianshou.data.html#asynccollector) for details."
2023-10-26 16:27:59 +02:00
]
2023-10-17 13:59:37 +02:00
}
2023-10-26 16:27:59 +02:00
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
2023-10-17 13:59:37 +02:00
}