fix: исправить drift bug в PyTorch net.py (критический)

PyTorch _apply_s2 имел ту же ошибку что и core.py:
- отсутствовал completion-of-square factor exp(b²τ/(4a))
- отсутствовал drift phase shift exp(2πi·k·b_mean·τ)

Это приводило к неправильным результатам RemizovNet и
EquationDiscoverer для уравнений с b≠0.

Добавлены тесты:
- test_s2_fft_matches_direct_with_drift (core, b=1.0)
- test_s2_with_drift (PyTorch layer)
- ужесточён tolerance: atol=0.15 → rtol=0.05

21 тестов проходят.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-05 22:27:53 +10:00
co-authored by Claude Opus 4.6
parent e79e2c64f3
commit 10d2aa284a
3 changed files with 52 additions and 15 deletions
+19 -12
View File
@@ -74,7 +74,12 @@ class RemizovLayer(nn.Module):
return gauss_ft
def _apply_s2(self, f: Tensor) -> Tensor:
"""Apply S₂(τ): Gaussian convolution + drift correction.
"""Apply S₂(τ): advection shift + Gaussian convolution + completion factor.
Mirrors the NumPy core.apply_s2_fft implementation:
1. Advection: shift by b_mean·τ via Fourier phase shift
2. Diffusion: Gaussian convolution via FFT (mean a)
3. Completion factor: exp(b(x)²τ/(4a(x)))
Args:
f: Input tensor of shape (batch, grid_size).
@@ -82,18 +87,20 @@ class RemizovLayer(nn.Module):
Returns:
Convolved tensor of shape (batch, grid_size).
"""
# FFT-based Gaussian convolution
gauss_ft = self._gaussian_kernel_fft(f.shape[0])
f_ft = torch.fft.fft(f, dim=-1)
result = torch.fft.ifft(f_ft * gauss_ft.unsqueeze(0), dim=-1).real
b_mean = self.b.mean()
# Pointwise drift correction for variable b(x)
a_mean = self.a.mean()
drift_correction = torch.exp(
-self.b**2 * self.tau / (4.0 * self.a)
+ self.b**2 * self.tau / (4.0 * a_mean)
)
result = result * drift_correction.unsqueeze(0)
# FFT-based Gaussian convolution + drift phase shift
gauss_ft = self._gaussian_kernel_fft(f.shape[0])
k = torch.fft.fftfreq(self.grid_size, d=self.dx, device=f.device)
drift_ft = torch.exp(2j * math.pi * k * b_mean * self.tau)
kernel_ft = gauss_ft * drift_ft
f_ft = torch.fft.fft(f, dim=-1)
result = torch.fft.ifft(f_ft * kernel_ft.unsqueeze(0), dim=-1).real
# Completion-of-square factor: exp(b(x)²τ/(4a(x)))
completion = torch.exp(self.b**2 * self.tau / (4.0 * self.a))
result = result * completion.unsqueeze(0)
return result
+14 -3
View File
@@ -37,14 +37,25 @@ class TestChernoffStep:
np.testing.assert_allclose(result[interior], 3.0, atol=0.1)
def test_s2_fft_matches_direct(self):
"""FFT-based S₂ should approximate direct computation."""
"""FFT-based S₂ should approximate direct computation (b=0)."""
f = np.exp(-self.x**2)
# For constant coefficients, FFT should be close to direct
result_direct = self.step.apply_s2(f, tau=0.05)
result_fft = self.step.apply_s2_fft(f, tau=0.05)
interior = slice(20, 80)
np.testing.assert_allclose(
result_fft[interior], result_direct[interior], atol=0.15
result_fft[interior], result_direct[interior], rtol=0.05,
)
def test_s2_fft_matches_direct_with_drift(self):
"""FFT-based S₂ should match direct computation when b != 0."""
coeffs = ODECoefficients(a=0.5, b=1.0, c=0.0)
step = ChernoffStep(coeffs, self.x)
f = np.exp(-self.x**2)
result_direct = step.apply_s2(f, tau=0.05)
result_fft = step.apply_s2_fft(f, tau=0.05)
interior = slice(20, 80)
np.testing.assert_allclose(
result_fft[interior], result_direct[interior], rtol=0.05,
)
def test_potential_computation(self):
+19
View File
@@ -44,6 +44,25 @@ class TestRemizovLayer:
expected = 3.0 - 4.0 / (4.0 * a)
torch.testing.assert_close(layer.potential, expected)
def test_s2_with_drift(self):
"""S₂ with b != 0 should include drift shift and completion factor."""
layer = RemizovLayer(grid_size=64, tau=0.05, dx=0.1)
# Set constant a=0.5, b=1.0
with torch.no_grad():
# softplus(x) ≈ 0.5 when x ≈ -0.19
layer.log_a.data = torch.full((64,), -0.19)
layer.b.data = torch.full((64,), 1.0)
f = torch.exp(-torch.linspace(-3, 3, 64).unsqueeze(0) ** 2)
# Run two steps: with b=1 vs b=0
result_drift = layer._apply_s2(f)
with torch.no_grad():
layer.b.data.zero_()
result_nodrift = layer._apply_s2(f)
# With drift, result should be shifted — mid-point values must differ
assert not torch.allclose(result_drift, result_nodrift, atol=1e-3)
class TestRemizovNet:
"""Test the full RemizovNet."""