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

proposed fix for RunningMeanStd overflow #1954

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions stable_baselines3/common/running_mean_std.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,30 @@ def update_from_moments(self, batch_mean: np.ndarray, batch_var: np.ndarray, bat
delta = batch_mean - self.mean
tot_count = self.count + batch_count

new_mean = self.mean + delta * batch_count / tot_count
m_a = self.var * self.count
m_b = batch_var * batch_count
m_2 = m_a + m_b + np.square(delta) * self.count * batch_count / (self.count + batch_count)
new_var = m_2 / (self.count + batch_count)
with np.errstate(over="raise"):
try:
new_mean = self.mean + delta * batch_count / tot_count
m_a = self.var * self.count
m_b = batch_var * batch_count

new_count = batch_count + self.count
# Calculate the products/divisions in an order that reduces the chance of overflow
# Original code:
# m_2 = m_a + m_b + np.square(delta) * self.count * batch_count / (self.count + batch_count)
# new_var = m_2 / (self.count + batch_count)
mult1 = self.count / (self.count + batch_count)
mult2 = batch_count / (self.count + batch_count)
var_delta = np.square(delta) * mult1 * mult2
new_var = (m_a + m_b) / (self.count + batch_count) + var_delta

self.mean = new_mean
self.var = new_var
self.count = new_count
new_count = batch_count + self.count

self.mean = new_mean
self.var = new_var
self.count = new_count

except FloatingPointError:
# This happens because self.count has gotten too large and the multiplication is overflowing
# We need to scale down the batch statistics
self.count /= 2
batch_count /= 2
self.update_from_moments(batch_mean, batch_var, batch_count)