import torch import torch.nn as nn def _validate_mixture_shapes(logits, means, scale_tril): if logits.dim() != 2: raise ValueError(f"mixture logits must have shape [B, M], got {tuple(logits.shape)}") if means.dim() != 3: raise ValueError(f"mixture means must have shape [B, M, K], got {tuple(means.shape)}") if scale_tril.dim() != 4: raise ValueError( f"mixture scales must have shape [B, M, K, K], got {tuple(scale_tril.shape)}" ) if means.shape[:2] != logits.shape or scale_tril.shape[:3] != means.shape: raise ValueError("mixture logits, means, and scale_tril have incompatible shapes") if scale_tril.shape[-1] != means.shape[-1]: raise ValueError("mixture scale matrices must be square in coefficient space") def mixture_mean_and_covariance_factor(logits, means, scale_tril): """Return the mixture mean and an exact factor S such that Cov[c] = S S^T.""" _validate_mixture_shapes(logits, means, scale_tril) weights = torch.softmax(logits.float(), dim=-1) means = means.float() scale_tril = scale_tril.float() mixture_mean = torch.einsum("bm,bmk->bk", weights, means) sqrt_weights = torch.sqrt(weights) centered_means = means - mixture_mean[:, None, :] batch, components, dimensions = means.shape component_factor = ( scale_tril * sqrt_weights[..., None, None] ).permute(0, 2, 1, 3).reshape(batch, dimensions, components * dimensions) between_component_factor = ( centered_means * sqrt_weights[..., None] ).transpose(1, 2) covariance_factor = torch.cat( [component_factor, between_component_factor], dim=-1, ) return mixture_mean, covariance_factor def mixture_mean_and_covariance(logits, means, scale_tril): """Exact first two moments of a full-covariance Gaussian mixture.""" mixture_mean, covariance_factor = mixture_mean_and_covariance_factor( logits, means, scale_tril, ) covariance = covariance_factor @ covariance_factor.transpose(-1, -2) covariance = 0.5 * (covariance + covariance.transpose(-1, -2)) return mixture_mean, covariance def physical_low_rank_target( modes, res_mask, coefficient_covariance_factor, rank, eps=1e-6, ): """Map a coefficient covariance factor through U and retain its physical SVD.""" if modes.dim() != 4 or modes.shape[-1] != 3: raise ValueError(f"modes must have shape [B, N, K, 3], got {tuple(modes.shape)}") if res_mask.shape != modes.shape[:2]: raise ValueError("res_mask must match the [B, N] dimensions of modes") batch, num_res, num_modes, _ = modes.shape if ( coefficient_covariance_factor.dim() != 3 or coefficient_covariance_factor.shape[:2] != (batch, num_modes) ): raise ValueError("coefficient_covariance_factor must have shape [B, K, P]") if rank < 1 or rank > num_modes: raise ValueError(f"collective rank must be in [1, {num_modes}], got {rank}") with torch.autocast(device_type=modes.device.type, enabled=False): modes = modes.float() coefficient_covariance_factor = coefficient_covariance_factor.float() if not torch.isfinite(modes).all(): raise FloatingPointError("physical modes contain non-finite values") if not torch.isfinite(coefficient_covariance_factor).all(): raise FloatingPointError("q coefficient covariance factor contains non-finite values") mask_xyz = res_mask.float()[..., None].expand(-1, -1, 3).reshape(batch, -1) modes_flat = modes.permute(0, 1, 3, 2).reshape(batch, num_res * 3, num_modes) modes_flat = modes_flat * mask_xyz[..., None] physical_factor = modes_flat @ coefficient_covariance_factor factor_scale = physical_factor.abs().amax(dim=(-2, -1), keepdim=True) if not torch.isfinite(factor_scale).all(): raise FloatingPointError("physical covariance factor scale is non-finite") normalized_factor = physical_factor / factor_scale.clamp_min( torch.finfo(physical_factor.dtype).tiny ) basis_flat, singular_values, _ = torch.linalg.svd( normalized_factor, full_matrices=False, ) physical_variance = ( singular_values * factor_scale.reshape(batch, 1) ).square() if not torch.isfinite(physical_variance).all(): raise FloatingPointError("q-implied physical covariance has non-finite variance") top_evals = physical_variance[:, :rank] if torch.any(top_evals <= eps).detach().item(): raise ValueError( f"physical covariance does not support collective rank={rank}; " f"minimum retained eigenvalue={top_evals.detach().min().item():.6g}" ) basis_flat = basis_flat[:, :, :rank] basis_flat = basis_flat * mask_xyz[..., None] basis = basis_flat.reshape(batch, num_res, 3, rank).permute(0, 1, 3, 2) target_covariance = torch.diag_embed(top_evals) normalized_variance = singular_values.square() retained_fraction = normalized_variance[:, :rank].sum( dim=-1 ) / normalized_variance.sum(dim=-1).clamp_min(eps) return { "collective_basis_global": basis, "collective_target_covariance": target_covariance, "collective_target_variance": top_evals, "collective_retained_fraction": retained_fraction, } def masked_centered_displacement(trans, equilibrium, res_mask): if trans.shape != equilibrium.shape or trans.shape[-1] != 3: raise ValueError("trans and equilibrium must have matching shape [B, N, 3]") if res_mask.shape != trans.shape[:2]: raise ValueError("res_mask must match trans [B, N]") mask = res_mask.float()[..., None] displacement = (trans.float() - equilibrium.float()) * mask center = displacement.sum(dim=1, keepdim=True) / mask.sum( dim=1, keepdim=True ).clamp_min(1.0) return (displacement - center) * mask def project_onto_basis(displacement, basis, res_mask): if basis.dim() != 4 or basis.shape[:2] != displacement.shape[:2]: raise ValueError("basis must have shape [B, N, R, 3]") masked = displacement.float() * res_mask.float()[..., None] return torch.einsum("bnrd,bnd->br", basis.float(), masked) def _validate_groups(group_index, batch_size, rank): if group_index.dim() != 1 or group_index.shape[0] != batch_size: raise ValueError(f"group_index must have shape [{batch_size}]") groups, counts = torch.unique(group_index, sorted=True, return_counts=True) if groups.numel() == 0: raise ValueError("collective control requires at least one group") if torch.any(counts <= rank): raise ValueError( f"every collective group must contain more than rank={rank} particles; " f"observed sizes={counts.detach().cpu().tolist()}" ) return groups def _require_shared_group_value(values, members, name, atol=1e-6, rtol=1e-6): group_values = values[members] reference = group_values[:1].expand_as(group_values) if not torch.allclose(group_values, reference, atol=atol, rtol=rtol): raise ValueError(f"{name} must be shared by every particle in a collective group") return group_values[0] class CollectiveMeasureController(nn.Module): """Particle- and basis-equivariant covariance controller for a finite ensemble.""" def __init__(self, rank, hidden_dim=128, output_scale=1.0, eps=1e-6): super().__init__() self.rank = int(rank) self.output_scale = float(output_scale) self.eps = float(eps) self.network = nn.Sequential( nn.Linear(6, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, 1), ) nn.init.normal_(self.network[-1].weight, mean=0.0, std=1e-3) nn.init.zeros_(self.network[-1].bias) def forward( self, trans_t, equilibrium, res_mask, basis_global, target_covariance, group_index, time, ): batch = trans_t.shape[0] groups = _validate_groups(group_index, batch, self.rank) if basis_global.shape != ( batch, trans_t.shape[1], self.rank, 3, ): raise ValueError("collective_basis_global has the wrong shape") if target_covariance.shape != (batch, self.rank, self.rank): raise ValueError("collective_target_covariance has the wrong shape") if time.shape[0] != batch: raise ValueError("time must have one value per particle") displacement = masked_centered_displacement(trans_t, equilibrium, res_mask) coefficients = project_onto_basis(displacement, basis_global, res_mask) coefficient_update = torch.zeros_like(coefficients) for group in groups: members = group_index == group _require_shared_group_value( basis_global, members, "collective_basis_global" ) z = coefficients[members] z_centered = z - z.mean(dim=0) z_cov = z_centered.transpose(0, 1) @ z_centered / float(z.shape[0] - 1) group_target_cov = _require_shared_group_value( target_covariance, members, "collective_target_covariance" ).float() target_std = torch.sqrt( torch.diagonal(group_target_cov, dim1=-2, dim2=-1).clamp_min(self.eps) ) scale_matrix = target_std[:, None] * target_std[None, :] particle_state = z_centered / target_std covariance_error = (group_target_cov - z_cov) / scale_matrix.clamp_min( self.eps ) group_time = time[members].reshape(z.shape[0], -1)[:, :1] if torch.max(torch.abs(group_time - group_time[:1])).detach().item() > 1e-6: raise ValueError("all particles in a collective group must share the same time") covariance_direction = particle_state @ covariance_error particle_energy = particle_state.square().mean(dim=-1, keepdim=True) direction_energy = covariance_direction.square().mean(dim=-1, keepdim=True) direction_scale = torch.sqrt(1.0 + direction_energy) unit_direction = covariance_direction / direction_scale covariance_trace = ( torch.trace(covariance_error) / float(self.rank) ).reshape(1, 1) covariance_energy = covariance_error.square().mean().reshape(1, 1) invariant_features = torch.cat( [ torch.log1p(particle_energy), torch.log1p(direction_energy), torch.asinh( (particle_state * covariance_direction).mean( dim=-1, keepdim=True ) ), torch.asinh(covariance_trace).expand(z.shape[0], -1), torch.log1p(covariance_energy).expand(z.shape[0], -1), group_time, ], dim=-1, ) scalar_gate = torch.tanh( self.network( invariant_features.to(dtype=self.network[0].weight.dtype) ).float() ) normalized_velocity = scalar_gate * unit_direction time_to_endpoint = (1.0 - group_time.float()).clamp_min(0.0) group_update = ( normalized_velocity * target_std * time_to_endpoint * self.output_scale ) # CMFM changes covariance only; BBFlow remains responsible for the mean. group_update = group_update - group_update.mean(dim=0, keepdim=True) coefficient_update[members] = group_update.to(dtype=coefficients.dtype) global_update = torch.einsum( "bnrd,br->bnd", basis_global.float(), coefficient_update.float() ) global_update = global_update * res_mask.float()[..., None] return global_update.to(dtype=trans_t.dtype), coefficients def collective_measure_dynamics_loss( trans_t, target_trans, predicted_trans, equilibrium, res_mask, basis_global, group_index, time, t_normalize_clip=0.9, eps=1e-6, target_covariance=None, rate_weighted=True, ): """Match covariance dynamics while leaving ensemble-mean learning to BBFlow. The error matrix is normalized by a single scalar, the group's mean projected variance ``trace(group_target_cov) / rank``, rather than element-wise by ``std_i * std_j``. The element-wise form was not basis invariant. Under an orthogonal rotation of the collective basis the error matrix transforms as ``E -> R E R^T``, so ``||E||_F**2 / trace(C)**2`` is unchanged while ``E_ij / (std_i * std_j)`` is not: it silently encodes a preference for whichever basis the SVD happened to return. It also handed the smallest observed direction a weight of ``1 / var**2``, and the collective basis comes from the q-implied covariance with no obligation to align with the motion the sampled MD frames actually show, so that direction is routinely the one estimated from almost no signal. The relative floor that used to cap this amplification is gone with it -- with a scalar normalizer a direction with no observed motion contributes a near-zero ``cov_rate`` and therefore a near-zero term, instead of diverging. The loss remains invariant under a global rescaling of the coordinates, since numerator and denominator are both quadratic in the displacement. ``target_covariance`` supplies the population second moment in the collective basis, one ``[R, R]`` per particle, shared within a group. When it is given the normalizer is ``trace/rank`` of that instead of the group's own 8-sample estimate. Estimating the denominator from the same 8 endpoints as the numerator breaks the conditional orthogonality that makes the objective unbiased: the weight ``(R/trace)^2`` falls as the batch's endpoint spread rises, so batches with large dispersion are systematically down-weighted, a contraction of order ``1/(G-1)``. A cached population value removes it, and with a data-derived basis the population value is exact rather than estimated. ``rate_weighted=False`` removes the ``1/tau`` in the velocities, equivalently multiplying the loss by ``tau^2``. With the division in place the weight ``tau^-2`` puts 53% of the integrated loss mass in ``t > 0.9`` -- exactly where the bridge has converged, the true covariance rate has gone to zero and the estimator is worst. Expanding the objective shows why the division buys nothing: the shared ``z_t`` cancels in the difference, leaving ``2 Sym(z~^T r~)/(G-1)`` with ``r`` the endpoint residual, so this is an endpoint statistic wearing a rate's clothing and the ``t`` weighting is free to choose. """ rank = basis_global.shape[2] groups = _validate_groups(group_index, trans_t.shape[0], rank) z_t = project_onto_basis( masked_centered_displacement(trans_t, equilibrium, res_mask), basis_global, res_mask, ) z_target = project_onto_basis( masked_centered_displacement(target_trans, equilibrium, res_mask), basis_global, res_mask, ) z_pred = project_onto_basis( masked_centered_displacement(predicted_trans, equilibrium, res_mask), basis_global, res_mask, ) clipped_t = torch.minimum( time.float().reshape(-1, 1), time.new_full((time.shape[0], 1), float(t_normalize_clip)).float(), ) denominator = (1.0 - clipped_t).clamp_min(eps) target_velocity = (z_target - z_t) / denominator predicted_velocity = (z_pred - z_t) / denominator covariance_losses = [] mean_errors = [] covariance_errors = [] # Localization instrumentation: the empirical covariance normalizer is the # prime suspect for non-finite backward gradients, so every quantity that # feeds it is recorded per group. All entries are detached. group_diagnostics = [] for group in groups: members = group_index == group z = z_t[members] target_v = target_velocity[members] predicted_v = predicted_velocity[members] z_centered = z - z.mean(dim=0) z_target_group = z_target[members] z_target_centered = z_target_group - z_target_group.mean(dim=0) target_v_centered = target_v - target_v.mean(dim=0) predicted_v_centered = predicted_v - predicted_v.mean(dim=0) denom = float(z.shape[0] - 1) target_cov_rate = ( z_centered.transpose(0, 1) @ target_v_centered + target_v_centered.transpose(0, 1) @ z_centered ) / denom predicted_cov_rate = ( z_centered.transpose(0, 1) @ predicted_v_centered + predicted_v_centered.transpose(0, 1) @ z_centered ) / denom group_target_cov = ( z_target_centered.transpose(0, 1) @ z_target_centered ) / denom target_variance = torch.diagonal( group_target_cov, dim1=-2, dim2=-1 ) mean_variance = target_variance.mean() if bool((mean_variance <= eps).detach().item()): # The whole group is static in the collective subspace: there is no # covariance dynamics to match and no scale to normalize by. raise ValueError( "observed target ensemble has no motion in the collective basis; " f"mean projected variance={mean_variance.detach().item():.6g}" ) # Single scalar normalizer: the group's mean projected variance, from the # cached population value when one is available and from the 8 endpoints # otherwise. Detached either way so the model cannot lower the loss by # shrinking the target scale. if target_covariance is not None: population = _require_shared_group_value( target_covariance, members, "collective_target_covariance" ).float() covariance_scale = torch.diagonal( population, dim1=-2, dim2=-1 ).mean().detach() if bool((covariance_scale <= eps).detach().item()): raise ValueError( "population collective covariance has no variance; " f"mean diagonal={covariance_scale.detach().item():.6g}" ) else: covariance_scale = mean_variance.detach() covariance_error = (predicted_cov_rate - target_cov_rate) / covariance_scale group_loss = covariance_error.square().mean() if not rate_weighted: # Undo the 1/tau carried by both velocities. group_loss = group_loss * denominator[members][0, 0].detach().square() covariance_losses.append(group_loss) target_std = torch.sqrt(covariance_scale) group_diagnostics.append({ "group": int(group.detach().item()), "size": int(z.shape[0]), "observed_target_variance_min": target_variance.detach().min(), "observed_target_variance_max": target_variance.detach().max(), "covariance_scale_min": covariance_scale, # d loss / d z_pred scales like error / covariance_scale. With a # scalar normalizer this is a single number per group rather than the # 1 / min(var)^2 blow-up the element-wise form produced. "covariance_inverse_scale_max": 1.0 / covariance_scale, "target_cov_rate_absmax": target_cov_rate.detach().abs().max(), "predicted_cov_rate_absmax": predicted_cov_rate.detach().abs().max(), "covariance_error_absmax": covariance_error.detach().abs().max(), "z_t_absmax": z.detach().abs().max(), "z_target_absmax": z_target_group.detach().abs().max(), "target_velocity_absmax": target_v.detach().abs().max(), "predicted_velocity_absmax": predicted_v.detach().abs().max(), }) mean_errors.append( ( (predicted_v.mean(dim=0) - target_v.mean(dim=0)) / target_std ).abs().mean() ) covariance_errors.append(covariance_error.abs().mean()) covariance_loss = torch.stack(covariance_losses).mean() parts = { "collective_measure_loss": covariance_loss, "collective_cov_dynamics_loss": covariance_loss, "collective_mean_dynamics_abs_error": torch.stack(mean_errors).mean(), "collective_cov_dynamics_abs_error": torch.stack(covariance_errors).mean(), } parts.update(_aggregate_group_diagnostics(group_diagnostics)) return parts # Group-level statistics reduced with min (worst normalizer) rather than max. _MIN_REDUCED_DIAGNOSTICS = ( "observed_target_variance_min", "covariance_scale_min", ) def _aggregate_group_diagnostics(group_diagnostics): """Reduce the per-group localization statistics to logged scalars.""" if not group_diagnostics: return {} tensor_keys = [ key for key, value in group_diagnostics[0].items() if torch.is_tensor(value) ] aggregated = {} for key in tensor_keys: stacked = torch.stack([ entry[key].detach().float().reshape(()) for entry in group_diagnostics ]) reduced = stacked.min() if key in _MIN_REDUCED_DIAGNOSTICS else stacked.max() aggregated[f"collective_{key}"] = reduced aggregated["collective_group_diagnostics"] = group_diagnostics return aggregated