"""Regression tests for the two operators behind the CMFM gradient collapse. Both had a finite forward and an unbounded backward, which is why ~600 unrelated parameters went non-finite while ``train_loss`` still looked healthy: * the empirical covariance normalizer in ``collective_measure_dynamics_loss``, whose denominator was only bounded below by an absolute ``eps=1e-6``; * the mode gauge in ``LatentEncoder``, whose ``torch.linalg.qr`` backward scales like ``1/r_ii`` while the guard only rejected ``r_ii/scale <= 1e-6``. Each test checks the fixed behaviour and, by disabling the corresponding bound, also reproduces the original explosion so the tests keep documenting it. """ import torch from bbflow.models.collective import collective_measure_dynamics_loss from bbflow.models.latent import LatentEncoder class _Cfg: dim = 16 num_modes = 8 motion_hidden_dim = 16 motion_dist_bins = 4 motion_dist_width = 4.0 motion_message_passing_layers = 1 template_residual_scale = 0.1 template_remove_rotation = True def _mean_free_basis(batch, num_res): """Two residue-mean-free modes so that displacement centering is a no-op.""" basis = torch.zeros(batch, num_res, 2, 3) basis[:, 0, 0, 0] = 1.0 basis[:, 1, 0, 0] = -1.0 basis[:, 2, 1, 1] = 1.0 basis[:, 3, 1, 1] = -1.0 return basis def _collective_case(mode0_std, seed=0, basis_rotation=None, **kwargs): """Build one CMFM group whose first collective mode has a chosen spread. ``basis_rotation`` post-multiplies the basis by an orthogonal [R, R] matrix, which spans the same subspace and must leave the loss unchanged. """ torch.manual_seed(seed) group_size, num_res = 8, 4 basis = _mean_free_basis(group_size, num_res) if basis_rotation is not None: basis = torch.einsum("rs,bnsd->bnrd", basis_rotation, basis) res_mask = torch.ones(group_size, num_res) equilibrium = torch.zeros(group_size, num_res, 3) group_index = torch.zeros(group_size, dtype=torch.long) time = torch.full((group_size,), 0.5) def field(amplitudes): displacement = torch.zeros(group_size, num_res, 3) displacement[:, 0, 0] = amplitudes[:, 0] displacement[:, 1, 0] = -amplitudes[:, 0] displacement[:, 2, 1] = amplitudes[:, 1] displacement[:, 3, 1] = -amplitudes[:, 1] return displacement def standardized(sample, spread): centered = sample - sample.mean() return centered / centered.std() * spread # The observed spread is pinned exactly so the group's projected variance is # a known 4 * spread^2 rather than an 8-sample lottery around it. target_amplitudes = torch.stack( [ standardized(torch.randn(group_size), mode0_std), standardized(torch.randn(group_size), 0.5), ], dim=-1, ) # trans_t and the prediction keep a normal 0.1 A spread in *both* modes: the # q-implied collective basis is not required to align with observed motion, # so the generator can move along a direction the MD ensemble barely uses. trans_t = equilibrium + field(torch.randn(group_size, 2) * 0.1) target_trans = equilibrium + field(target_amplitudes) predicted_trans = ( equilibrium + field(torch.randn(group_size, 2) * 0.1) ).requires_grad_(True) parts = collective_measure_dynamics_loss( trans_t, target_trans, predicted_trans, equilibrium, res_mask, basis, group_index, time, **kwargs, ) return parts, predicted_trans def _collective_grad_absmax(**kwargs): parts, predicted = _collective_case(**kwargs) parts["collective_measure_loss"].backward() return predicted.grad.abs().max() def test_collective_scalar_normalizer_bounds_the_backward(): # var(z_0) = (2 * 6e-4)^2 = 1.44e-6 against var(z_1) = 1.0, i.e. a collective # mode the sampled MD frames barely use. Under the old element-wise # normalizer this divided by std_0 twice and handed the backward ~1e12; the # scalar normalizer is the group's mean variance (here 0.5) regardless of how # small any single direction's observed variance is. degenerate = _collective_grad_absmax(mode0_std=6e-4) healthy = _collective_grad_absmax(mode0_std=0.5) assert torch.isfinite(degenerate) assert degenerate < 1e3 # The whole point: a near-static direction no longer amplifies the backward. assert degenerate < 1e2 * healthy def test_collective_loss_is_invariant_under_basis_rotation(): """The collective basis is only defined up to a rotation of its span. ``project_onto_basis`` maps ``basis -> basis @ R`` to ``z -> R z``, so the error matrix transforms as ``E -> R E R^T``. A correct normalizer leaves ``||E||_F**2 / trace(C)**2`` untouched; the element-wise ``E_ij/(s_i s_j)`` did not, which meant the loss encoded a preference for whichever basis the SVD happened to return. Only the squared-Frobenius loss is asserted: the ``_abs_error`` diagnostics are L1 reductions and are genuinely not rotation invariant. """ torch.manual_seed(11) angle = torch.rand(()) * 6.283 rotation = torch.stack([ torch.stack([torch.cos(angle), -torch.sin(angle)]), torch.stack([torch.sin(angle), torch.cos(angle)]), ]) plain, _ = _collective_case(mode0_std=6e-4) rotated, _ = _collective_case(mode0_std=6e-4, basis_rotation=rotation) torch.testing.assert_close( rotated["collective_measure_loss"], plain["collective_measure_loss"], rtol=1e-5, atol=1e-7, ) def _population(scale, group_size=8, rank=2): return torch.eye(rank)[None].repeat(group_size, 1, 1) * float(scale) def test_population_normalizer_sets_the_scale_exactly(): """The loss is inversely quadratic in the supplied population scale.""" one, _ = _collective_case(mode0_std=0.5, target_covariance=_population(1.0)) three, _ = _collective_case(mode0_std=0.5, target_covariance=_population(3.0)) torch.testing.assert_close( three["collective_measure_loss"] * 9.0, one["collective_measure_loss"], rtol=1e-5, atol=1e-8, ) def test_population_normalizer_ignores_the_group_spread(): """The point of the population value: the denominator stops depending on the same 8 endpoints as the numerator, which is what biased the minimiser.""" tight, _ = _collective_case(mode0_std=6e-4, target_covariance=_population(2.0)) wide, _ = _collective_case(mode0_std=0.5, target_covariance=_population(2.0)) torch.testing.assert_close( tight["collective_covariance_scale_min"], wide["collective_covariance_scale_min"], rtol=0.0, atol=0.0, ) torch.testing.assert_close( tight["collective_covariance_scale_min"], torch.tensor(2.0), rtol=1e-6, atol=1e-8, ) # Without it the normalizer tracks the group and the two differ by orders. tight_own, _ = _collective_case(mode0_std=6e-4) wide_own, _ = _collective_case(mode0_std=0.5) assert not torch.isclose( tight_own["collective_covariance_scale_min"], wide_own["collective_covariance_scale_min"], ) def test_rate_weight_removal_is_exactly_tau_squared(): """`rate_weighted=False` must undo the 1/tau in both velocities and nothing else. The fixture fixes t = 0.5, so tau = 0.5 and the factor is 0.25.""" weighted, _ = _collective_case(mode0_std=0.5) plain, _ = _collective_case(mode0_std=0.5, rate_weighted=False) torch.testing.assert_close( plain["collective_measure_loss"], weighted["collective_measure_loss"] * 0.25, rtol=1e-5, atol=1e-8, ) def test_collective_diagnostics_report_the_scalar_normalizer(): parts, _ = _collective_case(mode0_std=6e-4) # The unfloored per-direction variance still reports how degenerate the # group was, even though it no longer drives the normalizer. assert parts["collective_observed_target_variance_min"] < 1e-5 # ... while the normalizer actually used is the group's mean variance. assert parts["collective_covariance_scale_min"] > 1e-3 assert parts["collective_covariance_inverse_scale_max"] < 1e3 # The localization statistics must never hold on to the graph. diagnostic_keys = [ key for key in parts if key.startswith("collective_") and key.endswith(("_min", "_max", "_absmax")) ] assert diagnostic_keys for key in diagnostic_keys: assert not parts[key].requires_grad, key group_rows = parts["collective_group_diagnostics"] assert len(group_rows) == 1 assert group_rows[0]["size"] == 8 assert set(group_rows[0]) >= { "observed_target_variance_min", "covariance_scale_min", "target_cov_rate_absmax", "predicted_cov_rate_absmax", } def _collapsed_modes(collinearity, seed=3): torch.manual_seed(seed) modes = torch.randn(1, 16, 8, 3) # Mode 7 is (almost) a copy of mode 6: the raw mode head collapsing. modes[:, :, 7] = modes[:, :, 6] + collinearity * torch.randn(1, 16, 3) return modes.requires_grad_(True) def _gauge_grad_absmax(encoder, modes, mask, reference, **kwargs): basis = encoder._masked_orthonormalize_modes(modes, mask, **kwargs) if isinstance(basis, tuple): basis = basis[0] (basis * reference).sum().backward() return modes.grad.abs().max() def test_mode_gauge_backward_is_bounded_for_collapsed_modes(): encoder = LatentEncoder(_Cfg()) mask = torch.ones(1, 16) torch.manual_seed(11) reference = torch.randn(1, 16, 8, 3) # ridge=1e-10 stands in for the old unregularised factorisation: four orders # below the 1e-6 default, but still above the rank-deficiency guard. The # guard trips at a relative Cholesky diagonal of 1e-6, i.e. roughly # sqrt(ridge), so anything below ~1e-12 now raises instead of returning a # basis. That is the float64 gauge being honest -- under float32 a ridge # that small was masked by rounding noise of ~1e-7 and slipped past. unridged = _gauge_grad_absmax( encoder, _collapsed_modes(1e-8), mask, reference, ridge=1e-10 ) ridged = _gauge_grad_absmax(encoder, _collapsed_modes(1e-8), mask, reference) assert torch.isfinite(ridged) # Both numbers are a directional derivative along one fixed reference, not # the operator norm, so they sit far below the analytic 1/sqrt(ridge) bound # and their ratio is a few-fold, not orders of magnitude. This is a seed- # bound regression pin; the bound itself is argued in the docstring. assert ridged < 1e3 assert unridged > 4.0 * ridged def test_mode_gauge_is_unchanged_for_well_conditioned_modes(): encoder = LatentEncoder(_Cfg()) mask = torch.ones(1, 16) modes = _collapsed_modes(1.0) basis, diagnostics = encoder._masked_orthonormalize_modes( modes, mask, return_diagnostics=True ) gram = torch.einsum("bnkd,bnld->bkl", basis, basis) / mask.sum(dim=1)[:, None, None] assert torch.allclose(gram, torch.eye(8).expand_as(gram), atol=2e-5, rtol=2e-5) assert diagnostics["prior_qr_condition"].max() < 1e2 def test_mode_orthogonality_loss_must_run_on_the_pre_gauge_modes(): encoder = LatentEncoder(_Cfg()) mask = torch.ones(1, 16) raw_modes = _collapsed_modes(1e-4) raw_metrics = encoder.mode_gram_diagnostics(raw_modes, mask) raw_loss = encoder.mode_orthogonality_loss(raw_modes, mask) basis = encoder._masked_orthonormalize_modes(raw_modes, mask) post_gauge_loss = encoder.mode_orthogonality_loss(basis, mask) assert raw_metrics["mode_max_cosine_abs"].max() > 0.99 # On the raw modes the collapse is penalised; on the gauge output, which is # approximately orthonormal after ridge regularization, the same loss is # three orders of magnitude smaller and constrains nothing useful. assert float(raw_loss) > 1e-2 assert float(post_gauge_loss) < 1e-4 assert post_gauge_loss < 1e-3 * raw_loss