Files
anorandClaude Opus 4.6 10d2aa284a 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>
2026-03-05 22:27:53 +10:00

128 lines
4.3 KiB
Python

"""Tests for the RemizovNet PyTorch module."""
import torch
from remizov_net.net import RemizovLayer, RemizovNet
class TestRemizovLayer:
"""Test individual RemizovLayer."""
def test_output_shape(self):
layer = RemizovLayer(grid_size=64, tau=0.1)
x = torch.randn(4, 64)
y = layer(x)
assert y.shape == (4, 64)
def test_a_positive(self):
"""Coefficient a(x) must always be positive."""
layer = RemizovLayer(grid_size=32, tau=0.1)
# Even with negative log_a, softplus keeps a > 0
layer.log_a.data = torch.full((32,), -10.0)
assert (layer.a > 0).all()
def test_gradient_flows(self):
"""Gradients should propagate through the layer."""
layer = RemizovLayer(grid_size=32, tau=0.1)
x = torch.randn(2, 32, requires_grad=True)
y = layer(x)
loss = y.sum()
loss.backward()
assert layer.log_a.grad is not None
assert layer.b.grad is not None
assert layer.c.grad is not None
def test_potential_formula(self):
"""V(x) = c - b^2/(4a)."""
layer = RemizovLayer(grid_size=16, tau=0.1)
layer.log_a.data = torch.ones(16) # a ≈ softplus(1) ≈ 1.31
layer.b.data = torch.full((16,), 2.0)
layer.c.data = torch.full((16,), 3.0)
a = layer.a
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."""
def test_output_shape(self):
net = RemizovNet(grid_size=64, n_steps=10, total_time=1.0)
x = torch.randn(8, 64)
y = net(x)
assert y.shape == (8, 64)
def test_shared_coefficients(self):
"""Shared mode: all steps use the same parameters."""
net = RemizovNet(grid_size=32, n_steps=5, shared_coeffs=True)
params = list(net.parameters())
# Should have exactly 3 parameters: log_a, b, c
assert len(params) == 3
def test_independent_coefficients(self):
"""Independent mode: each step has its own parameters."""
net = RemizovNet(grid_size=32, n_steps=5, shared_coeffs=False)
params = list(net.parameters())
# Should have 3 * n_steps = 15 parameters
assert len(params) == 15
def test_get_coefficients(self):
net = RemizovNet(grid_size=32, n_steps=5, shared_coeffs=True)
coeffs = net.get_coefficients()
assert "a" in coeffs
assert "b" in coeffs
assert "c" in coeffs
assert coeffs["a"].shape == (32,)
def test_equation_string(self):
net = RemizovNet(grid_size=16, n_steps=5, shared_coeffs=True)
eq = net.equation_string()
assert "y''" in eq
assert "y'" in eq
assert "g(x)" in eq
def test_training_step(self):
"""Single training step should reduce loss."""
net = RemizovNet(grid_size=32, n_steps=5, total_time=1.0)
optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
g = torch.randn(4, 32)
y_target = torch.randn(4, 32)
# Training step
optimizer.zero_grad()
y_pred = net(g)
loss = torch.nn.functional.mse_loss(y_pred, y_target)
loss.backward()
optimizer.step()
# After step
with torch.no_grad():
y_pred = net(g)
loss_after = torch.nn.functional.mse_loss(y_pred, y_target).item()
# Loss should decrease (not guaranteed but very likely with random init)
# Use a weak check: loss_after should be finite
assert torch.isfinite(torch.tensor(loss_after))