-
Notifications
You must be signed in to change notification settings - Fork 328
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature] multiagent data standardization: PPO advantages #2677
Merged
Merged
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3d1e978
multiagent norm
matteobettini 9cfe213
review comments
matteobettini fbe20d4
warning
matteobettini 1f9e7df
special case for no dim exclusion
matteobettini 2917287
typo
matteobettini 926a08d
better type suggestions
matteobettini 1b428f0
use included_dims instead of excluded
matteobettini 278a6c0
doc
matteobettini 121bbc1
add tests and fix bugs
vmoens File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,7 +24,7 @@ | |
from distutils.util import strtobool | ||
from functools import wraps | ||
from importlib import import_module | ||
from typing import Any, Callable, cast, Dict, TypeVar, Union | ||
from typing import Any, Callable, cast, Dict, Tuple, TypeVar, Union | ||
|
||
import numpy as np | ||
import torch | ||
|
@@ -872,6 +872,71 @@ def set_mode(self, type: Any | None) -> None: | |
self._mode = type | ||
|
||
|
||
def _standardize( | ||
input, exclude_dims: Tuple[int] = (), mean=None, std=None, eps: float = None | ||
): | ||
"""Standardizes the input tensor with the possibility of excluding specific dims from the statistics. | ||
|
||
Useful when processing multi-agent data to keep the agent dimensions independent. | ||
|
||
Args: | ||
input (Tensor): the input tensor to be standardized. | ||
exclude_dims (Sequence[int]): dimensions to exclude from the statistics, can be negative. Default: (). | ||
mean (Tensor): a mean to be used for standardization. Must be of shape broadcastable to input. Default: None. | ||
std (Tensor): a standard deviation to be used for standardization. Must be of shape broadcastable to input. Default: None. | ||
eps (float): epsilon to be used for numerical stability. Default: float32 resolution. | ||
|
||
""" | ||
if eps is None: | ||
eps = torch.finfo(torch.float.dtype).resolution | ||
|
||
input_shape = input.shape | ||
exclude_dims = [ | ||
d if d >= 0 else d + len(input_shape) for d in exclude_dims | ||
] # Make negative dims positive | ||
|
||
if len(set(exclude_dims)) != len(exclude_dims): | ||
raise ValueError("Exclude dims has repeating elements") | ||
if any(dim < 0 or dim >= len(input_shape) for dim in exclude_dims): | ||
raise ValueError( | ||
f"exclude_dims={exclude_dims} provided outside bounds for input of shape={input_shape}" | ||
) | ||
if len(exclude_dims) == len(input_shape): | ||
warnings.warn( | ||
"standardize called but all dims were excluded from the statistics, returning unprocessed input" | ||
) | ||
return input | ||
|
||
if len(exclude_dims): | ||
# Put all excluded dims in the beginning | ||
permutation = list(range(len(input_shape))) | ||
for dim in exclude_dims: | ||
permutation.insert(0, permutation.pop(permutation.index(dim))) | ||
permuted_input = input.permute(*permutation) | ||
else: | ||
permuted_input = input | ||
normalized_shape_len = len(input_shape) - len(exclude_dims) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This doesn't need to be computed if |
||
|
||
if mean is None: | ||
mean = torch.mean( | ||
permuted_input, keepdim=True, dim=tuple(range(-normalized_shape_len, 0)) | ||
) | ||
if std is None: | ||
std = torch.std( | ||
permuted_input, keepdim=True, dim=tuple(range(-normalized_shape_len, 0)) | ||
) | ||
vmoens marked this conversation as resolved.
Show resolved
Hide resolved
|
||
output = (permuted_input - mean) / std.clamp_min(eps) | ||
|
||
# Reverse permutation | ||
if len(exclude_dims): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here, we're checking multiple times if |
||
inv_permutation = torch.argsort( | ||
torch.tensor(permutation, dtype=torch.long, device=input.device) | ||
).tolist() | ||
output = torch.permute(output, inv_permutation) | ||
|
||
return output | ||
|
||
|
||
@wraps(torch.compile) | ||
def compile_with_warmup(*args, warmup: int = 1, **kwargs): | ||
"""Compile a model with warm-up. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All of this can be skipped if
exclude_dims
is empty