Skip to content
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

Fix integer overflow in MultiDiscrete.flatten() #55

Merged
merged 2 commits into from
Oct 14, 2022

Conversation

olipinski
Copy link
Contributor

@olipinski olipinski commented Oct 13, 2022

Description

Fixes integer overflow in the flatten function when dtype is small.

The current code will calculate the offsets as is, overflowing the max integer value and going to negatives. Once this is passed to one_hot we get an error as per the linked issue.

File "C:\Users\user\Anaconda3\envs\TRG\lib\site-packages\gym\spaces\utils.py", line 90, in _flatten_multidiscrete
    onehot = np.zeros((offsets[-1],), dtype=space.dtype)
ValueError: negative dimensions are not allowed

Fixes

#53

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Test

import gym
import numpy as np

space = gym.spaces.MultiDiscrete([101, 101, 101, 101], dtype=np.int8)
x = space.sample()

y = gym.spaces.flatten(space, x)

x = gym.spaces.unflatten(space, y)

print(x)
[82 52 50 66]

Checklist:

  • I have run the pre-commit checks with pre-commit run --all-files (see CONTRIBUTING.md instructions to set it up)
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Signed-off-by: Olaf Lipinski <[email protected]>
@pseudo-rnd-thoughts
Copy link
Member

Could you explain the error that occurred before running the example code

Could you add a test in tests/spaces/test_discrete.py using the example provided in the PR.

Signed-off-by: Olaf Lipinski <[email protected]>
@olipinski
Copy link
Contributor Author

Updated, and test added.

Copy link
Member

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think changing to int32 is good enough. It is impractical to anyone to have more subspaces than ~2 billion so I think this is a safe choice.

@pseudo-rnd-thoughts pseudo-rnd-thoughts merged commit dec9f2c into Farama-Foundation:main Oct 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants