hanghang214 commited on
Commit
9ae7e2d
·
verified ·
1 Parent(s): c6c1dc6

upload-bbflow-base

Browse files
.gitattributes CHANGED
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
62
+ bbflow_base/bbflow/models/__pycache__/latent.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
63
+ bbflow_base/test_data/test_pdbs/MD_trajectory.xtc filter=lfs diff=lfs merge=lfs -text
bbflow_base/assets/flowchart.png ADDED

Git LFS Details

  • SHA256: 33844f0242785a4926ba18732cdcccc5538fdbb501b6ba05da860a1bad413613
  • Pointer size: 132 Bytes
  • Size of remote file: 1.25 MB
bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8844818b2af52dc9645ddb6139ef1f2468d322299b4611b3421dce807297751
3
+ size 165899
bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-39.pyc CHANGED
Binary files a/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-39.pyc and b/bbflow_base/bbflow/models/__pycache__/bbflow_module.cpython-39.pyc differ
 
bbflow_base/bbflow/models/__pycache__/latent.cpython-310.pyc CHANGED
Binary files a/bbflow_base/bbflow/models/__pycache__/latent.cpython-310.pyc and b/bbflow_base/bbflow/models/__pycache__/latent.cpython-310.pyc differ
 
bbflow_base/bbflow/models/__pycache__/latent.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:180648917d2d5a8ea7bd063e5c1f4b3e4bf573c9be804756191beddff5668d35
3
+ size 136182
bbflow_base/bbflow/models/__pycache__/latent.cpython-39.pyc CHANGED
Binary files a/bbflow_base/bbflow/models/__pycache__/latent.cpython-39.pyc and b/bbflow_base/bbflow/models/__pycache__/latent.cpython-39.pyc differ
 
bbflow_base/bbflow/models/bbflow_module.py CHANGED
@@ -81,6 +81,10 @@ MD_EPOCH_SUMMARY_KEYS = [
81
  "gen_cov_loss",
82
  "gen_local_shape_loss",
83
  "gen_cross_shape_loss",
 
 
 
 
84
  "gen_trace_anchor_loss",
85
  "gen_response_abs_mean",
86
  "gen_response_trace_mean",
@@ -383,12 +387,17 @@ class BBFlowModule(FlowModule):
383
  needs_oracle_modes = bool(getattr(self._exp_cfg.training, "oracle_condition", False)) or (
384
  float(getattr(self._exp_cfg.training, "lambda_pca_align", 0.0)) > 0.0
385
  ) or bool(getattr(self, "collective_basis_from_data", False)) or (
 
 
386
  float(getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0)) > 0.0
387
  ) or (
388
  float(getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0)) > 0.0
389
  )
390
  if needs_oracle_modes:
391
- optional_fields = ["oracle_modes", "oracle_energy", "oracle_mean_disp"]
 
 
 
392
  for name in pdb_names:
393
  key = str(name)
394
  value = None
@@ -1394,6 +1403,32 @@ class BBFlowModule(FlowModule):
1394
  use_cross = bool(getattr(self._exp_cfg.training, "generator_cov_use_cross", False))
1395
  if use_cross and "cross_cov" not in targets:
1396
  use_cross = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1397
 
1398
  # t = 1 is clean, t = 0 is pure noise; mid-high noise is low-to-mid t.
1399
  t_min = float(getattr(self._exp_cfg.training, "generator_cov_t_min", 0.1))
@@ -1865,9 +1900,11 @@ class BBFlowModule(FlowModule):
1865
  teacher_trace_denominator=teacher_trace_denominator,
1866
  amplitude_anchor=amplitude_anchor,
1867
  trace_target_scale=trace_target_scale,
 
1868
  )
1869
  w_local = float(getattr(self._exp_cfg.training, "lambda_gen_local_shape", 1.0))
1870
  w_cross = float(getattr(self._exp_cfg.training, "lambda_gen_cross_shape", 1.0))
 
1871
  w_anchor = float(getattr(self._exp_cfg.training, "lambda_gen_trace_anchor", 0.05))
1872
  # Anchor warmup: ramp the amplitude-anchor weight 0 -> full over N epochs.
1873
  # Slamming the calibrated anchor to full on epoch 0 drove the condition to MD
@@ -1882,12 +1919,24 @@ class BBFlowModule(FlowModule):
1882
  total = w_local * losses["gen_local_shape_loss"]
1883
  if use_cross and "gen_cross_shape_loss" in losses:
1884
  total = total + w_cross * losses["gen_cross_shape_loss"]
 
 
 
 
1885
  if "gen_trace_anchor_loss" in losses:
1886
  total = total + w_anchor * losses["gen_trace_anchor_loss"]
1887
  weighted = lambda_gen * total
1888
  out_metrics = {key: value.detach() for key, value in losses.items()}
1889
  out_metrics.update(metrics)
1890
  out_metrics.update(rollout_metrics)
 
 
 
 
 
 
 
 
1891
  out_metrics["gen_cov_loss"] = weighted.detach()
1892
  return weighted, out_metrics
1893
 
 
81
  "gen_cov_loss",
82
  "gen_local_shape_loss",
83
  "gen_cross_shape_loss",
84
+ "gen_oracle_shape_loss",
85
+ "gen_oracle_weighted_loss",
86
+ "gen_oracle_active_frac",
87
+ "gen_oracle_rank_used",
88
  "gen_trace_anchor_loss",
89
  "gen_response_abs_mean",
90
  "gen_response_trace_mean",
 
387
  needs_oracle_modes = bool(getattr(self._exp_cfg.training, "oracle_condition", False)) or (
388
  float(getattr(self._exp_cfg.training, "lambda_pca_align", 0.0)) > 0.0
389
  ) or bool(getattr(self, "collective_basis_from_data", False)) or (
390
+ int(getattr(self._exp_cfg.training, "generator_cov_oracle_rank", 0)) > 0
391
+ ) or (
392
  float(getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0)) > 0.0
393
  ) or (
394
  float(getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0)) > 0.0
395
  )
396
  if needs_oracle_modes:
397
+ # Append rather than replace. The previous reassignment dropped
398
+ # `gen_response_trace_anchor`, which silently switched the generator
399
+ # trace anchor from the cached value to constructing a frozen teacher.
400
+ optional_fields = optional_fields + ["oracle_modes", "oracle_energy"]
401
  for name in pdb_names:
402
  key = str(name)
403
  value = None
 
1403
  use_cross = bool(getattr(self._exp_cfg.training, "generator_cov_use_cross", False))
1404
  if use_cross and "cross_cov" not in targets:
1405
  use_cross = False
1406
+ # Projection onto the cached MD principal directions. Fails closed: if it is
1407
+ # requested and the cache cannot supply the basis, raise rather than train a
1408
+ # silently different objective. Rank is capped at the number of antithetic
1409
+ # perturbations, since the response covariance cannot exceed that rank.
1410
+ oracle_rank = int(getattr(self._exp_cfg.training, "generator_cov_oracle_rank", 0))
1411
+ oracle_weight = float(
1412
+ getattr(self._exp_cfg.training, "lambda_gen_oracle_shape", 0.0)
1413
+ )
1414
+ # Rank and weight must agree. Either alone is a configuration that looks
1415
+ # enabled and trains nothing: a positive weight with rank 0 never builds the
1416
+ # term, a positive rank with weight 0 builds it and discards it.
1417
+ if (oracle_rank > 0) != (oracle_weight > 0.0):
1418
+ raise ValueError(
1419
+ "generator_cov_oracle_rank and lambda_gen_oracle_shape must be both "
1420
+ f"zero or both positive; got rank={oracle_rank}, weight={oracle_weight}"
1421
+ )
1422
+ if oracle_rank > 0:
1423
+ missing = [
1424
+ field for field in ("oracle_modes", "oracle_energy")
1425
+ if field not in targets
1426
+ ]
1427
+ if missing:
1428
+ raise KeyError(
1429
+ f"generator_cov_oracle_rank={oracle_rank} requires {missing} in the "
1430
+ "motion target cache"
1431
+ )
1432
 
1433
  # t = 1 is clean, t = 0 is pure noise; mid-high noise is low-to-mid t.
1434
  t_min = float(getattr(self._exp_cfg.training, "generator_cov_t_min", 0.1))
 
1900
  teacher_trace_denominator=teacher_trace_denominator,
1901
  amplitude_anchor=amplitude_anchor,
1902
  trace_target_scale=trace_target_scale,
1903
+ oracle_rank=oracle_rank,
1904
  )
1905
  w_local = float(getattr(self._exp_cfg.training, "lambda_gen_local_shape", 1.0))
1906
  w_cross = float(getattr(self._exp_cfg.training, "lambda_gen_cross_shape", 1.0))
1907
+ w_oracle = oracle_weight
1908
  w_anchor = float(getattr(self._exp_cfg.training, "lambda_gen_trace_anchor", 0.05))
1909
  # Anchor warmup: ramp the amplitude-anchor weight 0 -> full over N epochs.
1910
  # Slamming the calibrated anchor to full on epoch 0 drove the condition to MD
 
1919
  total = w_local * losses["gen_local_shape_loss"]
1920
  if use_cross and "gen_cross_shape_loss" in losses:
1921
  total = total + w_cross * losses["gen_cross_shape_loss"]
1922
+ oracle_weighted = None
1923
+ if "gen_oracle_shape_loss" in losses:
1924
+ oracle_weighted = w_oracle * losses["gen_oracle_shape_loss"]
1925
+ total = total + oracle_weighted
1926
  if "gen_trace_anchor_loss" in losses:
1927
  total = total + w_anchor * losses["gen_trace_anchor_loss"]
1928
  weighted = lambda_gen * total
1929
  out_metrics = {key: value.detach() for key, value in losses.items()}
1930
  out_metrics.update(metrics)
1931
  out_metrics.update(rollout_metrics)
1932
+ # The only number that proves the oracle term reached the backward. The
1933
+ # unweighted loss says nothing about its weight, `gen_oracle_active_frac`
1934
+ # says nothing about either, and `gen_cov_loss` may be entirely the local
1935
+ # term.
1936
+ if oracle_weighted is not None:
1937
+ out_metrics["gen_oracle_weighted_loss"] = (
1938
+ lambda_gen * oracle_weighted
1939
+ ).detach()
1940
  out_metrics["gen_cov_loss"] = weighted.detach()
1941
  return weighted, out_metrics
1942
 
bbflow_base/bbflow/models/latent.py CHANGED
@@ -1644,6 +1644,7 @@ class LatentEncoder(nn.Module):
1644
  teacher_trace_denominator="teacher",
1645
  amplitude_anchor="teacher_trace",
1646
  trace_target_scale=None,
 
1647
  ):
1648
  """Match generator response shape without rewarding global expansion.
1649
 
@@ -1658,6 +1659,22 @@ class LatentEncoder(nn.Module):
1658
  current response norm near the frozen initial/A30 response under the same
1659
  ``t`` and coefficient perturbations. This anchor does not assume that
1660
  one-step trace equals the 20-step inference ensemble trace.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1661
  """
1662
  with torch.autocast(device_type=res_mask.device.type, enabled=False):
1663
  d = response_deltas.float()
@@ -1788,6 +1805,69 @@ class LatentEncoder(nn.Module):
1788
  cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)
1789
  ) / cross_denom
1790
  losses["gen_cross_shape_loss"] = cross_shape_loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1791
  return losses, metrics
1792
 
1793
  def motion_metrics(self, condition, res_mask):
 
1644
  teacher_trace_denominator="teacher",
1645
  amplitude_anchor="teacher_trace",
1646
  trace_target_scale=None,
1647
+ oracle_rank=0,
1648
  ):
1649
  """Match generator response shape without rewarding global expansion.
1650
 
 
1659
  current response norm near the frozen initial/A30 response under the same
1660
  ``t`` and coefficient perturbations. This anchor does not assume that
1661
  one-step trace equals the 20-step inference ensemble trace.
1662
+
1663
+ ``oracle_rank > 0`` adds a term comparing the response covariance projected
1664
+ onto the cached MD principal directions against their variances. This is the
1665
+ only target in this function that lives in the basis the reported PCA-W2 is
1666
+ computed in: ``local_cov`` is per-residue 3x3 and ``cross_cov`` is summed
1667
+ over coordinates to N x N, so neither can identify a direction in the 3N
1668
+ space where the principal plane lives.
1669
+
1670
+ Two limits are deliberate rather than incidental. It is a **shape** term
1671
+ only: by the law of total covariance the generated covariance splits into an
1672
+ initial-noise part and a coefficient-steerable part, ``response_deltas``
1673
+ approximates only the second, and ``oracle_energy`` is the total. Anchoring
1674
+ the response trace to the MD trace would double-count. And the projected
1675
+ covariance has rank at most ``S = response_deltas.shape[0]``, so a rank
1676
+ beyond that cannot be matched even in principle -- with the default two
1677
+ antithetic perturbations, ``oracle_rank`` above 2 is not estimable.
1678
  """
1679
  with torch.autocast(device_type=res_mask.device.type, enabled=False):
1680
  d = response_deltas.float()
 
1805
  cross_diff.square().sum() / offdiag_mask.sum().clamp_min(1.0)
1806
  ) / cross_denom
1807
  losses["gen_cross_shape_loss"] = cross_shape_loss
1808
+
1809
+ if int(oracle_rank or 0) > 0:
1810
+ for field in ("oracle_modes", "oracle_energy"):
1811
+ if field not in targets:
1812
+ raise KeyError(
1813
+ f"generator_cov_oracle_rank > 0 requires {field} in the "
1814
+ "motion target cache; regenerate it with "
1815
+ "scripts/extract_shape_fingerprints.py"
1816
+ )
1817
+ modes = targets["oracle_modes"].to(device=d.device, dtype=d.dtype)
1818
+ energy = targets["oracle_energy"].to(device=d.device, dtype=d.dtype)
1819
+ # The projected covariance is a sum of S outer products, so its rank
1820
+ # cannot exceed S. Accepting a larger request would silently train
1821
+ # against a target that is unmatchable by construction.
1822
+ if int(oracle_rank) > int(d.shape[0]):
1823
+ raise ValueError(
1824
+ f"generator_cov_oracle_rank={int(oracle_rank)} exceeds the "
1825
+ f"{int(d.shape[0])} antithetic perturbations available; the "
1826
+ "projected response covariance cannot have that rank. Raise "
1827
+ "generator_cov_num_deltas or lower the rank."
1828
+ )
1829
+ rank = min(int(oracle_rank), int(modes.shape[2]), int(energy.shape[1]))
1830
+ # Mask before renormalising: the cached modes are unit norm over the
1831
+ # full 3N of their own protein, and padding rows would otherwise
1832
+ # leak into the projection.
1833
+ basis = modes[:, :, :rank, :] * target_mask[:, :, None, None]
1834
+ basis = basis / torch.linalg.vector_norm(
1835
+ basis, dim=(1, 3), keepdim=True
1836
+ ).clamp_min(1e-8)
1837
+
1838
+ proj = torch.einsum("sbnd,bnrd->sbr", d, basis)
1839
+ resp_cov = torch.einsum("sbr,sbq->brq", proj, proj) / float(d.shape[0])
1840
+ resp_trace = torch.diagonal(resp_cov, dim1=-2, dim2=-1).sum(dim=-1)
1841
+
1842
+ target_cov = torch.diag_embed(energy[:, :rank])
1843
+ target_trace = energy[:, :rank].sum(dim=-1)
1844
+
1845
+ # Activity is decided by the exogenous masks alone, never by the
1846
+ # response magnitude. Gating on `resp_trace > eps` would hand the
1847
+ # model a discontinuous escape: shrink an example's response below
1848
+ # the threshold and its loss becomes exactly zero and it leaves the
1849
+ # denominator. That reads as training success while the objective is
1850
+ # being switched off example by example.
1851
+ #
1852
+ # Examples outside the t window still have to be excluded -- `d` was
1853
+ # zeroed for them upstream, so normalising their covariance would
1854
+ # charge them the full shape error for having been excluded -- but
1855
+ # that is a property of `sample_weight`, which is exogenous.
1856
+ active = (mask.sum(dim=-1) > 0) & (target_trace > 1e-8)
1857
+ resp_norm = resp_cov / resp_trace.clamp_min(1e-8)[:, None, None]
1858
+ target_norm = target_cov / target_trace.clamp_min(1e-8)[:, None, None]
1859
+ per_example = (resp_norm - target_norm).square().sum(dim=(-2, -1))
1860
+ oracle_shape_loss = (
1861
+ (per_example * active.to(per_example.dtype)).sum()
1862
+ / active.sum().clamp_min(1).to(per_example.dtype)
1863
+ )
1864
+ losses["gen_oracle_shape_loss"] = oracle_shape_loss
1865
+ metrics["gen_oracle_active_frac"] = (
1866
+ active.detach().float().mean()
1867
+ )
1868
+ metrics["gen_oracle_rank_used"] = torch.tensor(
1869
+ float(rank), device=d.device
1870
+ )
1871
  return losses, metrics
1872
 
1873
  def motion_metrics(self, condition, res_mask):
bbflow_base/code_exports/a30_redesign_source_20260719.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:085e0a9966226f2764249e214ab0c6e4c02df38427edfe919bb4270ed5798b90
3
+ size 95616
bbflow_base/configs/experiment/default.yaml CHANGED
@@ -83,6 +83,20 @@ training:
83
  generator_cov_rollout_ema_decay: 0.9
84
  lambda_gen_local_shape: 1.0
85
  lambda_gen_cross_shape: 1.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  lambda_gen_trace_anchor: 0.05
87
  wandb:
88
  name: baseline
 
83
  generator_cov_rollout_ema_decay: 0.9
84
  lambda_gen_local_shape: 1.0
85
  lambda_gen_cross_shape: 1.0
86
+ # Project the generator response onto the cached MD principal directions and
87
+ # match their relative variances. This is the only generator-response target in
88
+ # the basis PCA-W2 is actually computed in: local_cov is per-residue 3x3 and
89
+ # cross_cov is summed over coordinates to N x N, so neither identifies a
90
+ # direction in 3N. Shape only -- the response is the coefficient-steerable part
91
+ # of the covariance while oracle_energy is the total, so anchoring the trace to
92
+ # it would double-count the part generated from initial noise.
93
+ #
94
+ # The rank cannot exceed the number of antithetic perturbations
95
+ # (generator_cov_num_deltas), since the projected covariance is a sum of that
96
+ # many outer products. 2 is both the estimable rank at the default and the
97
+ # dimension of the plane the reported PCA-W2 scores.
98
+ generator_cov_oracle_rank: 0
99
+ lambda_gen_oracle_shape: 0.0
100
  lambda_gen_trace_anchor: 0.05
101
  wandb:
102
  name: baseline
bbflow_base/kabsch_static_fix_bundle.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94c09efc04e6d65dfe017ae3ac8aca61f9cfb46bce3996761e18c182f0a59255
3
+ size 38658
bbflow_base/kabsch_static_ridge_recon_fix_bundle.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f044909a488abcf5a25fb0c76e4670ae1853f0271f27ea2f99f989d71b78e74e
3
+ size 41701
bbflow_base/metric_plots/condition.png ADDED

Git LFS Details

  • SHA256: 3102b76ffd094e901e811d0c3b3bf04518b953ea6b2462e39b33ef345c361a6b
  • Pointer size: 131 Bytes
  • Size of remote file: 104 kB
bbflow_base/metric_plots/covariance.png ADDED

Git LFS Details

  • SHA256: 44e3e6e9a8ef3c8e8236dcd77066bcaa21d59b4780fcb015e0e6e987f7ef354b
  • Pointer size: 131 Bytes
  • Size of remote file: 296 kB
bbflow_base/metric_plots/losses.png ADDED

Git LFS Details

  • SHA256: 878b051391e996b625a7b8e35650378bbf9d2ad7074bcad255883f1387e99532
  • Pointer size: 131 Bytes
  • Size of remote file: 190 kB
bbflow_base/metric_plots/mode_health.png ADDED

Git LFS Details

  • SHA256: 58a8be516fe1f239f660a02dbd2d907558801311f76ac8dc0ae0cabcfe47697a
  • Pointer size: 131 Bytes
  • Size of remote file: 256 kB
bbflow_base/models/bbflow-0.1/bbflow-0.1.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:848a0f021e5cb28e9d8810af9bb9145815c5f845c6f5a2c4ef10912fd2a236e0
3
+ size 75874050
bbflow_base/reproduction/outputs/metrics/analysis_data.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebf4317dd3e072df6f62ae0a3bae9738f8af3469ec91d9ecf4bd9883f386b073
3
+ size 1340489239
bbflow_base/scripts/__pycache__/cmfm_replay_failure.cpython-39.pyc ADDED
Binary file (9.28 kB). View file
 
bbflow_base/scripts/__pycache__/scale_calibration_sweep.cpython-39.pyc ADDED
Binary file (18.7 kB). View file
 
bbflow_base/scripts/__pycache__/smoke_gen_oracle_shape.cpython-39.pyc ADDED
Binary file (6.77 kB). View file
 
bbflow_base/scripts/__pycache__/surrogate_validation.cpython-39.pyc ADDED
Binary file (11.5 kB). View file
 
bbflow_base/scripts/smoke_gen_oracle_shape.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Check the MD-eigenbasis response term on synthetic inputs, before any training.
3
+
4
+ Three prior conditioning objectives were launched and each cost a full cycle. Two
5
+ of the three could not have worked for a reason visible in the code: the target
6
+ was in the wrong space. This term targets the cached MD principal directions,
7
+ which is the basis the reported PCA-W2 is computed in, so the thing worth
8
+ checking before spending GPU time is not whether the idea is good but whether the
9
+ implementation does what it says.
10
+
11
+ Four properties, each falsifiable here in seconds:
12
+
13
+ 1. A response aligned with the target spectrum scores lower than a misaligned one.
14
+ If this fails the term carries no directional signal.
15
+ 2. The term is invariant to scaling the whole response. It is a shape term by
16
+ construction -- the response is only the coefficient-steerable half of the
17
+ generated covariance while `oracle_energy` is the total, so it must not be
18
+ read as an amplitude target.
19
+ 3. Examples masked out of the `t` window contribute nothing. They are zeroed
20
+ upstream, so without an explicit guard they would be charged the full shape
21
+ error for having been excluded.
22
+ 4. Requesting the term without the cached basis raises rather than returning zero.
23
+ Every silent-return path in this file's neighbourhood has cost a run.
24
+
25
+ Run: python scripts/smoke_gen_oracle_shape.py
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ import torch
34
+
35
+ REPO_ROOT = Path(__file__).resolve().parents[1]
36
+ if str(REPO_ROOT) not in sys.path:
37
+ sys.path.insert(0, str(REPO_ROOT))
38
+
39
+ from bbflow.models.latent import LatentEncoder
40
+
41
+
42
+ class _Cfg:
43
+ dim = 16
44
+ num_modes = 8
45
+ motion_hidden_dim = 16
46
+ motion_dist_bins = 4
47
+ motion_dist_width = 4.0
48
+ motion_message_passing_layers = 1
49
+ template_residual_scale = 1.0
50
+ template_remove_rotation = True
51
+
52
+
53
+ def _orthonormal_modes(num_res, rank, generator):
54
+ """`rank` directions, unit norm over the flattened 3N, as the cache stores them."""
55
+ flat = torch.randn(num_res * 3, rank, generator=generator, dtype=torch.float64)
56
+ flat, _ = torch.linalg.qr(flat)
57
+ return flat.reshape(num_res, 3, rank).permute(0, 2, 1).float().contiguous()
58
+
59
+
60
+ def _targets(num_res, rank, energy, generator, modes=None):
61
+ if modes is None:
62
+ modes = _orthonormal_modes(num_res, rank, generator)
63
+ return {
64
+ "local_cov": torch.zeros(1, num_res, 3, 3),
65
+ "cross_cov": torch.zeros(1, num_res, num_res),
66
+ "rmsf": torch.zeros(1, num_res),
67
+ "oracle_modes": modes[None],
68
+ "oracle_energy": torch.as_tensor(energy, dtype=torch.float32)[None],
69
+ }
70
+
71
+
72
+ def _response_along(modes, weights, num_res):
73
+ """A response whose projected covariance is exactly diag(weights)."""
74
+ rank = modes.shape[1]
75
+ deltas = []
76
+ for r in range(rank):
77
+ amp = float(weights[r]) ** 0.5 * (rank ** 0.5)
78
+ deltas.append(amp * modes[:, r, :])
79
+ return torch.stack(deltas, dim=0)[:, None] # [S, 1, N, 3]
80
+
81
+
82
+ def main() -> None:
83
+ torch.manual_seed(0)
84
+ gen = torch.Generator().manual_seed(0)
85
+ encoder = LatentEncoder(_Cfg())
86
+ num_res, rank = 24, 2
87
+ res_mask = torch.ones(1, num_res)
88
+
89
+ modes = _orthonormal_modes(num_res, rank, gen)
90
+ energy = [4.0, 1.0] # a steep target: 80% / 20%
91
+ targets = _targets(num_res, rank, energy, gen, modes=modes)
92
+
93
+ def loss_for(weights, mask=res_mask, sample_weight=None, tgts=targets):
94
+ response = _response_along(modes, weights, num_res)
95
+ losses, metrics = encoder.generator_response_cov_loss(
96
+ response, res_mask=mask, targets=tgts,
97
+ sample_weight=sample_weight, oracle_rank=rank,
98
+ )
99
+ return float(losses["gen_oracle_shape_loss"]), metrics
100
+
101
+ print("target spectrum (normalised):", [e / sum(energy) for e in energy], flush=True)
102
+
103
+ aligned, _ = loss_for([4.0, 1.0]) # same shape as the target
104
+ flat, _ = loss_for([1.0, 1.0]) # isotropic
105
+ inverted, _ = loss_for([1.0, 4.0]) # target reversed
106
+ print(f"\n1. directional signal")
107
+ print(f" aligned {aligned:.6f}")
108
+ print(f" flat {flat:.6f}")
109
+ print(f" inverted {inverted:.6f}", flush=True)
110
+ assert aligned < flat < inverted, "the term does not rank shapes correctly"
111
+ assert aligned < 1e-6, f"an exactly aligned response should score ~0, got {aligned}"
112
+
113
+ scaled, _ = loss_for([400.0, 100.0]) # same shape, 100x the amplitude
114
+ print(f"\n2. scale invariance")
115
+ print(f" x1 {aligned:.6e}")
116
+ print(f" x100 {scaled:.6e}", flush=True)
117
+ assert abs(scaled - aligned) < 1e-5, "the term is not shape-only"
118
+
119
+ # An example outside the t window is zeroed upstream by sample_weight.
120
+ excluded, metrics = loss_for([1.0, 4.0], sample_weight=torch.zeros(1))
121
+ print(f"\n3. masked examples contribute nothing")
122
+ print(f" worst shape, but excluded: {excluded:.6f}"
123
+ f" active_frac={float(metrics['gen_oracle_active_frac']):.2f}", flush=True)
124
+ assert excluded == 0.0, "an excluded example was still charged"
125
+
126
+ print(f"\n4. fails closed without the cached basis")
127
+ bare = {k: v for k, v in targets.items() if not k.startswith("oracle_")}
128
+ try:
129
+ loss_for([4.0, 1.0], tgts=bare)
130
+ except KeyError as exc:
131
+ print(f" raised as required: {str(exc)[:70]}...", flush=True)
132
+ else:
133
+ raise AssertionError("missing oracle targets returned silently")
134
+
135
+ # Rank cannot exceed the number of antithetic perturbations; the projected
136
+ # covariance is a sum of S outer products.
137
+ _, metrics = loss_for([4.0, 1.0])
138
+ print(f"\nrank actually used: {int(metrics['gen_oracle_rank_used'])}"
139
+ f" (perturbations available: {rank})", flush=True)
140
+
141
+ # 5. The term must actually reach the backward, and a shrinking response must
142
+ # not be able to escape it. An earlier version gated `active` on
143
+ # `resp_trace > eps`, so driving a response toward zero removed that example
144
+ # from the average entirely -- a discontinuous reward that reads as success.
145
+ print(f"\n5. backward reaches the response, and shrinking does not escape")
146
+ leaf = _response_along(modes, [1.0, 4.0], num_res).clone().requires_grad_(True)
147
+ losses, _ = encoder.generator_response_cov_loss(
148
+ leaf, res_mask=res_mask, targets=targets, oracle_rank=rank,
149
+ )
150
+ losses["gen_oracle_shape_loss"].backward()
151
+ grad_norm = float(leaf.grad.norm())
152
+ print(f" grad norm w.r.t. response: {grad_norm:.6e}", flush=True)
153
+ assert grad_norm > 0 and torch.isfinite(leaf.grad).all(), "no usable gradient"
154
+
155
+ tiny, tiny_metrics = loss_for([1e-12, 4e-12])
156
+ print(f" same shape at 1e-12 amplitude: loss {tiny:.6f}"
157
+ f" active_frac={float(tiny_metrics['gen_oracle_active_frac']):.2f}",
158
+ flush=True)
159
+ assert abs(tiny - inverted) < 1e-4, (
160
+ "a vanishing response escaped the loss; activity must not depend on "
161
+ "response magnitude"
162
+ )
163
+
164
+ # 6. A rank beyond the number of perturbations is unmatchable and must raise.
165
+ print(f"\n6. unmatchable rank raises")
166
+ try:
167
+ response = _response_along(modes, [4.0, 1.0], num_res)
168
+ encoder.generator_response_cov_loss(
169
+ response[:1], res_mask=res_mask, targets=targets, oracle_rank=2,
170
+ )
171
+ except ValueError as exc:
172
+ print(f" raised as required: {str(exc)[:78]}...", flush=True)
173
+ else:
174
+ raise AssertionError("rank above the perturbation count was accepted")
175
+
176
+ print("\nall six properties hold", flush=True)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
bbflow_base/test_data/test_pdbs/MD_trajectory.xtc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:150673d6e46600e51af58134f83517f69fa26e1e104d82b7e9494fb04992f7d5
3
+ size 720956