import pytest import torch from bbflow.models.latent import LatentEncoder class _Cfg: dim = 16 num_modes = 3 mixture_components = 2 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 sample_coefficients = True q_lstsq_ridge = 1e-6 def test_project_displacement_lstsq_recovers_known_coefficients(): modes = torch.zeros(1, 4, 3, 3) modes[0, :, 0, 0] = torch.tensor([1.0, -1.0, 0.5, -0.5]) modes[0, :, 1, 1] = torch.tensor([0.25, 0.5, -0.25, -0.5]) modes[0, :, 2, 2] = torch.tensor([0.3, -0.2, 0.4, -0.1]) coeff = torch.tensor([[2.0, -3.0, 0.75]]) disp = torch.einsum("bk,bnkd->bnd", coeff, modes) mask = torch.ones(1, 4) recovered = LatentEncoder.project_displacement_lstsq( disp, modes, mask, ridge=1e-8, detach_modes=True, ) assert torch.allclose(recovered, coeff, atol=1e-4, rtol=1e-4) def test_mixture_q_shapes_nll_and_sampling_are_finite(): encoder = LatentEncoder(_Cfg()) trans = torch.randn(2, 5, 3) rot = torch.eye(3).reshape(1, 1, 3, 3).repeat(2, 5, 1, 1) seq = torch.zeros(2, 5, 21) seq[..., 0] = 1.0 mask = torch.ones(2, 5) condition, _ = encoder.forward_prior(trans, rot, seq, mask) coeff = torch.randn(2, _Cfg.num_modes) nll = encoder.mixture_nll(condition, coeff) sampled = encoder.sample_prior_z(trans, rot, seq, mask) assert condition["mixture_logits"].shape == (2, _Cfg.mixture_components) assert condition["mixture_mu"].shape == (2, _Cfg.mixture_components, _Cfg.num_modes) assert condition["mixture_scale_tril"].shape == (2, _Cfg.mixture_components, _Cfg.num_modes, _Cfg.num_modes) assert torch.isfinite(nll) assert sampled["mode_coefficients"].shape == (2, _Cfg.num_modes) assert sampled["disp_node_cond"].shape == (2, 5, 3) assert sampled["disp_edge_cond"].shape == (2, 5, 5, 1) def test_energy_from_q_uses_mixture_second_moment_diagonal(): class EnergyFromQCfg(_Cfg): energy_from_q = True encoder = LatentEncoder(EnergyFromQCfg()) trans = torch.randn(2, 5, 3) rot = torch.eye(3).reshape(1, 1, 3, 3).repeat(2, 5, 1, 1) seq = torch.zeros(2, 5, 21) seq[..., 0] = 1.0 mask = torch.ones(2, 5) condition, _ = encoder.forward_prior(trans, rot, seq, mask) expected = torch.diagonal( LatentEncoder.mixture_second_moment(condition), dim1=-2, dim2=-1, ) assert torch.allclose(condition["energy"], expected.to(condition["energy"].dtype), rtol=1e-5, atol=1e-6) def test_energy_from_q_full_covariance_uses_full_second_moment_for_motion_stats(): class FullCovCfg(_Cfg): energy_from_q_full_cov = True encoder = LatentEncoder(FullCovCfg()) trans = torch.randn(2, 5, 3) rot = torch.eye(3).reshape(1, 1, 3, 3).repeat(2, 5, 1, 1) seq = torch.zeros(2, 5, 21) seq[..., 0] = 1.0 mask = torch.ones(2, 5) condition, _ = encoder.forward_prior(trans, rot, seq, mask) second = condition["q_second_moment"].float() modes = condition["u_global"].float() expected_local = torch.einsum("bkl,bnki,bnlj->bnij", second, modes, modes) expected_cross = torch.einsum("bkl,bikd,bjld->bij", second, modes, modes) assert torch.allclose(condition["local_cov_pred"].float(), expected_local, rtol=1e-5, atol=1e-5) assert torch.allclose(condition["cross_cov_pred"].float(), expected_cross, rtol=1e-5, atol=1e-5) def test_frame_projection_uses_centered_fluctuation_target(): encoder = LatentEncoder(_Cfg()) trans_eq = torch.tensor( [[[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0]]] ) trans_1 = trans_eq + torch.tensor( [[[0.2, 0.0, 0.0], [-0.2, 0.0, 0.0], [0.0, 0.3, 0.0], [0.0, -0.3, 0.0]]] ) rot = torch.eye(3).reshape(1, 1, 3, 3).repeat(1, 4, 1, 1) mask = torch.ones(1, 4) mean_disp = encoder.relative_displacement(trans_1, trans_eq, mask) modes = torch.randn(1, 4, _Cfg.num_modes, 3) condition, coefficients = encoder.frame_condition_from_projection( trans_1, trans_eq, rot, mask, {"u_global": modes}, mean_disp=mean_disp, ) assert torch.allclose(coefficients, torch.zeros_like(coefficients), atol=1e-6) assert torch.allclose(condition["projection_target_disp"], torch.zeros_like(mean_disp), atol=1e-6) assert condition["projection_recon_rel_error"].item() == 0.0 assert condition["projection_uncentered_recon_rel_error"].item() > 0.99 def test_mode_gram_diagnostics_detect_collinearity(): mask = torch.ones(1, 3) orthogonal = torch.zeros(1, 3, 2, 3) orthogonal[0, :, 0, 0] = 1.0 orthogonal[0, :, 1, 1] = 1.0 collinear = orthogonal.clone() collinear[0, :, 1] = collinear[0, :, 0] good = LatentEncoder.mode_gram_diagnostics(orthogonal, mask) bad = LatentEncoder.mode_gram_diagnostics(collinear, mask) assert torch.allclose(good["mode_gram_condition"], torch.ones(1), atol=1e-6) assert good["mode_max_cosine_abs"].item() == 0.0 assert bad["mode_gram_min_eig"].item() < 1e-6 assert bad["mode_gram_condition"].item() > 1e6 assert torch.allclose(bad["mode_max_cosine_abs"], torch.ones(1), atol=1e-6) def test_frame_projection_rejects_missing_mean_displacement(): encoder = LatentEncoder(_Cfg()) trans_eq = torch.randn(1, 4, 3) trans_1 = trans_eq + 0.1 * torch.randn_like(trans_eq) rot = torch.eye(3).reshape(1, 1, 3, 3).repeat(1, 4, 1, 1) mask = torch.ones(1, 4) modes = torch.randn(1, 4, _Cfg.num_modes, 3) with pytest.raises(ValueError, match="oracle_mean_disp"): encoder.frame_condition_from_projection( trans_1, trans_eq, rot, mask, {"u_global": modes}, mean_disp=None, ) def test_q_detach_keeps_mixture_gradients_out_of_shared_encoder(): class DetachCfg(_Cfg): q_detach_shared_encoder = True encoder = LatentEncoder(DetachCfg()) trans = torch.randn(2, 5, 3) rot = torch.eye(3).reshape(1, 1, 3, 3).repeat(2, 5, 1, 1) seq = torch.zeros(2, 5, 21) seq[..., 0] = 1.0 mask = torch.ones(2, 5) condition, _ = encoder.forward_prior(trans, rot, seq, mask) encoder.mixture_nll(condition, torch.randn(2, DetachCfg.num_modes)).backward() assert encoder.mixture_mu_out.weight.grad is not None assert encoder.mixture_mu_out.weight.grad.abs().sum() > 0 assert encoder.prior_node_mlp[0].weight.grad is None def test_mode_orthogonality_loss_penalizes_collinear_modes(): mask = torch.ones(1, 3) orthogonal = torch.zeros(1, 3, 2, 3) orthogonal[0, :, 0, 0] = 1.0 orthogonal[0, :, 1, 1] = 1.0 collinear = orthogonal.clone() collinear[0, :, 1] = collinear[0, :, 0] assert LatentEncoder.mode_orthogonality_loss(orthogonal, mask).item() == 0.0 assert torch.allclose( LatentEncoder.mode_orthogonality_loss(collinear, mask), torch.tensor(1.0), atol=1e-6, ) def test_projection_reconstruction_objective_matches_ridge_value_and_detaches_coefficients(): modes = torch.zeros(1, 3, 2, 3, requires_grad=True) with torch.no_grad(): modes[0, :, 0, 0] = torch.tensor([1.0, -0.5, 0.25]) modes[0, :, 1, 1] = torch.tensor([0.5, 1.0, -0.25]) coefficients = torch.tensor([[0.75, -0.4]], requires_grad=True) mask = torch.ones(1, 3) displacement = torch.einsum( "bk,bnkd->bnd", coefficients.detach(), modes.detach() ) displacement = displacement + torch.tensor( [[[0.0, 0.0, 0.3], [0.0, 0.0, -0.2], [0.0, 0.0, 0.1]]] ) ridge = 1e-4 objective = LatentEncoder.projection_reconstruction_objective( displacement, modes, coefficients, mask, ridge=ridge, ) detached_coeff = coefficients.detach() expected_recon = torch.einsum("bk,bnkd->bnd", detached_coeff, modes) residual_sq = (displacement - expected_recon).square().sum(dim=(1, 2)) target_sq = displacement.square().sum(dim=(1, 2)).clamp_min(1e-8) expected_loss = ( residual_sq + ridge * detached_coeff.square().sum(dim=-1) ) / target_sq expected_rel_error = torch.sqrt(residual_sq / target_sq) assert torch.allclose(objective["loss"], expected_loss) assert torch.allclose(objective["rel_error"], expected_rel_error) assert torch.allclose(objective["recon"], expected_recon) objective["loss"].mean().backward() assert coefficients.grad is None assert modes.grad is not None assert torch.isfinite(modes.grad).all() assert modes.grad.abs().sum() > 0