# 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>
282 lines
8.3 KiB
Python
Executable File
282 lines
8.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
import os
|
|
import re
|
|
|
|
import matplotlib.pyplot as plt
|
|
import matplotlib.ticker as mticker
|
|
import numpy as np
|
|
from tools import csv2numpy, find_all_files, group_files
|
|
|
|
|
|
def smooth(y, radius, mode='two_sided', valid_only=False):
|
|
'''Smooth signal y, where radius is determines the size of the window.
|
|
|
|
mode='twosided':
|
|
average over the window [max(index - radius, 0), min(index + radius, len(y)-1)]
|
|
mode='causal':
|
|
average over the window [max(index - radius, 0), index]
|
|
valid_only: put nan in entries where the full-sized window is not available
|
|
'''
|
|
assert mode in ('two_sided', 'causal')
|
|
if len(y) < 2 * radius + 1:
|
|
return np.ones_like(y) * y.mean()
|
|
elif mode == 'two_sided':
|
|
convkernel = np.ones(2 * radius + 1)
|
|
out = np.convolve(y, convkernel, mode='same') / \
|
|
np.convolve(np.ones_like(y), convkernel, mode='same')
|
|
if valid_only:
|
|
out[:radius] = out[-radius:] = np.nan
|
|
elif mode == 'causal':
|
|
convkernel = np.ones(radius)
|
|
out = np.convolve(y, convkernel, mode='full') / \
|
|
np.convolve(np.ones_like(y), convkernel, mode='full')
|
|
out = out[:-radius + 1]
|
|
if valid_only:
|
|
out[:radius] = np.nan
|
|
return out
|
|
|
|
|
|
COLORS = (
|
|
[
|
|
# deepmind style
|
|
'#0072B2',
|
|
'#009E73',
|
|
'#D55E00',
|
|
'#CC79A7',
|
|
# '#F0E442',
|
|
'#d73027', # RED
|
|
# built-in color
|
|
'blue',
|
|
'red',
|
|
'pink',
|
|
'cyan',
|
|
'magenta',
|
|
'yellow',
|
|
'black',
|
|
'purple',
|
|
'brown',
|
|
'orange',
|
|
'teal',
|
|
'lightblue',
|
|
'lime',
|
|
'lavender',
|
|
'turquoise',
|
|
'darkgreen',
|
|
'tan',
|
|
'salmon',
|
|
'gold',
|
|
'darkred',
|
|
'darkblue',
|
|
'green',
|
|
# personal color
|
|
'#313695', # DARK BLUE
|
|
'#74add1', # LIGHT BLUE
|
|
'#f46d43', # ORANGE
|
|
'#4daf4a', # GREEN
|
|
'#984ea3', # PURPLE
|
|
'#f781bf', # PINK
|
|
'#ffc832', # YELLOW
|
|
'#000000', # BLACK
|
|
]
|
|
)
|
|
|
|
|
|
def plot_ax(
|
|
ax,
|
|
file_lists,
|
|
legend_pattern=".*",
|
|
xlabel=None,
|
|
ylabel=None,
|
|
title=None,
|
|
xlim=None,
|
|
xkey="env_step",
|
|
ykey="reward",
|
|
smooth_radius=0,
|
|
shaded_std=True,
|
|
legend_outside=False,
|
|
):
|
|
|
|
def legend_fn(x):
|
|
# return os.path.split(os.path.join(
|
|
# args.root_dir, x))[0].replace('/', '_') + " (10)"
|
|
return re.search(legend_pattern, x).group(0)
|
|
|
|
legneds = map(legend_fn, file_lists)
|
|
# sort filelist according to legends
|
|
file_lists = [f for _, f in sorted(zip(legneds, file_lists))]
|
|
legneds = list(map(legend_fn, file_lists))
|
|
|
|
for index, csv_file in enumerate(file_lists):
|
|
csv_dict = csv2numpy(csv_file)
|
|
x, y = csv_dict[xkey], csv_dict[ykey]
|
|
y = smooth(y, radius=smooth_radius)
|
|
color = COLORS[index % len(COLORS)]
|
|
ax.plot(x, y, color=color)
|
|
if shaded_std and ykey + ':shaded' in csv_dict:
|
|
y_shaded = smooth(csv_dict[ykey + ':shaded'], radius=smooth_radius)
|
|
ax.fill_between(x, y - y_shaded, y + y_shaded, color=color, alpha=.2)
|
|
|
|
ax.legend(
|
|
legneds,
|
|
loc=2 if legend_outside else None,
|
|
bbox_to_anchor=(1, 1) if legend_outside else None
|
|
)
|
|
ax.xaxis.set_major_formatter(mticker.EngFormatter())
|
|
if xlim is not None:
|
|
ax.set_xlim(xmin=0, xmax=xlim)
|
|
# add title
|
|
ax.set_title(title)
|
|
# add labels
|
|
if xlabel is not None:
|
|
ax.set_xlabel(xlabel)
|
|
if ylabel is not None:
|
|
ax.set_ylabel(ylabel)
|
|
|
|
|
|
def plot_figure(
|
|
file_lists,
|
|
group_pattern=None,
|
|
fig_length=6,
|
|
fig_width=6,
|
|
sharex=False,
|
|
sharey=False,
|
|
title=None,
|
|
**kwargs,
|
|
):
|
|
if not group_pattern:
|
|
fig, ax = plt.subplots(figsize=(fig_length, fig_width))
|
|
plot_ax(ax, file_lists, title=title, **kwargs)
|
|
else:
|
|
res = group_files(file_lists, group_pattern)
|
|
row_n = int(np.ceil(len(res) / 3))
|
|
col_n = min(len(res), 3)
|
|
fig, axes = plt.subplots(
|
|
row_n,
|
|
col_n,
|
|
sharex=sharex,
|
|
sharey=sharey,
|
|
figsize=(fig_length * col_n, fig_width * row_n),
|
|
squeeze=False
|
|
)
|
|
axes = axes.flatten()
|
|
for i, (k, v) in enumerate(res.items()):
|
|
plot_ax(axes[i], v, title=k, **kwargs)
|
|
if title: # add title
|
|
fig.suptitle(title, fontsize=20)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description='plotter')
|
|
parser.add_argument(
|
|
'--fig-length',
|
|
type=int,
|
|
default=6,
|
|
help='matplotlib figure length (default: 6)'
|
|
)
|
|
parser.add_argument(
|
|
'--fig-width', type=int, default=6, help='matplotlib figure width (default: 6)'
|
|
)
|
|
parser.add_argument(
|
|
'--style', default='seaborn', help='matplotlib figure style (default: seaborn)'
|
|
)
|
|
parser.add_argument(
|
|
'--title', default=None, help='matplotlib figure title (default: None)'
|
|
)
|
|
parser.add_argument(
|
|
'--xkey', default='env_step', help='x-axis key in csv file (default: env_step)'
|
|
)
|
|
parser.add_argument(
|
|
'--ykey', default='rew', help='y-axis key in csv file (default: rew)'
|
|
)
|
|
parser.add_argument(
|
|
'--smooth', type=int, default=0, help='smooth radius of y axis (default: 0)'
|
|
)
|
|
parser.add_argument(
|
|
'--xlabel', default='Timesteps', help='matplotlib figure xlabel'
|
|
)
|
|
parser.add_argument(
|
|
'--ylabel', default='Episode Reward', help='matplotlib figure ylabel'
|
|
)
|
|
parser.add_argument(
|
|
'--shaded-std',
|
|
action='store_true',
|
|
help='shaded region corresponding to standard deviation of the group'
|
|
)
|
|
parser.add_argument(
|
|
'--sharex',
|
|
action='store_true',
|
|
help='whether to share x axis within multiple sub-figures'
|
|
)
|
|
parser.add_argument(
|
|
'--sharey',
|
|
action='store_true',
|
|
help='whether to share y axis within multiple sub-figures'
|
|
)
|
|
parser.add_argument(
|
|
'--legend-outside',
|
|
action='store_true',
|
|
help='place the legend outside of the figure'
|
|
)
|
|
parser.add_argument(
|
|
'--xlim', type=int, default=None, help='x-axis limitation (default: None)'
|
|
)
|
|
parser.add_argument('--root-dir', default='./', help='root dir (default: ./)')
|
|
parser.add_argument(
|
|
'--file-pattern',
|
|
type=str,
|
|
default=r".*/test_rew_\d+seeds.csv$",
|
|
help='regular expression to determine whether or not to include target csv '
|
|
'file, default to including all test_rew_{num}seeds.csv file under rootdir'
|
|
)
|
|
parser.add_argument(
|
|
'--group-pattern',
|
|
type=str,
|
|
default=r"(/|^)\w*?\-v(\d|$)",
|
|
help='regular expression to group files in sub-figure, default to grouping '
|
|
'according to env_name dir, "" means no grouping'
|
|
)
|
|
parser.add_argument(
|
|
'--legend-pattern',
|
|
type=str,
|
|
default=r".*",
|
|
help='regular expression to extract legend from csv file path, default to '
|
|
'using file path as legend name.'
|
|
)
|
|
parser.add_argument('--show', action='store_true', help='show figure')
|
|
parser.add_argument(
|
|
'--output-path', type=str, help='figure save path', default="./figure.png"
|
|
)
|
|
parser.add_argument(
|
|
'--dpi', type=int, default=200, help='figure dpi (default: 200)'
|
|
)
|
|
args = parser.parse_args()
|
|
file_lists = find_all_files(args.root_dir, re.compile(args.file_pattern))
|
|
file_lists = [os.path.relpath(f, args.root_dir) for f in file_lists]
|
|
if args.style:
|
|
plt.style.use(args.style)
|
|
os.chdir(args.root_dir)
|
|
plot_figure(
|
|
file_lists,
|
|
group_pattern=args.group_pattern,
|
|
legend_pattern=args.legend_pattern,
|
|
fig_length=args.fig_length,
|
|
fig_width=args.fig_width,
|
|
title=args.title,
|
|
xlabel=args.xlabel,
|
|
ylabel=args.ylabel,
|
|
xkey=args.xkey,
|
|
ykey=args.ykey,
|
|
xlim=args.xlim,
|
|
sharex=args.sharex,
|
|
sharey=args.sharey,
|
|
smooth_radius=args.smooth,
|
|
shaded_std=args.shaded_std,
|
|
legend_outside=args.legend_outside
|
|
)
|
|
if args.output_path:
|
|
plt.savefig(args.output_path, dpi=args.dpi, bbox_inches='tight')
|
|
if args.show:
|
|
plt.show()
|