2021-09-24 19:22:23 +05:30
|
|
|
import argparse
|
2023-08-25 23:40:56 +02:00
|
|
|
import contextlib
|
2021-09-24 19:22:23 +05:30
|
|
|
import os
|
2023-09-05 23:34:23 +02:00
|
|
|
from collections.abc import Callable
|
2021-09-24 19:22:23 +05:30
|
|
|
|
2022-03-06 17:40:47 -05:00
|
|
|
from torch.utils.tensorboard import SummaryWriter
|
|
|
|
|
|
|
|
from tianshou.utils import BaseLogger, TensorboardLogger
|
2024-04-21 01:25:33 +02:00
|
|
|
from tianshou.utils.logger.base import VALID_LOG_VALS_TYPE, TRestoredData
|
2021-08-30 10:35:02 -04:00
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
with contextlib.suppress(ImportError):
|
2021-08-30 10:35:02 -04:00
|
|
|
import wandb
|
|
|
|
|
|
|
|
|
2021-09-24 19:22:23 +05:30
|
|
|
class WandbLogger(BaseLogger):
|
|
|
|
"""Weights and Biases logger that sends data to https://wandb.ai/.
|
2021-08-30 10:35:02 -04:00
|
|
|
|
2021-09-24 19:22:23 +05:30
|
|
|
This logger creates three panels with plots: train, test, and update.
|
2021-08-30 10:35:02 -04:00
|
|
|
Make sure to select the correct access for each panel in weights and biases:
|
|
|
|
|
|
|
|
Example of usage:
|
|
|
|
::
|
|
|
|
|
2022-03-06 17:40:47 -05:00
|
|
|
logger = WandbLogger()
|
|
|
|
logger.load(SummaryWriter(log_path))
|
Improved typing and reduced duplication (#912)
# Goals of the PR
The PR introduces **no changes to functionality**, apart from improved
input validation here and there. The main goals are to reduce some
complexity of the code, to improve types and IDE completions, and to
extend documentation and block comments where appropriate. Because of
the change to the trainer interfaces, many files are affected (more
details below), but still the overall changes are "small" in a certain
sense.
## Major Change 1 - BatchProtocol
**TL;DR:** One can now annotate which fields the batch is expected to
have on input params and which fields a returned batch has. Should be
useful for reading the code. getting meaningful IDE support, and
catching bugs with mypy. This annotation strategy will continue to work
if Batch is replaced by TensorDict or by something else.
**In more detail:** Batch itself has no fields and using it for
annotations is of limited informational power. Batches with fields are
not separate classes but instead instances of Batch directly, so there
is no type that could be used for annotation. Fortunately, python
`Protocol` is here for the rescue. With these changes we can now do
things like
```python
class ActionBatchProtocol(BatchProtocol):
logits: Sequence[Union[tuple, torch.Tensor]]
dist: torch.distributions.Distribution
act: torch.Tensor
state: Optional[torch.Tensor]
class RolloutBatchProtocol(BatchProtocol):
obs: torch.Tensor
obs_next: torch.Tensor
info: Dict[str, Any]
rew: torch.Tensor
terminated: torch.Tensor
truncated: torch.Tensor
class PGPolicy(BasePolicy):
...
def forward(
self,
batch: RolloutBatchProtocol,
state: Optional[Union[dict, Batch, np.ndarray]] = None,
**kwargs: Any,
) -> ActionBatchProtocol:
```
The IDE and mypy are now very helpful in finding errors and in
auto-completion, whereas before the tools couldn't assist in that at
all.
## Major Change 2 - remove duplication in trainer package
**TL;DR:** There was a lot of duplication between `BaseTrainer` and its
subclasses. Even worse, it was almost-duplication. There was also
interface fragmentation through things like `onpolicy_trainer`. Now this
duplication is gone and all downstream code was adjusted.
**In more detail:** Since this change affects a lot of code, I would
like to explain why I thought it to be necessary.
1. The subclasses of `BaseTrainer` just duplicated docstrings and
constructors. What's worse, they changed the order of args there, even
turning some kwargs of BaseTrainer into args. They also had the arg
`learning_type` which was passed as kwarg to the base class and was
unused there. This made things difficult to maintain, and in fact some
errors were already present in the duplicated docstrings.
2. The "functions" a la `onpolicy_trainer`, which just called the
`OnpolicyTrainer.run`, not only introduced interface fragmentation but
also completely obfuscated the docstring and interfaces. They themselves
had no dosctring and the interface was just `*args, **kwargs`, which
makes it impossible to understand what they do and which things can be
passed without reading their implementation, then reading the docstring
of the associated class, etc. Needless to say, mypy and IDEs provide no
support with such functions. Nevertheless, they were used everywhere in
the code-base. I didn't find the sacrifices in clarity and complexity
justified just for the sake of not having to write `.run()` after
instantiating a trainer.
3. The trainers are all very similar to each other. As for my
application I needed a new trainer, I wanted to understand their
structure. The similarity, however, was hard to discover since they were
all in separate modules and there was so much duplication. I kept
staring at the constructors for a while until I figured out that
essentially no changes to the superclass were introduced. Now they are
all in the same module and the similarities/differences between them are
much easier to grasp (in my opinion)
4. Because of (1), I had to manually change and check a lot of code,
which was very tedious and boring. This kind of work won't be necessary
in the future, since now IDEs can be used for changing signatures,
renaming args and kwargs, changing class names and so on.
I have some more reasons, but maybe the above ones are convincing
enough.
## Minor changes: improved input validation and types
I added input validation for things like `state` and `action_scaling`
(which only makes sense for continuous envs). After adding this, some
tests failed to pass this validation. There I added
`action_scaling=isinstance(env.action_space, Box)`, after which tests
were green. I don't know why the tests were green before, since action
scaling doesn't make sense for discrete actions. I guess some aspect was
not tested and didn't crash.
I also added Literal in some places, in particular for
`action_bound_method`. Now it is no longer allowed to pass an empty
string, instead one should pass `None`. Also here there is input
validation with clear error messages.
@Trinkle23897 The functional tests are green. I didn't want to fix the
formatting, since it will change in the next PR that will solve #914
anyway. I also found a whole bunch of code in `docs/_static`, which I
just deleted (shouldn't it be copied from the sources during docs build
instead of committed?). I also haven't adjusted the documentation yet,
which atm still mentions the trainers of the type
`onpolicy_trainer(...)` instead of `OnpolicyTrainer(...).run()`
## Breaking Changes
The adjustments to the trainer package introduce breaking changes as
duplicated interfaces are deleted. However, it should be very easy for
users to adjust to them
---------
Co-authored-by: Michael Panchenko <m.panchenko@appliedai.de>
2023-08-22 18:54:46 +02:00
|
|
|
result = OnpolicyTrainer(policy, train_collector, test_collector,
|
|
|
|
logger=logger).run()
|
2021-08-30 10:35:02 -04:00
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
:param train_interval: the log interval in log_train_data(). Default to 1000.
|
|
|
|
:param test_interval: the log interval in log_test_data(). Default to 1.
|
|
|
|
:param update_interval: the log interval in log_update_data().
|
2021-08-30 10:35:02 -04:00
|
|
|
Default to 1000.
|
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
|
|
|
:param info_interval: the log interval in log_info_data(). Default to 1.
|
2023-10-08 17:57:03 +02:00
|
|
|
:param save_interval: the save interval in save_data(). Default to 1 (save at
|
2022-03-29 20:04:23 -04:00
|
|
|
the end of each epoch).
|
2023-10-08 17:57:03 +02:00
|
|
|
:param write_flush: whether to flush tensorboard result after each
|
2022-03-29 20:04:23 -04:00
|
|
|
add_scalar operation. Default to True.
|
2021-09-24 19:22:23 +05:30
|
|
|
:param str project: W&B project name. Default to "tianshou".
|
|
|
|
:param str name: W&B run name. Default to None. If None, random name is assigned.
|
|
|
|
:param str entity: W&B team/organization name. Default to None.
|
|
|
|
:param str run_id: run id of W&B run to be resumed. Default to None.
|
|
|
|
:param argparse.Namespace config: experiment configurations. Default to None.
|
2021-08-30 10:35:02 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
train_interval: int = 1000,
|
|
|
|
test_interval: int = 1,
|
|
|
|
update_interval: int = 1000,
|
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
|
|
|
info_interval: int = 1,
|
2021-09-24 19:22:23 +05:30
|
|
|
save_interval: int = 1000,
|
2022-03-29 20:04:23 -04:00
|
|
|
write_flush: bool = True,
|
2023-09-05 23:34:23 +02:00
|
|
|
project: str | None = None,
|
|
|
|
name: str | None = None,
|
|
|
|
entity: str | None = None,
|
|
|
|
run_id: str | None = None,
|
2023-09-26 10:48:13 +02:00
|
|
|
config: argparse.Namespace | dict | None = None,
|
2023-08-10 00:13:25 +02:00
|
|
|
monitor_gym: bool = True,
|
2021-08-30 10:35:02 -04:00
|
|
|
) -> None:
|
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
|
|
|
super().__init__(train_interval, test_interval, update_interval, info_interval)
|
2021-09-24 19:22:23 +05:30
|
|
|
self.last_save_step = -1
|
|
|
|
self.save_interval = save_interval
|
2022-03-29 20:04:23 -04:00
|
|
|
self.write_flush = write_flush
|
2021-09-24 19:22:23 +05:30
|
|
|
self.restored = False
|
2022-03-06 17:40:47 -05:00
|
|
|
if project is None:
|
|
|
|
project = os.getenv("WANDB_PROJECT", "tianshou")
|
2021-09-24 19:22:23 +05:30
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
self.wandb_run = (
|
|
|
|
wandb.init(
|
|
|
|
project=project,
|
|
|
|
name=name,
|
|
|
|
id=run_id,
|
|
|
|
resume="allow",
|
|
|
|
entity=entity,
|
|
|
|
sync_tensorboard=True,
|
|
|
|
monitor_gym=monitor_gym,
|
|
|
|
config=config, # type: ignore
|
|
|
|
)
|
|
|
|
if not wandb.run
|
|
|
|
else wandb.run
|
|
|
|
)
|
2024-04-21 01:25:33 +02:00
|
|
|
# TODO: don't access private attribute!
|
2021-09-24 19:22:23 +05:30
|
|
|
self.wandb_run._label(repo="tianshou") # type: ignore
|
2023-09-05 23:34:23 +02:00
|
|
|
self.tensorboard_logger: TensorboardLogger | None = None
|
2024-04-21 01:25:33 +02:00
|
|
|
self.writer: SummaryWriter | None = None
|
|
|
|
|
|
|
|
def prepare_dict_for_logging(self, log_data: dict) -> dict[str, VALID_LOG_VALS_TYPE]:
|
|
|
|
if self.tensorboard_logger is None:
|
|
|
|
raise Exception(
|
|
|
|
"`logger` needs to load the Tensorboard Writer before "
|
|
|
|
"preparing data for logging. Try `logger.load(SummaryWriter(log_path))`",
|
|
|
|
)
|
|
|
|
return self.tensorboard_logger.prepare_dict_for_logging(log_data)
|
2022-03-06 17:40:47 -05:00
|
|
|
|
|
|
|
def load(self, writer: SummaryWriter) -> None:
|
|
|
|
self.writer = writer
|
2022-03-29 20:04:23 -04:00
|
|
|
self.tensorboard_logger = TensorboardLogger(
|
2023-08-25 23:40:56 +02:00
|
|
|
writer,
|
|
|
|
self.train_interval,
|
|
|
|
self.test_interval,
|
|
|
|
self.update_interval,
|
|
|
|
self.save_interval,
|
|
|
|
self.write_flush,
|
2022-03-29 20:04:23 -04:00
|
|
|
)
|
2021-08-30 10:35:02 -04:00
|
|
|
|
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
|
|
|
def write(self, step_type: str, step: int, data: dict[str, VALID_LOG_VALS_TYPE]) -> None:
|
2022-03-06 17:40:47 -05:00
|
|
|
if self.tensorboard_logger is None:
|
2024-04-21 01:25:33 +02:00
|
|
|
raise RuntimeError(
|
2022-03-06 17:40:47 -05:00
|
|
|
"`logger` needs to load the Tensorboard Writer before "
|
2023-08-25 23:40:56 +02:00
|
|
|
"writing data. Try `logger.load(SummaryWriter(log_path))`",
|
2022-03-06 17:40:47 -05:00
|
|
|
)
|
2023-08-25 23:40:56 +02:00
|
|
|
self.tensorboard_logger.write(step_type, step, data)
|
2021-09-24 19:22:23 +05:30
|
|
|
|
|
|
|
def save_data(
|
|
|
|
self,
|
|
|
|
epoch: int,
|
|
|
|
env_step: int,
|
|
|
|
gradient_step: int,
|
2023-09-05 23:34:23 +02:00
|
|
|
save_checkpoint_fn: Callable[[int, int, int], str] | None = None,
|
2021-09-24 19:22:23 +05:30
|
|
|
) -> None:
|
|
|
|
"""Use writer to log metadata when calling ``save_checkpoint_fn`` in trainer.
|
|
|
|
|
2023-10-08 17:57:03 +02:00
|
|
|
:param epoch: the epoch in trainer.
|
|
|
|
:param env_step: the env_step in trainer.
|
|
|
|
:param gradient_step: the gradient_step in trainer.
|
2021-09-24 19:22:23 +05:30
|
|
|
:param function save_checkpoint_fn: a hook defined by user, see trainer
|
|
|
|
documentation for detail.
|
|
|
|
"""
|
|
|
|
if save_checkpoint_fn and epoch - self.last_save_step >= self.save_interval:
|
|
|
|
self.last_save_step = epoch
|
|
|
|
checkpoint_path = save_checkpoint_fn(epoch, env_step, gradient_step)
|
|
|
|
|
|
|
|
checkpoint_artifact = wandb.Artifact(
|
2023-08-25 23:40:56 +02:00
|
|
|
"run_" + self.wandb_run.id + "_checkpoint", # type: ignore
|
|
|
|
type="model",
|
2021-09-24 19:22:23 +05:30
|
|
|
metadata={
|
|
|
|
"save/epoch": epoch,
|
|
|
|
"save/env_step": env_step,
|
|
|
|
"save/gradient_step": gradient_step,
|
2022-06-02 12:07:07 -05:00
|
|
|
"checkpoint_path": str(checkpoint_path),
|
2023-08-25 23:40:56 +02:00
|
|
|
},
|
2021-09-24 19:22:23 +05:30
|
|
|
)
|
|
|
|
checkpoint_artifact.add_file(str(checkpoint_path))
|
|
|
|
self.wandb_run.log_artifact(checkpoint_artifact) # type: ignore
|
|
|
|
|
2023-08-25 23:40:56 +02:00
|
|
|
def restore_data(self) -> tuple[int, int, int]:
|
|
|
|
checkpoint_artifact = self.wandb_run.use_artifact( # type: ignore
|
|
|
|
f"run_{self.wandb_run.id}_checkpoint:latest", # type: ignore
|
2021-09-24 19:22:23 +05:30
|
|
|
)
|
|
|
|
assert checkpoint_artifact is not None, "W&B dataset artifact doesn't exist"
|
|
|
|
|
|
|
|
checkpoint_artifact.download(
|
2023-08-25 23:40:56 +02:00
|
|
|
os.path.dirname(checkpoint_artifact.metadata["checkpoint_path"]),
|
2021-09-24 19:22:23 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
try: # epoch / gradient_step
|
|
|
|
epoch = checkpoint_artifact.metadata["save/epoch"]
|
|
|
|
self.last_save_step = self.last_log_test_step = epoch
|
|
|
|
gradient_step = checkpoint_artifact.metadata["save/gradient_step"]
|
|
|
|
self.last_log_update_step = gradient_step
|
|
|
|
except KeyError:
|
|
|
|
epoch, gradient_step = 0, 0
|
|
|
|
try: # offline trainer doesn't have env_step
|
|
|
|
env_step = checkpoint_artifact.metadata["save/env_step"]
|
|
|
|
self.last_log_train_step = env_step
|
|
|
|
except KeyError:
|
|
|
|
env_step = 0
|
|
|
|
return epoch, env_step, gradient_step
|
2024-04-21 01:25:33 +02:00
|
|
|
|
|
|
|
def restore_logged_data(self, log_path: str) -> TRestoredData:
|
|
|
|
if self.tensorboard_logger is None:
|
|
|
|
raise NotImplementedError(
|
|
|
|
"Restoring logged data directly from W&B is not yet implemented."
|
|
|
|
"Try instantiating the internal TensorboardLogger by calling something"
|
|
|
|
"like `logger.load(SummaryWriter(log_path))`",
|
|
|
|
)
|
|
|
|
return self.tensorboard_logger.restore_logged_data(log_path)
|