Spaces:
Sleeping
Sleeping
File size: 13,503 Bytes
3e3ee14 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | """Geometric tensor metrics consumed directly from ``ChemBatch``.
These run in every representation (no RDKit, no validity conditioning). Target
stats (per-element-pair distance histogram, RoG histogram) are computed once at
preprocessing time on training-set coords in Angstroms and stored in
``Distributions``. Generated coords are expected to arrive in Angstroms too —
``sample()`` in the LightningModule already multiplies by ``coordinate_std``
before returning the final ``ChemBatch``.
Also hosts the shared bin edges + histogram accumulators because both this
module and ``preprocessing.py`` must agree on them exactly.
"""
from dataclasses import dataclass
import torch
from torchmetrics import Metric
from morph.dataset.core.atomic_data import ChemBatch
# Shared bin edges (Angstroms). Used both at preprocessing time to compute
# target histograms and at metric time to bin generated samples — they must
# match exactly. Defaults are generous enough for QM9 / GEOM / TMQM; values
# above the upper bound are counted in an overflow accumulator (see the binning
# helpers below) so silent clamping is visible at validation time.
DIST_RANGE = (0.0, 15.0)
DIST_N_BINS = 150
RG_RANGE = (0.0, 8.0)
RG_N_BINS = 80
@dataclass(frozen=True)
class BatchGeometry:
"""Geometry shared by all tensor metrics for one generated batch."""
num_graphs: int
node_counts: torch.Tensor
pair_distances: torch.Tensor
pair_atom_lo: torch.Tensor
pair_atom_hi: torch.Tensor
pair_graph: torch.Tensor
radii_of_gyration: torch.Tensor
def compute_batch_geometry(batch: ChemBatch) -> BatchGeometry:
"""Compute pair distances and radii of gyration once for all metrics."""
rows, cols = batch.edge_index
upper = rows < cols
rows, cols = rows[upper], cols[upper]
pair_distances = (batch.x[rows] - batch.x[cols]).norm(dim=-1)
atom_i, atom_j = batch.a[rows], batch.a[cols]
counts = batch.num_nodes_per_graph
centers = batch.x.new_zeros((batch.num_graphs, batch.x.shape[-1]))
centers.index_add_(0, batch.batch, batch.x)
centers = centers / counts.clamp(min=1).unsqueeze(1)
squared_radius = (batch.x - centers[batch.batch]).square().sum(dim=-1)
mean_squared_radius = batch.x.new_zeros(batch.num_graphs)
mean_squared_radius.index_add_(0, batch.batch, squared_radius)
mean_squared_radius = mean_squared_radius / counts.clamp(min=1)
return BatchGeometry(
num_graphs=batch.num_graphs,
node_counts=counts,
pair_distances=pair_distances,
pair_atom_lo=torch.minimum(atom_i, atom_j),
pair_atom_hi=torch.maximum(atom_i, atom_j),
pair_graph=batch.batch[rows],
radii_of_gyration=mean_squared_radius.sqrt(),
)
def dist_edges() -> torch.Tensor:
return torch.linspace(DIST_RANGE[0], DIST_RANGE[1], DIST_N_BINS + 1)
def rg_edges() -> torch.Tensor:
return torch.linspace(RG_RANGE[0], RG_RANGE[1], RG_N_BINS + 1)
def accumulate_pairwise_distance_hist(
hist: torch.Tensor,
coord: torch.Tensor,
atom_idx: torch.Tensor,
edges: torch.Tensor,
) -> tuple[int, int]:
"""Add upper-triangular pair distances to ``hist`` (A, A, B), in place.
The pair key is ``(min(a_i, a_j), max(a_i, a_j))`` so the histogram is
naturally invariant to atom ordering.
Returns ``(n_overflow, n_total)`` for the pairs in this molecule, so callers
can track the fraction of distances that fell beyond the histogram range
(silent clamping otherwise hides "the cloud is way too large").
"""
n = coord.shape[0]
if n < 2:
return 0, 0
i_idx, j_idx = torch.triu_indices(n, n, offset=1, device=coord.device)
dists = (coord[i_idx] - coord[j_idx]).norm(dim=-1)
lo = torch.minimum(atom_idx[i_idx], atom_idx[j_idx])
hi = torch.maximum(atom_idx[i_idx], atom_idx[j_idx])
edges_d = edges.to(coord.device)
n_overflow = int((dists >= edges_d[-1]).sum().item())
bin_idx = torch.bucketize(dists, edges_d).sub_(1).clamp_(0, hist.shape[-1] - 1)
a = hist.shape[0]
flat = (lo.long() * a + hi.long()) * hist.shape[-1] + bin_idx
hist.view(-1).index_add_(
0, flat, torch.ones_like(flat, dtype=hist.dtype, device=coord.device)
)
return n_overflow, int(dists.numel())
def accumulate_rog_hist(
hist: torch.Tensor, coord: torch.Tensor, edges: torch.Tensor
) -> tuple[int, int]:
"""Add one molecule's radius of gyration into ``hist`` (B,), in place.
Returns ``(n_overflow, n_total)`` (0 or 1 each) for the same reason as
``accumulate_pairwise_distance_hist``.
"""
if coord.shape[0] == 0:
return 0, 0
centered = coord - coord.mean(dim=0)
rog = (centered.pow(2).sum(dim=-1).mean()).sqrt()
edges_d = edges.to(coord.device)
overflow = int((rog >= edges_d[-1]).item())
bin_idx = (
torch.bucketize(rog.unsqueeze(0), edges_d).sub_(1).clamp_(0, hist.shape[0] - 1)
)
hist.index_add_(0, bin_idx, torch.ones(1, dtype=hist.dtype, device=coord.device))
return overflow, 1
class BatchMetric(Metric):
"""Base class for metrics that consume a ``ChemBatch`` directly."""
def update(self, batch: ChemBatch) -> None:
"""Accumulate tensor statistics from molecular batches."""
raise NotImplementedError
def compute(self) -> torch.Tensor:
"""Reduce the accumulated tensor statistics to a metric value."""
raise NotImplementedError
class PairwiseDistanceL1(BatchMetric):
"""Mean per-element-pair L1 distance between gen and target distance histograms.
For every ordered (lo, hi) atom-type pair the *target* has meaningful mass
for, we normalize gen and target slices independently and report
``|gen - target|.sum()``. The mean over those pairs is a 0-2 metric where 0
means perfect distributional match.
Note: gen-empty pairs are *not* excluded. If the target has C-N distances
but the model never generates a C-N pair, the L1 against zeros is 1.0 and
that pair counts in the average — which is what we want.
"""
def __init__(
self, target_hist: torch.Tensor, min_pair_count: float = 10.0, **kwargs
):
super().__init__(**kwargs)
self.register_buffer("target_hist", target_hist.detach().to(torch.float32))
self.register_buffer("edges", dist_edges())
self.min_pair_count = min_pair_count
self.add_state(
"gen_hist",
default=torch.zeros_like(self.target_hist),
dist_reduce_fx="sum",
)
def update(self, geometry: BatchGeometry) -> None:
"""Accumulate pair-distance histograms by unordered atom-type pair."""
distances = geometry.pair_distances
if distances.numel() == 0:
return
edges = self.edges.to(distances.device)
bins = (
torch.bucketize(distances, edges)
.sub_(1)
.clamp_(0, self.gen_hist.shape[-1] - 1)
)
num_atom_types = self.gen_hist.shape[0]
flat = (
geometry.pair_atom_lo.long() * num_atom_types + geometry.pair_atom_hi.long()
) * self.gen_hist.shape[-1] + bins
self.gen_hist.view(-1).index_add_(
0, flat, torch.ones_like(flat, dtype=self.gen_hist.dtype)
)
def compute(self) -> torch.Tensor:
"""Average normalized histogram L1 errors over populated target pairs."""
gen = self.gen_hist # (A, A, B)
tgt = self.target_hist
pair_t = tgt.sum(dim=-1)
# Target-populated only: a pair the training set knows about counts in
# the metric even if the model generates zero of them (gen_n = 0 →
# L1 == tgt_n.sum() == 1, which is maximal pain).
populated = pair_t >= self.min_pair_count
if not populated.any():
return torch.tensor(0.0, device=gen.device)
gen_n = gen / gen.sum(dim=-1).unsqueeze(-1).clamp(min=1.0)
tgt_n = tgt / pair_t.unsqueeze(-1).clamp(min=1.0)
l1 = (gen_n - tgt_n).abs().sum(dim=-1) # (A, A)
return l1[populated].mean()
class MinDistanceViolation(BatchMetric):
"""Fraction of generated molecules whose smallest pairwise distance is below
a physical threshold (default 0.5 Å). Catches collapse and overlap.
"""
def __init__(self, threshold: float = 0.5, **kwargs):
super().__init__(**kwargs)
self.threshold = float(threshold)
self.add_state("violations", default=torch.tensor(0.0), dist_reduce_fx="sum")
self.add_state("total", default=torch.tensor(0.0), dist_reduce_fx="sum")
def update(self, geometry: BatchGeometry) -> None:
"""Count graphs with an atom pair below the distance threshold."""
valid = geometry.node_counts >= 2
minima = geometry.pair_distances.new_full((geometry.num_graphs,), float("inf"))
minima.scatter_reduce_(
0, geometry.pair_graph, geometry.pair_distances, reduce="amin"
)
self.violations += ((minima < self.threshold) & valid).sum()
self.total += valid.sum()
def compute(self) -> torch.Tensor:
"""Return the violation fraction among graphs with at least two atoms."""
if self.total <= 0:
return torch.tensor(0.0, device=self.violations.device)
return self.violations / self.total
class RangeOverflow(BatchMetric):
"""Fraction of generated values that landed outside the histogram range.
If this is non-trivial (say >1%), the fixed range in this module is too
small for the dataset and we're silently clamping into the last bin —
revisit ``DIST_RANGE`` / ``RG_RANGE`` or switch to target-derived edges.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.register_buffer("dist_edges_buf", dist_edges())
self.register_buffer("rog_edges_buf", rg_edges())
self.add_state("dist_over", default=torch.tensor(0.0), dist_reduce_fx="sum")
self.add_state("dist_total", default=torch.tensor(0.0), dist_reduce_fx="sum")
self.add_state("rog_over", default=torch.tensor(0.0), dist_reduce_fx="sum")
self.add_state("rog_total", default=torch.tensor(0.0), dist_reduce_fx="sum")
def update(self, geometry: BatchGeometry) -> None:
"""Count distances and radii outside their histogram ranges."""
self.dist_over += (geometry.pair_distances >= self.dist_edges_buf[-1]).sum()
self.dist_total += geometry.pair_distances.numel()
valid = geometry.node_counts > 0
self.rog_over += (
(geometry.radii_of_gyration >= self.rog_edges_buf[-1]) & valid
).sum()
self.rog_total += valid.sum()
def compute(self) -> torch.Tensor:
"""Return the larger of the distance and radius overflow fractions."""
d = self.dist_over / self.dist_total.clamp(min=1.0)
r = self.rog_over / self.rog_total.clamp(min=1.0)
return torch.maximum(d, r)
class RoGL1(BatchMetric):
"""L1 distance between gen and target normalized radius-of-gyration histograms."""
def __init__(self, target_hist: torch.Tensor, **kwargs):
super().__init__(**kwargs)
self.register_buffer("target_hist", target_hist.detach().to(torch.float32))
self.register_buffer("edges", rg_edges())
self.add_state(
"gen_hist",
default=torch.zeros_like(self.target_hist),
dist_reduce_fx="sum",
)
def update(self, geometry: BatchGeometry) -> None:
"""Accumulate radii of gyration for nonempty graphs."""
valid = geometry.node_counts > 0
radii = geometry.radii_of_gyration[valid]
if radii.numel() == 0:
return
bins = (
torch.bucketize(radii, self.edges.to(radii.device))
.sub_(1)
.clamp_(0, self.gen_hist.shape[0] - 1)
)
self.gen_hist.index_add_(
0, bins, torch.ones_like(bins, dtype=self.gen_hist.dtype)
)
def compute(self) -> torch.Tensor:
"""Return the L1 distance between normalized radius histograms."""
gen = self.gen_hist
tgt = self.target_hist
if gen.sum() <= 0 or tgt.sum() <= 0:
return torch.tensor(0.0, device=gen.device)
gen_n = gen / gen.sum().clamp(min=1.0)
tgt_n = tgt / tgt.sum().clamp(min=1.0)
return (gen_n - tgt_n).abs().sum()
def build_batch_metrics(distributions) -> dict[str, BatchMetric]:
"""Construct the geometric batch-side metric set from training target stats.
Atom-count / atom-type / edge / charge KLs live in the distribution
collection (see ``init_metrics``), not here — this set is purely geometric.
Returns an empty dict if Distributions lacks either geometric target stat
(e.g. an older cache built before these were added). Both are checked
independently in case one is added without the other later.
"""
if (
distributions.pairwise_distance_histogram is None
or distributions.radius_of_gyration_histogram is None
):
return {}
return {
"min_dist_violation": MinDistanceViolation(
threshold=0.5, sync_on_compute=False
),
"range_overflow": RangeOverflow(sync_on_compute=False),
"pair_dist_l1": PairwiseDistanceL1(
distributions.pairwise_distance_histogram, sync_on_compute=False
),
"rog_l1": RoGL1(
distributions.radius_of_gyration_histogram, sync_on_compute=False
),
}
|