Spaces:
Sleeping
Sleeping
File size: 12,558 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 | """Validation: per-batch and epoch-end metrics.
Mixin split out of :class:`morph.model.lightning.base.LightningModuleRates`.
"""
import os
from contextlib import ExitStack
import torch
import torch.distributed as dist
from morph.utils.metrics import (
build_marginal_plots,
calc_atom_stabilities,
calc_metrics_,
)
from morph.utils.metrics.tensor import compute_batch_geometry
class ValidationMixin:
def _validation_context(self, batch):
"""Optionally snapshot task-specific inputs before sampling."""
return None
def _update_task_metrics(self, context, mols, rdkit_mols):
"""Consume generated graphs and decoded molecules in conditional tasks."""
def _compute_chemistry_metrics(self, rdkit_mols):
"""Evaluate the gathered population, optionally with task context."""
return calc_metrics_(rdkit_mols, self.metrics)
def on_validation_epoch_start(self):
# ``seed_everything`` deliberately gives every DDP process the same base
# seed. That is correct for model initialization, but an unconditional
# validation dataset otherwise draws the same priors on every rank and
# turns 4,096 requested samples into four copies of 1,024. Salt the
# validation RNG by rank; keeping the seed fixed across epochs also makes
# changes in the validation curve attributable to the model, not priors.
self._training_rng_state = torch.random.get_rng_state()
self._training_cuda_rng_states = (
torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None
)
base_seed = int(os.environ.get("PL_GLOBAL_SEED", "0"))
torch.manual_seed(base_seed + self.global_rank)
self.model_ema.eval()
# Tensor-style collections accumulate raw counts/histograms across the
# epoch so the reported metric is computed from the full epoch's atoms
# (not a per-batch rate averaged with the wrong weighting).
if self.distribution_metrics is not None:
self.distribution_metrics.reset()
if self.batch_metrics is not None:
self.batch_metrics.reset()
if self.stability_metrics is not None:
self.stability_metrics.reset()
if self.metrics is not None:
self.metrics.reset()
self._validation_rdkit_mols = []
def validation_step(self, batch, batch_idx):
context = self._validation_context(batch)
batched_mols = self.sample(batch, batch_idx, return_traj=False)
# Tensor / distribution metrics consume the batch directly and work in
# every representation, so they always run — no early return. Only the
# RDKit-mol chemistry metrics below require real topology.
if self.batch_metrics is not None and len(self.batch_metrics) > 0:
self.batch_metrics.update(compute_batch_geometry(batched_mols))
if self.distribution_metrics is not None and len(self.distribution_metrics) > 0:
self.distribution_metrics.update(batched_mols)
if not self.representation.requires_topology:
del batched_mols
return
# RDKit is CPU-only. Transfer each batch tensor once before splitting;
# converting GPU graph views one molecule at a time would synchronize
# every coordinate/type/edge ``.cpu()`` call separately.
mols = batched_mols.to_inplace("cpu", non_blocking=False).to_data_list()
del batched_mols
# List of RDKit molecules or None
rdkit_mols = []
for mol in mols:
try:
rdkit_mols.append(
mol.to_rdkit_mol(
self.vocab.atom_tokens,
self.vocab.edge_tokens,
self.vocab.charge_tokens,
)
)
except Exception as e:
print(f"Error converting molecule to RDKit: {e}")
rdkit_mols.append(None)
self._update_task_metrics(context, mols, rdkit_mols)
self._validation_rdkit_mols.extend(rdkit_mols)
# RDKit per-atom stability — fed precomputed bools (not RDKit mols).
# Accumulate only here; compute/log/reset happens in
# on_validation_epoch_end so the rate is weighted by atom count across
# the full epoch, not molecule count per batch.
if self.stability_metrics is not None and len(self.stability_metrics) > 0:
stabilities = []
for graph in mols:
try:
mol = graph.to_rdkit_mol(
self.vocab.atom_tokens,
self.vocab.edge_tokens,
self.vocab.charge_tokens,
sanitize=False,
)
stabilities.append(calc_atom_stabilities(mol))
except Exception as exc:
# The generated atom count is known even if decoding fails;
# do not drop these atoms or molecules from the denominator.
print(f"Raw graph stability check failed: {exc}")
stabilities.append([False] * graph.num_nodes)
if stabilities:
self.stability_metrics.update(stabilities)
del mols
def on_validation_epoch_end(self):
# Python/list-backed chemistry metrics cannot use torchmetrics' DDP
# state reduction. Gather the complete molecule population, compute it
# once on rank zero, then broadcast the small scalar result dictionary
# so every rank exposes identical callback metrics.
if self.representation.requires_topology:
local_mols = self._validation_rdkit_mols
if dist.is_available() and dist.is_initialized():
gathered = (
[None] * dist.get_world_size() if dist.get_rank() == 0 else None
)
dist.gather_object(local_mols, gathered, dst=0)
rdkit_mols = (
[mol for rank_mols in gathered for mol in rank_mols]
if gathered is not None
else []
)
else:
rdkit_mols = local_mols
eval_metrics = {}
if self.trainer.is_global_zero:
try:
eval_metrics = self._compute_chemistry_metrics(rdkit_mols)
except Exception as e:
print(f"Error calculating chemistry metrics: {e}")
if dist.is_available() and dist.is_initialized():
payload = [eval_metrics]
dist.broadcast_object_list(payload, src=0)
eval_metrics = payload[0]
if eval_metrics:
self.log_dict(
{f"val/{key}": value for key, value in eval_metrics.items()},
on_step=False,
on_epoch=True,
prog_bar=False,
logger=True,
sync_dist=False,
)
self._validation_rdkit_mols = []
# RDKit per-atom stability — accumulated across the full epoch in
# validation_step; compute the atom-weighted rate once here.
if self.stability_metrics is not None and len(self.stability_metrics) > 0:
try:
stab_results = self.stability_metrics.compute()
self.log_dict(
{
f"val/{k}": (v.detach() if isinstance(v, torch.Tensor) else v)
for k, v in stab_results.items()
},
on_step=False,
on_epoch=True,
prog_bar=False,
logger=True,
sync_dist=False,
)
except Exception as e:
print(f"Error in stability-metric epoch-end logging: {e}")
finally:
self.stability_metrics.reset()
# Tensor-based metrics run in every representation; logged here so the
# values land in the same wandb step as everything else.
if self.batch_metrics is not None and len(self.batch_metrics) > 0:
try:
# Sync once for both scalar computation and histogram plots.
# Every rank must enter each collective context; only rank zero
# reads the synchronized state to render figures.
with ExitStack() as stack:
for m in self.batch_metrics.values():
stack.enter_context(m.sync_context())
batch_results = self.batch_metrics.compute()
self.log_dict(
{
f"val/batch/{key}": (
v.detach() if isinstance(v, torch.Tensor) else v
)
for key, v in batch_results.items()
},
on_step=False,
on_epoch=True,
prog_bar=False,
logger=True,
sync_dist=False,
)
if self.trainer.is_global_zero and hasattr(
self.logger, "log_image"
):
from morph.utils.metrics.plotting import ( # noqa: PLC0415
build_batch_marginal_plots,
)
figs = build_batch_marginal_plots(
self.batch_metrics,
atom_tokens=list(self.vocab.atom_tokens),
)
for name, fig in figs.items():
try:
self.logger.log_image(key=name, images=[fig])
except Exception as e:
print(f"Error logging {name}: {e}")
if figs:
import matplotlib.pyplot as plt # noqa: PLC0415
for fig in figs.values():
plt.close(fig)
except Exception as e:
print(f"Error in batch-metric epoch-end logging: {e}")
finally:
self.batch_metrics.reset()
# Distribution KLs are tensor-native and accumulate in every
# representation; edge/charge KLs are only registered when meaningful
# (see init_metrics), so an empty/absent collection just no-ops.
if self.distribution_metrics is None or len(self.distribution_metrics) == 0:
self._restore_training_rng()
return
try:
# Sync once for both pooled KLs and their marginal plots.
with ExitStack() as stack:
for m in self.distribution_metrics.values():
stack.enter_context(m.sync_context())
dist_results = self.distribution_metrics.compute()
self.log_dict(
{
f"val/{key}": (v.detach() if isinstance(v, torch.Tensor) else v)
for key, v in dist_results.items()
},
on_step=False,
on_epoch=True,
prog_bar=False,
logger=True,
sync_dist=False,
)
if self.trainer.is_global_zero and hasattr(self.logger, "log_image"):
figures = build_marginal_plots(self.distribution_metrics)
for name, fig in figures.items():
self.logger.log_image(key=f"val/marginals/{name}", images=[fig])
if figures:
import matplotlib.pyplot as plt # noqa: PLC0415
for fig in figures.values():
plt.close(fig)
except Exception as e:
print(f"Error in validation-epoch-end distribution logging: {e}")
finally:
self.distribution_metrics.reset()
self._restore_training_rng()
def _restore_training_rng(self):
"""Keep deterministic validation sampling from changing training RNG."""
torch.random.set_rng_state(self._training_rng_state)
if self._training_cuda_rng_states is not None:
torch.cuda.set_rng_state_all(self._training_cuda_rng_states)
|