diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py index 8f88457a..c23605a6 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py @@ -411,10 +411,10 @@ def update(self, x: torch.Tensor) -> None: new_count = self.count + batch_size delta = batch_mean - self._mean self._mean.copy_(self._mean + delta * (batch_size / new_count)) - delta2 = batch_mean - self._mean m_a = self._var * self.count m_b = batch_var * batch_size - big_m2 = m_a + m_b + delta2.pow(2) * (self.count * batch_size / new_count) + # Use the pre-update difference: a rounded new mean can erase delta2. + big_m2 = m_a + m_b + delta.square() * (self.count / new_count) * batch_size self._var.copy_(big_m2 / new_count) self._std.copy_(self._var.sqrt()) self.count.copy_(new_count) @@ -429,11 +429,10 @@ def update(self, x: torch.Tensor) -> None: l_count = self._local_count + batch_size delta = b_mean - self._local_mean self._local_mean += delta * (batch_size / l_count) - delta2 = b_mean - self._local_mean l_m2 = ( self._local_var * self._local_count + b_var * batch_size - + delta2.pow(2) * (self._local_count * batch_size / l_count) + + delta.square() * (self._local_count / l_count) * batch_size ) self._local_var.copy_(l_m2 / l_count) self._local_count = l_count diff --git a/motrix_rl_builtin/tests/test_fastsac_buffer.py b/motrix_rl_builtin/tests/test_fastsac_buffer.py index 2e507836..9990690d 100644 --- a/motrix_rl_builtin/tests/test_fastsac_buffer.py +++ b/motrix_rl_builtin/tests/test_fastsac_buffer.py @@ -14,7 +14,7 @@ import pytest import torch -from motrix_rl_builtin.fastsac.buffer import SimpleReplayBuffer +from motrix_rl_builtin.fastsac.buffer import EmpiricalNormalization, SimpleReplayBuffer N_ENV = 3 N_OBS = 4 @@ -74,6 +74,70 @@ def _sample_all(rb, batch_size): return rb.sample(batch_size) +@pytest.mark.parametrize( + "batches", + [ + [torch.tensor([[0.0]]), torch.tensor([[10.0]])], + [ + torch.tensor([[0.0, 2.0], [0.0, 4.0]]), + torch.tensor([[8.0, -2.0], [10.0, -4.0], [12.0, -6.0]]), + torch.tensor([[-3.0, 9.0]]), + ], + [torch.full((n, 2), 5.0) for n in (1, 3, 2)], + ], + ids=["two-singletons", "unequal-batches", "constant-features"], +) +def test_normalizer_streaming_statistics_match_concatenated_samples(batches: list[torch.Tensor]) -> None: + """Partitioning samples preserves their population statistics and local sums.""" + normalizer = EmpiricalNormalization(batches[0].shape[1], device="cpu") + normalizer.seed_local_accumulators() + seen = [] + for batch in batches: + seen.append(batch) + normalizer.update(batch) + samples = torch.cat(seen) + mean = samples.mean(dim=0, keepdim=True) + variance = samples.var(dim=0, keepdim=True, unbiased=False) + assert normalizer.count.item() == len(samples) + torch.testing.assert_close(normalizer._mean, mean) + torch.testing.assert_close(normalizer._var, variance) + torch.testing.assert_close(normalizer._std, variance.sqrt()) + sufficient_stats = normalizer.local_sufficient_stats_flat() + expected = torch.cat( + ( + torch.tensor([len(samples)], dtype=torch.float64), + samples.double().sum(dim=0), + samples.double().square().sum(dim=0), + ) + ) + torch.testing.assert_close(sufficient_stats, expected) + + +def test_normalizer_preserves_variance_when_new_mean_rounds_to_batch_mean() -> None: + """One zero and many ones retain nonzero variance despite float32 mean rounding.""" + normalizer = EmpiricalNormalization(1, device="cpu") + normalizer.seed_local_accumulators() + normalizer.update(torch.zeros(1, 1)) + batch_size = 2**24 + # A stride-zero batch avoids allocating millions of identical samples. + normalizer.update(torch.ones(1, 1).expand(batch_size, 1)) + # Bernoulli population with one zero and batch_size ones, calculated in Python float64. + expected_variance = batch_size / (batch_size + 1) ** 2 + assert normalizer._mean.item() == 1.0 + torch.testing.assert_close( + normalizer._var, + torch.tensor([[expected_variance]]), + rtol=1e-6, + atol=0, + ) + torch.testing.assert_close( + normalizer._local_var, + torch.tensor([expected_variance], dtype=torch.float64), + rtol=1e-12, + atol=0, + ) + + def test_observations_stored_once_per_timestep(): rb = SimpleReplayBuffer(N_ENV, BUFFER_SIZE, N_OBS, N_ACT, N_CRITIC_OBS, device="cpu") assert rb.observations.shape == (N_ENV, BUFFER_SIZE + 1, N_OBS)