s42chen commited on
Commit
ffcc0e3
·
verified ·
1 Parent(s): cbf9c8a

Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 50)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/training/checkpoint.py +65 -0
  3. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/training/schedulers.py +91 -0
  4. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/alignment.py +102 -0
  5. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/components.py +434 -0
  6. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/datasets.py +416 -0
  7. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/ddp.py +111 -0
  8. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/instantiators.py +72 -0
  9. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/logging.py +281 -0
  10. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/rigid.py +1466 -0
  11. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/rotation_augmentation.py +67 -0
  12. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/squashfs.py +172 -0
  13. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/torch.py +367 -0
  14. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/weights.py +274 -0
  15. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/__init__.py +27 -0
  16. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/single_xpu_strategy.py +47 -0
  17. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/xpu_accelerator.py +91 -0
  18. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/xpu_precision.py +72 -0
  19. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/version.py +24 -0
  20. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3_collect.py +247 -0
  21. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3_infer.sh +83 -0
  22. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3_inputs.py +334 -0
  23. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/sampling.json +1 -0
  24. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/training_record.json +9 -0
  25. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/trajectory.jsonl +48 -0
  26. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/index.json +0 -0
  27. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/codex.stderr +21 -0
  28. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/preflight.jsonl +8 -0
  29. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/preflight.stderr +0 -0
  30. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/sessions/2026/10/22/rollout-2026-10-22T03-00-28-01a1618d-8956-7b80-9cc4-d67245b7663a.jsonl +3 -0
  31. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl +3 -0
  32. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/LICENSE.md +28 -0
  33. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/MEASUREMENTS.json +68 -0
  34. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md +43 -0
  35. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/RESULTS.md +59 -0
  36. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/TRAINING_DATA.md +405 -0
  37. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/design.py +207 -0
  38. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/harness.json +14 -0
  39. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh +12 -0
  40. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/publish.py +79 -0
  41. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/residues.py +66 -0
  42. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/LICENSE.md +28 -0
  43. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/default.yaml +5 -0
  44. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/dump_validation_structures.yaml +6 -0
  45. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/metrics_logging.yaml +10 -0
  46. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/train_logging.yaml +16 -0
  47. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/dataloader/default.yaml +15 -0
  48. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/datasets/base.yaml +31 -0
  49. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/datasets/pdb_and_distillation.yaml +55 -0
  50. tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/datasets/pdb_only.yaml +17 -0
.gitattributes CHANGED
@@ -1157,3 +1157,7 @@ tasks/mass-spectrometry-molecule-retrieval/mass-spectrometry-molecule-retrieval-
1157
  tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a/index.json filter=lfs diff=lfs merge=lfs -text
1158
  tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a/logs/sessions/2026/10/20/rollout-2026-10-20T08-00-22-01a15853-62be-7f40-8462-cc37f5a654b3.jsonl filter=lfs diff=lfs merge=lfs -text
1159
  tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
1157
  tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a/index.json filter=lfs diff=lfs merge=lfs -text
1158
  tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a/logs/sessions/2026/10/20/rollout-2026-10-20T08-00-22-01a15853-62be-7f40-8462-cc37f5a654b3.jsonl filter=lfs diff=lfs merge=lfs -text
1159
  tasks/natural-disease-progression/ndp-astra-xhigh-48h-20261020a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
1160
+ tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/sessions/2026/10/22/rollout-2026-10-22T03-00-28-01a1618d-8956-7b80-9cc4-d67245b7663a.jsonl filter=lfs diff=lfs merge=lfs -text
1161
+ tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
1162
+ tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/logs/sessions/2026/10/22/rollout-2026-10-22T03-38-50-01a161b0-ac23-78b3-96d0-140821a2d85b.jsonl filter=lfs diff=lfs merge=lfs -text
1163
+ tasks/protein-sequence-modeling/protein-sequence-modeling-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl filter=lfs diff=lfs merge=lfs -text
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/training/checkpoint.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for gradient checkpointing.
2
+
3
+ References:
4
+ * `PyTorch Checkpoint Documentation`_
5
+
6
+ .. _PyTorch Checkpoint Documentation: https://pytorch.org/docs/stable/checkpoint.html
7
+ """
8
+
9
+ from typing import Any, Callable
10
+
11
+ import torch
12
+ from torch.utils.checkpoint import checkpoint
13
+
14
+
15
+ def create_custom_forward(
16
+ module: Callable[..., Any], **kwargs: Any
17
+ ) -> Callable[..., Any]:
18
+ """Create a custom forward function for gradient checkpointing with fixed kwargs.
19
+
20
+ Enables passing keyword arguments to a module when using PyTorch's checkpoint function,
21
+ which only accepts positional arguments for the function to be checkpointed.
22
+
23
+ Args:
24
+ module: The callable (typically a nn.Module) to wrap.
25
+ **kwargs: Keyword arguments to pass to the module during forward.
26
+
27
+ Returns:
28
+ A callable that accepts only positional arguments and forwards them along
29
+ with the fixed kwargs to the original module.
30
+ """
31
+
32
+ def custom_forward(*inputs: Any) -> Any:
33
+ return module(*inputs, **kwargs)
34
+
35
+ return custom_forward
36
+
37
+
38
+ def activation_checkpointing(function: Callable[..., Any]) -> Callable[..., Any]:
39
+ """Decorator to enable gradient checkpointing for a function during training.
40
+
41
+ Args:
42
+ function: The function to apply gradient checkpointing to.
43
+
44
+ Returns:
45
+ Wrapped function that conditionally applies checkpointing based on gradient state.
46
+
47
+ Examples:
48
+ Apply to a forward pass method::
49
+
50
+ @activation_checkpointing
51
+ def forward(self, x, mask=None):
52
+ return self.layer(x, mask)
53
+
54
+ Notes:
55
+ Uses ``use_reentrant=False`` for compatibility with recent PyTorch versions.
56
+ """
57
+
58
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
59
+ if torch.is_grad_enabled():
60
+ return checkpoint(
61
+ create_custom_forward(function, **kwargs), *args, use_reentrant=False
62
+ )
63
+ return function(*args, **kwargs)
64
+
65
+ return wrapper
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/training/schedulers.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from torch.optim.lr_scheduler import LRScheduler, _LRScheduler
4
+ from torch.optim.optimizer import Optimizer
5
+
6
+
7
+ class AF3Scheduler(_LRScheduler):
8
+ """Implements a two-phase learning rate schedule a-la AF-3:
9
+ 1. The base learning rate is 1.8 · 10^−3, which is linearly increased from 0 over the first 1,000 steps.
10
+ 2. The learning rate is then decreased by a factor of 0.95 every 50,000 steps.
11
+
12
+ From the AF-3 Supplement, Section 5.4:
13
+ > "For training we use the Adam optimizer with parameters β1 = 0.9, β2 = 0.95, ϵ = 10^−8. The base learning rate
14
+ is 1.8 · 10^−3, which is linearly increased from 0 over the first 1,000 steps. The learning rate is then decreased
15
+ by a factor of 0.95 every 5 · 10^4 steps."
16
+
17
+ References:
18
+ - AF-3 Supplement
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ optimizer: Optimizer,
24
+ base_lr: float = 1.8e-3,
25
+ warmup_steps: int = 1000,
26
+ decay_factor: float = 0.95,
27
+ decay_steps: int = 50000,
28
+ last_epoch: int = -1,
29
+ ) -> None:
30
+ """Initializes a new instance of AF3LRScheduler.
31
+
32
+ Note that the "last_epoch" value is incremented every time we call `scheduler.step()`
33
+ method; we name it "epoch" to follow the PyTorch convention.
34
+
35
+ Args:
36
+ optimizer (Optimizer): Wrapped optimizer.
37
+ base_lr (float): The base learning rate after warmup (which will then be decayed).
38
+ warmup_steps (int): Number of steps for linear warmup.
39
+ decay_factor (float): Factor by which the learning rate is multiplied every decay_steps.
40
+ decay_steps (int): Number of steps between each decay.
41
+ last_epoch (int): The index of the last epoch. Default: -1.
42
+ """
43
+ self.base_lr = base_lr
44
+ self.warmup_steps = warmup_steps
45
+ self.decay_factor = decay_factor
46
+ self.decay_steps = decay_steps
47
+ super(AF3Scheduler, self).__init__(optimizer, last_epoch)
48
+
49
+ def get_lr(self) -> list[float]:
50
+ if self.last_epoch < self.warmup_steps:
51
+ # Linear warmup
52
+ return [
53
+ self.base_lr * (self.last_epoch / self.warmup_steps)
54
+ for _ in self.optimizer.param_groups
55
+ ]
56
+ else:
57
+ # Decay after warmup
58
+ num_decays = (self.last_epoch - self.warmup_steps) // self.decay_steps
59
+ return [
60
+ self.base_lr * (self.decay_factor**num_decays)
61
+ for _ in self.optimizer.param_groups
62
+ ]
63
+
64
+
65
+ @dataclass
66
+ class SchedulerConfig:
67
+ """Flexible configuration for a learning rate scheduler.
68
+
69
+ Modeled on the PyTorch Lightning scheduler configuration.
70
+
71
+ Attributes:
72
+ scheduler (LRScheduler): The learning rate scheduler instance. Must inherit from `torch.optim.lr_scheduler.LRScheduler`.
73
+ interval (str): The interval at which to apply the scheduler, typically "epoch" or "step". Defaults to "step".
74
+ frequency (int): The frequency of applying the scheduler. For example, a frequency of 1 means the scheduler is applied every epoch. Defaults to 1.
75
+ """
76
+
77
+ scheduler: LRScheduler
78
+ interval: str = "step"
79
+ frequency: int = 1
80
+
81
+ def state_dict(self) -> dict:
82
+ return {
83
+ "scheduler": self.scheduler.state_dict(),
84
+ "interval": self.interval,
85
+ "frequency": self.frequency,
86
+ }
87
+
88
+ def load_state_dict(self, state_dict: dict) -> None:
89
+ self.scheduler.load_state_dict(state_dict["scheduler"])
90
+ self.interval = state_dict["interval"]
91
+ self.frequency = state_dict["frequency"]
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/alignment.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import torch
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+
8
+ def weighted_rigid_align(
9
+ X_L: torch.Tensor, # [B, L, 3]
10
+ X_gt_L: torch.Tensor, # [B, L, 3]
11
+ X_exists_L: torch.Tensor | None = None, # [L]
12
+ w_L: torch.Tensor | None = None, # [B, L]
13
+ ) -> torch.Tensor:
14
+ """
15
+ Weighted rigid body alignment of X_gt_L onto X_L with weights w_L
16
+ Allows for "moving target" ground truth that is se3 invariant
17
+ Following algorithm 28 in AF3 paper
18
+ Returns:
19
+ X_align_L: [B, L, 3]
20
+ """
21
+
22
+ # Canonicalize dimensions
23
+ if X_L.ndim == 2:
24
+ X_L = X_L[None]
25
+ if X_gt_L.ndim == 2:
26
+ X_gt_L = X_gt_L[None]
27
+ if X_exists_L is None:
28
+ X_exists_L = torch.ones((X_L.shape[-2]), dtype=torch.bool)
29
+ if w_L is None:
30
+ w_L = torch.ones_like(X_L[..., 0])
31
+ else:
32
+ if w_L.ndim == 1:
33
+ w_L = w_L[None]
34
+ w_L = w_L.to(torch.float32)
35
+
36
+ # Assert `X_exists_L` is a boolean mask
37
+ assert (
38
+ X_exists_L.dtype == torch.bool
39
+ ), "X_exists_L should be a boolean mask! Otherwise, the alignment will be incorrect (silent failure)!"
40
+
41
+ assert X_L.shape == X_gt_L.shape
42
+ assert X_L.shape[:-1] == w_L.shape
43
+
44
+ X_resolved = X_L[:, X_exists_L]
45
+ X_gt_resolved = X_gt_L[:, X_exists_L]
46
+ w_resolved = w_L[:, X_exists_L]
47
+ u_X = torch.sum(X_resolved * w_resolved.unsqueeze(-1), dim=-2) / torch.sum(
48
+ w_resolved, dim=-1, keepdim=True
49
+ )
50
+ u_X_gt = torch.sum(X_gt_resolved * w_resolved.unsqueeze(-1), dim=-2) / torch.sum(
51
+ w_resolved, dim=-1, keepdim=True
52
+ )
53
+
54
+ X_resolved = X_resolved - u_X.unsqueeze(-2)
55
+ X_gt_resolved = X_gt_resolved - u_X_gt.unsqueeze(-2)
56
+
57
+ # Computation of the covariance matrix
58
+ C = torch.einsum("bji,bjk->bik", w_resolved[..., None] * X_gt_resolved, X_resolved)
59
+
60
+ U, S, V = torch.linalg.svd(C)
61
+
62
+ R = U @ V
63
+ B, _, _ = X_L.shape
64
+ # F is the reflection correction for the Kabsch rotation: its last diagonal
65
+ # entry flips to -1 when det(R) < 0 so R stays a proper rotation. It feeds
66
+ # `U @ F @ V` below, where matmul requires a shared dtype — U and V carry
67
+ # X_L's dtype (SVD of an input-derived covariance), so F must too. torch.eye
68
+ # defaults to float32, so without dtype= float64 inputs raise a mismatch.
69
+ F = torch.eye(3, 3, device=X_L.device, dtype=X_L.dtype)[None].tile(
70
+ (
71
+ B,
72
+ 1,
73
+ 1,
74
+ )
75
+ )
76
+
77
+ det = torch.linalg.det(R)
78
+ F[..., -1, -1] = torch.sign(det)
79
+ R = U @ F @ V
80
+
81
+ X_gt_L = X_gt_L - u_X_gt.unsqueeze(-2)
82
+ X_align_L = X_gt_L @ R + u_X.unsqueeze(-2)
83
+
84
+ return X_align_L.detach()
85
+
86
+
87
+ def get_rmsd(xyz1: torch.Tensor, xyz2: torch.Tensor, eps: float = 1e-4) -> torch.Tensor:
88
+ L = xyz1.shape[-2]
89
+ rmsd = torch.sqrt(torch.sum((xyz2 - xyz1) * (xyz2 - xyz1), dim=(-1, -2)) / L + eps)
90
+ return rmsd
91
+
92
+
93
+ def superimpose(
94
+ xyz1: torch.Tensor, xyz2: torch.Tensor, mask: torch.Tensor, eps: float = 1e-4
95
+ ) -> None:
96
+ """
97
+ Superimpose xyz1 onto xyz2 using mask
98
+ """
99
+ L = xyz1.shape[-2]
100
+ assert mask.shape == (L,)
101
+ assert xyz1.shape == xyz2.shape
102
+ assert mask.dtype == torch.bool
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/components.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import re
3
+ from typing import List
4
+
5
+ import numpy as np
6
+ from atomworks.ml.encoding_definitions import AF3SequenceEncoding
7
+ from biotite.structure import AtomArray
8
+
9
+ from foundry.constants import (
10
+ TIP_BY_RESTYPE,
11
+ )
12
+ from foundry.utils.ddp import RankedLogger
13
+
14
+ global_logger = RankedLogger(__name__, rank_zero_only=False)
15
+ sequence_encoding = AF3SequenceEncoding()
16
+ _aa_like_res_names = sequence_encoding.all_res_names[sequence_encoding.is_aa_like]
17
+
18
+
19
+ #################################################################################
20
+ # Component / contig parsing
21
+ #################################################################################
22
+
23
+
24
+ class ComponentValidationError(ValueError):
25
+ """Raised when contig/component inputs cannot be parsed or validated."""
26
+
27
+ def __init__(
28
+ self,
29
+ message: str,
30
+ *,
31
+ component: str | None = None,
32
+ details: dict | None = None,
33
+ ):
34
+ self.component = component
35
+ self.details = details or {}
36
+ prefix = f"[component={component}] " if component else ""
37
+ suffix = f" Details: {self.details}" if self.details else ""
38
+ super().__init__(f"{prefix}{message}{suffix}")
39
+
40
+
41
+ class ComponentStr(str):
42
+ """Component identifier, e.g. "A1" for residues, "B12", etc. Previously named `contig_string`"""
43
+
44
+ def split_component(v) -> list:
45
+ return split_contig(v)
46
+
47
+
48
+ def split_contig(x: str) -> list:
49
+ try:
50
+ chain = str(x[0])
51
+ idx = int(x[1:])
52
+ if idx < 0:
53
+ raise ComponentValidationError(
54
+ "Residue index must be a non-negative integer.", component=str(x)
55
+ )
56
+ except Exception as e:
57
+ raise ComponentValidationError(
58
+ f"Invalid contig format: '{x}'. Expected format is 'ChainIDResID' (e.g. 'A20').",
59
+ component=str(x),
60
+ ) from e
61
+ return [chain, idx]
62
+
63
+
64
+ def extract_pn_unit_info(contig: str) -> tuple[str, int, int]:
65
+ """
66
+ Convert substring like A20-21 or A20 to separate terms: A, 20, 21.
67
+ """
68
+ pattern = r"([A-Za-z])(\d+)(?:-(\d+))?"
69
+
70
+ match = re.match(pattern, contig)
71
+ if match:
72
+ pn_unit_id = match.group(1)
73
+ start = int(match.group(2))
74
+ end = int(match.group(3)) if match.group(3) else start
75
+ return pn_unit_id, start, end
76
+
77
+ raise ComponentValidationError(
78
+ "Invalid contig format. Expected 'ChainIDStart-Stop' or 'ChainIDIdx'.",
79
+ component=contig,
80
+ )
81
+
82
+
83
+ def get_design_pattern_with_constraints(
84
+ contig: str, length: str | None = None
85
+ ) -> list[str]:
86
+ """
87
+ Convert the contig string to separate modules.
88
+ e.g. '1-5,A20-21,1-5,A25-25,1-5,A30-30,/0,1-5' with length = 10-10 may be converted to [2, A20, A21, 2, A25, 3, A30, /0, 3]
89
+ Integers represent number of free residues to put there.
90
+
91
+ """
92
+ contig_parts = contig.split(",")
93
+
94
+ # Separate fixed segments (e.g., "A1051-1051") and variable ranges (e.g., "0-40")
95
+ variable_ranges: list[list[int]] = []
96
+ fixed_parts: list[tuple[str, int, int]] = []
97
+ pos_to_put_motif = []
98
+
99
+ suff = [] # suffixes for diffused regions P(optional),R,D
100
+
101
+ for part in contig_parts:
102
+ ## updating to include DNA and RNA generation
103
+ if part[-1] in ["R", "D"]: ##Detect non-fixed RNA and DNA contig part
104
+ suff.append(part[-1])
105
+ part = part[:-1]
106
+ if "-" in part:
107
+ start, end = map(int, part.split("-"))
108
+ else:
109
+ start = end = int(part)
110
+ variable_ranges.append([start, end])
111
+ pos_to_put_motif.append(0)
112
+
113
+ elif any(c.isalpha() for c in part): # Detect parts containing letters as fixed
114
+ pn_unit_id, pn_unit_start, pn_unit_end = extract_pn_unit_info(part)
115
+ fixed_parts.append((pn_unit_id, pn_unit_start, pn_unit_end))
116
+ pos_to_put_motif.append(1)
117
+ elif part == "/0":
118
+ pos_to_put_motif.append(2)
119
+ else:
120
+ if "-" in part:
121
+ start, end = map(int, part.split("-"))
122
+ else:
123
+ start = end = int(part)
124
+ variable_ranges.append([start, end])
125
+ pos_to_put_motif.append(0)
126
+ suff.append("P")
127
+
128
+ # adjust the total length to solely for free residues
129
+ num_motif_residues = sum([i[2] - i[1] + 1 for i in fixed_parts])
130
+
131
+ if length is None:
132
+ length_min, length_max = 0, 9999
133
+ else:
134
+ if "-" in length:
135
+ length_min, length_max = map(int, length.split("-"))
136
+ else:
137
+ length_min = length_max = int(length)
138
+
139
+ length_min -= num_motif_residues
140
+ length_max -= num_motif_residues
141
+
142
+ remaining_length_min = length_min
143
+ remaining_length_max = length_max
144
+
145
+ num_free_atoms: list[int] = []
146
+ for range_limits in variable_ranges:
147
+ min_value = range_limits[0]
148
+ max_value = range_limits[1]
149
+
150
+ # Calculate the valid range for the current segment
151
+ valid_min = max(
152
+ min_value,
153
+ remaining_length_min
154
+ - sum(r[1] for r in variable_ranges[len(num_free_atoms) + 1 :]),
155
+ )
156
+ valid_max = min(
157
+ max_value,
158
+ remaining_length_max
159
+ - sum(r[0] for r in variable_ranges[len(num_free_atoms) + 1 :]),
160
+ )
161
+
162
+ if valid_min > valid_max and length is not None:
163
+ raise ComponentValidationError(
164
+ "No valid selections possible with the given constraints."
165
+ )
166
+
167
+ # Randomly select a value for the current segment
168
+ selected_value = random.randint(valid_min, valid_max)
169
+ num_free_atoms.append(selected_value)
170
+
171
+ # Update remaining lengths
172
+ remaining_length_min -= selected_value
173
+ remaining_length_max -= selected_value
174
+
175
+ atoms_with_motif = []
176
+ for idx in range(len(pos_to_put_motif)):
177
+ if pos_to_put_motif[idx] == 1:
178
+ motif = fixed_parts.pop(0)
179
+ pn_unit_id, pn_unit_start, pn_unit_end = motif[0], motif[1], motif[2]
180
+ for index in range(pn_unit_start, pn_unit_end + 1):
181
+ atoms_with_motif.append(f"{pn_unit_id}{index}")
182
+ elif pos_to_put_motif[idx] == 0:
183
+ free_atom = num_free_atoms.pop(0)
184
+ atoms_with_motif.append(str(free_atom) + suff.pop(0))
185
+ elif pos_to_put_motif[idx] == 2:
186
+ atoms_with_motif.append("/0")
187
+
188
+ return atoms_with_motif
189
+
190
+
191
+ def get_motif_components_and_breaks(
192
+ unindexed_contig: str, index_all: bool = False
193
+ ) -> tuple[list[str], list[bool | None]]:
194
+ """
195
+ Convert a contig string into its components and breaks in motif
196
+ This way you can specify in your contigs where the breaks in the motif should be, so that,
197
+ say, residues aren't glued together by the model. Used for parsing unindexed inputs.
198
+
199
+ e.g.:
200
+ contig="A14,A15,A16" -> components=[A14, A15, A16] breaks=[True, True, True]
201
+ contig="A14-15,A16" -> components=[A14, A15, A16] breaks=[True, False, True]
202
+
203
+ args:
204
+ unindexed_contig: Contig string for unindexed tokens, see above for example on how positional
205
+ encodings between contigs can be selectively leaked
206
+ index_all: No breaks are used, allows for full indexing of concatenated tokens
207
+ Can use cleanup if this is the desired way to provide motif tokens.
208
+ """
209
+ components: list[str] = []
210
+ breaks: list[bool | None] = []
211
+
212
+ contig_parts = unindexed_contig.split(",")
213
+ for part in contig_parts:
214
+ if any(c.isalpha() for c in part):
215
+ # ... Parse possibilities: A11 | A11-12 | A11-11
216
+ pn_unit_id, pn_unit_start, pn_unit_end = extract_pn_unit_info(part)
217
+
218
+ if pn_unit_start == pn_unit_end:
219
+ # ... For single residues, append and break
220
+ components.append(f"{pn_unit_id}{pn_unit_start}")
221
+ breaks.append(True)
222
+ else:
223
+ # ... For multiple residues, break and then append without breaks
224
+ for index in range(pn_unit_start, pn_unit_end + 1):
225
+ components.append(f"{pn_unit_id}{index}")
226
+ if index == pn_unit_start:
227
+ breaks.append(True)
228
+ else:
229
+ breaks.append(False)
230
+ elif part == "/0":
231
+ components.append(part)
232
+ breaks.append(None)
233
+ else:
234
+ if "-" in part:
235
+ raise ComponentValidationError(
236
+ "Partial unindexing without fixed length is not supported.",
237
+ component=part,
238
+ )
239
+ components.append(part)
240
+ breaks.append(None)
241
+
242
+ breaks[0] = True # Decouple unindexed region from global index
243
+ if index_all:
244
+ global_logger.info("Unindexing all residues")
245
+ breaks = [(False if b is not None else None) for b in breaks]
246
+ return components, breaks
247
+
248
+
249
+ #################################################################################
250
+ # Mask getters
251
+ #################################################################################
252
+
253
+
254
+ def get_name_mask(
255
+ source_names: np.ndarray,
256
+ query_names: str | list[str],
257
+ source_resname: str | None = None,
258
+ ) -> np.ndarray:
259
+ """
260
+ Args:
261
+ source_names: list of all names to match in current token
262
+ query_string: specifier of names to get:
263
+ "ALL" - All atom names in token are matched
264
+ "BKBN - Only backbone atoms (not CB)
265
+ "TIP" - 2 farthest atoms from the backbone are fixed with any
266
+ additional atoms that automatically constrain geometries
267
+ (e.g. 4 atoms for carboxylates/amides). See `constants.py`.
268
+ Comma-separated string - e.g. "N,CA,C,O,CB" for exact queries
269
+ List of names - e.g. ["N", "CA", "C", "O"] for exact queries
270
+ source_resname: residue name is required when specifying just to grab the names for a "TIP"
271
+
272
+ Raises error if not all exact atom names are found and unique
273
+
274
+ Returns:
275
+ mask of atoms corresponding to token
276
+ """
277
+ if isinstance(query_names, list):
278
+ names = query_names
279
+ elif isinstance(query_names, str):
280
+ if query_names.upper() == "ALL":
281
+ return np.ones(source_names.shape[0], dtype=bool)
282
+ elif query_names.upper() == "BKBN":
283
+ names = ["N", "CA", "C", "O"]
284
+ elif query_names.upper() == "TIP":
285
+ if source_resname is None:
286
+ raise ComponentValidationError(
287
+ "TIP selection requires a residue name.",
288
+ component=str(source_resname),
289
+ )
290
+ tip_names = TIP_BY_RESTYPE[source_resname]
291
+ if tip_names is None:
292
+ raise ComponentValidationError(
293
+ "Residue does not define TIP atoms; use ALL, BKBN, or explicit names.",
294
+ component=str(source_resname),
295
+ )
296
+ names = tip_names
297
+ elif query_names == "":
298
+ names = []
299
+ else:
300
+ names = query_names.split(",")
301
+ else:
302
+ raise ComponentValidationError(
303
+ "query_names must be a string or list of strings.",
304
+ details={"got_type": str(type(query_names))},
305
+ )
306
+
307
+ if any(n == "" for n in names):
308
+ raise ComponentValidationError(
309
+ f"Empty atom name found in selection '{query_names}'.",
310
+ component=str(source_resname),
311
+ )
312
+ mask = np.isin(source_names, names)
313
+
314
+ if len(names) == 0:
315
+ return mask
316
+
317
+ if not len(set(names)) == len(names):
318
+ raise ComponentValidationError(
319
+ f"Atom names in '{query_names}' must be unique.",
320
+ details={"duplicates": names},
321
+ )
322
+ if not mask.any():
323
+ raise ComponentValidationError(
324
+ f"Could not find requested atoms '{query_names}' in atom array.",
325
+ details={"source_names": np.asarray(source_names).tolist()},
326
+ )
327
+ if mask.sum() != len(names):
328
+ global_logger.warning(
329
+ "Not all atoms found in atom array. Are you expecting multiple residues/ligands with the same names? "
330
+ + "If not, check your input pdb file. "
331
+ + "Atom array requested to contain names {}. Got: {}. Requested {}".format(
332
+ query_names,
333
+ np.asarray(source_names).tolist(),
334
+ np.asarray(names).tolist(),
335
+ )
336
+ )
337
+ if mask.sum() % len(names) != 0:
338
+ # for the case where source_names are originated from multiple residues with the same names
339
+ # (e.g. two ORO ligands in the input pdb: {ligand: "ORO", fixed_atoms: {ORO:"N3,C2,C4,N1"}})
340
+ raise ComponentValidationError(
341
+ "Number of atoms must be a multiple of the requested names.",
342
+ details={
343
+ "query": query_names,
344
+ "source_names": np.asarray(source_names).tolist(),
345
+ "requested": np.asarray(names).tolist(),
346
+ },
347
+ )
348
+
349
+ return mask
350
+
351
+
352
+ def fetch_mask_from_idx(contig_str: str, *, atom_array: AtomArray) -> np.ndarray:
353
+ """
354
+ contig_str: A11
355
+ returns:
356
+ mask of atoms within contig (e.g. residue 11 in chain A)
357
+ """
358
+ chain, res_id = split_contig(contig_str)
359
+ mask = (atom_array.chain_id == chain) & (atom_array.res_id == res_id)
360
+ if not np.any(mask):
361
+ raise ComponentValidationError(
362
+ f"Residue {chain}{res_id} not found in atom array.",
363
+ component=f"{chain}{res_id}",
364
+ )
365
+ return mask
366
+
367
+
368
+ def fetch_mask_from_name(name: str, *, atom_array: AtomArray) -> np.ndarray:
369
+ """
370
+ name: LIG_NAME
371
+ returns:
372
+ mask of atoms corresponding to non-protein
373
+ """
374
+ mask = atom_array.res_name == name
375
+ if not np.any(mask):
376
+ non_protein_res_names = np.unique(
377
+ atom_array.res_name[~np.isin(atom_array.res_name, _aa_like_res_names)]
378
+ )
379
+ raise ComponentValidationError(
380
+ "Component not found in input atom array.",
381
+ component=name,
382
+ details={"available_non_protein": non_protein_res_names.tolist()},
383
+ )
384
+ return mask
385
+
386
+
387
+ def fetch_mask_from_component(component: str, *, atom_array: AtomArray) -> np.ndarray:
388
+ """
389
+ Catch-all function for fetching a component by non-protein name or contig
390
+ component: A11 or LIG_NAME
391
+ returns:
392
+ mask of atoms corresponding to component
393
+ """
394
+ try:
395
+ mask = fetch_mask_from_name(component, atom_array=atom_array)
396
+ except ComponentValidationError:
397
+ mask = fetch_mask_from_idx(component, atom_array=atom_array)
398
+ return mask
399
+
400
+
401
+ def unravel_components(
402
+ v: str, *, atom_array: AtomArray = None, allow_multiple_matches: bool = False
403
+ ) -> List[str]:
404
+ """Safely unravel components from a string input."""
405
+ components = []
406
+ if "," in v or "-" in v:
407
+ components.extend(get_design_pattern_with_constraints(v))
408
+ else:
409
+ # Safely canonicalize to single component
410
+ mask = fetch_mask_from_component(v, atom_array=atom_array)
411
+ if mask.sum() > 0:
412
+ res_ids, chain_ids = atom_array.res_id[mask], atom_array.chain_id[mask]
413
+ # assert unique resids for component
414
+ if len(set(zip(chain_ids, res_ids))) != 1:
415
+ if not allow_multiple_matches:
416
+ raise ComponentValidationError(
417
+ f"Component '{v}' maps to multiple residues.",
418
+ component=v,
419
+ )
420
+ else:
421
+ global_logger.warning(
422
+ f"Component '{v}' maps to multiple residues. If you are using Symmetry this is OK."
423
+ )
424
+ components.extend([f"{c}{r}" for c, r in zip(chain_ids, res_ids)])
425
+ components = list(set(components)) # unique components
426
+ return components
427
+ res_id, chain_id = res_ids[0], chain_ids[0]
428
+
429
+ component = f"{chain_id}{res_id}"
430
+ global_logger.debug(
431
+ "Canonicalized component string: %s -> %s", v, component
432
+ )
433
+ components.append(component)
434
+ return components
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/datasets.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hydra
2
+ import torch
3
+ from atomworks.ml.samplers import (
4
+ DistributedMixedSampler,
5
+ FallbackSamplerWrapper,
6
+ LazyWeightedRandomSampler,
7
+ LoadBalancedDistributedSampler,
8
+ MixedSampler,
9
+ )
10
+ from beartype.typing import Any
11
+ from omegaconf import DictConfig, ListConfig
12
+ from torch.utils.data import (
13
+ DataLoader,
14
+ Dataset,
15
+ RandomSampler,
16
+ Sampler,
17
+ SequentialSampler,
18
+ Subset,
19
+ WeightedRandomSampler,
20
+ )
21
+ from torch.utils.data.distributed import DistributedSampler
22
+
23
+ from foundry.hydra.resolvers import register_resolvers
24
+ from foundry.utils.ddp import RankedLogger
25
+
26
+ ranked_logger = RankedLogger(__name__, rank_zero_only=True)
27
+ try:
28
+ from atomworks.ml.datasets import (
29
+ ConcatDatasetWithID,
30
+ FallbackDatasetWrapper,
31
+ get_row_and_index_by_example_id,
32
+ )
33
+ except Exception as e:
34
+ ranked_logger.warning(
35
+ f"Failed to import atomworks.ml.datasets: {type(e).__name__}: {e}. "
36
+ "If training networks, the PDB_MIRROR environment variable must be set."
37
+ )
38
+
39
+
40
+ register_resolvers()
41
+
42
+
43
+ def wrap_dataset_and_sampler_with_fallbacks(
44
+ dataset_to_be_wrapped: Dataset,
45
+ sampler_to_be_wrapped: Sampler,
46
+ dataset_to_fallback_to: Dataset,
47
+ sampler_to_fallback_to: Sampler,
48
+ n_fallback_retries: int,
49
+ ) -> tuple[Dataset, Sampler]:
50
+ """Wrap the specified dataset and sampler with fallback dataloading.
51
+
52
+ If the provided fallback sampler does not have weights (e.g., a MixedSampler), we will use uniform weights.
53
+
54
+ Args:
55
+ dataset_to_be_wrapped (Dataset): The main dataset to be wrapped.
56
+ sampler_to_be_wrapped (Sampler): The main sampler to be wrapped.
57
+ dataset_to_fallback_to (Dataset): The fallback dataset. We will sample from this dataset if the main dataset fails.
58
+ sampler_to_fallback_to (Sampler): The fallback sampler. We will sample from this sampler if the main sampler fails.
59
+ n_fallback_retries (int): Number of retries for the fallback mechanism before raising an exception.
60
+
61
+ Returns:
62
+ tuple[Dataset, Sampler]: The wrapped dataset and sampler with fallbacks.
63
+ """
64
+ # Instantiate a new fallback sampler to avoid scaling issues.
65
+ # `hasattr`, not `"weights" in sampler`: `in` on a Sampler has no `__contains__`, so it
66
+ # iterates the sampler's indices (ints) and never matches the string "weights" — the
67
+ # weighted branch was dead and the membership test needlessly drew samples.
68
+ if hasattr(sampler_to_fallback_to, "weights"):
69
+ fallback_weights = sampler_to_fallback_to.weights
70
+ else:
71
+ # torch types `Dataset` without `__len__`, but map-style datasets provide it.
72
+ fallback_weights = torch.ones(len(dataset_to_fallback_to)) # type: ignore[arg-type]
73
+ fallback_sampler = LazyWeightedRandomSampler(
74
+ weights=fallback_weights,
75
+ num_samples=int(1e9),
76
+ replacement=True, # replacement for fallback dataloading, so we can draw a huge number of samples
77
+ generator=None,
78
+ prefetch_buffer_size=4,
79
+ )
80
+
81
+ # Wrap the dataset and sampler with fallback mechanisms
82
+ wrapped_dataset = FallbackDatasetWrapper(
83
+ dataset_to_be_wrapped, fallback_dataset=dataset_to_fallback_to
84
+ )
85
+ wrapped_sampler = FallbackSamplerWrapper(
86
+ sampler_to_be_wrapped,
87
+ fallback_sampler=fallback_sampler,
88
+ n_fallback_retries=n_fallback_retries,
89
+ )
90
+
91
+ return wrapped_dataset, wrapped_sampler
92
+
93
+
94
+ def instantiate_single_dataset_and_sampler(cfg: DictConfig) -> dict[str, Any]:
95
+ """Instantiate a dataset and its corresponding sampler from a configuration dictionary.
96
+
97
+ Args:
98
+ cfg (DictConfig): Configuration dictionary defining the dataset and its parameters.
99
+
100
+ Returns:
101
+ dict[str, Any]: A dictionary containing the instantiated dataset and sampler.
102
+ """
103
+ # ... instantiate the dataset
104
+ dataset = hydra.utils.instantiate(cfg.dataset)
105
+
106
+ # Users may provide only weights, in which case we will use a WeightedRandomSampler,
107
+ # or they may provide a sampler directly
108
+
109
+ if "weights" in cfg and "sampler" not in cfg:
110
+ # ... instantiate the weights and create a WeightedRandomSampler
111
+ weights = hydra.utils.instantiate(cfg.weights, dataset_df=dataset.data)
112
+ sampler = WeightedRandomSampler(
113
+ weights=weights,
114
+ num_samples=len(dataset),
115
+ replacement=True,
116
+ )
117
+ elif "sampler" in cfg and "weights" not in cfg:
118
+ # ... instantiate the sampler with the number of samples
119
+ sampler = hydra.utils.instantiate(cfg.sampler)
120
+ else:
121
+ dataset_name = getattr(getattr(cfg.dataset, "dataset", None), "name", None)
122
+ ranked_logger.warning(
123
+ f"No weights or sampler provided for dataset: {dataset_name}, using uniform weights with replacement."
124
+ )
125
+ sampler = WeightedRandomSampler(
126
+ # torch types `weights` as `Sequence[float]`; a Tensor is accepted at runtime.
127
+ weights=torch.ones(len(dataset)), # type: ignore[arg-type]
128
+ num_samples=len(dataset),
129
+ replacement=True,
130
+ )
131
+
132
+ return {"dataset": dataset, "sampler": sampler}
133
+
134
+
135
+ def recursively_instantiate_datasets_and_samplers(
136
+ cfg: DictConfig, name: str | None = None
137
+ ) -> dict[str, Any]:
138
+ """Recursively instantiate datasets and samplers from a configuration dictionary.
139
+
140
+ We must handle three cases:
141
+ (1) A single "leaf" dataset (e.g., "distillation"), specified with the "dataset" key
142
+ (2) Multiple sub-datasets that should be concatenated together with their weights (e.g., "interfaces" and "pn_units"),
143
+ specified with the "sub_datasets" key
144
+ (3) Multiple "leaf" datasets that should be sampled from with a certain probability (e.g., "distillation" and "pdb"),
145
+
146
+ Args:
147
+ cfg (DictConfig): Configuration dictionary defining datasets and their parameters.
148
+ name (str, optional): The name of the dataset, used for reporting. Defaults to None.
149
+
150
+ Returns:
151
+ dict[str, Any]: A dictionary containing the instantiated dataset and sampler.
152
+ """
153
+ # ------- Base case (1): A single "leaf" dataset -------#
154
+ if "dataset" in cfg:
155
+ return {**instantiate_single_dataset_and_sampler(cfg), "name": name}
156
+
157
+ # ------- Recursive case (2): Multiple sub-datasets that must be concatenated together -------#
158
+ elif "sub_datasets" in cfg:
159
+ # ... create a list of dictionaries for each sub-dataset
160
+ datasets_info = []
161
+ for sub_dataset_name, sub_dataset_cfg in cfg.sub_datasets.items():
162
+ if sub_dataset_cfg is None:
163
+ # (Skip any None sub-datasets; e.g., those overrode by the experiment config)
164
+ continue
165
+
166
+ datasets_info.append(
167
+ recursively_instantiate_datasets_and_samplers(
168
+ sub_dataset_cfg, name=sub_dataset_name
169
+ )
170
+ )
171
+
172
+ # ... concatenate sub-datasets and weights (e.g., "interfaces" and "pn_units" into one ConcatDataset)
173
+ # NOTE: Order of the weights must match the order of the datasets!
174
+ concatenated_dataset = ConcatDatasetWithID(
175
+ datasets=[info["dataset"] for info in datasets_info]
176
+ )
177
+ concatenated_weights = torch.cat(
178
+ [info["sampler"].weights for info in datasets_info]
179
+ )
180
+ sampler = WeightedRandomSampler(
181
+ # torch types `weights` as `Sequence[float]`; a Tensor is accepted at runtime.
182
+ weights=concatenated_weights, # type: ignore[arg-type]
183
+ num_samples=len(concatenated_dataset),
184
+ replacement=True,
185
+ )
186
+
187
+ return {"dataset": concatenated_dataset, "sampler": sampler, "name": name}
188
+
189
+ # ------- Recursive case (3): Multiple datasets that must be sampled from with specified probabilities -------#
190
+ else:
191
+ datasets_info = []
192
+ for nested_dataset_name, nested_dataset_cfg in cfg.items():
193
+ if nested_dataset_cfg is None:
194
+ # (Skip any None training datasets; e.g., those overrode by the experiment config)
195
+ continue
196
+
197
+ # (To use a MixedSampler, we must provide a "probability" key for each dataset)
198
+ assert (
199
+ "probability" in nested_dataset_cfg
200
+ ), "Expected 'probability' key in dataset configuration"
201
+ datasets_info.append(
202
+ {
203
+ **recursively_instantiate_datasets_and_samplers(
204
+ nested_dataset_cfg, name=str(nested_dataset_name)
205
+ ),
206
+ "probability": nested_dataset_cfg["probability"],
207
+ }
208
+ )
209
+
210
+ # ... check that the sum of probabilities of all datasets is 1
211
+ assert (
212
+ abs(1 - sum(dataset_info["probability"] for dataset_info in datasets_info))
213
+ < 1e-5
214
+ ), "Sum of probabilities must be 1.0"
215
+
216
+ # ... compose the list of datasets into a single dataset
217
+ composed_train_dataset = ConcatDatasetWithID(
218
+ datasets=[dataset["dataset"] for dataset in datasets_info]
219
+ )
220
+
221
+ composed_train_sampler = MixedSampler(datasets_info=datasets_info, shuffle=True)
222
+
223
+ return {
224
+ "dataset": composed_train_dataset,
225
+ "sampler": composed_train_sampler,
226
+ "name": name,
227
+ }
228
+
229
+
230
+ def assemble_distributed_loader(
231
+ dataset: Dataset,
232
+ sampler: Sampler | None = None,
233
+ rank: int | None = None,
234
+ world_size: int | None = None,
235
+ n_examples_per_epoch: int | None = None,
236
+ loader_cfg: DictConfig | dict | None = None,
237
+ shuffle: bool = True,
238
+ drop_last: bool = False,
239
+ ) -> DataLoader:
240
+ """Assembles a distributed DataLoader for training or validation.
241
+
242
+ Performs the following steps:
243
+ (1) If not already a distributed sampler, wraps the sampler with a DistributedSampler or DistributedMixedSampler
244
+ (2) Wraps the dataset and sampler with a fallback mechanism, if needed
245
+ (3) Assembles the final DataLoader
246
+
247
+ Args:
248
+ dataset (Dataset): The dataset to be used for training or validation.
249
+ sampler (Sampler): The sampler to be used for training or validation. May already be distributed.
250
+ rank (int): The rank of the current process in distributed training.
251
+ world_size (int): The total number of processes participating in the distributed training.
252
+ n_examples_per_epoch (int): The number of examples to sample per epoch, across all GPUs.
253
+ For example, if we have 8 GPUs, with 2 gradient accumulation steps and 10 optimizer
254
+ steps per epoch, we would sample 160 examples per epoch (8 * 2 * 10).
255
+ loader_cfg (DictConfig or dict, optional): Additional configuration parameters for the
256
+ DataLoader, such as `batch_size` and `num_workers`. Defaults to an empty dictionary.
257
+ shuffle (bool, optional): Whether to shuffle the dataset. Defaults to True.
258
+ drop_last (bool, optional): Whether to drop the last incomplete batch if the dataset size
259
+ is not divisible by the number of GPUs. Defaults to False.
260
+
261
+ Returns:
262
+ DataLoader: A PyTorch DataLoader configured for distributed training, with datasets
263
+ concatenated and sampled according to their defined probabilities.
264
+ """
265
+ if not loader_cfg:
266
+ loader_cfg = {}
267
+
268
+ if isinstance(sampler, MixedSampler):
269
+ # (If given a MixedSampler, we must convert to a DistributedMixedSampler)
270
+ assert (
271
+ rank is not None
272
+ and world_size is not None
273
+ and n_examples_per_epoch is not None
274
+ ), "Rank, world_size, and n_examples_per_epoch must be provided for MixedSampler"
275
+ sampler = DistributedMixedSampler(
276
+ datasets_info=sampler.datasets_info,
277
+ num_replicas=world_size,
278
+ rank=rank,
279
+ n_examples_per_epoch=n_examples_per_epoch,
280
+ shuffle=shuffle,
281
+ drop_last=drop_last,
282
+ )
283
+ elif isinstance(sampler, (RandomSampler, SequentialSampler)):
284
+ # (If given a RandomSampler or SequentialSampler, we must convert to a DistributedSampler)
285
+ assert (
286
+ rank is not None and world_size is not None
287
+ ), "Rank and world_size must be provided for RandomSampler or SequentialSampler"
288
+ sampler = DistributedSampler(
289
+ dataset=dataset,
290
+ num_replicas=world_size,
291
+ rank=rank,
292
+ shuffle=shuffle,
293
+ drop_last=drop_last,
294
+ )
295
+ elif sampler is None and isinstance(dataset, Subset):
296
+ # We are subsetting the dataset to a specific set of example IDs
297
+ ranked_logger.info(f"Subsetting dataset to {len(dataset)} examples!")
298
+ else:
299
+ # (We assume we are already given a DistributedSampler or DistributedMixedSampler)
300
+ assert (
301
+ rank is None and world_size is None
302
+ ), "Rank and world_size will have no effect on the provided sampler and should be None"
303
+ assert isinstance(
304
+ sampler, (DistributedSampler, DistributedMixedSampler)
305
+ ), "Invalid sampler type for distributed training."
306
+
307
+ # ... wrap the composed dataset and sampler with a fallback mechanism, if needed
308
+ if (
309
+ "n_fallback_retries" in loader_cfg
310
+ and loader_cfg["n_fallback_retries"] > 0
311
+ and sampler is not None
312
+ ):
313
+ ranked_logger.info(
314
+ f"Wrapping train dataset and sampler with {loader_cfg['n_fallback_retries']} fallbacks..."
315
+ )
316
+ dataset, sampler = wrap_dataset_and_sampler_with_fallbacks(
317
+ dataset_to_be_wrapped=dataset,
318
+ sampler_to_be_wrapped=sampler,
319
+ dataset_to_fallback_to=dataset,
320
+ sampler_to_fallback_to=sampler,
321
+ n_fallback_retries=loader_cfg["n_fallback_retries"],
322
+ )
323
+
324
+ # ... assemble the final loader
325
+ loader = DataLoader(
326
+ dataset=dataset,
327
+ sampler=sampler,
328
+ collate_fn=lambda x: x, # No collation
329
+ **loader_cfg["dataloader_params"] if "dataloader_params" in loader_cfg else {},
330
+ )
331
+
332
+ return loader
333
+
334
+
335
+ def subset_dataset_to_example_ids(
336
+ dataset: Dataset,
337
+ example_ids: list[str] | ListConfig,
338
+ ) -> Dataset:
339
+ """Subset a dataset to a specific set of example IDs."""
340
+ indices = []
341
+ for example_id in example_ids:
342
+ # atomworks types the dataset arg as `ExampleIDMixin`; the datasets passed here mix it in.
343
+ index = get_row_and_index_by_example_id(dataset, example_id)["index"] # type: ignore[arg-type]
344
+ indices.append(index)
345
+
346
+ return Subset(dataset, indices)
347
+
348
+
349
+ def assemble_val_loader_dict(
350
+ cfg: DictConfig,
351
+ rank: int = 0,
352
+ world_size: int = 1,
353
+ loader_cfg: DictConfig | dict | None = None,
354
+ ) -> dict[str, DataLoader]:
355
+ """Assemble a dictionary of validation loaders for multiple datasets.
356
+
357
+ If a key is provided to balance the dataset, we will use a LoadBalancedDistributedSampler
358
+ rather than a DistributedSampler to maintain a balanced example load across processes
359
+ (i.e., avoid a situation where one GPU is allocated all small examples and another all large examples).
360
+
361
+ Args:
362
+ cfg (DictConfig): Configuration dictionary defining the validation datasets. Each key should correspond to a dataset name.
363
+ rank (int, optional): The rank of the current process in distributed training. Defaults to 0.
364
+ world_size (int, optional): The total number of processes participating in the distributed training. Defaults to 1.
365
+ loader_cfg (DictConfig, optional): Additional configuration parameters for the DataLoader, such as `batch_size` and `num_workers`. Defaults to None.
366
+ """
367
+ # ... loop through the validation datasets and create a DataLoader for each, preserving the dataset name
368
+ val_loaders = {}
369
+ for val_dataset_name, val_dataset in cfg.items():
370
+ if not val_dataset:
371
+ # (Skip any None validation datasets; e.g., those overrode by the experiment config)
372
+ continue
373
+ # DictConfig keys are typed as a broad union; coerce to the str they always are.
374
+ val_dataset_name = str(val_dataset_name)
375
+
376
+ assert (
377
+ "dataset" in val_dataset
378
+ ), f"Expected 'dataset' key in validation dataset config for {val_dataset_name}"
379
+ dataset = hydra.utils.instantiate(
380
+ val_dataset.dataset
381
+ ) # directly instantiate the dataset
382
+
383
+ if "key_to_balance" in val_dataset and val_dataset.key_to_balance:
384
+ # (If a key is provided to balance the dataset, we will use a LoadBalancedDistributedSampler)
385
+ key_to_balance = val_dataset.key_to_balance
386
+ ranked_logger.info(f"Balancing dataset with key: {key_to_balance}")
387
+
388
+ assert (
389
+ key_to_balance in dataset.data.columns
390
+ ), f"Key {key_to_balance} not found in dataset columns!"
391
+
392
+ sampler: Sampler = LoadBalancedDistributedSampler(
393
+ dataset=dataset,
394
+ num_replicas=world_size,
395
+ rank=rank,
396
+ key_to_balance=key_to_balance,
397
+ )
398
+ else:
399
+ # (Otherwise, we will use a DistributedSampler, without regard to sample size)
400
+ sampler = DistributedSampler(
401
+ dataset,
402
+ num_replicas=world_size,
403
+ rank=rank,
404
+ shuffle=False,
405
+ drop_last=False,
406
+ )
407
+
408
+ val_loader = assemble_distributed_loader(
409
+ dataset=dataset,
410
+ sampler=sampler,
411
+ loader_cfg=loader_cfg,
412
+ )
413
+
414
+ val_loaders[val_dataset_name] = val_loader
415
+
416
+ return val_loaders
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/ddp.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import torch
4
+ from beartype.typing import Any
5
+ from lightning.fabric.utilities import rank_zero_only
6
+ from lightning_utilities.core.rank_zero import rank_prefixed_message
7
+ from omegaconf import DictConfig
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def get_current_rank() -> int | None:
13
+ """Returns the rank of the current process, or None if it is not yet set."""
14
+ return getattr(rank_zero_only, "rank", None)
15
+
16
+
17
+ def is_rank_zero() -> bool:
18
+ """Returns whether the current process is rank zero."""
19
+ return get_current_rank() == 0
20
+
21
+
22
+ def set_accelerator_based_on_availability(cfg: DictConfig) -> DictConfig:
23
+ """Set training accelerator based on available hardware.
24
+
25
+ Args:
26
+ cfg: Hydra object with trainer settings "accelerator", "devices_per_node", and "num_nodes".
27
+
28
+ Returns:
29
+ The same `cfg` object, modified in place.
30
+ """
31
+ assert "trainer" in cfg, "Configuration object must have a 'trainer' key."
32
+ for key in ["accelerator", "devices_per_node", "num_nodes"]:
33
+ assert (
34
+ key in cfg.trainer
35
+ ), f"Configuration object must have a 'trainer.{key}' key."
36
+
37
+ if torch.cuda.is_available():
38
+ cfg.trainer.accelerator = "gpu"
39
+ elif hasattr(torch, "xpu") and torch.xpu.is_available():
40
+ logger.info("Intel XPU detected - using XPU accelerator")
41
+ cfg.trainer.accelerator = "xpu"
42
+ elif torch.backends.mps.is_available():
43
+ logger.info("Apple MPS detected - using MPS accelerator with float32 precision")
44
+ cfg.trainer.accelerator = "mps"
45
+ if hasattr(cfg.trainer, "precision"):
46
+ cfg.trainer.precision = "32-true"
47
+ else:
48
+ logger.error(
49
+ "No GPUs/XPUs/MPS available - Setting accelerator to 'cpu'. Are you sure you are using the correct configs?"
50
+ )
51
+ cfg.trainer.accelerator = "cpu"
52
+ cfg.trainer.devices_per_node = 1
53
+ cfg.trainer.num_nodes = 1
54
+
55
+ return cfg
56
+
57
+
58
+ class RankedLogger(logging.LoggerAdapter):
59
+ """A multi-GPU-friendly python command line logger.
60
+
61
+ Modified from https://github.com/ashleve/lightning-hydra-template/blob/main/src/utils/pylogger.py
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ name: str = __name__,
67
+ rank_zero_only: bool = False,
68
+ extra: Any | None = None,
69
+ ) -> None:
70
+ """Initializes a multi-GPU-friendly python command line logger that logs on all processes
71
+ with their rank prefixed in the log message.
72
+
73
+ :param name: The name of the logger. Default is ``__name__``.
74
+ :param rank_zero_only: Whether to force all logs to only occur on the rank zero process. Default is `False`.
75
+ :param extra: (Optional) A dict-like object which provides contextual information. See `logging.LoggerAdapter`.
76
+ """
77
+ logger = logging.getLogger(name)
78
+ super().__init__(logger=logger, extra=extra)
79
+ self.rank_zero_only = rank_zero_only
80
+
81
+ def log( # type: ignore[override] # deliberately extends LoggerAdapter.log with a `rank` parameter
82
+ self, level: int, msg: str, rank: int | None = None, *args: Any, **kwargs: Any
83
+ ) -> None:
84
+ """
85
+ Delegate a log call to the underlying logger, after prefixing its message with the rank
86
+ of the process it's being logged from. If `'rank'` is provided, then the log will only
87
+ occur on that rank/process.
88
+
89
+ Args:
90
+ level (int): The level to log at. Look at `logging.__init__.py` for more information.
91
+ msg (str): The message to log.
92
+ rank (Optional[int]): The rank to log at.
93
+ args: Additional args to pass to the underlying logging function.
94
+ kwargs: Any additional keyword args to pass to the underlying logging function.
95
+ """
96
+ if self.isEnabledFor(level):
97
+ msg, log_kwargs = self.process(msg, kwargs)
98
+ current_rank = getattr(rank_zero_only, "rank", None)
99
+ if current_rank is None:
100
+ raise RuntimeError(
101
+ "The `rank_zero_only.rank` needs to be set before use"
102
+ )
103
+ msg = rank_prefixed_message(msg, current_rank)
104
+ if self.rank_zero_only:
105
+ if current_rank == 0:
106
+ self.logger.log(level, msg, *args, **log_kwargs)
107
+ else:
108
+ if rank is None:
109
+ self.logger.log(level, msg, *args, **log_kwargs)
110
+ elif current_rank == rank:
111
+ self.logger.log(level, msg, *args, **log_kwargs)
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/instantiators.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hydra
2
+ from lightning.fabric.loggers import Logger
3
+ from omegaconf import DictConfig
4
+
5
+ from foundry.callbacks.callback import BaseCallback
6
+
7
+
8
+ def _can_be_instantiated(cfg: DictConfig) -> bool:
9
+ """Checks if a config can be instantiated."""
10
+ return isinstance(cfg, DictConfig) and "_target_" in cfg
11
+
12
+
13
+ class InstantiationError(ValueError):
14
+ """Raised when a config cannot be instantiated."""
15
+
16
+ pass
17
+
18
+
19
+ def instantiate_callbacks(callbacks_cfg: DictConfig | None) -> list[BaseCallback]:
20
+ """Instantiates callbacks from config.
21
+
22
+ Args:
23
+ callbacks_cfg: A DictConfig object containing callback configurations.
24
+
25
+ Returns:
26
+ A list of instantiated callbacks.
27
+
28
+ Reference:
29
+ - Lightning Hydra Template (https://github.com/ashleve/lightning-hydra-template/blob/main/src/utils/instantiators.py#L36)
30
+ """
31
+ callbacks: list[BaseCallback] = []
32
+
33
+ if not callbacks_cfg:
34
+ return callbacks
35
+
36
+ for _, cb_conf in callbacks_cfg.items():
37
+ if _can_be_instantiated(cb_conf):
38
+ callbacks.append(hydra.utils.instantiate(cb_conf))
39
+ else:
40
+ raise InstantiationError(
41
+ f"Skipping callback <{cb_conf}> - Not a DictConfig with `_target_` key! Please provide a valid `_target_` for instantiation."
42
+ )
43
+
44
+ return callbacks
45
+
46
+
47
+ def instantiate_loggers(logger_cfg: DictConfig | None) -> list[Logger]:
48
+ """Instantiates loggers from config.
49
+
50
+ Args:
51
+ logger_cfg: A DictConfig object containing logger configurations.
52
+
53
+ Return:
54
+ A list of instantiated loggers.
55
+
56
+ Reference:
57
+ - Lightning Hydra Template (https://github.com/ashleve/lightning-hydra-template/blob/main/src/utils/instantiators.py#L36)
58
+ """
59
+ loggers: list[Logger] = []
60
+
61
+ if not logger_cfg:
62
+ return loggers
63
+
64
+ for _, lg_conf in logger_cfg.items():
65
+ if _can_be_instantiated(lg_conf):
66
+ loggers.append(hydra.utils.instantiate(lg_conf))
67
+ else:
68
+ raise InstantiationError(
69
+ f"Skipping logger <{lg_conf}> - Not a DictConfig with `_target_` key! Please provide a valid `_target_` for instantiation."
70
+ )
71
+
72
+ return loggers
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/logging.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import warnings
3
+ from contextlib import contextmanager
4
+
5
+ import pandas as pd
6
+ from beartype.typing import Any, Iterator
7
+ from lightning.fabric.utilities import rank_zero_only
8
+ from omegaconf import DictConfig, OmegaConf
9
+ from rich.console import Console
10
+ from rich.syntax import Syntax
11
+ from rich.table import Table
12
+ from rich.tree import Tree
13
+ from torch import nn
14
+
15
+ from foundry.utils.ddp import RankedLogger
16
+
17
+ ranked_logger = RankedLogger(__name__, rank_zero_only=True)
18
+
19
+
20
+ class CachedDataFilter(logging.Filter):
21
+ """Filter to suppress atomworks cached data logging messages."""
22
+
23
+ def filter(self, record: logging.LogRecord) -> bool:
24
+ # Filter out "Cached data not found" messages
25
+ if "Cached data not found" in record.getMessage():
26
+ return False
27
+ return True
28
+
29
+
30
+ def silence_warnings() -> None:
31
+ """Silence common warnings that appear during foundry execution."""
32
+ warnings.filterwarnings(
33
+ "ignore", message="All-NaN slice encountered", category=RuntimeWarning
34
+ )
35
+
36
+ warnings.filterwarnings(
37
+ "ignore",
38
+ message="Category 'chem_comp_bond' not found. No bonds will be parsed",
39
+ category=UserWarning,
40
+ module="biotite.structure.io.pdbx.convert",
41
+ )
42
+
43
+ warnings.filterwarnings(
44
+ "ignore",
45
+ message="torch.get_autocast_gpu_dtype\\(\\) is deprecated.*",
46
+ category=DeprecationWarning,
47
+ module="cuequivariance_ops_torch.triangle_attention",
48
+ )
49
+
50
+ warnings.filterwarnings(
51
+ "ignore",
52
+ message=".*multi-threaded.*fork.*may lead to deadlocks.*",
53
+ category=DeprecationWarning,
54
+ )
55
+
56
+ warnings.filterwarnings(
57
+ "ignore",
58
+ message=".*is_pyramidine.*deprecated.*Use.*is_pyrimidine.*",
59
+ category=DeprecationWarning,
60
+ )
61
+
62
+ warnings.filterwarnings(
63
+ "ignore",
64
+ message=".*index_reduce.*is in beta.*API may change.*",
65
+ category=UserWarning,
66
+ )
67
+
68
+
69
+ @contextmanager
70
+ def suppress_warnings(is_inference: bool = False) -> Iterator[None]:
71
+ """Context manager to suppress specific warnings within its scope.
72
+
73
+ Args:
74
+ is_inference: If True, also suppress inference-specific logging messages
75
+ (e.g., atomworks cached data warnings).
76
+
77
+ Required to suppress warnings within multiprocessing contexts; e.g., `torch.multiprocessing.spawn`.
78
+ """
79
+ cached_data_filter = None
80
+
81
+ try:
82
+ with warnings.catch_warnings():
83
+ silence_warnings()
84
+ if is_inference:
85
+ # Add filter to suppress cached data messages
86
+ cached_data_filter = CachedDataFilter()
87
+ atomworks_ml_logger = logging.getLogger("atomworks.ml")
88
+ atomworks_ml_logger.addFilter(cached_data_filter)
89
+
90
+ yield
91
+ finally:
92
+ # Remove the filter
93
+ if cached_data_filter is not None:
94
+ atomworks_ml_logger = logging.getLogger("atomworks.ml")
95
+ atomworks_ml_logger.removeFilter(cached_data_filter)
96
+
97
+
98
+ def configure_minimal_inference_logging() -> None:
99
+ """Configure minimal logging for inference (quiet mode)."""
100
+ # Suppress most logging by default
101
+ logging.getLogger().setLevel(logging.WARNING)
102
+
103
+ # Suppress specific noisy loggers
104
+ for logger_name in [
105
+ "atomworks",
106
+ "transforms",
107
+ "foundry.metrics",
108
+ "foundry.trainers",
109
+ "foundry.inference_engines.base",
110
+ "rf3.trainers",
111
+ "rf3.utils.inference",
112
+ "lightning",
113
+ "lightning_fabric",
114
+ "root",
115
+ ]:
116
+ logging.getLogger(logger_name).setLevel(logging.ERROR)
117
+
118
+ # Keep model-specific inference engine loggers at INFO for progress messages
119
+ logging.getLogger("rf3.inference_engines").setLevel(logging.INFO)
120
+ logging.getLogger("rfd3.engine").setLevel(logging.INFO)
121
+
122
+ # Suppress warnings
123
+ warnings.filterwarnings("ignore")
124
+
125
+
126
+ @rank_zero_only
127
+ def print_config_tree(
128
+ cfg: DictConfig,
129
+ resolve: bool = False,
130
+ console_width: int = 100,
131
+ title: str = "CONFIG",
132
+ ) -> None:
133
+ """Prints the contents of a DictConfig as a tree structure using the Rich library.
134
+
135
+ Args:
136
+ cfg (DictConfig): A DictConfig composed by Hydra.
137
+ resolve (bool): Whether to resolve reference fields of DictConfig. Default is False.
138
+ console_width (int): The width of the console for printing. Default is 100.
139
+ """
140
+ console = Console(width=console_width)
141
+ style = "dim"
142
+ tree = Tree(title, style=style, guide_style=style)
143
+
144
+ # Generate config tree in natural order
145
+ for field in cfg:
146
+ branch = tree.add(str(field), style=style, guide_style=style)
147
+
148
+ config_group = cfg[field]
149
+ if isinstance(config_group, DictConfig):
150
+ branch_content = OmegaConf.to_yaml(config_group, resolve=resolve)
151
+ else:
152
+ branch_content = str(config_group)
153
+
154
+ branch.add(Syntax(branch_content, "yaml", word_wrap=True))
155
+
156
+ # Print config tree using Rich's Console
157
+ # (This call happens before instantiating other loggers, so we don't try to capture the output)
158
+ console.print(tree)
159
+
160
+
161
+ @rank_zero_only
162
+ def print_model_parameters(model: nn.Module, name: str = "") -> None:
163
+ """Prints the total and trainable parameters of a PyTorch model.
164
+
165
+ Args:
166
+ model (nn.Module): The PyTorch model to analyze.
167
+ """
168
+ total_params = sum(p.numel() for p in model.parameters())
169
+ trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
170
+ data = {
171
+ "Type": ["Total Parameters", "Trainable Parameters"],
172
+ "Count": [total_params, trainable_params],
173
+ }
174
+
175
+ title = f"Model Parameters: {name}" if name else "Model Parameters"
176
+ print_df_as_table(pd.DataFrame(data), title=title)
177
+
178
+
179
+ def log_hyperparameters_with_all_loggers(
180
+ trainer: Any, cfg: dict | DictConfig, model: Any
181
+ ) -> None:
182
+ """Logs hyperparameters using all loggers in the trainer.
183
+
184
+ Args:
185
+ trainer: The training object containing loggers.
186
+ cfg: Configuration dictionary containing hyperparameters.
187
+ model: The model to be tracked by loggers like WandbLogger.
188
+ """
189
+ # If given a DictConfig, convert it to a dictionary
190
+ if isinstance(cfg, DictConfig):
191
+ hparams = OmegaConf.to_container(cfg, resolve=True)
192
+ else:
193
+ hparams = cfg
194
+
195
+ for logger in trainer.fabric.loggers:
196
+ # ...log hyperparameters to each Fabric logger
197
+ # For Abstract Base Class of Fabric `Loggers`, see: https://lightning.ai/docs/fabric/stable/_modules/lightning/fabric/loggers/logger.html#Logger
198
+ assert hasattr(
199
+ logger, "log_hyperparams"
200
+ ), f"Logger {logger} does not have a `log_hyperparams` method. Ensure that the logger is a subclass of Fabric's ABC `Logger`."
201
+ try:
202
+ logger.log_hyperparams(hparams)
203
+ except NotImplementedError:
204
+ pass
205
+
206
+
207
+ def condense_count_columns_of_grouped_df(df: pd.DataFrame) -> pd.DataFrame:
208
+ """Returns modified DF with single Count column if valid, otherwise original DF.
209
+
210
+ Helpful to avoid repeating count columns in a DataFrame with multi-level columns.
211
+ """
212
+ if not isinstance(df.columns, pd.MultiIndex):
213
+ return df
214
+
215
+ try:
216
+ # Validate count structure
217
+ count_cols = df.xs("count", level=1, axis=1)
218
+ mean_cols = df.xs("mean", level=1, axis=1)
219
+
220
+ # Check count consistency per row and column existence
221
+ if not (count_cols.nunique(axis=1) == 1).all():
222
+ return df
223
+
224
+ # Build condensed dataframe
225
+ condensed_df = mean_cols.rename(columns=lambda c: f"{c} (mean)")
226
+ condensed_df["Count"] = count_cols.iloc[:, 0].astype(int)
227
+ return condensed_df
228
+
229
+ except (KeyError, IndexError):
230
+ return df
231
+
232
+
233
+ def table_from_df(df: pd.DataFrame, title: str) -> Table:
234
+ """Create a Rich Table from a DataFrame."""
235
+ table = Table(title=title, show_header=True, header_style="bold cyan")
236
+
237
+ # Add columns to the table
238
+ for col in df.columns:
239
+ table.add_column(col, justify="right", style="magenta", overflow="fold")
240
+
241
+ # Iterate through DataFrame rows and add them to the table
242
+ for _, row in df.iterrows():
243
+ row_cells = []
244
+
245
+ for col in df.columns:
246
+ cell_value = row[col]
247
+
248
+ # Determine formatting based on data type
249
+ if pd.api.types.is_integer_dtype(df[col]):
250
+ formatted_value = f"{int(cell_value):,}"
251
+ elif pd.api.types.is_float_dtype(df[col]):
252
+ formatted_value = f"{float(cell_value):,.4f}"
253
+ else:
254
+ formatted_value = str(cell_value)
255
+
256
+ row_cells.append(formatted_value)
257
+
258
+ table.add_row(*row_cells)
259
+
260
+ return table
261
+
262
+
263
+ def safe_print(obj: Any, console_width: int = 100, logger: Any | None = None) -> None:
264
+ """Print a Rich object in a console- and logger-safe manner."""
265
+ console = Console(force_terminal=False, color_system=None, width=console_width)
266
+
267
+ # Capture the table as a string and log it
268
+ with console.capture() as capture:
269
+ console.print(obj)
270
+
271
+ if logger:
272
+ # Use the provided logger
273
+ logger.info(f"\n{capture.get()}")
274
+ else:
275
+ # Use the default ranked logger
276
+ ranked_logger.info(f"\n{capture.get()}")
277
+
278
+
279
+ def print_df_as_table(df: pd.DataFrame, title: str, console_width: int = 100) -> None:
280
+ """Pretty-print a DataFrame using Rich Table"""
281
+ safe_print(table_from_df(df=df, title=title), console_width=console_width)
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/rigid.py ADDED
@@ -0,0 +1,1466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 AlQuraishi Laboratory
2
+ # Copyright 2021 DeepMind Technologies Limited
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Any, Callable, Optional, Tuple, cast
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+
22
+ def rot_matmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
23
+ """
24
+ Performs matrix multiplication of two rotation matrix tensors. Written
25
+ out by hand to avoid AMP downcasting.
26
+
27
+ Args:
28
+ a: [*, 3, 3] left multiplicand
29
+ b: [*, 3, 3] right multiplicand
30
+ Returns:
31
+ The product ab
32
+ """
33
+ row_1 = torch.stack(
34
+ [
35
+ a[..., 0, 0] * b[..., 0, 0]
36
+ + a[..., 0, 1] * b[..., 1, 0]
37
+ + a[..., 0, 2] * b[..., 2, 0],
38
+ a[..., 0, 0] * b[..., 0, 1]
39
+ + a[..., 0, 1] * b[..., 1, 1]
40
+ + a[..., 0, 2] * b[..., 2, 1],
41
+ a[..., 0, 0] * b[..., 0, 2]
42
+ + a[..., 0, 1] * b[..., 1, 2]
43
+ + a[..., 0, 2] * b[..., 2, 2],
44
+ ],
45
+ dim=-1,
46
+ )
47
+ row_2 = torch.stack(
48
+ [
49
+ a[..., 1, 0] * b[..., 0, 0]
50
+ + a[..., 1, 1] * b[..., 1, 0]
51
+ + a[..., 1, 2] * b[..., 2, 0],
52
+ a[..., 1, 0] * b[..., 0, 1]
53
+ + a[..., 1, 1] * b[..., 1, 1]
54
+ + a[..., 1, 2] * b[..., 2, 1],
55
+ a[..., 1, 0] * b[..., 0, 2]
56
+ + a[..., 1, 1] * b[..., 1, 2]
57
+ + a[..., 1, 2] * b[..., 2, 2],
58
+ ],
59
+ dim=-1,
60
+ )
61
+ row_3 = torch.stack(
62
+ [
63
+ a[..., 2, 0] * b[..., 0, 0]
64
+ + a[..., 2, 1] * b[..., 1, 0]
65
+ + a[..., 2, 2] * b[..., 2, 0],
66
+ a[..., 2, 0] * b[..., 0, 1]
67
+ + a[..., 2, 1] * b[..., 1, 1]
68
+ + a[..., 2, 2] * b[..., 2, 1],
69
+ a[..., 2, 0] * b[..., 0, 2]
70
+ + a[..., 2, 1] * b[..., 1, 2]
71
+ + a[..., 2, 2] * b[..., 2, 2],
72
+ ],
73
+ dim=-1,
74
+ )
75
+
76
+ return torch.stack([row_1, row_2, row_3], dim=-2)
77
+
78
+
79
+ def rot_vec_mul(r: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
80
+ """
81
+ Applies a rotation to a vector. Written out by hand to avoid transfer
82
+ to avoid AMP downcasting.
83
+
84
+ Args:
85
+ r: [*, 3, 3] rotation matrices
86
+ t: [*, 3] coordinate tensors
87
+ Returns:
88
+ [*, 3] rotated coordinates
89
+ """
90
+ x = t[..., 0]
91
+ y = t[..., 1]
92
+ z = t[..., 2]
93
+ return torch.stack(
94
+ [
95
+ r[..., 0, 0] * x + r[..., 0, 1] * y + r[..., 0, 2] * z,
96
+ r[..., 1, 0] * x + r[..., 1, 1] * y + r[..., 1, 2] * z,
97
+ r[..., 2, 0] * x + r[..., 2, 1] * y + r[..., 2, 2] * z,
98
+ ],
99
+ dim=-1,
100
+ )
101
+
102
+
103
+ def identity_rot_mats(
104
+ batch_dims: Tuple[int, ...],
105
+ dtype: Optional[torch.dtype] = None,
106
+ device: Optional[torch.device] = None,
107
+ requires_grad: bool = True,
108
+ ) -> torch.Tensor:
109
+ rots = torch.eye(3, dtype=dtype, device=device, requires_grad=requires_grad)
110
+ rots = rots.view(*((1,) * len(batch_dims)), 3, 3)
111
+ rots = rots.expand(*batch_dims, -1, -1)
112
+
113
+ return rots
114
+
115
+
116
+ def identity_trans(
117
+ batch_dims: Tuple[int, ...],
118
+ dtype: Optional[torch.dtype] = None,
119
+ device: Optional[torch.device] = None,
120
+ requires_grad: bool = True,
121
+ ) -> torch.Tensor:
122
+ trans = torch.zeros(
123
+ (*batch_dims, 3), dtype=dtype, device=device, requires_grad=requires_grad
124
+ )
125
+ return trans
126
+
127
+
128
+ def identity_quats(
129
+ batch_dims: Tuple[int, ...],
130
+ dtype: Optional[torch.dtype] = None,
131
+ device: Optional[torch.device] = None,
132
+ requires_grad: bool = True,
133
+ ) -> torch.Tensor:
134
+ quat = torch.zeros(
135
+ (*batch_dims, 4), dtype=dtype, device=device, requires_grad=requires_grad
136
+ )
137
+
138
+ with torch.no_grad():
139
+ quat[..., 0] = 1
140
+
141
+ return quat
142
+
143
+
144
+ _quat_elements = ["a", "b", "c", "d"]
145
+ _qtr_keys = [l1 + l2 for l1 in _quat_elements for l2 in _quat_elements]
146
+ _qtr_ind_dict = {key: ind for ind, key in enumerate(_qtr_keys)}
147
+
148
+
149
+ def _to_mat(pairs: list[tuple[str, int]]) -> np.ndarray:
150
+ mat = np.zeros((4, 4))
151
+ for pair in pairs:
152
+ key, value = pair
153
+ ind = _qtr_ind_dict[key]
154
+ mat[ind // 4][ind % 4] = value
155
+
156
+ return mat
157
+
158
+
159
+ _QTR_MAT = np.zeros((4, 4, 3, 3))
160
+ _QTR_MAT[..., 0, 0] = _to_mat([("aa", 1), ("bb", 1), ("cc", -1), ("dd", -1)])
161
+ _QTR_MAT[..., 0, 1] = _to_mat([("bc", 2), ("ad", -2)])
162
+ _QTR_MAT[..., 0, 2] = _to_mat([("bd", 2), ("ac", 2)])
163
+ _QTR_MAT[..., 1, 0] = _to_mat([("bc", 2), ("ad", 2)])
164
+ _QTR_MAT[..., 1, 1] = _to_mat([("aa", 1), ("bb", -1), ("cc", 1), ("dd", -1)])
165
+ _QTR_MAT[..., 1, 2] = _to_mat([("cd", 2), ("ab", -2)])
166
+ _QTR_MAT[..., 2, 0] = _to_mat([("bd", 2), ("ac", -2)])
167
+ _QTR_MAT[..., 2, 1] = _to_mat([("cd", 2), ("ab", 2)])
168
+ _QTR_MAT[..., 2, 2] = _to_mat([("aa", 1), ("bb", -1), ("cc", -1), ("dd", 1)])
169
+
170
+
171
+ def quat_to_rot(quat: torch.Tensor) -> torch.Tensor:
172
+ """
173
+ Converts a quaternion to a rotation matrix.
174
+
175
+ Args:
176
+ quat: [*, 4] quaternions
177
+ Returns:
178
+ [*, 3, 3] rotation matrices
179
+ """
180
+ # [*, 4, 4]
181
+ quat = quat[..., None] * quat[..., None, :]
182
+
183
+ # [4, 4, 3, 3]
184
+ mat = quat.new_tensor(_QTR_MAT, requires_grad=False)
185
+
186
+ # [*, 4, 4, 3, 3]
187
+ shaped_qtr_mat = mat.view((1,) * len(quat.shape[:-2]) + mat.shape)
188
+ quat = quat[..., None, None] * shaped_qtr_mat
189
+
190
+ # [*, 3, 3]
191
+ return torch.sum(quat, dim=(-3, -4))
192
+
193
+
194
+ def rot_to_quat(
195
+ rot: torch.Tensor,
196
+ ) -> torch.Tensor:
197
+ if rot.shape[-2:] != (3, 3):
198
+ raise ValueError("Input rotation is incorrectly shaped")
199
+
200
+ rot_elements = [[rot[..., i, j] for j in range(3)] for i in range(3)]
201
+ [[xx, xy, xz], [yx, yy, yz], [zx, zy, zz]] = rot_elements
202
+
203
+ k = [
204
+ [
205
+ xx + yy + zz,
206
+ zy - yz,
207
+ xz - zx,
208
+ yx - xy,
209
+ ],
210
+ [
211
+ zy - yz,
212
+ xx - yy - zz,
213
+ xy + yx,
214
+ xz + zx,
215
+ ],
216
+ [
217
+ xz - zx,
218
+ xy + yx,
219
+ yy - xx - zz,
220
+ yz + zy,
221
+ ],
222
+ [
223
+ yx - xy,
224
+ xz + zx,
225
+ yz + zy,
226
+ zz - xx - yy,
227
+ ],
228
+ ]
229
+
230
+ k_matrix = (1.0 / 3.0) * torch.stack([torch.stack(t, dim=-1) for t in k], dim=-2)
231
+
232
+ _, vectors = torch.linalg.eigh(k_matrix)
233
+ return vectors[..., -1]
234
+
235
+
236
+ _QUAT_MULTIPLY = np.zeros((4, 4, 4))
237
+ _QUAT_MULTIPLY[:, :, 0] = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]
238
+
239
+ _QUAT_MULTIPLY[:, :, 1] = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0]]
240
+
241
+ _QUAT_MULTIPLY[:, :, 2] = [[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, 1, 0, 0]]
242
+
243
+ _QUAT_MULTIPLY[:, :, 3] = [[0, 0, 0, 1], [0, 0, 1, 0], [0, -1, 0, 0], [1, 0, 0, 0]]
244
+
245
+ _QUAT_MULTIPLY_BY_VEC = _QUAT_MULTIPLY[:, 1:, :]
246
+
247
+
248
+ def quat_multiply(quat1: torch.Tensor, quat2: torch.Tensor) -> torch.Tensor:
249
+ """Multiply a quaternion by another quaternion."""
250
+ mat = quat1.new_tensor(_QUAT_MULTIPLY)
251
+ reshaped_mat = mat.view((1,) * len(quat1.shape[:-1]) + mat.shape)
252
+ return torch.sum(
253
+ reshaped_mat * quat1[..., :, None, None] * quat2[..., None, :, None],
254
+ dim=(-3, -2),
255
+ )
256
+
257
+
258
+ def quat_multiply_by_vec(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
259
+ """Multiply a quaternion by a pure-vector quaternion."""
260
+ mat = quat.new_tensor(_QUAT_MULTIPLY_BY_VEC)
261
+ reshaped_mat = mat.view((1,) * len(quat.shape[:-1]) + mat.shape)
262
+ return torch.sum(
263
+ reshaped_mat * quat[..., :, None, None] * vec[..., None, :, None], dim=(-3, -2)
264
+ )
265
+
266
+
267
+ def invert_rot_mat(rot_mat: torch.Tensor) -> torch.Tensor:
268
+ return rot_mat.transpose(-1, -2)
269
+
270
+
271
+ def invert_quat(quat: torch.Tensor) -> torch.Tensor:
272
+ quat_prime = quat.clone()
273
+ quat_prime[..., 1:] *= -1
274
+ inv = quat_prime / torch.sum(quat**2, dim=-1, keepdim=True)
275
+ return inv
276
+
277
+
278
+ class Rotation:
279
+ """
280
+ A 3D rotation. Depending on how the object is initialized, the
281
+ rotation is represented by either a rotation matrix or a
282
+ quaternion, though both formats are made available by helper functions.
283
+ To simplify gradient computation, the underlying format of the
284
+ rotation cannot be changed in-place. Like Rigid, the class is designed
285
+ to mimic the behavior of a torch Tensor, almost as if each Rotation
286
+ object were a tensor of rotations, in one format or another.
287
+ """
288
+
289
+ def __init__(
290
+ self,
291
+ rot_mats: Optional[torch.Tensor] = None,
292
+ quats: Optional[torch.Tensor] = None,
293
+ normalize_quats: bool = True,
294
+ ):
295
+ """
296
+ Args:
297
+ rot_mats:
298
+ A [*, 3, 3] rotation matrix tensor. Mutually exclusive with
299
+ quats
300
+ quats:
301
+ A [*, 4] quaternion. Mutually exclusive with rot_mats. If
302
+ normalize_quats is not True, must be a unit quaternion
303
+ normalize_quats:
304
+ If quats is specified, whether to normalize quats
305
+ """
306
+ if (rot_mats is None and quats is None) or (
307
+ rot_mats is not None and quats is not None
308
+ ):
309
+ raise ValueError("Exactly one input argument must be specified")
310
+
311
+ if (rot_mats is not None and rot_mats.shape[-2:] != (3, 3)) or (
312
+ quats is not None and quats.shape[-1] != 4
313
+ ):
314
+ raise ValueError("Incorrectly shaped rotation matrix or quaternion")
315
+
316
+ # Force full-precision
317
+ if quats is not None:
318
+ quats = quats.type(torch.float32)
319
+ if rot_mats is not None:
320
+ rot_mats = rot_mats.type(torch.float32)
321
+
322
+ if quats is not None and normalize_quats:
323
+ quats = quats / torch.linalg.norm(quats, dim=-1, keepdim=True)
324
+
325
+ self._rot_mats = rot_mats
326
+ self._quats = quats
327
+
328
+ @staticmethod
329
+ def identity(
330
+ shape: Tuple[int, ...],
331
+ dtype: Optional[torch.dtype] = None,
332
+ device: Optional[torch.device] = None,
333
+ requires_grad: bool = True,
334
+ fmt: str = "quat",
335
+ ) -> "Rotation":
336
+ """
337
+ Returns an identity Rotation.
338
+
339
+ Args:
340
+ shape:
341
+ The "shape" of the resulting Rotation object. See documentation
342
+ for the shape property
343
+ dtype:
344
+ The torch dtype for the rotation
345
+ device:
346
+ The torch device for the new rotation
347
+ requires_grad:
348
+ Whether the underlying tensors in the new rotation object
349
+ should require gradient computation
350
+ fmt:
351
+ One of "quat" or "rot_mat". Determines the underlying format
352
+ of the new object's rotation
353
+ Returns:
354
+ A new identity rotation
355
+ """
356
+ if fmt == "rot_mat":
357
+ rot_mats = identity_rot_mats(
358
+ shape,
359
+ dtype,
360
+ device,
361
+ requires_grad,
362
+ )
363
+ return Rotation(rot_mats=rot_mats, quats=None)
364
+ elif fmt == "quat":
365
+ quats = identity_quats(shape, dtype, device, requires_grad)
366
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
367
+ else:
368
+ raise ValueError(f"Invalid format: f{fmt}")
369
+
370
+ # Magic methods
371
+
372
+ def __getitem__(self, index: Any) -> "Rotation":
373
+ """
374
+ Allows torch-style indexing over the virtual shape of the rotation
375
+ object. See documentation for the shape property.
376
+
377
+ Args:
378
+ index:
379
+ A torch index. E.g. (1, 3, 2), or (slice(None,))
380
+ Returns:
381
+ The indexed rotation
382
+ """
383
+ if not isinstance(index, tuple):
384
+ index = (index,)
385
+
386
+ if self._rot_mats is not None:
387
+ rot_mats = self._rot_mats[index + (slice(None), slice(None))]
388
+ return Rotation(rot_mats=rot_mats)
389
+ elif self._quats is not None:
390
+ quats = self._quats[index + (slice(None),)]
391
+ return Rotation(quats=quats, normalize_quats=False)
392
+ else:
393
+ raise ValueError("Both rotations are None")
394
+
395
+ def __setitem__(self, index: Any, new: Any) -> None:
396
+ if not isinstance(index, tuple):
397
+ index = (index,)
398
+
399
+ if self._rot_mats is not None:
400
+ self._rot_mats[index + (slice(None), slice(None))] = new.get_rot_mats()
401
+ elif self._quats is not None:
402
+ self._quats[index + (slice(None),)] = new.get_quats()
403
+ else:
404
+ raise ValueError("Both rotations are None")
405
+
406
+ def __mul__(
407
+ self,
408
+ right: torch.Tensor,
409
+ ) -> "Rotation":
410
+ """
411
+ Pointwise left multiplication of the rotation with a tensor. Can be
412
+ used to e.g. mask the Rotation.
413
+
414
+ Args:
415
+ right:
416
+ The tensor multiplicand
417
+ Returns:
418
+ The product
419
+ """
420
+ if not (isinstance(right, torch.Tensor)):
421
+ raise TypeError("The other multiplicand must be a Tensor")
422
+
423
+ if self._rot_mats is not None:
424
+ rot_mats = self._rot_mats * right[..., None, None]
425
+ return Rotation(rot_mats=rot_mats, quats=None)
426
+ elif self._quats is not None:
427
+ quats = self._quats * right[..., None]
428
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
429
+ else:
430
+ raise ValueError("Both rotations are None")
431
+
432
+ def __rmul__(
433
+ self,
434
+ left: torch.Tensor,
435
+ ) -> "Rotation":
436
+ """
437
+ Reverse pointwise multiplication of the rotation with a tensor.
438
+
439
+ Args:
440
+ left:
441
+ The left multiplicand
442
+ Returns:
443
+ The product
444
+ """
445
+ return self.__mul__(left)
446
+
447
+ # Properties
448
+
449
+ @property
450
+ def shape(self) -> torch.Size:
451
+ """
452
+ Returns the virtual shape of the rotation object. This shape is
453
+ defined as the batch dimensions of the underlying rotation matrix
454
+ or quaternion. If the Rotation was initialized with a [10, 3, 3]
455
+ rotation matrix tensor, for example, the resulting shape would be
456
+ [10].
457
+
458
+ Returns:
459
+ The virtual shape of the rotation object
460
+ """
461
+ if self._quats is not None:
462
+ return self._quats.shape[:-1]
463
+ elif self._rot_mats is not None:
464
+ return self._rot_mats.shape[:-2]
465
+ else:
466
+ raise ValueError("Both rotations are None")
467
+
468
+ @property
469
+ def dtype(self) -> torch.dtype:
470
+ """
471
+ Returns the dtype of the underlying rotation.
472
+
473
+ Returns:
474
+ The dtype of the underlying rotation
475
+ """
476
+ if self._rot_mats is not None:
477
+ return self._rot_mats.dtype
478
+ elif self._quats is not None:
479
+ return self._quats.dtype
480
+ else:
481
+ raise ValueError("Both rotations are None")
482
+
483
+ @property
484
+ def device(self) -> torch.device:
485
+ """
486
+ The device of the underlying rotation
487
+
488
+ Returns:
489
+ The device of the underlying rotation
490
+ """
491
+ if self._rot_mats is not None:
492
+ return self._rot_mats.device
493
+ elif self._quats is not None:
494
+ return self._quats.device
495
+ else:
496
+ raise ValueError("Both rotations are None")
497
+
498
+ @property
499
+ def requires_grad(self) -> bool:
500
+ """
501
+ Returns the requires_grad property of the underlying rotation
502
+
503
+ Returns:
504
+ The requires_grad property of the underlying tensor
505
+ """
506
+ if self._rot_mats is not None:
507
+ return self._rot_mats.requires_grad
508
+ elif self._quats is not None:
509
+ return self._quats.requires_grad
510
+ else:
511
+ raise ValueError("Both rotations are None")
512
+
513
+ def get_rot_mats(self) -> torch.Tensor:
514
+ """
515
+ Returns the underlying rotation as a rotation matrix tensor.
516
+
517
+ Returns:
518
+ The rotation as a rotation matrix tensor
519
+ """
520
+ rot_mats = self._rot_mats
521
+ if rot_mats is None:
522
+ if self._quats is None:
523
+ raise ValueError("Both rotations are None")
524
+ else:
525
+ rot_mats = quat_to_rot(self._quats)
526
+
527
+ return rot_mats
528
+
529
+ def get_quats(self) -> torch.Tensor:
530
+ """
531
+ Returns the underlying rotation as a quaternion tensor.
532
+
533
+ Depending on whether the Rotation was initialized with a
534
+ quaternion, this function may call torch.linalg.eigh.
535
+
536
+ Returns:
537
+ The rotation as a quaternion tensor.
538
+ """
539
+ quats = self._quats
540
+ if quats is None:
541
+ if self._rot_mats is None:
542
+ raise ValueError("Both rotations are None")
543
+ else:
544
+ quats = rot_to_quat(self._rot_mats)
545
+
546
+ return quats
547
+
548
+ def get_cur_rot(self) -> torch.Tensor:
549
+ """
550
+ Return the underlying rotation in its current form
551
+
552
+ Returns:
553
+ The stored rotation
554
+ """
555
+ if self._rot_mats is not None:
556
+ return self._rot_mats
557
+ elif self._quats is not None:
558
+ return self._quats
559
+ else:
560
+ raise ValueError("Both rotations are None")
561
+
562
+ def get_rotvec(self, eps: float = 1e-4) -> torch.Tensor:
563
+ """
564
+ Return the underlying axis-angle rotation vector.
565
+
566
+ Follow's scipy's implementation:
567
+ https://github.com/scipy/scipy/blob/HEAD/scipy/spatial/transform/_rotation.pyx#L1385-L1402
568
+
569
+ Returns:
570
+ The stored rotation as a axis-angle vector.
571
+ """
572
+ quat = self.get_quats()
573
+ # w > 0 to ensure 0 <= angle <= pi
574
+ flip = (quat[..., :1] < 0).float()
575
+ quat = (-1 * quat) * flip + (1 - flip) * quat
576
+
577
+ angle = 2 * torch.atan2(torch.linalg.norm(quat[..., 1:], dim=-1), quat[..., 0])
578
+
579
+ angle2 = angle * angle
580
+ small_angle_scales = 2 + angle2 / 12 + 7 * angle2 * angle2 / 2880
581
+ large_angle_scales = angle / torch.sin(angle / 2 + eps)
582
+
583
+ small_angles = (angle <= 1e-3).float()
584
+ rot_vec_scale = (
585
+ small_angle_scales * small_angles + (1 - small_angles) * large_angle_scales
586
+ )
587
+ rot_vec = rot_vec_scale[..., None] * quat[..., 1:]
588
+ return rot_vec
589
+
590
+ # Rotation functions
591
+
592
+ def compose_q_update_vec(
593
+ self,
594
+ q_update_vec: torch.Tensor,
595
+ normalize_quats: bool = True,
596
+ update_mask: torch.Tensor | None = None,
597
+ ) -> "Rotation":
598
+ """
599
+ Returns a new quaternion Rotation after updating the current
600
+ object's underlying rotation with a quaternion update, formatted
601
+ as a [*, 3] tensor whose final three columns represent x, y, z such
602
+ that (1, x, y, z) is the desired (not necessarily unit) quaternion
603
+ update.
604
+
605
+ Args:
606
+ q_update_vec:
607
+ A [*, 3] quaternion update tensor
608
+ normalize_quats:
609
+ Whether to normalize the output quaternion
610
+ Returns:
611
+ An updated Rotation
612
+ """
613
+ quats = self.get_quats()
614
+ quat_update = quat_multiply_by_vec(quats, q_update_vec)
615
+ if update_mask is not None:
616
+ quat_update = quat_update * update_mask
617
+ new_quats = quats + quat_update
618
+ return Rotation(
619
+ rot_mats=None,
620
+ quats=new_quats,
621
+ normalize_quats=normalize_quats,
622
+ )
623
+
624
+ def compose_r(self, r: "Rotation") -> "Rotation":
625
+ """
626
+ Compose the rotation matrices of the current Rotation object with
627
+ those of another.
628
+
629
+ Args:
630
+ r:
631
+ An update rotation object
632
+ Returns:
633
+ An updated rotation object
634
+ """
635
+ r1 = self.get_rot_mats()
636
+ r2 = r.get_rot_mats()
637
+ new_rot_mats = rot_matmul(r1, r2)
638
+ return Rotation(rot_mats=new_rot_mats, quats=None)
639
+
640
+ def compose_q(self, r: "Rotation", normalize_quats: bool = True) -> "Rotation":
641
+ """
642
+ Compose the quaternions of the current Rotation object with those
643
+ of another.
644
+
645
+ Depending on whether either Rotation was initialized with
646
+ quaternions, this function may call torch.linalg.eigh.
647
+
648
+ Args:
649
+ r:
650
+ An update rotation object
651
+ Returns:
652
+ An updated rotation object
653
+ """
654
+ q1 = self.get_quats()
655
+ q2 = r.get_quats()
656
+ new_quats = quat_multiply(q1, q2)
657
+ return Rotation(rot_mats=None, quats=new_quats, normalize_quats=normalize_quats)
658
+
659
+ def apply(self, pts: torch.Tensor) -> torch.Tensor:
660
+ """
661
+ Apply the current Rotation as a rotation matrix to a set of 3D
662
+ coordinates.
663
+
664
+ Args:
665
+ pts:
666
+ A [*, 3] set of points
667
+ Returns:
668
+ [*, 3] rotated points
669
+ """
670
+ rot_mats = self.get_rot_mats()
671
+ return rot_vec_mul(rot_mats, pts)
672
+
673
+ def invert_apply(self, pts: torch.Tensor) -> torch.Tensor:
674
+ """
675
+ The inverse of the apply() method.
676
+
677
+ Args:
678
+ pts:
679
+ A [*, 3] set of points
680
+ Returns:
681
+ [*, 3] inverse-rotated points
682
+ """
683
+ rot_mats = self.get_rot_mats()
684
+ inv_rot_mats = invert_rot_mat(rot_mats)
685
+ return rot_vec_mul(inv_rot_mats, pts)
686
+
687
+ def invert(self) -> "Rotation":
688
+ """
689
+ Returns the inverse of the current Rotation.
690
+
691
+ Returns:
692
+ The inverse of the current Rotation
693
+ """
694
+ if self._rot_mats is not None:
695
+ return Rotation(rot_mats=invert_rot_mat(self._rot_mats), quats=None)
696
+ elif self._quats is not None:
697
+ return Rotation(
698
+ rot_mats=None,
699
+ quats=invert_quat(self._quats),
700
+ normalize_quats=False,
701
+ )
702
+ else:
703
+ raise ValueError("Both rotations are None")
704
+
705
+ # "Tensor" stuff
706
+
707
+ def unsqueeze(
708
+ self,
709
+ dim: int,
710
+ ) -> "Rotation":
711
+ """
712
+ Analogous to torch.unsqueeze. The dimension is relative to the
713
+ shape of the Rotation object.
714
+
715
+ Args:
716
+ dim: A positive or negative dimension index.
717
+ Returns:
718
+ The unsqueezed Rotation.
719
+ """
720
+ if dim >= len(self.shape):
721
+ raise ValueError("Invalid dimension")
722
+
723
+ if self._rot_mats is not None:
724
+ rot_mats = self._rot_mats.unsqueeze(dim if dim >= 0 else dim - 2)
725
+ return Rotation(rot_mats=rot_mats, quats=None)
726
+ elif self._quats is not None:
727
+ quats = self._quats.unsqueeze(dim if dim >= 0 else dim - 1)
728
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
729
+ else:
730
+ raise ValueError("Both rotations are None")
731
+
732
+ @staticmethod
733
+ def cat(
734
+ rs: list["Rotation"],
735
+ dim: int,
736
+ ) -> "Rotation":
737
+ """
738
+ Concatenates rotations along one of the batch dimensions. Analogous
739
+ to torch.cat().
740
+
741
+ Note that the output of this operation is always a rotation matrix,
742
+ regardless of the format of input rotations.
743
+
744
+ Args:
745
+ rs:
746
+ A list of rotation objects
747
+ dim:
748
+ The dimension along which the rotations should be
749
+ concatenated
750
+ Returns:
751
+ A concatenated Rotation object in rotation matrix format
752
+ """
753
+ rot_mats = [r.get_rot_mats() for r in rs]
754
+ cat_rot_mats = torch.cat(rot_mats, dim=dim if dim >= 0 else dim - 2)
755
+
756
+ return Rotation(rot_mats=cat_rot_mats, quats=None)
757
+
758
+ def map_tensor_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> "Rotation":
759
+ """
760
+ Apply a Tensor -> Tensor function to underlying rotation tensors,
761
+ mapping over the rotation dimension(s). Can be used e.g. to sum out
762
+ a one-hot batch dimension.
763
+
764
+ Args:
765
+ fn:
766
+ A Tensor -> Tensor function to be mapped over the Rotation
767
+ Returns:
768
+ The transformed Rotation object
769
+ """
770
+ if self._rot_mats is not None:
771
+ rot_mats = self._rot_mats.view(self._rot_mats.shape[:-2] + (9,))
772
+ rot_mats = torch.stack(
773
+ list(map(fn, torch.unbind(rot_mats, dim=-1))), dim=-1
774
+ )
775
+ rot_mats = rot_mats.view(rot_mats.shape[:-1] + (3, 3))
776
+ return Rotation(rot_mats=rot_mats, quats=None)
777
+ elif self._quats is not None:
778
+ quats = torch.stack(
779
+ list(map(fn, torch.unbind(self._quats, dim=-1))), dim=-1
780
+ )
781
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
782
+ else:
783
+ raise ValueError("Both rotations are None")
784
+
785
+ def cuda(self) -> "Rotation":
786
+ """
787
+ Analogous to the cuda() method of torch Tensors
788
+
789
+ Returns:
790
+ A copy of the Rotation in CUDA memory
791
+ """
792
+ if self._rot_mats is not None:
793
+ return Rotation(rot_mats=self._rot_mats.cuda(), quats=None)
794
+ elif self._quats is not None:
795
+ return Rotation(
796
+ rot_mats=None, quats=self._quats.cuda(), normalize_quats=False
797
+ )
798
+ else:
799
+ raise ValueError("Both rotations are None")
800
+
801
+ def to(
802
+ self, device: Optional[torch.device], dtype: Optional[torch.dtype]
803
+ ) -> "Rotation":
804
+ """
805
+ Analogous to the to() method of torch Tensors
806
+
807
+ Args:
808
+ device:
809
+ A torch device
810
+ dtype:
811
+ A torch dtype
812
+ Returns:
813
+ A copy of the Rotation using the new device and dtype
814
+ """
815
+ if self._rot_mats is not None:
816
+ return Rotation(
817
+ rot_mats=self._rot_mats.to(device=device, dtype=dtype),
818
+ quats=None,
819
+ )
820
+ elif self._quats is not None:
821
+ return Rotation(
822
+ rot_mats=None,
823
+ quats=self._quats.to(device=device, dtype=dtype),
824
+ normalize_quats=False,
825
+ )
826
+ else:
827
+ raise ValueError("Both rotations are None")
828
+
829
+ def detach(self) -> "Rotation":
830
+ """
831
+ Returns a copy of the Rotation whose underlying Tensor has been
832
+ detached from its torch graph.
833
+
834
+ Returns:
835
+ A copy of the Rotation whose underlying Tensor has been detached
836
+ from its torch graph
837
+ """
838
+ if self._rot_mats is not None:
839
+ return Rotation(rot_mats=self._rot_mats.detach(), quats=None)
840
+ elif self._quats is not None:
841
+ return Rotation(
842
+ rot_mats=None,
843
+ quats=self._quats.detach(),
844
+ normalize_quats=False,
845
+ )
846
+ else:
847
+ raise ValueError("Both rotations are None")
848
+
849
+
850
+ class Rigid:
851
+ """
852
+ A class representing a rigid transformation. Little more than a wrapper
853
+ around two objects: a Rotation object and a [*, 3] translation
854
+ Designed to behave approximately like a single torch tensor with the
855
+ shape of the shared batch dimensions of its component parts.
856
+ """
857
+
858
+ def __init__(
859
+ self,
860
+ rots: Optional[Rotation],
861
+ trans: Optional[torch.Tensor],
862
+ ):
863
+ """
864
+ Args:
865
+ rots: A [*, 3, 3] rotation tensor
866
+ trans: A corresponding [*, 3] translation tensor
867
+ """
868
+ # (we need device, dtype, etc. from at least one input)
869
+
870
+ batch_dims, dtype, device, requires_grad = None, None, None, None
871
+ if trans is not None:
872
+ batch_dims = trans.shape[:-1]
873
+ dtype = trans.dtype
874
+ device = trans.device
875
+ requires_grad = trans.requires_grad
876
+ elif rots is not None:
877
+ batch_dims = rots.shape
878
+ dtype = rots.dtype
879
+ device = rots.device
880
+ requires_grad = rots.requires_grad
881
+ else:
882
+ raise ValueError("At least one input argument must be specified")
883
+
884
+ if rots is None:
885
+ rots = Rotation.identity(
886
+ batch_dims,
887
+ dtype,
888
+ device,
889
+ requires_grad,
890
+ )
891
+ if trans is None:
892
+ trans = identity_trans(
893
+ batch_dims,
894
+ dtype,
895
+ device,
896
+ requires_grad,
897
+ )
898
+
899
+ if (rots.shape != trans.shape[:-1]) or (rots.device != trans.device):
900
+ raise ValueError("Rots and trans incompatible")
901
+
902
+ # Force full precision. Happens to the rotations automatically.
903
+ trans = trans.type(torch.float32)
904
+
905
+ self._rots = rots
906
+ self._trans = trans
907
+
908
+ @staticmethod
909
+ def identity(
910
+ shape: Tuple[int, ...],
911
+ dtype: Optional[torch.dtype] = None,
912
+ device: Optional[torch.device] = None,
913
+ requires_grad: bool = True,
914
+ fmt: str = "quat",
915
+ ) -> "Rigid":
916
+ """
917
+ Constructs an identity transformation.
918
+
919
+ Args:
920
+ shape:
921
+ The desired shape
922
+ dtype:
923
+ The dtype of both internal tensors
924
+ device:
925
+ The device of both internal tensors
926
+ requires_grad:
927
+ Whether grad should be enabled for the internal tensors
928
+ Returns:
929
+ The identity transformation
930
+ """
931
+ return Rigid(
932
+ Rotation.identity(shape, dtype, device, requires_grad, fmt=fmt),
933
+ identity_trans(shape, dtype, device, requires_grad),
934
+ )
935
+
936
+ def __getitem__(
937
+ self,
938
+ index: Any,
939
+ ) -> "Rigid":
940
+ """
941
+ Indexes the affine transformation with PyTorch-style indices.
942
+ The index is applied to the shared dimensions of both the rotation
943
+ and the translation.
944
+
945
+ E.g.::
946
+
947
+ r = Rotation(rot_mats=torch.rand(10, 10, 3, 3), quats=None)
948
+ t = Rigid(r, torch.rand(10, 10, 3))
949
+ indexed = t[3, 4:6]
950
+ assert indexed.shape == (2,)
951
+ assert indexed.get_rots().shape == (2,)
952
+ assert indexed.get_trans().shape == (2, 3)
953
+
954
+ Args:
955
+ index: A standard torch tensor index. E.g. 8, (10, None, 3),
956
+ or (3, slice(0, 1, None))
957
+ Returns:
958
+ The indexed tensor
959
+ """
960
+ if not isinstance(index, tuple):
961
+ index = (index,)
962
+
963
+ return Rigid(
964
+ self._rots[index],
965
+ self._trans[index + (slice(None),)],
966
+ )
967
+
968
+ def __mul__(
969
+ self,
970
+ right: torch.Tensor,
971
+ ) -> "Rigid":
972
+ """
973
+ Pointwise left multiplication of the transformation with a tensor.
974
+ Can be used to e.g. mask the Rigid.
975
+
976
+ Args:
977
+ right:
978
+ The tensor multiplicand
979
+ Returns:
980
+ The product
981
+ """
982
+ if not (isinstance(right, torch.Tensor)):
983
+ raise TypeError("The other multiplicand must be a Tensor")
984
+
985
+ new_rots = self._rots * right
986
+ new_trans = self._trans * right[..., None]
987
+
988
+ return Rigid(new_rots, new_trans)
989
+
990
+ def __rmul__(
991
+ self,
992
+ left: torch.Tensor,
993
+ ) -> "Rigid":
994
+ """
995
+ Reverse pointwise multiplication of the transformation with a
996
+ tensor.
997
+
998
+ Args:
999
+ left:
1000
+ The left multiplicand
1001
+ Returns:
1002
+ The product
1003
+ """
1004
+ return self.__mul__(left)
1005
+
1006
+ @property
1007
+ def shape(self) -> torch.Size:
1008
+ """
1009
+ Returns the shape of the shared dimensions of the rotation and
1010
+ the translation.
1011
+
1012
+ Returns:
1013
+ The shape of the transformation
1014
+ """
1015
+ s = self._trans.shape[:-1]
1016
+ return s
1017
+
1018
+ @property
1019
+ def device(self) -> torch.device:
1020
+ """
1021
+ Returns the device on which the Rigid's tensors are located.
1022
+
1023
+ Returns:
1024
+ The device on which the Rigid's tensors are located
1025
+ """
1026
+ return self._trans.device
1027
+
1028
+ def get_rots(self) -> Rotation:
1029
+ """
1030
+ Getter for the rotation.
1031
+
1032
+ Returns:
1033
+ The rotation object
1034
+ """
1035
+ return self._rots
1036
+
1037
+ def get_trans(self) -> torch.Tensor:
1038
+ """
1039
+ Getter for the translation.
1040
+
1041
+ Returns:
1042
+ The stored translation
1043
+ """
1044
+ return self._trans
1045
+
1046
+ def compose_q_update_vec(
1047
+ self,
1048
+ q_update_vec: torch.Tensor,
1049
+ update_mask: torch.Tensor | None = None,
1050
+ ) -> "Rigid":
1051
+ """
1052
+ Composes the transformation with a quaternion update vector of
1053
+ shape [*, 6], where the final 6 columns represent the x, y, and
1054
+ z values of a quaternion of form (1, x, y, z) followed by a 3D
1055
+ translation.
1056
+
1057
+ Args:
1058
+ q_vec: The quaternion update vector.
1059
+ Returns:
1060
+ The composed transformation.
1061
+ """
1062
+ q_vec, t_vec = q_update_vec[..., :3], q_update_vec[..., 3:]
1063
+ new_rots = self._rots.compose_q_update_vec(q_vec, update_mask=update_mask)
1064
+
1065
+ trans_update = self._rots.apply(t_vec)
1066
+ if update_mask is not None:
1067
+ trans_update = trans_update * update_mask
1068
+ new_translation = self._trans + trans_update
1069
+
1070
+ return Rigid(new_rots, new_translation)
1071
+
1072
+ def compose_tran_update_vec(
1073
+ self,
1074
+ t_vec: torch.Tensor,
1075
+ update_mask: torch.Tensor | None = None,
1076
+ ) -> "Rigid":
1077
+ """
1078
+ Composes the transformation with a quaternion update vector of
1079
+ shape [*, 3], where columns represent a 3D translation.
1080
+
1081
+ Args:
1082
+ q_vec: The quaternion update vector.
1083
+ Returns:
1084
+ The composed transformation.
1085
+ """
1086
+ trans_update = self._rots.apply(t_vec)
1087
+ if update_mask is not None:
1088
+ trans_update = trans_update * update_mask
1089
+ new_translation = self._trans + trans_update
1090
+
1091
+ return Rigid(self._rots, new_translation)
1092
+
1093
+ def compose(
1094
+ self,
1095
+ r: "Rigid",
1096
+ ) -> "Rigid":
1097
+ """
1098
+ Composes the current rigid object with another.
1099
+
1100
+ Args:
1101
+ r:
1102
+ Another Rigid object
1103
+ Returns:
1104
+ The composition of the two transformations
1105
+ """
1106
+ new_rot = self._rots.compose_r(r._rots)
1107
+ new_trans = self._rots.apply(r._trans) + self._trans
1108
+ return Rigid(new_rot, new_trans)
1109
+
1110
+ def compose_r(self, rot: Rotation, order: str = "right") -> "Rigid":
1111
+ """
1112
+ Composes the current rigid object with another.
1113
+
1114
+ Args:
1115
+ r:
1116
+ Another Rigid object
1117
+ order:
1118
+ Order in which to perform rotation multiplication.
1119
+ Returns:
1120
+ The composition of the two transformations
1121
+ """
1122
+ if order == "right":
1123
+ new_rot = self._rots.compose_r(rot)
1124
+ elif order == "left":
1125
+ new_rot = rot.compose_r(self._rots)
1126
+ else:
1127
+ raise ValueError(f"Unrecognized multiplication order: {order}")
1128
+ return Rigid(new_rot, self._trans)
1129
+
1130
+ def apply(
1131
+ self,
1132
+ pts: torch.Tensor,
1133
+ ) -> torch.Tensor:
1134
+ """
1135
+ Applies the transformation to a coordinate tensor.
1136
+
1137
+ Args:
1138
+ pts: A [*, 3] coordinate tensor.
1139
+ Returns:
1140
+ The transformed points.
1141
+ """
1142
+ rotated = self._rots.apply(pts)
1143
+ return rotated + self._trans
1144
+
1145
+ def invert_apply(self, pts: torch.Tensor) -> torch.Tensor:
1146
+ """
1147
+ Applies the inverse of the transformation to a coordinate tensor.
1148
+
1149
+ Args:
1150
+ pts: A [*, 3] coordinate tensor
1151
+ Returns:
1152
+ The transformed points.
1153
+ """
1154
+ pts = pts - self._trans
1155
+ return self._rots.invert_apply(pts)
1156
+
1157
+ def invert(self) -> "Rigid":
1158
+ """
1159
+ Inverts the transformation.
1160
+
1161
+ Returns:
1162
+ The inverse transformation.
1163
+ """
1164
+ rot_inv = self._rots.invert()
1165
+ trn_inv = rot_inv.apply(self._trans)
1166
+
1167
+ return Rigid(rot_inv, -1 * trn_inv)
1168
+
1169
+ def map_tensor_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> "Rigid":
1170
+ """
1171
+ Apply a Tensor -> Tensor function to underlying translation and
1172
+ rotation tensors, mapping over the translation/rotation dimensions
1173
+ respectively.
1174
+
1175
+ Args:
1176
+ fn:
1177
+ A Tensor -> Tensor function to be mapped over the Rigid
1178
+ Returns:
1179
+ The transformed Rigid object
1180
+ """
1181
+ new_rots = self._rots.map_tensor_fn(fn)
1182
+ new_trans = torch.stack(
1183
+ list(map(fn, torch.unbind(self._trans, dim=-1))), dim=-1
1184
+ )
1185
+
1186
+ return Rigid(new_rots, new_trans)
1187
+
1188
+ def to_tensor_4x4(self) -> torch.Tensor:
1189
+ """
1190
+ Converts a transformation to a homogenous transformation tensor.
1191
+
1192
+ Returns:
1193
+ A [*, 4, 4] homogenous transformation tensor
1194
+ """
1195
+ tensor = self._trans.new_zeros((*self.shape, 4, 4))
1196
+ tensor[..., :3, :3] = self._rots.get_rot_mats()
1197
+ tensor[..., :3, 3] = self._trans
1198
+ tensor[..., 3, 3] = 1
1199
+ return tensor
1200
+
1201
+ @staticmethod
1202
+ def from_tensor_4x4(t: torch.Tensor) -> "Rigid":
1203
+ """
1204
+ Constructs a transformation from a homogenous transformation
1205
+ tensor.
1206
+
1207
+ Args:
1208
+ t: [*, 4, 4] homogenous transformation tensor
1209
+ Returns:
1210
+ T object with shape [*]
1211
+ """
1212
+ if t.shape[-2:] != (4, 4):
1213
+ raise ValueError("Incorrectly shaped input tensor")
1214
+
1215
+ rots = Rotation(rot_mats=t[..., :3, :3], quats=None)
1216
+ trans = t[..., :3, 3]
1217
+
1218
+ return Rigid(rots, trans)
1219
+
1220
+ def to_tensor_7(self) -> torch.Tensor:
1221
+ """
1222
+ Converts a transformation to a tensor with 7 final columns, four
1223
+ for the quaternion followed by three for the translation.
1224
+
1225
+ Returns:
1226
+ A [*, 7] tensor representation of the transformation
1227
+ """
1228
+ tensor = self._trans.new_zeros((*self.shape, 7))
1229
+ tensor[..., :4] = self._rots.get_quats()
1230
+ tensor[..., 4:] = self._trans
1231
+
1232
+ return tensor
1233
+
1234
+ @staticmethod
1235
+ def from_tensor_7(
1236
+ t: torch.Tensor,
1237
+ normalize_quats: bool = False,
1238
+ ) -> "Rigid":
1239
+ if t.shape[-1] != 7:
1240
+ raise ValueError("Incorrectly shaped input tensor")
1241
+
1242
+ quats, trans = t[..., :4], t[..., 4:]
1243
+
1244
+ rots = Rotation(rot_mats=None, quats=quats, normalize_quats=normalize_quats)
1245
+
1246
+ return Rigid(rots, trans)
1247
+
1248
+ @staticmethod
1249
+ def from_3_points(
1250
+ p_neg_x_axis: torch.Tensor,
1251
+ origin: torch.Tensor,
1252
+ p_xy_plane: torch.Tensor,
1253
+ eps: float = 1e-4,
1254
+ ) -> "Rigid":
1255
+ """
1256
+ Implements algorithm 21. Constructs transformations from sets of 3
1257
+ points using the Gram-Schmidt algorithm.
1258
+
1259
+ Args:
1260
+ p_neg_x_axis: [*, 3] coordinates
1261
+ origin: [*, 3] coordinates used as frame origins
1262
+ p_xy_plane: [*, 3] coordinates
1263
+ eps: Small epsilon value
1264
+ Returns:
1265
+ A transformation object of shape [*]
1266
+ """
1267
+ p_neg_x_axis_cols = torch.unbind(p_neg_x_axis, dim=-1)
1268
+ origin_cols = torch.unbind(origin, dim=-1)
1269
+ p_xy_plane_cols = torch.unbind(p_xy_plane, dim=-1)
1270
+
1271
+ e0 = [c1 - c2 for c1, c2 in zip(origin_cols, p_neg_x_axis_cols)]
1272
+ e1 = [c1 - c2 for c1, c2 in zip(p_xy_plane_cols, origin_cols)]
1273
+
1274
+ denom = torch.sqrt(cast(torch.Tensor, sum(c * c for c in e0)) + eps)
1275
+ e0 = [c / denom for c in e0]
1276
+ dot = sum((c1 * c2 for c1, c2 in zip(e0, e1)))
1277
+ e1 = [c2 - c1 * dot for c1, c2 in zip(e0, e1)]
1278
+ denom = torch.sqrt(cast(torch.Tensor, sum(c * c for c in e1)) + eps)
1279
+ e1 = [c / denom for c in e1]
1280
+ e2 = [
1281
+ e0[1] * e1[2] - e0[2] * e1[1],
1282
+ e0[2] * e1[0] - e0[0] * e1[2],
1283
+ e0[0] * e1[1] - e0[1] * e1[0],
1284
+ ]
1285
+
1286
+ rots = torch.stack([c for tup in zip(e0, e1, e2) for c in tup], dim=-1)
1287
+ rots = rots.reshape(rots.shape[:-1] + (3, 3))
1288
+
1289
+ rot_obj = Rotation(rot_mats=rots, quats=None)
1290
+
1291
+ return Rigid(rot_obj, torch.stack(origin_cols, dim=-1))
1292
+
1293
+ def unsqueeze(
1294
+ self,
1295
+ dim: int,
1296
+ ) -> "Rigid":
1297
+ """
1298
+ Analogous to torch.unsqueeze. The dimension is relative to the
1299
+ shared dimensions of the rotation/translation.
1300
+
1301
+ Args:
1302
+ dim: A positive or negative dimension index.
1303
+ Returns:
1304
+ The unsqueezed transformation.
1305
+ """
1306
+ if dim >= len(self.shape):
1307
+ raise ValueError("Invalid dimension")
1308
+ rots = self._rots.unsqueeze(dim)
1309
+ trans = self._trans.unsqueeze(dim if dim >= 0 else dim - 1)
1310
+
1311
+ return Rigid(rots, trans)
1312
+
1313
+ @staticmethod
1314
+ def cat(
1315
+ ts: list["Rigid"],
1316
+ dim: int,
1317
+ ) -> "Rigid":
1318
+ """
1319
+ Concatenates transformations along a new dimension.
1320
+
1321
+ Args:
1322
+ ts:
1323
+ A list of T objects
1324
+ dim:
1325
+ The dimension along which the transformations should be
1326
+ concatenated
1327
+ Returns:
1328
+ A concatenated transformation object
1329
+ """
1330
+ rots = Rotation.cat([t._rots for t in ts], dim)
1331
+ trans = torch.cat([t._trans for t in ts], dim=dim if dim >= 0 else dim - 1)
1332
+
1333
+ return Rigid(rots, trans)
1334
+
1335
+ def apply_rot_fn(self, fn: Callable[[Rotation], Rotation]) -> "Rigid":
1336
+ """
1337
+ Applies a Rotation -> Rotation function to the stored rotation
1338
+ object.
1339
+
1340
+ Args:
1341
+ fn: A function of type Rotation -> Rotation
1342
+ Returns:
1343
+ A transformation object with a transformed rotation.
1344
+ """
1345
+ return Rigid(fn(self._rots), self._trans)
1346
+
1347
+ def apply_trans_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> "Rigid":
1348
+ """
1349
+ Applies a Tensor -> Tensor function to the stored translation.
1350
+
1351
+ Args:
1352
+ fn:
1353
+ A function of type Tensor -> Tensor to be applied to the
1354
+ translation
1355
+ Returns:
1356
+ A transformation object with a transformed translation.
1357
+ """
1358
+ return Rigid(self._rots, fn(self._trans))
1359
+
1360
+ def scale_translation(self, trans_scale_factor: float) -> "Rigid":
1361
+ """
1362
+ Scales the translation by a constant factor.
1363
+
1364
+ Args:
1365
+ trans_scale_factor:
1366
+ The constant factor
1367
+ Returns:
1368
+ A transformation object with a scaled translation.
1369
+ """
1370
+ fn = lambda t: t * trans_scale_factor # noqa: E731
1371
+ return self.apply_trans_fn(fn)
1372
+
1373
+ def stop_rot_gradient(self) -> "Rigid":
1374
+ """
1375
+ Detaches the underlying rotation object
1376
+
1377
+ Returns:
1378
+ A transformation object with detached rotations
1379
+ """
1380
+ fn = lambda r: r.detach() # noqa: E731
1381
+ return self.apply_rot_fn(fn)
1382
+
1383
+ @staticmethod
1384
+ def make_transform_from_reference(
1385
+ n_xyz: torch.Tensor,
1386
+ ca_xyz: torch.Tensor,
1387
+ c_xyz: torch.Tensor,
1388
+ eps: float = 1e-20,
1389
+ ) -> "Rigid":
1390
+ """
1391
+ Returns a transformation object from reference coordinates.
1392
+
1393
+ Note that this method does not take care of symmetries. If you
1394
+ provide the atom positions in the non-standard way, the N atom will
1395
+ end up not at [-0.527250, 1.359329, 0.0] but instead at
1396
+ [-0.527250, -1.359329, 0.0]. You need to take care of such cases in
1397
+ your code.
1398
+
1399
+ Args:
1400
+ n_xyz: A [*, 3] tensor of nitrogen xyz coordinates.
1401
+ ca_xyz: A [*, 3] tensor of carbon alpha xyz coordinates.
1402
+ c_xyz: A [*, 3] tensor of carbon xyz coordinates.
1403
+ Returns:
1404
+ A transformation object. After applying the translation and
1405
+ rotation to the reference backbone, the coordinates will
1406
+ approximately equal to the input coordinates.
1407
+ """
1408
+ translation = -1 * ca_xyz
1409
+ n_xyz = n_xyz + translation
1410
+ c_xyz = c_xyz + translation
1411
+
1412
+ c_x, c_y, c_z = [c_xyz[..., i] for i in range(3)]
1413
+ norm = torch.sqrt(eps + c_x**2 + c_y**2)
1414
+ sin_c1 = -c_y / norm
1415
+ cos_c1 = c_x / norm
1416
+
1417
+ c1_rots = sin_c1.new_zeros((*sin_c1.shape, 3, 3))
1418
+ c1_rots[..., 0, 0] = cos_c1
1419
+ c1_rots[..., 0, 1] = -1 * sin_c1
1420
+ c1_rots[..., 1, 0] = sin_c1
1421
+ c1_rots[..., 1, 1] = cos_c1
1422
+ c1_rots[..., 2, 2] = 1
1423
+
1424
+ norm = torch.sqrt(eps + c_x**2 + c_y**2 + c_z**2)
1425
+ sin_c2 = c_z / norm
1426
+ cos_c2 = torch.sqrt(c_x**2 + c_y**2) / norm
1427
+
1428
+ c2_rots = sin_c2.new_zeros((*sin_c2.shape, 3, 3))
1429
+ c2_rots[..., 0, 0] = cos_c2
1430
+ c2_rots[..., 0, 2] = sin_c2
1431
+ c2_rots[..., 1, 1] = 1
1432
+ c1_rots[..., 2, 0] = -1 * sin_c2
1433
+ c1_rots[..., 2, 2] = cos_c2
1434
+
1435
+ c_rots = rot_matmul(c2_rots, c1_rots)
1436
+ n_xyz = rot_vec_mul(c_rots, n_xyz)
1437
+
1438
+ _, n_y, n_z = [n_xyz[..., i] for i in range(3)]
1439
+ norm = torch.sqrt(eps + n_y**2 + n_z**2)
1440
+ sin_n = -n_z / norm
1441
+ cos_n = n_y / norm
1442
+
1443
+ n_rots = sin_c2.new_zeros((*sin_c2.shape, 3, 3))
1444
+ n_rots[..., 0, 0] = 1
1445
+ n_rots[..., 1, 1] = cos_n
1446
+ n_rots[..., 1, 2] = -1 * sin_n
1447
+ n_rots[..., 2, 1] = sin_n
1448
+ n_rots[..., 2, 2] = cos_n
1449
+
1450
+ rots = rot_matmul(n_rots, c_rots)
1451
+
1452
+ rots = rots.transpose(-1, -2)
1453
+ translation = -1 * translation
1454
+
1455
+ rot_obj = Rotation(rot_mats=rots, quats=None)
1456
+
1457
+ return Rigid(rot_obj, translation)
1458
+
1459
+ def cuda(self) -> "Rigid":
1460
+ """
1461
+ Moves the transformation object to GPU memory
1462
+
1463
+ Returns:
1464
+ A version of the transformation on GPU
1465
+ """
1466
+ return Rigid(self._rots.cuda(), self._trans.cuda())
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/rotation_augmentation.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+
5
+ from foundry.utils.rigid import rot_vec_mul
6
+
7
+
8
+ def centre(X_L: torch.Tensor, X_exists_L: torch.Tensor) -> torch.Tensor:
9
+ X_L = X_L.clone()
10
+ X_L[X_exists_L] = X_L[X_exists_L] - torch.mean(
11
+ X_L[X_exists_L], dim=-2, keepdim=True
12
+ )
13
+ X_L[~X_exists_L] = 0.0
14
+ return X_L
15
+
16
+
17
+ def get_random_augmentation(X_L: torch.Tensor, s_trans: float) -> torch.Tensor:
18
+ """
19
+ Inputs:
20
+ X_L [D, L, 3]: Batched atom coordinates
21
+ s_trans (float): standard deviation of a global translation to be applied for each
22
+ element in the batch
23
+ """
24
+ D, L, _ = X_L.shape
25
+ R = uniform_random_rotation((D,)).to(X_L.device)
26
+ noise = s_trans * torch.normal(mean=0, std=1, size=(D, 1, 3)).to(X_L.device)
27
+ return rot_vec_mul(R[:, None], X_L) + noise
28
+
29
+
30
+ def centre_random_augmentation(
31
+ X_L: torch.Tensor, X_exists_L: torch.Tensor, s_trans: float
32
+ ) -> torch.Tensor:
33
+ X_L = centre(X_L, X_exists_L)
34
+ return get_random_augmentation(X_L, s_trans)
35
+
36
+
37
+ def uniform_random_rotation(size: tuple[int, ...]) -> torch.Tensor:
38
+ # Sample random angles for rotations around X, Y, and Z axes
39
+ theta_x = torch.rand(size) * 2 * math.pi
40
+ theta_y = torch.rand(size) * 2 * math.pi
41
+ theta_z = torch.rand(size) * 2 * math.pi
42
+
43
+ # Calculate the cosines and sines of the angles
44
+ cos_x = torch.cos(theta_x)
45
+ sin_x = torch.sin(theta_x)
46
+ cos_y = torch.cos(theta_y)
47
+ sin_y = torch.sin(theta_y)
48
+ cos_z = torch.cos(theta_z)
49
+ sin_z = torch.sin(theta_z)
50
+
51
+ # Create the rotation matrices around X, Y, and Z axes
52
+ rotation_x = torch.stack(
53
+ [torch.tensor([[1, 0, 0], [0, c, -s], [0, s, c]]) for c, s in zip(cos_x, sin_x)]
54
+ )
55
+
56
+ rotation_y = torch.stack(
57
+ [torch.tensor([[c, 0, s], [0, 1, 0], [-s, 0, c]]) for c, s in zip(cos_y, sin_y)]
58
+ )
59
+
60
+ rotation_z = torch.stack(
61
+ [torch.tensor([[c, -s, 0], [s, c, 0], [0, 0, 1]]) for c, s in zip(cos_z, sin_z)]
62
+ )
63
+
64
+ # Combine the rotation matrices
65
+ rotation_matrix = torch.matmul(rotation_z, torch.matmul(rotation_y, rotation_x))
66
+
67
+ return rotation_matrix
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/squashfs.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Squashfs filesystem mount management.
2
+
3
+ Provides a singleton manager for mounting and caching squashfs filesystems.
4
+ Mounts are lazy (happen on first access) and persist for the lifetime of the program.
5
+ """
6
+
7
+ import atexit
8
+ import logging
9
+ import os
10
+ import subprocess
11
+ import tempfile
12
+ import threading
13
+ from pathlib import Path
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class SquashfsManager:
19
+ """Singleton manager for squashfs filesystem mounts.
20
+
21
+ Provides lazy mounting of squashfs files with automatic caching and cleanup.
22
+ Thread-safe for use with multiprocessing/DataLoader workers.
23
+
24
+ Examples:
25
+ Get mount directory (mounts automatically if needed)::
26
+
27
+ from foundry.utils.squashfs import SquashfsManager
28
+
29
+ mount_dir = SquashfsManager.get_mount("/path/to/file.sqfs")
30
+ file_path = os.path.join(mount_dir, "internal/path/to/file")
31
+
32
+ Inspect active mounts::
33
+
34
+ mounts = SquashfsManager.list_mounts()
35
+ print(f"Active mounts: {len(mounts)}")
36
+
37
+ Cleanup (typically for tests)::
38
+
39
+ SquashfsManager.unmount_all()
40
+ """
41
+
42
+ _mounts: dict[str, str] = {}
43
+ _lock = threading.Lock()
44
+ _cleanup_registered = False
45
+
46
+ @classmethod
47
+ def get_mount(cls, sqfs_file: str) -> str:
48
+ """Get mount directory for squashfs file, mounting if needed.
49
+
50
+ Args:
51
+ sqfs_file: Path to the .sqfs file.
52
+
53
+ Returns:
54
+ Path to the mount directory containing the squashfs contents.
55
+
56
+ Raises:
57
+ FileNotFoundError: If the sqfs file doesn't exist.
58
+ RuntimeError: If mounting fails.
59
+ """
60
+ sqfs_file = str(Path(sqfs_file).resolve())
61
+
62
+ # Check file exists
63
+ if not os.path.exists(sqfs_file):
64
+ raise FileNotFoundError(f"Squashfs file not found: {sqfs_file}")
65
+
66
+ with cls._lock:
67
+ # Register cleanup on first use
68
+ if not cls._cleanup_registered:
69
+ atexit.register(cls._cleanup_on_exit)
70
+ cls._cleanup_registered = True
71
+
72
+ # Return cached mount if exists
73
+ if sqfs_file in cls._mounts:
74
+ return cls._mounts[sqfs_file]
75
+
76
+ # Mount and cache
77
+ mount_dir = cls._mount(sqfs_file)
78
+ cls._mounts[sqfs_file] = mount_dir
79
+ logger.info(f"Mounted {sqfs_file} at {mount_dir}")
80
+ return mount_dir
81
+
82
+ @classmethod
83
+ def _mount(cls, sqfs_file: str) -> str:
84
+ """Internal: Actually perform the squashfs mount.
85
+
86
+ Args:
87
+ sqfs_file: Path to the .sqfs file.
88
+
89
+ Returns:
90
+ Path to the mount directory.
91
+
92
+ Raises:
93
+ RuntimeError: If mounting fails.
94
+ """
95
+ mount_dir = tempfile.mkdtemp(prefix="sqfs_")
96
+ try:
97
+ subprocess.run(
98
+ ["squashfuse", sqfs_file, mount_dir],
99
+ check=True,
100
+ capture_output=True,
101
+ )
102
+ return mount_dir
103
+ except subprocess.CalledProcessError as e:
104
+ # Cleanup failed mount directory
105
+ try:
106
+ os.rmdir(mount_dir)
107
+ except OSError:
108
+ pass
109
+ raise RuntimeError(
110
+ f"Failed to mount {sqfs_file}: {e.stderr.decode()}"
111
+ ) from e
112
+
113
+ @classmethod
114
+ def _unmount(cls, sqfs_file: str) -> None:
115
+ """Internal: Unmount a squashfs filesystem.
116
+
117
+ Args:
118
+ sqfs_file: Path to the .sqfs file to unmount.
119
+ """
120
+ if sqfs_file not in cls._mounts:
121
+ return
122
+
123
+ mount_dir = cls._mounts[sqfs_file]
124
+ try:
125
+ subprocess.run(
126
+ ["fusermount", "-u", mount_dir],
127
+ check=True,
128
+ capture_output=True,
129
+ )
130
+ os.rmdir(mount_dir)
131
+ logger.info(f"Unmounted {sqfs_file}")
132
+ except (subprocess.CalledProcessError, OSError) as e:
133
+ logger.warning(f"Failed to unmount {sqfs_file}: {e}")
134
+ finally:
135
+ del cls._mounts[sqfs_file]
136
+
137
+ @classmethod
138
+ def list_mounts(cls) -> dict[str, str]:
139
+ """List all active squashfs mounts.
140
+
141
+ Returns:
142
+ Dictionary mapping sqfs file paths to mount directories.
143
+
144
+ Examples:
145
+ >>> mounts = SquashfsManager.list_mounts()
146
+ >>> print(f"Active mounts: {len(mounts)}")
147
+ >>> for sqfs, mount_dir in mounts.items():
148
+ ... print(f"{sqfs} -> {mount_dir}")
149
+ """
150
+ with cls._lock:
151
+ return cls._mounts.copy()
152
+
153
+ @classmethod
154
+ def unmount_all(cls) -> None:
155
+ """Unmount all squashfs filesystems.
156
+
157
+ Useful for cleanup in tests or explicit resource management.
158
+ Normally not needed as cleanup happens automatically on program exit.
159
+
160
+ Examples:
161
+ >>> SquashfsManager.unmount_all() # Clean up in test teardown
162
+ """
163
+ with cls._lock:
164
+ sqfs_files = list(cls._mounts.keys())
165
+ for sqfs_file in sqfs_files:
166
+ cls._unmount(sqfs_file)
167
+
168
+ @classmethod
169
+ def _cleanup_on_exit(cls) -> None:
170
+ """Cleanup hook called on program exit via atexit."""
171
+ logger.debug("Cleaning up squashfs mounts on exit")
172
+ cls.unmount_all()
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/torch.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """General convenience utilities for PyTorch."""
2
+
3
+ __all__ = [
4
+ "map_to",
5
+ "assert_no_nans",
6
+ "assert_shape",
7
+ "assert_same_shape",
8
+ "scatter_mean",
9
+ ]
10
+
11
+ import time
12
+ import warnings
13
+ from contextlib import contextmanager
14
+
15
+ import numpy as np
16
+ import torch
17
+ from beartype.typing import Any, Iterator, Sequence
18
+ from toolz import valmap
19
+ from torch import Tensor
20
+ from torch._prims_common import DeviceLikeType
21
+ from torch.types import _dtype
22
+
23
+ from foundry import should_check_nans
24
+ from foundry.common import at_least_one_exists, do_nothing
25
+
26
+
27
+ def map_to(
28
+ x: Any,
29
+ *,
30
+ device: DeviceLikeType | None = None,
31
+ dtype: _dtype | None = None,
32
+ non_blocking: bool = False,
33
+ **to_kwargs: Any,
34
+ ) -> Any:
35
+ """
36
+ Recursively applies the `.to()` method to all tensors in a nested structure.
37
+
38
+ This function handles nested structures such as dictionaries and lists, applying the `.to()` method
39
+ to any PyTorch tensors while leaving other types unchanged.
40
+
41
+ NOTE: If you are instantiating a new tensor, you should use the `device` and `dtype` arguments
42
+ instead of calling `map_to()` on the tensor.
43
+ (https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html#create-tensors-directly-on-the-target-device)
44
+
45
+
46
+ Args:
47
+ - x (Any): The input structure, which can be a tensor, dictionary, list, or any other type.
48
+ - device (DeviceLikeType | None): The target device to move tensors to (e.g., 'cpu', 'cuda').
49
+ - dtype (_dtype | None): The target dtype to cast tensors to.
50
+ - non_blocking (bool): Whether to use non-blocking transfers when possible.
51
+ - **to_kwargs: Additional keyword arguments to pass to the `.to()` method.
52
+
53
+ Returns:
54
+ - Any: The input structure with all contained tensors processed by the `.to()` method.
55
+
56
+ Example:
57
+ >>> data = {"tensor": torch.tensor([1, 2, 3]), "list": [torch.tensor([4, 5]), "string"]}
58
+ >>> map_to(data, device="cuda", dtype=torch.float32)
59
+ {'tensor': tensor([1., 2., 3.], device='cuda:0', dtype=torch.float32),
60
+ 'list': [tensor([4., 5.], device='cuda:0', dtype=torch.float32), 'string']}
61
+ """
62
+ torch._assert(
63
+ at_least_one_exists(device, dtype),
64
+ "Must provide at least one of `device` or `dtype`",
65
+ )
66
+
67
+ if isinstance(x, dict):
68
+ return valmap(
69
+ lambda v: map_to(
70
+ v, device=device, dtype=dtype, non_blocking=non_blocking, **to_kwargs
71
+ ),
72
+ x,
73
+ )
74
+ elif isinstance(x, (list, tuple)):
75
+ return type(x)(
76
+ map(
77
+ lambda v: map_to(
78
+ v,
79
+ device=device,
80
+ dtype=dtype,
81
+ non_blocking=non_blocking,
82
+ **to_kwargs,
83
+ ),
84
+ x,
85
+ )
86
+ )
87
+ elif isinstance(x, Tensor):
88
+ return x.to(device=device, dtype=dtype, non_blocking=non_blocking, **to_kwargs)
89
+ else:
90
+ return x
91
+
92
+
93
+ def _assert_no_nans(x: Any, *, msg: str = "", fail_if_not_tensor: bool = False) -> None:
94
+ """Recursively checks for NaN values in tensor-like objects.
95
+
96
+ Args:
97
+ - x (Any): Input to check for NaNs. Can be a tensor, dict, list, tuple, or other type.
98
+ - msg (str): Prefix for error messages.
99
+ - fail_if_not_tensor (bool): If True, raises error for non-tensor types.
100
+ """
101
+ if isinstance(x, Tensor):
102
+ torch._assert(
103
+ not torch.isnan(x).any(),
104
+ ": ".join(filter(bool, [msg, "Tensor contains NaNs!"])),
105
+ )
106
+ elif isinstance(x, np.ndarray):
107
+ torch._assert(
108
+ not np.isnan(x).any(),
109
+ ": ".join(filter(bool, [msg, "Numpy array contains NaNs!"])),
110
+ )
111
+ elif isinstance(x, float):
112
+ torch._assert(
113
+ not np.isnan(x),
114
+ ": ".join(filter(bool, [msg, "float is NaN!"])),
115
+ )
116
+ elif isinstance(x, dict):
117
+ for k, v in x.items():
118
+ _assert_no_nans(
119
+ v,
120
+ msg=".".join(filter(bool, [msg, k])),
121
+ fail_if_not_tensor=fail_if_not_tensor,
122
+ )
123
+ elif isinstance(x, (list, tuple)):
124
+ for idx, v in enumerate(x):
125
+ _assert_no_nans(
126
+ v,
127
+ msg=".".join(filter(bool, [msg, str(idx)])),
128
+ fail_if_not_tensor=fail_if_not_tensor,
129
+ )
130
+ elif fail_if_not_tensor:
131
+ raise ValueError(f"Unsupported type: {type(x)}")
132
+
133
+
134
+ assert_no_nans = _assert_no_nans if should_check_nans else do_nothing
135
+
136
+
137
+ @contextmanager
138
+ def _suppress_tracer_warnings() -> Iterator[None]:
139
+ """
140
+ Context manager to temporarily suppress known warnings in torch.jit.trace().
141
+ Note: Cannot use catch_warnings because of https://bugs.python.org/issue29672
142
+
143
+ References:
144
+ - https://github.com/NVlabs/edm2/blob/main/torch_utils/misc.py
145
+ """
146
+ tracer_warning_filter = ("ignore", None, torch.jit.TracerWarning, None, 0)
147
+ # warnings.filters is typed as an immutable Sequence in typeshed but is a mutable
148
+ # list at runtime, so insert/remove are valid.
149
+ warnings.filters.insert(0, tracer_warning_filter) # type: ignore[attr-defined]
150
+ yield
151
+ warnings.filters.remove(tracer_warning_filter) # type: ignore[attr-defined]
152
+
153
+
154
+ def assert_shape(tensor: Tensor, ref_shape: Sequence[int | None]) -> None:
155
+ """
156
+ Assert that the shape of a tensor matches the given list of integers.
157
+ None indicates that the size of a dimension is allowed to vary.
158
+ Performs symbolic assertion when used in torch.jit.trace().
159
+
160
+ Args:
161
+ - tensor (Tensor): The tensor to check the shape of.
162
+ - ref_shape (Sequence[int | None]): The expected shape of the tensor.
163
+
164
+ References:
165
+ - https://github.com/NVlabs/edm2/blob/main/torch_utils/misc.py
166
+ """
167
+
168
+ if tensor.ndim != len(ref_shape):
169
+ raise AssertionError(
170
+ f"Wrong number of dimensions: got {tensor.ndim}, expected {len(ref_shape)}"
171
+ )
172
+
173
+ for idx, (size, ref_size) in enumerate(zip(tensor.shape, ref_shape)):
174
+ if tensor.ndim != len(ref_shape):
175
+ raise AssertionError(
176
+ f"Wrong number of dimensions: got {tensor.ndim}, expected {len(ref_shape)}"
177
+ )
178
+
179
+ for idx, (size, ref_size) in enumerate(zip(tensor.shape, ref_shape)):
180
+ if ref_size is None:
181
+ pass
182
+ elif isinstance(ref_size, torch.Tensor):
183
+ with (
184
+ _suppress_tracer_warnings()
185
+ ): # as_tensor results are registered as constants
186
+ torch._assert(
187
+ torch.equal(torch.as_tensor(size), ref_size),
188
+ f"Wrong size for dimension {idx}",
189
+ )
190
+ elif isinstance(size, torch.Tensor):
191
+ with (
192
+ _suppress_tracer_warnings()
193
+ ): # as_tensor results are registered as constants
194
+ torch._assert(
195
+ torch.equal(size, torch.as_tensor(ref_size)),
196
+ f"Wrong size for dimension {idx}: expected {ref_size}",
197
+ )
198
+ elif size != ref_size:
199
+ raise AssertionError(
200
+ f"Wrong size for dimension {idx}: got {size}, expected {ref_size}"
201
+ )
202
+
203
+
204
+ def assert_same_shape(tensor: Tensor, ref_tensor: Tensor) -> None:
205
+ """Assert that two tensors have the same shape."""
206
+ assert_shape(tensor, ref_tensor.shape)
207
+
208
+
209
+ def scatter_mean(zeros: Tensor, dim: int, index: Tensor, source: Tensor) -> Tensor:
210
+ """Scatter-mean aggregation, with an MPS-compatible fallback.
211
+
212
+ On non-MPS devices uses index_reduce (faster, in-place kernel).
213
+ On MPS, index_reduce is not implemented so falls back to scatter_add + count.
214
+
215
+ Equivalent to: zeros.index_reduce(dim, index, source, 'mean', include_self=False)
216
+
217
+ Args:
218
+ zeros: Pre-allocated zero tensor, shape (..., I, C). Will not be modified in-place.
219
+ dim: Dimension to scatter along. Must not be the last dimension.
220
+ index: 1D index tensor of shape (N,) mapping source positions to output positions.
221
+ source: Source tensor where size at `dim` equals N.
222
+
223
+ Returns:
224
+ Tensor of same shape as zeros.
225
+ """
226
+ if zeros.device.type != "mps":
227
+ return zeros.index_reduce(dim, index, source, "mean", include_self=False)
228
+
229
+ ndim = source.dim()
230
+ if dim < 0:
231
+ dim = ndim + dim
232
+
233
+ # Expand 1D index (N,) to match source shape (..., N, C)
234
+ shape = [1] * ndim
235
+ shape[dim] = index.shape[0]
236
+ idx = index.view(shape).expand_as(source)
237
+
238
+ # Sum source values into output positions
239
+ result = zeros.scatter_add(dim, idx, source)
240
+
241
+ # Count how many source values land in each output position.
242
+ # Take a single slice along the last dim to avoid allocating a full (N, C) ones tensor.
243
+ idx_count = idx[..., :1] # (..., N, 1)
244
+ ones = torch.ones_like(source[..., :1]) # (..., N, 1)
245
+ count = torch.zeros(*zeros.shape[:-1], 1, device=zeros.device, dtype=zeros.dtype)
246
+ count = count.scatter_add(dim, idx_count, ones) # (..., I, 1)
247
+
248
+ return result / count.clamp(min=1)
249
+
250
+
251
+ def device_of(obj: Any) -> torch.device:
252
+ """Get the device of a PyTorch object, e.g. a `nn.Module` or a `Tensor`."""
253
+ if hasattr(obj, "device"):
254
+ return obj.device
255
+ elif hasattr(obj, "parameters"):
256
+ return next(obj.parameters()).device
257
+ else:
258
+ raise ValueError(f"Unsupported type: {type(obj)}")
259
+
260
+
261
+ class Timer:
262
+ """
263
+ A simple timer class for measuring elapsed time.
264
+
265
+ This class provides functionality to start, stop, reset, and measure elapsed time.
266
+ It can optionally use CUDA or MPS synchronization barriers for more accurate timing
267
+ when working with GPU operations.
268
+
269
+ Attributes:
270
+ name_ (str): The name of the timer.
271
+ elapsed_ (float): The total elapsed time.
272
+ started_ (bool): Flag indicating if the timer is currently running.
273
+ start_time (float): The start time of the current timing session.
274
+ use_barrier (bool): Whether to use CUDA or MPS synchronization barriers.
275
+
276
+ Args:
277
+ name (str): The name of the timer.
278
+ use_barrier (bool, optional): Whether to use synchronization barriers. Defaults to True.
279
+ """
280
+
281
+ def __init__(self, name: str, use_barrier: bool = True):
282
+ self.name_ = name
283
+ self.elapsed_ = 0.0
284
+ self.started_ = False
285
+ self.start_time = time.time()
286
+ self.use_barrier = use_barrier
287
+
288
+ def start(self) -> None:
289
+ """Start the timer."""
290
+ assert not self.started_, f"timer {self.name_} has already been started"
291
+ if self.use_barrier and torch.cuda.is_available():
292
+ torch.cuda.synchronize()
293
+ elif self.use_barrier and torch.backends.mps.is_available():
294
+ torch.mps.synchronize()
295
+ self.start_time = time.time()
296
+ self.started_ = True
297
+
298
+ def stop(self) -> None:
299
+ """Stop the timer."""
300
+ assert self.started_, f"timer {self.name_} is not started"
301
+ if self.use_barrier and torch.cuda.is_available():
302
+ torch.cuda.synchronize()
303
+ elif self.use_barrier and torch.backends.mps.is_available():
304
+ torch.mps.synchronize()
305
+ self.elapsed_ += time.time() - self.start_time
306
+ self.started_ = False
307
+
308
+ def reset(self) -> None:
309
+ """Reset timer."""
310
+ self.elapsed_ = 0.0
311
+ self.started_ = False
312
+
313
+ def elapsed(self, reset: bool = True) -> float:
314
+ """Calculate the elapsed time."""
315
+ started_ = self.started_
316
+ # If the timing in progress, end it first.
317
+ if self.started_:
318
+ self.stop()
319
+ # Get the elapsed time.
320
+ elapsed_ = self.elapsed_
321
+ # Reset the elapsed time
322
+ if reset:
323
+ self.reset()
324
+ # If timing was in progress, set it back.
325
+ if started_:
326
+ self.start()
327
+ return elapsed_
328
+
329
+
330
+ class Timers:
331
+ """
332
+ A collection of named Timer objects.
333
+
334
+ This class manages multiple Timer instances, allowing for easy creation,
335
+ starting, stopping, resetting, and querying of elapsed times for multiple timers.
336
+
337
+ Attributes:
338
+ timers (dict): A dictionary of Timer objects, keyed by their names.
339
+ """
340
+
341
+ def __init__(self) -> None:
342
+ self.timers: dict[str, Timer] = {}
343
+
344
+ def __call__(self, name: str, use_barrier: bool = True) -> Timer:
345
+ """Get or create a Timer object."""
346
+ if name not in self.timers:
347
+ self.timers[name] = Timer(name, use_barrier=use_barrier)
348
+ return self.timers[name]
349
+
350
+ def start(self, *names: str) -> None:
351
+ """Start the specified timers."""
352
+ for name in names:
353
+ self(name).start()
354
+
355
+ def stop(self, *names: str) -> None:
356
+ """Stop the specified timers."""
357
+ for name in names:
358
+ self.timers[name].stop()
359
+
360
+ def reset(self, *names: str) -> None:
361
+ """Reset the specified timers."""
362
+ for name in names:
363
+ self.timers[name].reset()
364
+
365
+ def elapsed(self, *names: str, reset: bool = True) -> dict[str, float]:
366
+ """Get the elapsed time for the specified timers."""
367
+ return {name: self.timers[name].elapsed(reset=reset) for name in names}
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/weights.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utils for loading weights from checkpoints."""
2
+
3
+ import re
4
+ from dataclasses import dataclass, field
5
+ from enum import StrEnum, auto
6
+ from os import PathLike
7
+
8
+ import torch
9
+ from beartype.typing import Any, Pattern
10
+ from torch import nn
11
+
12
+ from foundry.utils.ddp import RankedLogger
13
+
14
+ ranked_logger = RankedLogger(__name__, rank_zero_only=True)
15
+
16
+
17
+ class WeightLoadingError(Exception):
18
+ """Exception raised when there's an error loading weights."""
19
+
20
+ pass
21
+
22
+
23
+ class WeightLoadingPolicy(StrEnum):
24
+ """Policy for handling weights when loading checkpoints."""
25
+
26
+ # Always keep default initialization, regardless of whether the parameter is in the checkpoint or shapes match
27
+ REINIT = auto()
28
+
29
+ # Always zero-initialize, regardless of whether the parameter is in the checkpoint or shapes match
30
+ ZERO_INIT = auto()
31
+
32
+ # Copy from checkpoint only when shapes match exactly, otherwise error
33
+ COPY = auto()
34
+
35
+ # Copy from checkpoint if tensors are the same rank, padding with zeros if shapes don't match exectly
36
+ COPY_AND_ZERO_PAD = auto()
37
+
38
+
39
+ class _PatternPolicyMixin:
40
+ """Mixin for handling glob-to-regex pattern compilation and matching for parameter policies.
41
+
42
+ Patterns can use the following wildcards:
43
+ - * matches any sequence of characters
44
+ - ? matches any single character
45
+ - [abc] matches any character in the brackets
46
+ - . matches a literal dot
47
+
48
+ Examples:
49
+ - "model.*.weight" matches any weight parameter in the model
50
+ - "model.encoder?.weight" matches encoder1.weight, encoder2.weight, etc.
51
+ - "model.encoder[12].weight" matches encoder1.weight and encoder2.weight
52
+ - "model.encoder.*.bias" matches any bias parameter in encoder submodules
53
+ """
54
+
55
+ _compiled_patterns: dict[Pattern, Any]
56
+
57
+ @staticmethod
58
+ def _glob_to_regex(pattern: str) -> str:
59
+ # Convert glob pattern to regex string
60
+ return (
61
+ pattern.replace(".", r"\.")
62
+ .replace("*", ".*")
63
+ .replace("?", ".")
64
+ .replace("[", "[")
65
+ .replace("]", "]")
66
+ )
67
+
68
+ def _compile_patterns(self, policy_dict: dict[str, Any]) -> dict[Pattern, Any]:
69
+ compiled = {}
70
+ for pattern, value in list(policy_dict.items()):
71
+ if any(c in pattern for c in ["*", "?", "[", "]"]):
72
+ regex = self._glob_to_regex(pattern)
73
+ compiled[re.compile(f"^{regex}$")] = value
74
+ return compiled
75
+
76
+ def _get_policy_by_pattern(
77
+ self, param_name: str, policy_dict: dict[str, Any], default: Any
78
+ ) -> Any:
79
+ # Exact match first
80
+ if policy_dict and param_name in policy_dict:
81
+ return policy_dict[param_name]
82
+ # Pattern match
83
+ for pattern, value in self._compiled_patterns.items():
84
+ if pattern.match(param_name):
85
+ return value
86
+ return default
87
+
88
+
89
+ @dataclass
90
+ class WeightLoadingConfig(_PatternPolicyMixin):
91
+ """Configuration for handling weights when loading a checkpoint."""
92
+
93
+ default_policy: WeightLoadingPolicy | str = WeightLoadingPolicy.COPY
94
+ fallback_policy: WeightLoadingPolicy | str = WeightLoadingPolicy.REINIT
95
+ param_policies: dict[str, WeightLoadingPolicy | str] = field(default_factory=dict)
96
+ _compiled_patterns: dict[Pattern, WeightLoadingPolicy] = field(
97
+ default_factory=dict, repr=False
98
+ )
99
+
100
+ def __post_init__(self) -> None:
101
+ if isinstance(self.default_policy, str):
102
+ self.default_policy = WeightLoadingPolicy(self.default_policy)
103
+ if isinstance(self.fallback_policy, str):
104
+ self.fallback_policy = WeightLoadingPolicy(self.fallback_policy)
105
+ for key, value in self.param_policies.items():
106
+ if isinstance(value, str):
107
+ self.param_policies[key] = WeightLoadingPolicy(value)
108
+ self._compiled_patterns = self._compile_patterns(self.param_policies)
109
+
110
+ def get_policy(self, param_name: str) -> WeightLoadingPolicy:
111
+ policy = self._get_policy_by_pattern(
112
+ param_name, self.param_policies, self.default_policy
113
+ )
114
+ assert isinstance(policy, WeightLoadingPolicy)
115
+ return policy
116
+
117
+
118
+ @dataclass
119
+ class ParameterFreezingConfig(_PatternPolicyMixin):
120
+ """Configuration for freezing model parameters after loading weights.
121
+
122
+ Allows specifying which parameters to freeze (set requires_grad=False) by exact name or pattern.
123
+ Patterns use glob-style wildcards (*, ?).
124
+
125
+ Attributes:
126
+ param_policies: Dict mapping parameter names or patterns to True (freeze) or False (do not freeze).
127
+ freeze_by_default: Whether to freeze parameters not matched by any pattern (default: False).
128
+ """
129
+
130
+ param_policies: dict[str, bool] = field(default_factory=dict)
131
+ freeze_by_default: bool = False
132
+ _compiled_patterns: dict[Pattern, bool] = field(default_factory=dict, repr=False)
133
+
134
+ def __post_init__(self) -> None:
135
+ self._compiled_patterns = self._compile_patterns(self.param_policies)
136
+
137
+ def is_frozen(self, param_name: str) -> bool:
138
+ """Get whether a parameter is frozen according to the config."""
139
+ is_frozen = self._get_policy_by_pattern(
140
+ param_name, self.param_policies, self.freeze_by_default
141
+ )
142
+ assert isinstance(is_frozen, bool)
143
+ return is_frozen
144
+
145
+
146
+ def freeze_parameters_with_config(
147
+ model: nn.Module, config: ParameterFreezingConfig, verbose: bool = True
148
+ ) -> None:
149
+ """Freeze (set requires_grad=False) or unfreeze parameters according to config.
150
+
151
+ Args:
152
+ model: The model whose parameters to freeze/unfreeze.
153
+ config: ParameterFreezingConfig specifying which parameters to freeze.
154
+ verbose: Whether to log which parameters have non-default policies applied.
155
+ """
156
+ for name, param in model.named_parameters():
157
+ is_frozen = config.is_frozen(name)
158
+ param.requires_grad = not is_frozen
159
+
160
+ if is_frozen != config.freeze_by_default and verbose:
161
+ ranked_logger.info(f"Non-default freezing applied to {name}: {is_frozen}")
162
+
163
+
164
+ def load_weights_with_policies(
165
+ model: nn.Module,
166
+ ckpt: dict[str, torch.Tensor],
167
+ config: WeightLoadingConfig | None = None,
168
+ ) -> dict:
169
+ """Load checkpoint weights into model according to the specified configuration.
170
+
171
+ Allows for partial loading of weights and zero-initialization of mismatched and arbitrary parameters.
172
+
173
+ Args:
174
+ model: The model to load weights INTO. By default, all model weights are re-initialized; we overwrite
175
+ with the checkpoint weights where appropriate
176
+ ckpt: Dictionary mapping parameter names to tensors (loaded from checkpoint on disk)
177
+ config: Configuration for handling weight loading. If None, uses default config
178
+ Returns:
179
+ dict: The updated state_dict (not loaded into model yet)
180
+ """
181
+ if config is None:
182
+ # (Initialize default config if not provided)
183
+ config = WeightLoadingConfig()
184
+
185
+ current_state = model.state_dict()
186
+ updated_state = {} # We will update this with the new weights
187
+
188
+ def _apply_policy(
189
+ name: str,
190
+ current_param: torch.Tensor,
191
+ checkpoint_param: torch.Tensor | None,
192
+ policy: WeightLoadingPolicy,
193
+ ) -> torch.Tensor:
194
+ """Apply a weight loading policy and return the resulting tensor.
195
+
196
+ Raises WeightLoadingError for any policy application failures.
197
+ """
198
+ if policy == WeightLoadingPolicy.REINIT:
199
+ # Keep original initialization
200
+ return current_param
201
+
202
+ elif policy == WeightLoadingPolicy.ZERO_INIT:
203
+ # Zero-initialize
204
+ return torch.zeros_like(current_param)
205
+
206
+ elif policy == WeightLoadingPolicy.COPY:
207
+ # Must have checkpoint param and shapes must match
208
+ if checkpoint_param is None:
209
+ raise WeightLoadingError(f"Parameter '{name}' not found in checkpoint")
210
+ if current_param.shape != checkpoint_param.shape:
211
+ raise WeightLoadingError(
212
+ f"Shape mismatch for '{name}': model {current_param.shape} vs checkpoint {checkpoint_param.shape}"
213
+ )
214
+ return checkpoint_param
215
+
216
+ elif policy == WeightLoadingPolicy.COPY_AND_ZERO_PAD:
217
+ # Must have checkpoint param and same number of dimensions
218
+ if checkpoint_param is None:
219
+ raise WeightLoadingError(f"Parameter '{name}' not found in checkpoint")
220
+ if len(current_param.shape) != len(checkpoint_param.shape):
221
+ raise WeightLoadingError(
222
+ f"Different dimensions for '{name}': model {len(current_param.shape)}D vs checkpoint {len(checkpoint_param.shape)}D"
223
+ )
224
+
225
+ # Copy where shapes match, zero-init the rest
226
+ new_param = torch.zeros_like(current_param)
227
+ slices = tuple(
228
+ slice(0, min(d_ckpt, d_current))
229
+ for d_ckpt, d_current in zip(
230
+ checkpoint_param.shape, current_param.shape
231
+ )
232
+ )
233
+ new_param[slices] = checkpoint_param[slices]
234
+ return new_param
235
+
236
+ # ... loop through all named parameters in the model
237
+ for name, current_param in current_state.items():
238
+ # Get the policy for this parameter
239
+ policy = config.get_policy(name)
240
+
241
+ # Get the corresponding parameter from the checkpoint
242
+ checkpoint_param = ckpt.get(name, None)
243
+
244
+ try:
245
+ # Try to apply the primary policy
246
+ result = _apply_policy(name, current_param, checkpoint_param, policy)
247
+ updated_state[name] = result
248
+ except WeightLoadingError as e:
249
+ # Primary policy failed, try fallback
250
+ ranked_logger.warning(
251
+ f"Failed to apply policy: '{policy}' to '{name}': {str(e)}. Falling back to policy: '{config.fallback_policy}'."
252
+ )
253
+ # __post_init__ normalises fallback_policy from str to the enum.
254
+ fallback_policy = config.fallback_policy
255
+ assert isinstance(fallback_policy, WeightLoadingPolicy)
256
+ result = _apply_policy(
257
+ name, current_param, checkpoint_param, fallback_policy
258
+ )
259
+ updated_state[name] = result
260
+
261
+ return updated_state
262
+
263
+
264
+ @dataclass
265
+ class CheckpointConfig:
266
+ """Configuration for loading checkpoints.
267
+
268
+ TODO: Implement reset_scheduler and reset_ema
269
+ """
270
+
271
+ path: PathLike
272
+ reset_optimizer: bool = False
273
+ weight_loading_config: WeightLoadingConfig | None = None
274
+ parameter_freezing_config: ParameterFreezingConfig | None = None
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """XPU utilities for Intel GPU support.
2
+
3
+ XPU support in PyTorch is now native (torch.xpu.is_available()), but Lightning Fabric
4
+ requires custom Accelerator, Strategy, and Precision plugins for proper XPU handling.
5
+
6
+ These components are used directly (not via registry) when XPU is detected:
7
+ - XPUAccelerator: Custom accelerator for XPU devices
8
+ - SingleXPUStrategy: Strategy for single-device XPU training/inference
9
+ - XPUMixedPrecision: Precision plugin with proper XPU autocast support
10
+
11
+ Usage:
12
+ from foundry.utils.xpu import XPUAccelerator, SingleXPUStrategy, XPUMixedPrecision
13
+
14
+ # Check availability
15
+ if XPUAccelerator.is_available():
16
+ strategy = SingleXPUStrategy(precision_plugin=XPUMixedPrecision("bf16-mixed"))
17
+
18
+ Note:
19
+ The FabricTrainer automatically uses these components when XPU is detected.
20
+ You typically don't need to use them directly unless customizing behavior.
21
+ """
22
+
23
+ from .single_xpu_strategy import SingleXPUStrategy
24
+ from .xpu_accelerator import XPUAccelerator
25
+ from .xpu_precision import XPUMixedPrecision
26
+
27
+ __all__ = ["SingleXPUStrategy", "XPUAccelerator", "XPUMixedPrecision"]
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/single_xpu_strategy.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lightning Fabric strategy for single XPU device.
2
+
3
+ https://docs.pytorch.org/docs/stable/notes/get_start_xpu.html
4
+ """
5
+
6
+ import torch
7
+ from lightning.fabric.plugins import CheckpointIO
8
+ from lightning.fabric.plugins.precision import Precision
9
+ from lightning.fabric.strategies import SingleDeviceStrategy
10
+ from lightning.fabric.utilities.types import _DEVICE
11
+
12
+
13
+ class SingleXPUStrategy(SingleDeviceStrategy):
14
+ """Strategy for training/inference on a single Intel XPU device.
15
+
16
+ This strategy extends SingleDeviceStrategy to properly handle XPU devices.
17
+ """
18
+
19
+ strategy_name = "xpu_single"
20
+
21
+ def __init__(
22
+ self,
23
+ device: _DEVICE = "xpu:0",
24
+ checkpoint_io: CheckpointIO | None = None,
25
+ precision_plugin: Precision | None = None,
26
+ ) -> None:
27
+ """Initialize the single XPU strategy.
28
+
29
+ Args:
30
+ device: The XPU device to use. Defaults to "xpu:0".
31
+ checkpoint_io: Plugin for checkpoint I/O.
32
+ precision_plugin: Plugin for precision handling (set via _precision property).
33
+
34
+ Raises:
35
+ RuntimeError: If XPU devices are not available.
36
+ """
37
+ if not (hasattr(torch, "xpu") and torch.xpu.is_available()):
38
+ msg = "`SingleXPUStrategy` requires XPU devices to run"
39
+ raise RuntimeError(msg)
40
+
41
+ super().__init__(
42
+ device=device,
43
+ checkpoint_io=checkpoint_io,
44
+ )
45
+ # Precision is handled via the _precision property in newer Lightning versions
46
+ if precision_plugin is not None:
47
+ self._precision = precision_plugin
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/xpu_accelerator.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """XPU Accelerator for Intel XPU devices."""
2
+
3
+ from typing import Any
4
+
5
+ import torch
6
+ from lightning.fabric.accelerators import Accelerator
7
+
8
+
9
+ class XPUAccelerator(Accelerator):
10
+ """Accelerator for Intel XPU devices.
11
+
12
+ This accelerator enables training and inference on Intel GPUs using
13
+ PyTorch's native XPU support (torch.xpu).
14
+ """
15
+
16
+ @staticmethod
17
+ def name() -> str:
18
+ """Return the name of this accelerator."""
19
+ return "xpu"
20
+
21
+ @staticmethod
22
+ def setup_device(device: torch.device) -> None:
23
+ """Set up the specified XPU device.
24
+
25
+ Args:
26
+ device: The torch device to set up.
27
+
28
+ Raises:
29
+ RuntimeError: If device is not an XPU device.
30
+ """
31
+ if device.type != "xpu":
32
+ msg = f"Device should be xpu, got {device} instead"
33
+ raise RuntimeError(msg)
34
+
35
+ torch.xpu.set_device(device)
36
+
37
+ @staticmethod
38
+ def parse_devices(devices: str | list | torch.device) -> list:
39
+ """Parse devices specification for XPU training.
40
+
41
+ Args:
42
+ devices: Device specification (int, list of ints, or string).
43
+
44
+ Returns:
45
+ List of device indices.
46
+ """
47
+ if isinstance(devices, list):
48
+ return devices
49
+ return [devices]
50
+
51
+ @staticmethod
52
+ def get_parallel_devices(devices: list) -> list[torch.device]:
53
+ """Generate a list of parallel XPU devices.
54
+
55
+ Args:
56
+ devices: List of device indices.
57
+
58
+ Returns:
59
+ List of torch.device objects for XPU.
60
+ """
61
+ return [torch.device("xpu", idx) for idx in devices]
62
+
63
+ @staticmethod
64
+ def auto_device_count() -> int:
65
+ """Return the number of available XPU devices."""
66
+ return torch.xpu.device_count()
67
+
68
+ @staticmethod
69
+ def is_available() -> bool:
70
+ """Check if XPU is available."""
71
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
72
+
73
+ @staticmethod
74
+ def get_device_stats(device: str | torch.device) -> dict[str, Any]:
75
+ """Return XPU device statistics.
76
+
77
+ Currently returns an empty dict as XPU stats API may vary.
78
+
79
+ Args:
80
+ device: The device to get stats for.
81
+
82
+ Returns:
83
+ Dictionary of device statistics.
84
+ """
85
+ del device # Unused
86
+ return {}
87
+
88
+ def teardown(self) -> None:
89
+ """Clean up XPU accelerator resources."""
90
+ # Empty implementation required by base class
91
+ pass
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/utils/xpu/xpu_precision.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """XPU Precision Plugin for Lightning Fabric."""
2
+
3
+ from contextlib import contextmanager
4
+ from typing import Any, Generator, Literal
5
+
6
+ import torch
7
+ from lightning.fabric.plugins.precision import MixedPrecision
8
+ from torch import Tensor
9
+
10
+
11
+ class XPUMixedPrecision(MixedPrecision):
12
+ """Mixed precision plugin for Intel XPU devices.
13
+
14
+ This overrides the default MixedPrecision plugin to use 'xpu' as the
15
+ device type for torch.autocast instead of 'cuda'.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ precision: Literal["16-mixed", "bf16-mixed"] = "bf16-mixed",
21
+ ) -> None:
22
+ """Initialize XPU mixed precision.
23
+
24
+ Args:
25
+ precision: The precision mode. "16-mixed" uses float16,
26
+ "bf16-mixed" uses bfloat16. Defaults to "bf16-mixed".
27
+
28
+ Raises:
29
+ ValueError: If precision is not "16-mixed" or "bf16-mixed".
30
+ """
31
+ # Determine dtype from precision string
32
+ if precision == "16-mixed":
33
+ dtype = torch.float16
34
+ elif precision == "bf16-mixed":
35
+ dtype = torch.bfloat16
36
+ else:
37
+ msg = f"Invalid precision: {precision}. Must be '16-mixed' or 'bf16-mixed'"
38
+ raise ValueError(msg)
39
+
40
+ # Initialize with xpu device type
41
+ super().__init__(precision=precision, device="xpu")
42
+ self._desired_input_dtype = dtype
43
+
44
+ @contextmanager
45
+ def forward_context(self) -> Generator[None, None, None]:
46
+ """Context manager for forward pass with XPU autocast."""
47
+ with torch.autocast(device_type="xpu", dtype=self._desired_input_dtype):
48
+ yield
49
+
50
+ def convert_input(self, data: Any) -> Any:
51
+ """Convert input data to the appropriate precision.
52
+
53
+ Args:
54
+ data: Input data to convert.
55
+
56
+ Returns:
57
+ Converted data.
58
+ """
59
+ return self._convert_fp_tensor(data)
60
+
61
+ def _convert_fp_tensor(self, data: Any) -> Any:
62
+ """Convert floating point tensors to the desired dtype.
63
+
64
+ Args:
65
+ data: Data to convert.
66
+
67
+ Returns:
68
+ Converted data if it's a floating point tensor, otherwise unchanged.
69
+ """
70
+ if isinstance(data, Tensor) and data.is_floating_point():
71
+ return data.to(self._desired_input_dtype)
72
+ return data
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3/src/foundry/version.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.0.1.dev1+gb02eed6a6.d20260916'
22
+ __version_tuple__ = version_tuple = (0, 0, 1, 'dev1', 'gb02eed6a6.d20260916')
23
+
24
+ __commit_id__ = commit_id = None
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3_collect.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Convert RFdiffusion3 inference output into a protein-design submission.
3
+
4
+ Pairs with `rfd3_inputs.py`: that builds the specs, `rfd3 design` runs upstream
5
+ inference, this turns the result back into what the grader reads. View-agnostic -
6
+ it works on fit, tune or the evaluation view alike.
7
+
8
+ RFD3 writes one gzipped mmCIF per design, holding everything it was given: the designed
9
+ chain, the fixed target chain for a binder, and the ligand. The task's grader wants the
10
+ opposite - one PDB per design containing ONLY the designed chain, exactly
11
+ `design_length` residues, every atom name valid for its residue in the atom14 table
12
+ (`tests/geometry.py::parse_allatom_pdb`) - plus a `<track>.jsonl` index.
13
+
14
+ For the enzyme track it also wants `motif_map`: which design position each motif residue
15
+ landed on. That is the whole point of the unindexed setting - the model chooses - so the
16
+ mapping is recovered from the output by matching the motif's fixed atoms, which RFD3
17
+ holds at noise level zero and therefore reproduces exactly.
18
+ """
19
+
20
+ import argparse
21
+ import gzip
22
+ import json
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+
28
+ # The starter's `residues.py` is asserted byte-identical to the grader's
29
+ # (tests/test_task.py::test_starter_and_grader_share_one_atom14_table), so the
30
+ # atom14 table used to write a submission is the one used to read it back.
31
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
32
+ from residues import ATOM14, ATOM14_WIDTH, atom_slot # noqa: E402
33
+
34
+ BACKBONE = (0, 1, 2, 3)
35
+
36
+
37
+ def read_cif(path):
38
+ """Parse one RFD3 output into per-chain residue lists.
39
+
40
+ Returns {chain: [(residue_number, residue_name, {atom_name: (x, y, z)}), ...]}.
41
+ """
42
+ from biotite.structure.io.pdbx import CIFFile, get_structure
43
+ with gzip.open(path, "rt") as handle:
44
+ structure = get_structure(CIFFile.read(handle), model=1)
45
+ chains = {}
46
+ for atom in structure:
47
+ if atom.element == "H":
48
+ continue
49
+ key = str(atom.chain_id)
50
+ residues = chains.setdefault(key, {})
51
+ entry = residues.setdefault(int(atom.res_id), [str(atom.res_name), {}])
52
+ entry[1][str(atom.atom_name)] = tuple(float(value) for value in atom.coord)
53
+ return {chain: [(number, *residues[number]) for number in sorted(residues)]
54
+ for chain, residues in chains.items()}
55
+
56
+
57
+ def design_chain(chains, design_length):
58
+ """The designed chain is the amino-acid chain with exactly `design_length` residues.
59
+
60
+ Cheap and unambiguous: a binder's target chain is a different length by construction,
61
+ and the ligand is not an amino-acid chain at all.
62
+ """
63
+ candidates = [(chain, residues) for chain, residues in chains.items()
64
+ if len(residues) == design_length
65
+ and all(name in ATOM14 for _, name, _ in residues)]
66
+ if len(candidates) != 1:
67
+ raise ValueError(f"expected one chain of {design_length} residues, "
68
+ f"found {[(c, len(r)) for c, r in chains.items()]}")
69
+ return candidates[0][1]
70
+
71
+
72
+ def to_atom14(residues):
73
+ """[L, 14, 3] coordinates and an [L, 14] mask, dropping atoms atom14 has no slot for."""
74
+ length = len(residues)
75
+ coordinates = np.zeros((length, ATOM14_WIDTH, 3))
76
+ mask = np.zeros((length, ATOM14_WIDTH), dtype=bool)
77
+ names = []
78
+ for index, (_, residue_name, atoms) in enumerate(residues):
79
+ names.append(residue_name)
80
+ for atom, position in atoms.items():
81
+ slot = atom_slot(residue_name, atom)
82
+ if slot is None: # OXT, virtual slots, anything non-atom14
83
+ continue
84
+ coordinates[index, slot] = position
85
+ mask[index, slot] = True
86
+ return coordinates, mask, names
87
+
88
+
89
+ def recover_motif_map(metadata, names, context, coordinates, mask):
90
+ """Which design residue each motif position landed on.
91
+
92
+ Upstream reports this itself: the output metadata carries `diffused_index_map`,
93
+ input residue -> output residue, which for an unindexed motif is precisely the
94
+ placement decision the model made. The context lists its motif residues in the same
95
+ order as the spec's `unindex` field, and the result is checked against the residue
96
+ identities before it is trusted; if anything disagrees, fall back to matching the
97
+ motif's own atoms in the output.
98
+ """
99
+ motif_types = [str(name) for name in context["motif_restypes"]]
100
+ index_map = metadata.get("diffused_index_map") or {}
101
+ unindexed = str(metadata.get("specification", {}).get("unindex", "")).split(",")
102
+ unindexed = [item.strip() for item in unindexed if item.strip()]
103
+ if len(unindexed) == len(motif_types) and index_map:
104
+ mapping = []
105
+ for source in unindexed:
106
+ target = lookup(index_map, source)
107
+ position = int("".join(c for c in str(target) if c.isdigit())) - 1 if target else -1
108
+ mapping.append(position)
109
+ if (all(0 <= position < len(names) for position in mapping)
110
+ and len(set(mapping)) == len(mapping)
111
+ and [names[position] for position in mapping] == motif_types):
112
+ return mapping
113
+ return match_motif_by_coordinates(coordinates, mask, names, context)
114
+
115
+
116
+ def lookup(index_map, source):
117
+ """`diffused_index_map` keyed by input residue, tolerating upstream's truncation.
118
+
119
+ Upstream writes four-digit residue ids short - a motif residue `B1029` comes back as
120
+ the key `B102` - so an exact lookup silently misses and the design gets dropped.
121
+ Fall back to a prefix match, and only when it is unambiguous.
122
+ """
123
+ if source in index_map:
124
+ return index_map[source]
125
+ hits = [value for key, value in index_map.items()
126
+ if source.startswith(key) or key.startswith(source)]
127
+ return hits[0] if len(hits) == 1 else None
128
+
129
+
130
+ def match_motif_by_coordinates(coordinates, mask, names, context):
131
+ """Fallback placement: the closest residue of the right identity, greedily assigned."""
132
+ motif = context["motif_coords"]
133
+ motif_mask = context["motif_mask"].astype(bool)
134
+ motif_types = [str(name) for name in context["motif_restypes"]]
135
+ scores = np.full((len(motif_types), len(names)), np.inf)
136
+ for i, residue_name in enumerate(motif_types):
137
+ shared = motif_mask[i][None, :] & mask # [L, 14]
138
+ for j in range(len(names)):
139
+ # A motif position carries only the atoms the context kept - for these
140
+ # benchmarks that is the 2-3 fixed tip atoms, NOT a whole backbone - so the
141
+ # overlap is whatever both sides have, and one atom is too few to place on.
142
+ if names[j] != residue_name or shared[j].sum() < 2:
143
+ continue
144
+ selected = shared[j]
145
+ difference = coordinates[j][selected] - motif[i][selected]
146
+ scores[i, j] = float(np.sqrt((difference ** 2).sum(axis=-1).mean()))
147
+ assignment, taken = [None] * len(motif_types), set()
148
+ for i in np.argsort(scores.min(axis=1)):
149
+ order = np.argsort(scores[i])
150
+ choice = next((int(j) for j in order
151
+ if int(j) not in taken and np.isfinite(scores[i, j])), None)
152
+ if choice is None:
153
+ return None
154
+ assignment[int(i)] = choice
155
+ taken.add(choice)
156
+ return assignment
157
+
158
+
159
+ def write_pdb(path, coordinates, mask, names, chain="A"):
160
+ """Canonical atom14 PDB, the same columns `tests/geometry.py` parses."""
161
+ lines, serial = [], 1
162
+ for index, residue_name in enumerate(names):
163
+ for slot, atom in enumerate(ATOM14[residue_name]):
164
+ if not mask[index, slot]:
165
+ continue
166
+ x, y, z = coordinates[index, slot]
167
+ lines.append(f"ATOM {serial:>5d} {(' ' + atom):<4s} {residue_name:<3s} "
168
+ f"{chain}{index + 1:>4d} "
169
+ f"{x:>8.3f}{y:>8.3f}{z:>8.3f} 1.00 0.00" + " " * 10
170
+ + f"{atom[0]:>2s}")
171
+ serial += 1
172
+ lines.append("END")
173
+ path.write_text("\n".join(lines) + "\n")
174
+
175
+
176
+ def outputs_for(track_dir, example):
177
+ """RFD3 names a design `<prefix><example>_<batch>_model_<i>.cif.gz`."""
178
+ return sorted(track_dir.glob(f"*{example}_*_model_*.cif.gz"))
179
+
180
+
181
+ def collect(view, designs, out, tracks):
182
+ predictions = out / "predictions"
183
+ structures = predictions / "structures"
184
+ structures.mkdir(parents=True, exist_ok=True)
185
+ summary = {}
186
+
187
+ for track in tracks:
188
+ source = view / f"{track}.jsonl"
189
+ track_dir = designs / track
190
+ if not source.is_file() or not track_dir.is_dir():
191
+ continue
192
+ rows, kept, dropped = [], 0, {}
193
+ for line in source.read_text().splitlines():
194
+ if not line.strip():
195
+ continue
196
+ request = json.loads(line)
197
+ example, length = request["example_id"], int(request["design_length"])
198
+ context = dict(np.load(view / request["context_path"], allow_pickle=False))
199
+ records = []
200
+ for index, path in enumerate(outputs_for(track_dir, example)):
201
+ if index >= request["num_designs"]:
202
+ break
203
+ try:
204
+ residues = design_chain(read_cif(path), length)
205
+ coordinates, mask, names = to_atom14(residues)
206
+ if not mask[:, BACKBONE].all():
207
+ raise ValueError("a residue is missing backbone atoms")
208
+ record = {"design_index": index,
209
+ "ranking_score": 1.0 - 0.01 * index,
210
+ "structure_path": f"{example}-{index}.pdb"}
211
+ if "motif_coords" in context:
212
+ metadata = json.loads(path.with_suffix("").with_suffix(".json")
213
+ .read_text())
214
+ motif_map = recover_motif_map(metadata, names, context,
215
+ coordinates, mask)
216
+ if motif_map is None:
217
+ raise ValueError("could not locate the motif in the design")
218
+ record["motif_map"] = motif_map
219
+ except (OSError, ValueError, KeyError) as error:
220
+ dropped[str(error)[:90]] = dropped.get(str(error)[:90], 0) + 1
221
+ continue
222
+ write_pdb(structures / record["structure_path"],
223
+ coordinates, mask, names)
224
+ records.append(record)
225
+ kept += 1
226
+ rows.append({"example_id": example, "designs": records})
227
+ (predictions / f"{track}.jsonl").write_text(
228
+ "".join(json.dumps(row) + "\n" for row in rows))
229
+ summary[track] = {"targets": len(rows), "designs": kept, "dropped": dropped}
230
+ print(f"{track:15s} {len(rows):3d} targets, {kept:4d} designs"
231
+ + (f", dropped {dropped}" if dropped else ""))
232
+ (out / "collect.json").write_text(json.dumps(summary, indent=2) + "\n")
233
+
234
+
235
+ def main():
236
+ parser = argparse.ArgumentParser()
237
+ parser.add_argument("--view", required=True, type=Path)
238
+ parser.add_argument("--designs", required=True, type=Path)
239
+ parser.add_argument("--out", required=True, type=Path)
240
+ parser.add_argument("--tracks", nargs="*",
241
+ default=["unconditional", "sm_binder", "ppi_binder", "enzyme"])
242
+ arguments = parser.parse_args()
243
+ collect(arguments.view, arguments.designs, arguments.out, arguments.tracks)
244
+
245
+
246
+ if __name__ == "__main__":
247
+ main()
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3_infer.sh ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Designs from a trained upstream-RFD3 checkpoint, in the task's submission format.
3
+ #
4
+ # bash rfd3_infer.sh <ckpt> <view> <out> ["<tracks>"] [timesteps] [subset]
5
+ # bash rfd3_infer.sh /workspace/research/ckpt/epoch-0060.ckpt /data/tune /tmp/run
6
+ #
7
+ # Three stages, with upstream's inference untouched in the middle:
8
+ # rfd3_inputs.py request .npz -> RFD3 InputSpecification + a conditioning structure
9
+ # rfd3 design upstream, unmodified. Reduced widths come from the checkpoint's own
10
+ # `train_cfg`, so no config is repeated here.
11
+ # rfd3_collect.py output mmCIF -> one PDB per design plus <track>.jsonl
12
+ #
13
+ # Then score it yourself - scoring is unrestricted, see evaluation/README.md:
14
+ # python /workspace/evaluation/score.py --input <view> --designs <out>/submission
15
+ #
16
+ # That is the real designability metric; there is no geometry-only shortcut any more.
17
+ #
18
+ # Run that score from a normal working directory, NOT from /tmp: a phantom `matplotlib`
19
+ # directory there makes torchmetrics believe matplotlib is installed and then fail on
20
+ # `matplotlib.axes`. The full scorer imports rf3, so it inherits that trap.
21
+ set -euo pipefail
22
+
23
+ CKPT=${1:?checkpoint path}
24
+ VIEW=${2:?input view directory, e.g. /data/tune}
25
+ OUT=${3:?output directory}
26
+ TRACKS=${4:-"unconditional sm_binder ppi_binder enzyme"}
27
+ STEPS=${5:-200}
28
+ # Optional comma-separated example ids, for a cheap smoke run. Passed to hydra as
29
+ # a bracketed list: a bare `a,b` is rejected as an ambiguous value.
30
+ SUBSET=${6:-}
31
+
32
+ # Designs per target = N_BATCHES x 4 diffusion samples. The default 25 gives the 100
33
+ # designs per target that every task view requests and that RFdiffusion3's own protocol
34
+ # specifies - the same sample size behind the reference row in ../evaluation/RESULTS.md.
35
+ # Lower it only for a quick smoke test: at 4 designs per target the sm_binder and
36
+ # ppi_binder tracks return 0.000 whatever the model does, because their pass rates are a
37
+ # few percent over 4 and 5 targets. Budget ~110 s per design for the full scorer on top
38
+ # of generation.
39
+ N_BATCHES=${N_BATCHES:-25}
40
+
41
+ HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
42
+
43
+ # Dataloader workers bind an AF_UNIX socket under TMPDIR, and the path has a 108-char
44
+ # limit; a deep scratch path silently breaks inference rather than erroring clearly.
45
+ export TMPDIR=${TMPDIR:-/tmp}
46
+ export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}
47
+
48
+ # `rfd3` is a console script installed by `pip install rc-foundry`. The image vendors
49
+ # the SOURCE and reaches it through PYTHONPATH instead, so that script does not exist
50
+ # there - invoke the same Typer app as a module when it is missing.
51
+ run_rfd3() {
52
+ if command -v rfd3 >/dev/null 2>&1; then
53
+ rfd3 "$@"
54
+ else
55
+ python -c 'from rfd3.cli import app; app()' "$@"
56
+ fi
57
+ }
58
+
59
+ mkdir -p "$OUT"
60
+ python "$HERE/rfd3_inputs.py" --view "$VIEW" --out "$OUT/inputs" --tracks $TRACKS
61
+
62
+ for TRACK in $TRACKS; do
63
+ [ -f "$OUT/inputs/$TRACK.json" ] || { echo "-- $TRACK: no targets, skipping"; continue; }
64
+ echo "=== designing $TRACK ($((N_BATCHES * 4)) designs per target)"
65
+ # A batch is 4 diffusion samples, so N_BATCHES=25 gives the 100 designs per target every
66
+ # view requests while keeping peak memory at a single batch.
67
+ run_rfd3 design \
68
+ out_dir="$OUT/designs/$TRACK" \
69
+ inputs="$OUT/inputs/$TRACK.json" \
70
+ ckpt_path="$CKPT" \
71
+ n_batches="$N_BATCHES" \
72
+ diffusion_batch_size=4 \
73
+ inference_sampler.num_timesteps="$STEPS" \
74
+ skip_existing=True \
75
+ prevalidate_inputs=True \
76
+ ${SUBSET:+json_keys_subset=[$SUBSET]}
77
+ done
78
+
79
+ echo "=== collecting"
80
+ python "$HERE/rfd3_collect.py" --view "$VIEW" --designs "$OUT/designs" \
81
+ --out "$OUT/submission" --tracks $TRACKS
82
+
83
+ echo "=== done: $OUT/submission"
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/rfd3_inputs.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Turn any protein-design input view into RFdiffusion3 inference specs.
3
+
4
+ The task hands out a request as a `<track>.jsonl` row plus an `.npz` conditioning
5
+ context. Upstream RFD3 wants an `InputSpecification`: an input structure, a contig, and
6
+ selections over that structure. This script writes both - a conditioning structure
7
+ rebuilt from the context, and the spec that points at it.
8
+
9
+ It works on **fit and tune**, which is what an agent actually has: `docker-compose.yaml`
10
+ mounts only `development`, so `/data/fit` and `/data/tune` are the whole world inside the
11
+ container. That is the difference between this and `environment/evaluation/benchmark/make_inputs.py`, which
12
+ reuses upstream's published benchmark specs and therefore only works on the evaluation
13
+ view the verifier holds.
14
+
15
+ python rfd3_inputs.py --view /data/tune --out /workspace/research/inputs
16
+
17
+ Then design with upstream inference, and convert back with `rfd3_collect.py`:
18
+
19
+ rfd3 design out_dir=... inputs=.../enzyme.json ckpt_path=... \
20
+ n_batches=25 diffusion_batch_size=4 prevalidate_inputs=True
21
+ """
22
+
23
+ import argparse
24
+ import json
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ from residues import ATOM14 # noqa: E402
32
+
33
+ # Chains in the conditioning structure we write. The designed chain is generated, so it
34
+ # is not in this file at all; these hold only what the request fixes.
35
+ MOTIF_CHAIN = "A"
36
+ TARGET_CHAIN = "B"
37
+ # Each ligand needs its OWN chain: atomworks refuses two ligand residues on one chain
38
+ # ("Multiple ligand residues on chain L ... set 'allow_ligand_on_existing_chain: true'
39
+ # to restore the old behaviour"). 29 of the 41 enzyme targets carry 2 or 3 ligands, so
40
+ # hand out successive letters from L, skipping the motif and target chains.
41
+ LIGAND_CHAINS = [c for c in "LMNOPQRSTUVWXYZ" if c not in (MOTIF_CHAIN, TARGET_CHAIN)]
42
+
43
+
44
+ def ligand_atom_names(code, elements):
45
+ """Name a ligand's atoms by embedding its element sequence into the CCD's.
46
+
47
+ The context stores ligand coordinates and elements but no atom names, and RFD3 needs
48
+ names that match the chemical component so bonds and the reference conformer resolve.
49
+ Materialization keeps deposition order, which follows the CCD, so for a fully
50
+ resolved ligand the names are just the CCD's heavy atoms in order (checked: 22 of 24
51
+ sampled ligands match element-for-element).
52
+
53
+ The other two had *fewer* atoms than the CCD - unresolved density, not a reordering -
54
+ so positional assignment would slip after the first gap. Embedding the observed
55
+ element sequence as a subsequence of the CCD's, earliest match first, handles both.
56
+ Returns None if no embedding exists, so the caller can skip the target rather than
57
+ invent chemistry.
58
+ """
59
+ from biotite.structure.info import residue as ccd_residue
60
+
61
+ try:
62
+ component = ccd_residue(code)
63
+ except Exception: # noqa: BLE001 - an unknown code is a skip, not a crash
64
+ return None
65
+ heavy = [(str(atom.atom_name), str(atom.element).upper())
66
+ for atom in component if str(atom.element).upper() != "H"]
67
+ names, cursor = [], 0
68
+ for element in (str(e).upper() for e in elements):
69
+ while cursor < len(heavy) and heavy[cursor][1] != element:
70
+ cursor += 1
71
+ if cursor == len(heavy):
72
+ return None
73
+ names.append(heavy[cursor][0])
74
+ cursor += 1
75
+ return names
76
+
77
+
78
+ def split_ligands(context):
79
+ """Un-concatenate a context's ligands into
80
+ (code, names, elements, coordinates, pinned) tuples.
81
+
82
+ `ingest_targets.py` stores ALL of a target's ligands in one flat array each -
83
+ `ligand_coords` and `ligand_elements` concatenated, with `ligand_ccd` and
84
+ `ligand_atom_counts` saying where the boundaries are. 29 of the 41 enzyme targets
85
+ carry more than one ligand (a cofactor plus a substrate, often plus a metal,
86
+ e.g. MG + ADP + 3PG), so reading `ligand_ccd[0]` and handing it the whole
87
+ element array asks the CCD for a component that explains every ligand at once. That
88
+ never embeds, so the target was silently skipped - which cost 29 of 41 enzyme
89
+ targets, i.e. the agent-facing path could reach only 12 of them.
90
+
91
+ Returns None if any ligand's names cannot be resolved, so the caller still skips
92
+ rather than inventing chemistry.
93
+ """
94
+ codes = [str(code) for code in context["ligand_ccd"]]
95
+ counts = [int(n) for n in context["ligand_atom_counts"]]
96
+ elements = [str(e) for e in context["ligand_elements"]]
97
+ coordinates = context["ligand_coords"]
98
+ # Prefer the deposition names the context carries. Reconstructing them from the CCD
99
+ # by element subsequence works but is a guess, and it cannot recover WHICH atoms
100
+ # upstream pins - see `ligand_fixed_mask` below. Older contexts lack both keys, so
101
+ # the CCD path stays as the fallback.
102
+ supplied = ([str(n) for n in context["ligand_atom_names"]]
103
+ if "ligand_atom_names" in context else None)
104
+ pinned = (context["ligand_fixed_mask"].astype(bool).tolist()
105
+ if "ligand_fixed_mask" in context else None)
106
+ ligands, offset = [], 0
107
+ for code, count in zip(codes, counts):
108
+ chunk = elements[offset:offset + count]
109
+ names = (supplied[offset:offset + count] if supplied is not None
110
+ else ligand_atom_names(code, chunk))
111
+ if names is None:
112
+ return None
113
+ keep = (pinned[offset:offset + count] if pinned is not None
114
+ else [True] * len(names))
115
+ ligands.append((code, names, chunk, coordinates[offset:offset + count], keep))
116
+ offset += count
117
+ return ligands
118
+
119
+
120
+ class PDBWriter:
121
+ """Minimal PDB writer - only the columns atomworks reads back."""
122
+
123
+ def __init__(self):
124
+ self.lines = []
125
+ self.serial = 1
126
+
127
+ def residue(self, chain, number, name, coordinates, mask, record="ATOM "):
128
+ """One amino acid, written in atom14 slot order."""
129
+ for slot, atom in enumerate(ATOM14[name]):
130
+ if not mask[slot]:
131
+ continue
132
+ self.atom(chain, number, name, atom, coordinates[slot], atom[0], record)
133
+
134
+ def atom(self, chain, number, residue_name, atom_name, position, element,
135
+ record="ATOM "):
136
+ x, y, z = (float(value) for value in position)
137
+ # PDB column rule: a one- or two-letter atom name starts in column 14, so it is
138
+ # padded with a leading space. Four-character names (none in atom14) start at 13.
139
+ field = atom_name if len(atom_name) >= 4 else f" {atom_name:<3s}"
140
+ self.lines.append(
141
+ f"{record}{self.serial:>5d} {field} {residue_name:>3s} "
142
+ f"{chain}{number:>4d} "
143
+ f"{x:>8.3f}{y:>8.3f}{z:>8.3f} 1.00 0.00 {element:>2s}")
144
+ self.serial += 1
145
+
146
+ def write(self, path):
147
+ path.write_text("\n".join(self.lines + ["END"]) + "\n")
148
+
149
+
150
+ def fixed_atom_names(name, mask):
151
+ """The atom14 atoms a context actually carries for one residue."""
152
+ return [atom for slot, atom in enumerate(ATOM14[name]) if mask[slot]]
153
+
154
+
155
+ def build_enzyme(context, length, structure_path):
156
+ """Motif geometry with no positions: upstream's unindexed / guidepost setting.
157
+
158
+ The request says which catalytic residues exist and where they sit relative to each
159
+ other and the ligand, but not which design positions they occupy - that is the
160
+ model's decision, and `motif_map` reports it back. So every motif residue goes into
161
+ `unindex`, and `select_fixed_atoms` pins exactly the atoms the context supplies,
162
+ which for this benchmark is a few tip atoms per residue rather than a backbone.
163
+ """
164
+ writer = PDBWriter()
165
+ types = [str(name) for name in context["motif_restypes"]]
166
+ masks = context["motif_mask"].astype(bool)
167
+ fixed = {}
168
+ for index, name in enumerate(types):
169
+ number = index + 1
170
+ writer.residue(MOTIF_CHAIN, number, name, context["motif_coords"][index],
171
+ masks[index])
172
+ fixed[f"{MOTIF_CHAIN}{number}"] = ",".join(fixed_atom_names(name, masks[index]))
173
+
174
+ # Every ligand, each as its own residue with its own CCD code. Upstream's published
175
+ # specs for these same targets use exactly this shape - `"ligand": "ADP,MG,3PG"`
176
+ # with one select_fixed_atoms key per code (see data/targets/enzyme/input.yaml).
177
+ ligands = split_ligands(context)
178
+ if ligands is None:
179
+ return None
180
+ for chain, (code, names, elements, coordinates, keep) in zip(LIGAND_CHAINS, ligands):
181
+ for atom, position, element in zip(names, coordinates, elements):
182
+ writer.atom(chain, 1, code, atom, position, element, record="HETATM")
183
+ # Only the atoms upstream's spec pins, not every atom present. Every atom is
184
+ # still written to the PDB - the ligand's geometry is the conditioning - but
185
+ # pinning all of them posed a different, more constrained problem than the
186
+ # published benchmark does.
187
+ selected = [atom for atom, wanted in zip(names, keep) if wanted]
188
+ fixed[code] = ",".join(selected or names)
189
+
190
+ writer.write(structure_path)
191
+ return {"dialect": 2, "input": str(structure_path),
192
+ "ligand": ",".join(ligand[0] for ligand in ligands),
193
+ "unindex": ",".join(f"{MOTIF_CHAIN}{i + 1}" for i in range(len(types))),
194
+ "length": f"{length}-{length}", "select_fixed_atoms": fixed}
195
+
196
+
197
+ def build_sm_binder(context, length, structure_path):
198
+ """A bare ligand: build a chain around it, with no pocket template."""
199
+ writer = PDBWriter()
200
+ ligands = split_ligands(context)
201
+ if ligands is None:
202
+ return None
203
+ for chain, (code, names, elements, coordinates, _) in zip(LIGAND_CHAINS, ligands):
204
+ for atom, position, element in zip(names, coordinates, elements):
205
+ writer.atom(chain, 1, code, atom, position, element, record="HETATM")
206
+ writer.write(structure_path)
207
+ # All four shipped sm_binder targets are single-ligand, but the concatenation is the
208
+ # same, so this goes through split_ligands too rather than keeping a second code path
209
+ # that would break the first time a multi-ligand sm target appears.
210
+ return {"dialect": 2, "input": str(structure_path),
211
+ "ligand": ",".join(ligand[0] for ligand in ligands),
212
+ "contig": f"{length}-{length}", "select_fixed_atoms": True}
213
+
214
+
215
+ def build_ppi_binder(context, length, structure_path):
216
+ """A fixed target chain plus hotspots the binder should contact.
217
+
218
+ The contig is `<designed>,/0,<target range>`: `/0` is upstream's chain break, so the
219
+ designed chain and the target are separate chains rather than one fused polymer.
220
+ """
221
+ writer = PDBWriter()
222
+ types = [str(name) for name in context["target_restypes"]]
223
+ masks = context["target_mask"].astype(bool)
224
+ # Gap-preserving residue numbers where the context carries them: a break in the
225
+ # target's numbering is real structure, and numbering it `index + 1` would assert
226
+ # that residues either side of an unresolved stretch are adjacent. The development
227
+ # views have no such gaps to preserve, so they number sequentially.
228
+ resnums = ([int(n) for n in context["target_resnums"]]
229
+ if "target_resnums" in context else list(range(1, len(types) + 1)))
230
+ for index, name in enumerate(types):
231
+ writer.residue(TARGET_CHAIN, resnums[index], name,
232
+ context["target_coords"][index], masks[index])
233
+ writer.write(structure_path)
234
+
235
+ # One contig range per contiguous run, so the spec states the same range structure
236
+ # `input.yaml` does (`B0-47,B53-64,B104-165` -> `B1-48,B54-65,B105-166`).
237
+ ranges, start = [], 0
238
+ for index in range(1, len(resnums) + 1):
239
+ if index == len(resnums) or resnums[index] != resnums[index - 1] + 1:
240
+ ranges.append(f"{TARGET_CHAIN}{resnums[start]}-{resnums[index - 1]}")
241
+ start = index
242
+ target_contig = ",".join(ranges)
243
+
244
+ # Atom-level hotspots where the context carries them, matching `input.yaml`, which
245
+ # names exactly two sidechain atoms per hotspot. A contig string is accepted too,
246
+ # but `canonicalize_` expands it to EVERY atom of the residue, so the per-atom
247
+ # `is_atom_level_hotspot` feature would be set on ~8-11 atoms instead of 2. The
248
+ # development views built by materialize.py derive hotspots from coordinates and
249
+ # have no published atom selection, so they fall back to the token-level form.
250
+ if "hotspot_atoms" in context:
251
+ hotspots = {f"{TARGET_CHAIN}{resnums[int(i)]}": str(atoms)
252
+ for i, atoms in zip(context["hotspot_indices"],
253
+ context["hotspot_atoms"])}
254
+ else:
255
+ hotspots = ",".join(f"{TARGET_CHAIN}{resnums[int(i)]}"
256
+ for i in context["hotspot_indices"])
257
+ return {"dialect": 2, "input": str(structure_path),
258
+ "contig": f"{length}-{length},/0,{target_contig}",
259
+ "select_fixed_atoms": True, "select_hotspots": hotspots,
260
+ # NOT optional. With both `ori_token` and `infer_ori_strategy` unset,
261
+ # `set_com` (`rfd3/utils/inference.py`) falls through to "COM of fixed
262
+ # motif"; here the whole target chain IS the fixed motif, so the origin
263
+ # becomes the TARGET's centre of mass and the binder is diffused from
264
+ # inside it. Measured on a run that omitted this: median minimum
265
+ # binder-target atom distance 0.25-0.45 A on all five targets, binder COM
266
+ # 2.4-6.7 A from the target COM, ipTM 0.19 and pass rate 0/500 - the track
267
+ # was not measuring the model at all. `protein_binder_design.md` recommends
268
+ # "hotspots", which puts the origin 10 A along the outward normal from the
269
+ # hotspot centroid. `benchmark/standard/make_specs.py` has always set this;
270
+ # the graded path did not, which is the whole discrepancy on this track.
271
+ "infer_ori_strategy": "hotspots"}
272
+
273
+
274
+ BUILDERS = {"enzyme": build_enzyme, "sm_binder": build_sm_binder,
275
+ "ppi_binder": build_ppi_binder}
276
+
277
+
278
+ def build(view, out, tracks):
279
+ out.mkdir(parents=True, exist_ok=True)
280
+ structures = out / "conditioning"
281
+ structures.mkdir(exist_ok=True)
282
+ counts, skipped = {}, {}
283
+
284
+ for track in tracks:
285
+ if track != "unconditional" and track not in BUILDERS:
286
+ raise SystemExit(f"unknown track {track!r}; expected one of "
287
+ f"unconditional, {', '.join(sorted(BUILDERS))}")
288
+ source = view / f"{track}.jsonl"
289
+ if not source.is_file():
290
+ continue
291
+ rows = [json.loads(line) for line in source.read_text().splitlines()
292
+ if line.strip()]
293
+ if not rows:
294
+ continue
295
+ specs = {}
296
+ for request in rows:
297
+ example = request["example_id"]
298
+ length = int(request["design_length"])
299
+ if track == "unconditional":
300
+ # A length is the whole request - no structure, nothing to condition on.
301
+ specs[example] = {"length": f"{length}-{length}"}
302
+ continue
303
+ context = dict(np.load(view / request["context_path"], allow_pickle=False))
304
+ spec = BUILDERS[track](context, length, structures / f"{example}.pdb")
305
+ if spec is None:
306
+ skipped[track] = skipped.get(track, 0) + 1
307
+ continue
308
+ specs[example] = spec
309
+ if specs:
310
+ (out / f"{track}.json").write_text(json.dumps(specs, indent=2) + "\n")
311
+ counts[track] = len(specs)
312
+ return counts, skipped
313
+
314
+
315
+ def main():
316
+ parser = argparse.ArgumentParser(
317
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
318
+ parser.add_argument("--view", required=True, type=Path,
319
+ help="an input view directory: /data/fit or /data/tune")
320
+ parser.add_argument("--out", required=True, type=Path)
321
+ parser.add_argument("--tracks", nargs="*",
322
+ default=["unconditional", "sm_binder", "ppi_binder", "enzyme"])
323
+ arguments = parser.parse_args()
324
+ counts, skipped = build(arguments.view, arguments.out, set(arguments.tracks))
325
+ for track, number in sorted(counts.items()):
326
+ note = f" ({skipped[track]} skipped)" if track in skipped else ""
327
+ print(f"{track:15s} {number:3d} targets -> "
328
+ f"{arguments.out / (track + '.json')}{note}")
329
+ if not counts:
330
+ raise SystemExit(f"no targets found under {arguments.view}")
331
+
332
+
333
+ if __name__ == "__main__":
334
+ main()
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/sampling.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"timesteps": 24, "batch_size": 4, "step_scale": 1.5, "recycles": 1, "seed": 20261022}
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/submission/training_record.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "optimizer_steps": 32,
3
+ "epoch": 0,
4
+ "weight_selection": "online",
5
+ "parameters": 12445554,
6
+ "training_corpus": "fit/structures",
7
+ "pretrained_weights": false,
8
+ "checkpoint_sha256": "e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779"
9
+ }
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/finalization/trajectory.jsonl ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"type":"thread.started","thread_id":"01a1618d-8956-7b80-9cc4-d67245b7663a"}
2
+ {"type":"item.completed","item":{"id":"item_0","type":"error","message":"`[features].use_legacy_landlock` is deprecated and will be removed soon. (Remove this setting to stop opting into the legacy Linux sandbox behavior.)"}}
3
+ {"type":"turn.started"}
4
+ {"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"I’m stopping research and finalizing from the existing results. I’ll preserve the fully replayed trained-generator package: the later deployable experiments showed no measured improvement, and the hybrid’s required assets remain unavailable. I’ll use only static checks and atomic publication.\n"}}
5
+ {"type":"item.started","item":{"id":"item_2","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/harness.json'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
6
+ {"type":"item.started","item":{"id":"item_3","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/RESULTS.md'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
7
+ {"type":"item.started","item":{"id":"item_4","type":"command_execution","command":"/bin/sh -lc \"sed -n '1,240p' /workspace/baseline/rfd3-small/publish.py\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
8
+ {"type":"item.completed","item":{"id":"item_2","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/harness.json'","aggregated_output":"{\n \"schema\": \"protein-design-harness/v1\",\n \"kind\": \"trained_generator\",\n \"entry_point\": \"infer.sh\",\n \"pretrained_assets\": [],\n \"learned_components\": [\n {\n \"path\": \"generator.ckpt\",\n \"sha256\": \"e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779\",\n \"parameters\": 12445554,\n \"trained_in_session\": true\n }\n ]\n}\n","exit_code":0,"status":"completed"}}
9
+ {"type":"item.started","item":{"id":"item_5","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/MEASUREMENTS.json'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
10
+ {"type":"item.completed","item":{"id":"item_3","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/RESULTS.md'","aggregated_output":"# rfd3-small: results\n\nThe reproduced numbers for this baseline. The criteria behind them, the enzyme-target\ndistribution and the full write-up of how the graded and operator paths were reconciled are\nin [../../evaluation/RESULTS.md](../../evaluation/RESULTS.md).\n\n## What this baseline is\n\nUpstream RFdiffusion3, vendored at `rfd3/` from\n[RosettaCommons/foundry](https://github.com/RosettaCommons/foundry) `b02eed6a` and reduced in\n**layer widths only** to **12,445,554** parameters against upstream `pretrain`'s 168,038,994\n(7.4 %). Every depth is upstream's — 18 diffusion transformer blocks, 2 + 2 pairformer,\n3 + 3 atom encoder/decoder, `n_recycle` 2 — as are the crop, the losses, the AF-3\noptimizer/schedule and EMA. See [README.md](README.md) for the eight width leaves that change\nand how to run it.\n\n## Transfer (verifier, 51-target evaluation view)\n\nCheckpoint `epoch-0100.ckpt`, the real protocol of 51 targets × 100 designs.\n`conditioning_satisfied` is 100 % on all four tracks.\n\n| track | `pass_rate` | `diversity` | operator harness |\n|---|---:|---:|---:|\n| enzyme | 0.0624 | 0.341 | 0.054 |\n| sm_binder | 0.0275 | 0.750 | 0.030 |\n| ppi_binder | 0.002 | 0.200 | 0.004 |\n| unconditional | 0.420 | 1.000 | 0.410 |\n\nThe two paths agree within sampling noise, on counts of 12 vs 11, 1 vs 2, 220 vs 256 and\n41 vs 42 passing designs. Reaching that agreement required fixing five divergences in which\nthe graded path posed a different problem from the published specs; `input.yaml` is the source\nof truth and residue renumbering is the only licensed difference. The five are written up in\n[../../evaluation/RESULTS.md](../../evaluation/RESULTS.md).\n\n**This row is accepted from the task author's report rather than reproduced in this setup**,\nbecause the checkpoint is not distributable.\n\n## Anchors\n\n| system | enzyme | sm_binder | ppi_binder | unconditional |\n|---|---:|---:|---:|---:|\n| trivial generator (extended backbone, reduced view) | 0.000 | 0.000 | 0.000 | 0.000 |\n| `rfd3-small` above | 0.0624 | 0.0275 | 0.002 | 0.420 |\n\nThe trivial row is a **partial** null system: one target per track and two designs each, run\nthrough the real scorer, where nothing was designable on any track. The full\nnull row over all 51 targets is still open, and matters most on `enzyme`, where 28 of 41\ntargets score exactly 0.\n\n## Reading the numbers\n\n- `ppi_binder` is measurable, not good: 1 of 500 is not distinguishable from zero\n (P(0 of 500 | true rate 0.004) ≈ 13 %). What the cross-check establishes is that the number\n is produced by the model rather than by a spec bug, which was not true of any earlier run.\n- Thresholds come from RFdiffusion3's `success.txt`, which was calibrated with AlphaFold;\n scoring here uses RoseTTAFold3. Numbers are internally comparable and **not** comparable with\n the published table.\n- 5 designs of 5,100 never reached the grader, each carrying a single `UNK` residue that\n `rfd3_collect.py` rejects. They count as failed designs, which shifts pass rates by ≤ 0.1 %.\n","exit_code":0,"status":"completed"}}
11
+ {"type":"item.completed","item":{"id":"item_4","type":"command_execution","command":"/bin/sh -lc \"sed -n '1,240p' /workspace/baseline/rfd3-small/publish.py\"","aggregated_output":"#!/usr/bin/env python3\n\"\"\"Publish a package directory to /workspace/submission atomically.\n\n python /workspace/baseline/rfd3-small/publish.py SRC [--exclude GLOB ...] [--check]\n\nThe verifier may snapshot /workspace/submission at any moment, so the package must never be\nhalf-written. This copies SRC into a staging directory next to the target (training-only\nfiles excluded), optionally checks the harness manifest the way the verifier does, then swaps\nit in with one rename.\n\"\"\"\nimport argparse\nimport errno\nimport fnmatch\nimport os\nimport shutil\nimport sys\nimport tempfile\nfrom pathlib import Path\n\nDEFAULT_EXCLUDES = [\"__pycache__\", \"*.pyc\", \"*.ckpt.tmp\", \"optimizer.pt\", \"events.out.tfevents.*\"]\n\n\ndef ignore_for(source: Path, patterns: list[str]):\n def ignore(directory: str, names: list[str]) -> set[str]:\n relative = Path(directory).relative_to(source)\n return {name for name in names\n if any(fnmatch.fnmatch(name, p) or fnmatch.fnmatch((relative / name).as_posix(), p)\n for p in patterns)}\n return ignore\n\n\ndef swap_into(staged: Path, final: Path) -> None:\n old = final.with_name(f\".{final.name}.old-{os.getpid()}\")\n if final.exists():\n try:\n os.replace(final, old)\n except OSError as error:\n # A directory from a lower image layer cannot be renamed on overlayfs (EXDEV): move\n # its contents aside instead; the swap below is still a single rename.\n if error.errno != errno.EXDEV:\n raise\n shutil.copytree(final, old, symlinks=True)\n shutil.rmtree(final)\n os.replace(staged, final)\n shutil.rmtree(old, ignore_errors=True)\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(description=__doc__.split(\"\\n\\n\")[0])\n parser.add_argument(\"source\", type=Path)\n parser.add_argument(\"--output\", type=Path, default=Path(\"/workspace/submission\"))\n parser.add_argument(\"--exclude\", action=\"append\", default=[],\n help=f\"glob (name or path relative to SRC) to leave out; always excluded: {DEFAULT_EXCLUDES}\")\n parser.add_argument(\"--check\", action=\"store_true\",\n help=\"validate harness.json against the staged copy, as the verifier does\")\n args = parser.parse_args()\n source, final = args.source.resolve(), args.output.resolve()\n for required in (\"infer.sh\", \"harness.json\", \"README.md\"):\n if not (source / required).is_file():\n sys.exit(f\"{source} has no {required} (see /workspace/contract.md)\")\n final.parent.mkdir(parents=True, exist_ok=True)\n staged = Path(tempfile.mkdtemp(prefix=f\".{final.name}.stage-\", dir=final.parent))\n try:\n shutil.copytree(source, staged, symlinks=False, dirs_exist_ok=True,\n ignore=ignore_for(source, DEFAULT_EXCLUDES + args.exclude))\n if args.check:\n sys.path.insert(0, \"/workspace/evaluation/lib\")\n from common import validate_harness # the verifier's own check\n validate_harness(staged, Path(\"/pretrained\"))\n staged.chmod(0o755)\n swap_into(staged, final)\n except BaseException:\n shutil.rmtree(staged, ignore_errors=True)\n raise\n print(f\"published {source} -> {final}\")\n\n\nif __name__ == \"__main__\":\n main()\n","exit_code":0,"status":"completed"}}
12
+ {"type":"item.completed","item":{"id":"item_5","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/MEASUREMENTS.json'","aggregated_output":"{\n \"protocol\": \"First-ID tune target per track; two emitted designs, twenty requested per target. Missing eighteen designs remain failures. Diagnostic screen, not a full-rate estimate.\",\n \"checkpoint_steps\": 32,\n \"weight_selection\": \"online\",\n \"postprocessing\": \"input-frame restoration and residue-constrained unindexed motif assignment\",\n \"tracks\": {\n \"enzyme\": {\n \"designs_requested\": 20,\n \"designs_returned\": 2,\n \"designs_valid\": 2,\n \"designs_designable\": 0,\n \"conditioning_satisfied\": 2,\n \"failures\": {\n \"not designable (scRMSD 26.27, ipTM 0.48, PAE 8.23, motif 21.95, no sequence satisfied the criterion)\": 1,\n \"not designable (scRMSD 53.47, ipTM 0.38, PAE 9.65, motif 45.15, no sequence satisfied the criterion)\": 1\n },\n \"designs_novel\": 0,\n \"pass_rate\": 0.0,\n \"diversity\": 0.0,\n \"invalid_reason\": null\n },\n \"ppi_binder\": {\n \"conditioning_satisfied\": 2,\n \"designs_designable\": 0,\n \"designs_novel\": 0,\n \"designs_requested\": 20,\n \"designs_returned\": 2,\n \"designs_valid\": 2,\n \"diversity\": 0.0,\n \"failures\": {\n \"not designable (scRMSD 11.77, ipTM 0.21, PAE 14.18, no sequence satisfied the criterion)\": 1,\n \"not designable (scRMSD 13.47, ipTM 0.11, PAE 19.94, no sequence satisfied the criterion)\": 1\n },\n \"invalid_reason\": null,\n \"pass_rate\": 0.0\n },\n \"sm_binder\": {\n \"conditioning_satisfied\": 2,\n \"designs_designable\": 0,\n \"designs_novel\": 0,\n \"designs_requested\": 20,\n \"designs_returned\": 2,\n \"designs_valid\": 2,\n \"diversity\": 0.0,\n \"failures\": {\n \"not designable (scRMSD 83.21, ipTM 0.27, PAE 12.71, ligRMSD 127.52, no sequence satisfied the criterion)\": 1,\n \"not designable (scRMSD 83.58, ipTM 0.34, PAE 11.58, ligRMSD 38.29, no sequence satisfied the criterion)\": 1\n },\n \"invalid_reason\": null,\n \"pass_rate\": 0.0\n },\n \"unconditional\": {\n \"conditioning_satisfied\": 2,\n \"designs_designable\": 0,\n \"designs_novel\": 0,\n \"designs_requested\": 20,\n \"designs_returned\": 2,\n \"designs_valid\": 2,\n \"diversity\": 0.0,\n \"failures\": {\n \"not designable (scRMSD 10.85, ipTM 0.00, no sequence satisfied the criterion)\": 1,\n \"not designable (scRMSD 11.00, ipTM 0.00, no sequence satisfied the criterion)\": 1\n },\n \"invalid_reason\": null,\n \"pass_rate\": 0.0\n }\n }\n}\n","exit_code":0,"status":"completed"}}
13
+ {"type":"item.started","item":{"id":"item_6","type":"command_execution","command":"/bin/sh -lc \"sed -n '1,180p' /workspace/submission/README.md\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
14
+ {"type":"item.completed","item":{"id":"item_6","type":"command_execution","command":"/bin/sh -lc \"sed -n '1,180p' /workspace/submission/README.md\"","aggregated_output":"# Shared all-atom conditional diffusion\n\nRun `bash infer.sh INPUT_ROOT OUTPUT_ROOT`. The package owns all imported model\nsource and its checkpoint; it needs the image's Python dependencies and one GPU.\nNo network, training corpus, external cache, or pretrained weights are used at\ninference. The exact checkpoint digest is in `harness.json`.\n\nOne 12,445,554-parameter RFdiffusion3 network serves every track. Unconditional\nrequests supply only length. Small-molecule requests supply a bare ligand. PPI\nrequests supply a target and hotspot features, with the diffusion origin near the\nhotspots. Enzyme requests supply unindexed catalytic residues and ligand atoms;\nRFD3 chooses motif placement during all-atom diffusion. All use the same network,\nfeaturization, losses, and sampler. There are no per-track models or retrieved folds.\n\nSource derives from the mounted rfd3-small starter (Foundry b02eed6a). RF3 source\nutilities are included because a shared logging module imports them. No RF3 or\nLigandMPNN checkpoint is included or used by the generator.\n\nThe model is initialized randomly and trained in this session on fit structures\nwith the upstream all-atom EDM and sequence losses, PPI conditioning enabled,\n128-token crops, eight noise draws per structure, one structure per optimizer\nstep, a 100-step warmup, and peak learning rate 0.001. Training uses one H100.\n`training_record.json` states the actual optimizer-step count and whether online\nor moving-average weights were exported. Optimizer state is excluded.\n\n`sampling.json` records sampler settings. The initial research candidate uses 24\ndiffusion steps and one recycle to make full-suite contract replay affordable.\nThe explicit diffusion-origin translation is restored before writing each design.\nGuidepost insertion is constrained to distinct generated protein residues, fixing\nan upstream atomwise-assignment failure. Generated coordinates outside the\ninserted guideposts are preserved; unknown sequence\nhead outputs are represented as glycine backbone atoms for inverse folding.\nEach request receives its requested sample count, unless a documented sample or\nrequest error occurs. Errors are written to the output's failures.jsonl and do not\nabort the remaining batch. Ranking is neutral (0.0); no native structures are used.\n\nLimitations: the initial 32-step checkpoint is a pipeline smoke test, not a claim\nof designability or improvement over the reported reference. Contract replay and\nscientific evaluation are separate. Only the official LigandMPNN/RoseTTAFold3\ncriteria plus Foldseek novelty establish passing designs. The initial\nmeasured screen has zero passing designs on every track (two designs emitted and\ntwenty requested per target); see MEASUREMENTS.json. This is a diagnostic screen,\nnot a full-rate estimate. Early training is severely underfit.\n","exit_code":0,"status":"completed"}}
15
+ {"type":"item.started","item":{"id":"item_7","type":"command_execution","command":"/bin/sh -lc \"rg -n '240|replay|check_package' /workspace/research/NOTES.md | head -n 28\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
16
+ {"type":"item.completed","item":{"id":"item_7","type":"command_execution","command":"/bin/sh -lc \"rg -n '240|replay|check_package' /workspace/research/NOTES.md | head -n 28\"","aggregated_output":"39:The first full replay was intentionally interrupted to restart with the fix.\n43:Full replay is running before atomic initial publication. Concurrent training\n77:The 240-request replay passed all unconditional, small-molecule and PPI requests,\n84:in place; this does not rebuild the generated chain. Targeted replay covers the\n86:the required full replay.\n88:The independent length-boundary replay (40 and 400 residues for all tracks, one\n91:Targeted motif regression replay passed 4/4 requests with two valid samples each.\n92:The preceding full replay finished 232/240; all eight failures were enzyme motif\n93:assignment failures. A fresh full replay of the corrected package is running.\n134:Corrected full replay passed 240/240 tune requests, two designs each. Supplied\n171:004 (160 steps, 200 sampler steps) scored 0/20 on every track, 2 emitted each; no improvement over 24 steps. PPI RMSD 5.88/infinite with high PAE; enzyme both raw ligand clashes. 002 training finished all 928 steps and saved epoch-0007. The running shell reported a trailing parse error because its script was edited while running; checkpoint saved normally, current script passes bash -n. Exported 005 online928, sampler24, and replayed smoke4/4; official screen now running.\n306:Queued matched ONLINE 5,024-step screens 025-shortcrop5024 and 026-fullcrop5024 in session 4328, log 025-026-workflow.log. They wait for each epoch0039 saved marker, use the same 200-step sampler and the existing two-design/four-track panel, and never publish automatically. Training orchestration remains session 48099. Required full 240-request replay still precedes any future publication.\n346:The slow fit8er8 transform was a quadratic missing-central-atom loop in util_transforms.py, not RDKit or CIF parsing. Replaced with grouped reduction/expansion preserving the original fast path.34equivalence cases against pinned baseline matched retained atom IDs and coordinates; exact captured RNG/sample replay processed151360->59200atoms in~.11s, full dataset item5.318s. Both arms resumed their epoch36/global4640states with the fixed source and traced loader, active session76756. Old processes stopped cleanly; original orchestration48099exit1 and firstshortrecovery44899exit143 are intentional historical interruptions. New resultswillbe023-024-filter-recovery-results.json. Both realtrainers completed formerlystuck8er8 in4.55/4.93s.025/026queued screenpaths unchanged.\n430:Reference source defaults use2400examples/epoch,3accumulation passes and16noise draws/example; current research blocks use128examples/epoch,1pass and8draws. Epoch labels are not comparable. The5024-step research parent has5024training examples and40192noise draws in its optimizer history (examples can repeat structures). These reference defaults do NOT establish the actual exposure used for the author's accepted results; no baseline reproduction performed. Reporttraining-exposure-context.json. This supports planning a sustained continuation after recipe selection rather than treating a short pilot as a converged model.\n434:All old processes were confirmed absent; H100 idle. Operator reported158078researchsecondsremaining. Credentials were not inspected. 030compact saved6048/epoch47; final checkpoint hasfiniteweights, Adamcounter6048 andLR.001, SHA04a4d066842bc60f18fb9a6f163153d11b71a7e7bf01d6dade5ff8c26ffaa1d5. Exitstatuswasnotpersisted. 029control resumes5792/epoch45->6048 innewsession27677; preservedcheckpointSHA507b9804200f2fa8d6a8051181830dcdcc9b85b1672b7839b936f4804380e458. Onlycontrolgetsnewworker-RNGreset; unsavedupdatesreplay. Record029-030-second-pause-recovery.json.\n452:Operator reported157031researchseconds remaining. Old research processes confirmed absent, H100 idle; credentials not inspected. Both034/035 were interrupted at epoch48/batch100 before any new checkpoint. Restarted both from original verified6048states with their exact recorded commands, preserving matched loader reset and replaying unsaved updates. Session5207; recover_third_pause.py train;034-035-third-pause-recovery.json. Completed029/030 and denoising diagnostics are retained.\n705:Prepared a separate research ablation of the SAME generator: one frozen inverse-fold/refold projection, shared by allfourtracks. Session32255 runs run_refinement_probe.py, waits041summary, then takes official-scoring.lock so it cannot overlap another instrument job. Name046-shared-refold9120, log046-workflow.log. It holds041's eight generated seeds fixed, uses the first of4MPNN sequences(T.1,seed37), oneRF3prediction at independent seed20261024, and restores the supplied conditioning frame. Failed/invalid refolds fall back to the unchanged seed. Then contracts and the UNCHANGED official four-track score run with20requested/target and ALLfit novelty. It is a retained-output ablation, not a published/replayable hybrid package.\n709:Assetprovenance inrefinement-asset-proposal.json includes exactSHA256,licenses androles forRF3 andbothMPNN checkpoints. /pretrained remainsEMPTY. Using /assets is permitted for this research probe, but a hybrid CANNOTbe published under the current asset store. No weights copied/mounted and no harness/submission changed. Any future hybrid needs declared assets in/pretrained, live generator+refiner packaging, full240request replay, thenatomicpublication. Evaluation against the sameRF3checkpoint can inflate in-silico consistency; keep this recorded.\n759:Prepared but NOTexecuted: proposals/hybrid_design.py andbuild_hybrid_candidate.py. Theywould package livegenerationthenonepersistentfrozenrefiner,explicit/pretrainedassetsbydigest,noevaluationimports, no weightcopies/downloads, independentrequestfailurelogging/fallback. Builderrequires completedpositivefour-trackprobeandportableaudit; itdoesnotpublish orclaimfullreplay. Noassetsrequested/mounted yet, no draftcandidatebuilt. Fullcount054 and all240requestpackage replay remainnecessary before anypublicationdecision.\n789:Research asset adapter does NOT replace mandatory infer.sh full-tune replay.\n807:This is fresh live generator+refiner research, not /pretrained deployment replay.\n831:and mandatory full actual infer.sh replay. Operator question remains unanswered.\n866:records/31screens. Still research /assets adapter, NOTmandatorydeploymentreplay;\n984:CPU source/interface audit passed on all4tracks and repeated exactly: fixed supplied context, all preexisting feature tensors, global RNG and ground-truth metadata unchanged. Initial unindexed enzyme guideposts remain separate. Source hashes are frozen in060plan. Geometry-only audit spans40..400residues with correct alpha phi/psi and closed loops; none of this is a designability claim. 060runs actualinfer.sh on8samples, then officialall4score. Noautomaticpublication; anypositive needsbroadermeasurement/full240replay.\n998:Started audit_helical_tune_coverage.py(session65429), one procedural initialization perrequest acrossall240tune requests, CPUonly/no denoiser. Current83/240,zeroerrors. Purpose is catch unsupportedlength/context/layout cases whileofficialGPUscoringruns. This cannot replace actualinfer.sh fullreplay ordesignability. Perrequestjournal andfinalsummary retained separately. Existinghelical-prior-{length}-audit.npz geometry files preceded theCBvirtual-padding adjustment; their realbackbone atoms are unchanged. Finalinitializedinputs/sourcehashes are audited byhelical-initialization-audit.json and frozenin060plan.\n1006:The full CPU initialization sweep completed240/240 requests,0errors (session65429closed0), reporthelical-tune-initialization-coverage-summary.json; source hashes helical_prior.py762d51f1e9e42a3d471b09ccc82000cbf4e1478574f7885ed9868f18769800be andhelical_initialization.py41f32bbf4843a6fa79afd63259ed8f1d90191cd7897c55e910c4abb7307f7cbb. JournalSHAb32d691ea521d714975e7b8a386b1bc9c2355e874c0183439334320e8e8d0fea. This is initializationcoverage only, not learnedoutputvalidity/refolding/fullpackage replay. Largest input5035atoms (PPI4nee,design142). No deploymentchange.\n1016:Exportauditpassed807shadowtensors: exactequalitytosourceEMA, online/shadowprefixesaliasONEselectedstorage, finiteweights,nooptimizerstate. Comparedsource043packagechangesareonlygenerator.ckpt,harness.json,training_record.json,README.md,MEASUREMENTS.json. Docsnowdescribethisactualcandidate ratherthancopiedinitial32-stepstate. LearnedcomponentSHA: 1f49387a77968081b613bcb7483802f180e21663ae669fb71b226ebf551caeb4. Planfreezesallfiles. Driverwillscoreall4tracks, write043-061-late-ema-result.json andrefreshindex, neverpublish. Fullactualtune replay remainsrequiredifselected.\n1018:Reference source reread confirmsdefault2400examples/epoch,16noise draws and3accumulationpasses; currentstudy16examples/epoch,8draws,1structure/update. Actualauthorreportexposurecannotbeinferredfromdefaultswithoutoperatorinvocation/reproductionlogs(whicharenotsupplied). Thisrepeats earliertraining-exposure-context.json conclusion; no baseline retrainingperformed. Do notcompareepochnumbersorclaimconvergencefromshortzero-passscreens.\n","exit_code":0,"status":"completed"}}
17
+ {"type":"item.started","item":{"id":"item_8","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nimport json\nfrom pathlib import Path\nr=Path('/workspace/research/experiments')\np=r/'094-teacher-data43280-recovery2-workflow.json';w=json.loads(p.read_text())\nprint(json.dumps({'workflow_error':w.get('error'),'finished_utc':w.get('finished_utc'),'stages':{k:{x:v.get(x) for x in ['returncode','started_utc','finished_utc']} for k,v in w['stages'].items()}},indent=2))\nfor name in ['095-teacher-data-control43280','096-teacher-data-control43280-broader','097-teacher-data43280','098-teacher-data43280-broader']:\n for p in sorted(r.glob(name+'*summary*')):\n print(str(p));print(p.read_text()[:16000])\nPY\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
18
+ {"type":"item.completed","item":{"id":"item_8","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nimport json\nfrom pathlib import Path\nr=Path('/workspace/research/experiments')\np=r/'094-teacher-data43280-recovery2-workflow.json';w=json.loads(p.read_text())\nprint(json.dumps({'workflow_error':w.get('error'),'finished_utc':w.get('finished_utc'),'stages':{k:{x:v.get(x) for x in ['returncode','started_utc','finished_utc']} for k,v in w['stages'].items()}},indent=2))\nfor name in ['095-teacher-data-control43280','096-teacher-data-control43280-broader','097-teacher-data43280','098-teacher-data43280-broader']:\n for p in sorted(r.glob(name+'*summary*')):\n print(str(p));print(p.read_text()[:16000])\nPY\"","aggregated_output":"{\n \"workflow_error\": \"KeyboardInterrupt('Workflow received signal 15')\",\n \"finished_utc\": null,\n \"stages\": {\n \"training\": {\n \"returncode\": null,\n \"started_utc\": \"2026-10-26T14:49:10.254525+00:00\",\n \"finished_utc\": null\n }\n }\n}\n","exit_code":0,"status":"completed"}}
19
+ {"type":"item.started","item":{"id":"item_9","type":"command_execution","command":"/bin/sh -lc \"sed -n '110,148p' /workspace/research/NOTES.md\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
20
+ {"type":"item.started","item":{"id":"item_10","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/infer.sh'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
21
+ {"type":"item.completed","item":{"id":"item_9","type":"command_execution","command":"/bin/sh -lc \"sed -n '110,148p' /workspace/research/NOTES.md\"","aggregated_output":"\n## Experiment 003: expose structured-fold conditioning at inference\n\nSame 160-step checkpoint, 24 diffusion steps, one recycle, and seed as experiment\n002 probe. The only inference change is `is_non_loopy: true` on every track.\nThis feature is supervised on 99% of training examples, while the omitted\ninference setting is represented by zero. All four tracks will be scored on the\nsame first-ID panel. This is independent of the pending bare-ligand training\nchange; the ongoing long training run remains on experiment 001's recipe.\n\nScoring helper now logs unmodified per-design and per-track verdicts as they\nfinish. Future invocations reuse an official Foldseek database of the immutable\nfit corpus, keyed by corpus_entries.json and the Foldseek executable digests.\nOnly resource use and logging change; the scoring functions, search flags,\nthresholds, requested-design denominators, and all novelty criteria are unchanged.\nThis cache is development-only and is not used by or copied into the package.\n\nCorrected-matcher 32-step enzyme rescore also finished 0/20 (0/2 emitted),\ndiversity 0. Motif RMSDs were 21.95 and 45.15 A. Current candidate measurements\ncombine that enzyme rescore with the unaffected three tracks from the first\nofficial screen, and are recorded explicitly in shared_rfd3/MEASUREMENTS.json.\n\n## First publication, 03:27 UTC\n\nCorrected full replay passed 240/240 tune requests, two designs each. Supplied\npublish.py --check atomically installed the 32-step package at /workspace/submission.\nPost-publication harness verification passed. Checkpoint sha256:\ne79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779.\nThis is a validated initial candidate; all four diagnostic pass rates remain zero.\nResearch continues with the live longer training and isolated non-loopy comparison.\n\n## Experiment 004: resolve sampler discretization\n\nSame 160-step online checkpoint and original omitted non-loopy flag as experiment\n002 probe. Change only diffusion timesteps 24 -> 200; recycling remains 1 and\nstep_scale remains 1.5. Early atom geometry may reflect a coarse sampler as well\nas undertraining. Generate the same four-track panel and score every affected\ntrack before drawing conclusions. The published package stays unchanged.\n\n","exit_code":0,"status":"completed"}}
22
+ {"type":"item.completed","item":{"id":"item_10","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/infer.sh'","aggregated_output":"#!/usr/bin/env bash\nset -euo pipefail\nif [[ $# -ne 2 ]]; then\n echo 'usage: infer.sh INPUT_ROOT OUTPUT_ROOT' >&2\n exit 2\nfi\nhere=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nexport PROJECT_ROOT=\"$here/rfd3\"\nexport PYTHONPATH=\"$here:$here/rfd3/src:$here/rfd3/models/rfd3/src:$here/rfd3/models/rf3/src\"\nexport OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1\nexport PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True\nexec python \"$here/design.py\" \"$1\" \"$2\"\n","exit_code":0,"status":"completed"}}
23
+ {"type":"item.started","item":{"id":"item_11","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nfrom pathlib import Path\nimport json\nfor s in ['rf3/rf3_foundry_01_24_latest_remapped.ckpt','ligandmpnn_params/ligandmpnn_v_32_010_25.pt','ligandmpnn_params/proteinmpnn_v_48_020.pt']:\n print(json.dumps({'asset_id':s,'present':(Path('/pretrained')/s).is_file()}))\np=Path('/workspace/submission')\nprint('files',sum(1 for f in p.rglob('*') if f.is_file()))\nprint('bytes',sum(f.stat().st_size for f in p.rglob('*') if f.is_file()))\nprint('symlinks',[str(f.relative_to(p)) for f in p.rglob('*') if f.is_symlink()])\nPY\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
24
+ {"type":"item.completed","item":{"id":"item_11","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nfrom pathlib import Path\nimport json\nfor s in ['rf3/rf3_foundry_01_24_latest_remapped.ckpt','ligandmpnn_params/ligandmpnn_v_32_010_25.pt','ligandmpnn_params/proteinmpnn_v_48_020.pt']:\n print(json.dumps({'asset_id':s,'present':(Path('/pretrained')/s).is_file()}))\np=Path('/workspace/submission')\nprint('files',sum(1 for f in p.rglob('*') if f.is_file()))\nprint('bytes',sum(f.stat().st_size for f in p.rglob('*') if f.is_file()))\nprint('symlinks',[str(f.relative_to(p)) for f in p.rglob('*') if f.is_symlink()])\nPY\"","aggregated_output":"{\"asset_id\": \"rf3/rf3_foundry_01_24_latest_remapped.ckpt\", \"present\": false}\n{\"asset_id\": \"ligandmpnn_params/ligandmpnn_v_32_010_25.pt\", \"present\": false}\n{\"asset_id\": \"ligandmpnn_params/proteinmpnn_v_48_020.pt\", \"present\": false}\nfiles 309\nbytes 52329451\nsymlinks []\n","exit_code":0,"status":"completed"}}
25
+ {"type":"item.started","item":{"id":"item_12","type":"command_execution","command":"/bin/sh -lc \"rg --files --maxdepth 2 /workspace/research | rg '(package.*check|replay|check.*package|publication|publish)' | head -n 65\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
26
+ {"type":"item.completed","item":{"id":"item_12","type":"command_execution","command":"/bin/sh -lc \"rg --files --maxdepth 2 /workspace/research | rg '(package.*check|replay|check.*package|publication|publish)' | head -n 65\"","aggregated_output":"/workspace/research/replay_recorded_verdicts.py\n/workspace/research/shared_rfd3/publish.py\n/workspace/research/__pycache__/replay_recorded_verdicts.cpython-311.pyc\n/workspace/research/experiments/054-071-live-replay-result.json\n/workspace/research/experiments/001-publish.log\n","exit_code":0,"status":"completed"}}
27
+ {"type":"item.completed","item":{"id":"item_13","type":"agent_message","text":"The saved workflow confirms the teacher experiment was interrupted before scoring, so it provides no measured replacement. I’m keeping the previously replayed model and correcting the package’s results document to report its own zero-pass development screen clearly, separately from the author’s baseline results.\n"}}
28
+ {"type":"item.started","item":{"id":"item_14","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/training_record.json'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
29
+ {"type":"item.completed","item":{"id":"item_14","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/submission/training_record.json'","aggregated_output":"{\n \"optimizer_steps\": 32,\n \"epoch\": 0,\n \"weight_selection\": \"online\",\n \"parameters\": 12445554,\n \"training_corpus\": \"fit/structures\",\n \"pretrained_weights\": false,\n \"checkpoint_sha256\": \"e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779\"\n}\n","exit_code":0,"status":"completed"}}
30
+ {"type":"item.started","item":{"id":"item_15","type":"command_execution","command":"/bin/sh -lc \"rg -n 'workspace/research|/assets|/data|pretrained|torch.load|checkpoint' /workspace/submission/design.py /workspace/submission/shared_engine.py\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
31
+ {"type":"item.completed","item":{"id":"item_15","type":"command_execution","command":"/bin/sh -lc \"rg -n 'workspace/research|/assets|/data|pretrained|torch.load|checkpoint' /workspace/submission/design.py /workspace/submission/shared_engine.py\"","aggregated_output":"rg: /workspace/submission/shared_engine.py: No such file or directory (os error 2)\n","exit_code":2,"status":"failed"}}
32
+ {"type":"item.started","item":{"id":"item_16","type":"command_execution","command":"/bin/sh -lc \"rg --files --maxdepth 1 /workspace/research/experiments | rg '/001|check|validat' | head -n 70\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
33
+ {"type":"item.completed","item":{"id":"item_16","type":"command_execution","command":"/bin/sh -lc \"rg --files --maxdepth 1 /workspace/research/experiments | rg '/001|check|validat' | head -n 70\"","aggregated_output":"/workspace/research/experiments/whole-crop-hydra-validation.log\n/workspace/research/experiments/023-checkpoint-stability-audit.json\n/workspace/research/experiments/export_checkpoint.py-failure.json\n/workspace/research/experiments/central-filter-validation.log\n/workspace/research/experiments/lr-resume-validation.log\n/workspace/research/experiments/059-071-live-checkpoint-fullcount-result.json\n/workspace/research/experiments/compact-assembly-config-validation.json\n/workspace/research/experiments/central-filter-validation.json\n/workspace/research/experiments/001-score.log\n/workspace/research/experiments/export_checkpoint.py-first-audit.json\n/workspace/research/experiments/034-035-short-epoch-validation.json\n/workspace/research/experiments/report-comparison-validation-036-037.json\n/workspace/research/experiments/001-smoke.log\n/workspace/research/experiments/001-motif-fixed.log\n/workspace/research/experiments/001-frame-infer.log\n/workspace/research/experiments/001-publish.log\n/workspace/research/experiments/001-contract.log\n/workspace/research/experiments/spec-check.log\n/workspace/research/experiments/001-boundaries.log\n/workspace/research/experiments/lr-resume-validation.json\n/workspace/research/experiments/001-current-enzyme-score.log\n/workspace/research/experiments/001-infer.log\n/workspace/research/experiments/001-contract-final.log\n/workspace/research/experiments/lr-resume-validation.ckpt\n/workspace/research/experiments/001-contract-fixed.log\n","exit_code":0,"status":"completed"}}
34
+ {"type":"item.started","item":{"id":"item_17","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/research/experiments/001-publish.log'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
35
+ {"type":"item.started","item":{"id":"item_18","type":"command_execution","command":"/bin/sh -lc 'tail -n 12 /workspace/research/experiments/001-contract-final.log'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
36
+ {"type":"item.completed","item":{"id":"item_17","type":"command_execution","command":"/bin/sh -lc 'cat /workspace/research/experiments/001-publish.log'","aggregated_output":"published /run-state/workspace/research/shared_rfd3 -> /workspace/submission\n","exit_code":0,"status":"completed"}}
37
+ {"type":"item.completed","item":{"id":"item_18","type":"command_execution","command":"/bin/sh -lc 'tail -n 12 /workspace/research/experiments/001-contract-final.log'","aggregated_output":"03:26:57 INFO rfd3.engine: [rank: 0] Finished inference batch in 2.57 seconds.\nSERVED enzyme enzyme-5k18-0057: 2/2 in 3.3s\n03:26:58 WARNING atomworks.io: We can't fix formal charges without building from templates, as we need to know the true number of hydrogens bonded to a given atom, not the inferred number. This may lead to occasional inaccuracies after adding inter-residue bonds. To avoid this and fix formal charges, set `add_missing_atoms = True`.\n03:26:58 WARNING atomworks.io: The `extra_fields` argument will be ignored if there is no CIF file input.\n03:27:01 INFO rfd3.engine: [rank: 0] Finished inference batch in 2.44 seconds.\nSERVED enzyme enzyme-1v0c-0058: 2/2 in 3.2s\n03:27:01 WARNING atomworks.io: We can't fix formal charges without building from templates, as we need to know the true number of hydrogens bonded to a given atom, not the inferred number. This may lead to occasional inaccuracies after adding inter-residue bonds. To avoid this and fix formal charges, set `add_missing_atoms = True`.\n03:27:01 WARNING atomworks.io: The `extra_fields` argument will be ignored if there is no CIF file input.\n03:27:01 WARNING atomworks.ml.transforms.rdkit_utils: Initial conformer generation based on distance geometry failed. Successful: 0. Falling back to generating a conformer starting from random coordinates.\n03:27:04 INFO rfd3.engine: [rank: 0] Finished inference batch in 2.49 seconds.\nSERVED enzyme enzyme-5k04-0059: 2/2 in 3.3s\n240/240 requests have a valid design\n","exit_code":0,"status":"completed"}}
38
+ {"type":"item.started","item":{"id":"item_19","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nfrom pathlib import Path\nfrom datetime import datetime,timezone\nimport hashlib,json,shutil\nsrc=Path('/workspace/submission'); root=Path('/workspace/finalization'); dst=root/'selected-package'\nroot.mkdir(parents=True,exist_ok=True)\nassert not dst.exists()\ndef sha(p):\n h=hashlib.sha256()\n with p.open('rb') as f:\n for b in iter(lambda:f.read(1<<20),b''):h.update(b)\n return h.hexdigest()\ndef inventory(p):\n return {str(f.relative_to(p)):sha(f) for f in sorted(p.rglob('*')) if f.is_file() and '__pycache__' not in f.parts and f.suffix\"'!='\"'.pyc'}\nbefore=inventory(src)\nassert not any(p.is_symlink() for p in src.rglob('*'))\nassert before['generator.ckpt']=='e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779'\nshutil.copytree(src,dst,ignore=shutil.ignore_patterns('__pycache__','*.pyc'))\nassert inventory(dst)==before\nreplay=Path('/workspace/research/experiments/001-contract-final.log')\nlog=replay.read_text()\nassert '240/240 requests have a valid design' in log\nserved=[line for line in log.splitlines() if line.startswith('SERVED ')]\nassert len(served)==240 and all(': 2/2 ' in line for line in served)\n(dst/'RESULTS.md').write_text('''# Results for the submitted package\n\nThis package contains the 32-update, 12,445,554-parameter shared RFdiffusion3 model\nidentified in harness.json. These are its own development measurements.\n\n| Track | Pass rate | Diversity | Returned / requested |\n|---|---:|---:|---:|\n| unconditional | 0/20 | 0 | 2/20 |\n| sm_binder | 0/20 | 0 | 2/20 |\n| ppi_binder | 0/20 | 0 | 2/20 |\n| enzyme | 0/20 | 0 | 2/20 |\n\nEach row uses the first-ID tune target for that track. All eight emitted structures\nwere contract-valid, but none passed designability. The eighteen missing designs\nper target remain in the denominator. This small diagnostic screen is not a\nfull-output pass-rate estimate. MEASUREMENTS.json retains the detailed results.\n\nThe existing full check_package.py replay served all 240 tune requests with two\ndesigns each and reported 240/240 requests with a valid design. Contract replay\nestablishes invocation and output validity; it does not establish designability.\n\nLater completed deployable experiments did not demonstrate a pass-rate improvement.\nThe positive research hybrids require pretrained inference assets that are absent\nfrom /pretrained and were never fully replayed for deployment. The final teacher-data\ncontinuation was interrupted before its registered evaluations. None replaces this\npreviously replayed package during finalization.\n\nNo inference, evaluation, simulation or training was run in the submission-only\nwindow. Only documentation was updated; model weights, inference source, sampler\nand harness are unchanged. FINALIZATION.json records static verification and the\nexisting replay evidence. Reported author-baseline numbers are not results of this\nsubmitted checkpoint.\n''')\np=dst/'README.md'\np.write_text(p.read_text()+'''\nFinal selection: this previously replayed package is retained using existing\nresearch results. Finalization changed documentation only. No new training,\ninference or evaluation was performed; see RESULTS.md and FINALIZATION.json.\n''')\nafter=inventory(dst)\nchanged=sorted(k for k in before if before[k]\"'!=after[k])\nassert changed==['\"'README.md','RESULTS.md']\nrecord={'utc':datetime.now(timezone.utc).isoformat(),'selected_kind':'trained_generator','checkpoint_sha256':before['generator.ckpt'],'checkpoint_optimizer_steps':32,'selection':'Retain the existing fully replayed portable package; no measured stronger deployable replacement is available.','scientific_method_changed':False,'weights_runtime_sampler_harness_unchanged':True,'changed_existing_files':changed,'new_training_inference_evaluations_simulations':0,'existing_replay':{'source':'research/experiments/001-contract-final.log','sha256':sha(replay),'requests':240,'served_two_designs_each':240,'valid_requests':240,'final_line':'240/240 requests have a valid design'},'existing_measurements_sha256':before['MEASUREMENTS.json'],'source_package_files_sha256':before,'finalization_policy':'Reuse existing replay evidence for unchanged scientific code and weights; current submission-only instruction prohibits a new replay.','pretrained_assets':[]}\n(dst/'FINALIZATION.json').write_text(json.dumps(record,indent=2)+'\\\\n')\n(root/'selected-package-files.json').write_text(json.dumps(inventory(dst),indent=2)+'\\\\n')\nprint(json.dumps({'staged':str(dst),'files':len(inventory(dst)),'changed_existing_files':changed,'checkpoint_sha256':before['generator.ckpt'],'existing_replay_valid_requests':240}))\nPY\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
39
+ {"type":"item.completed","item":{"id":"item_19","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nfrom pathlib import Path\nfrom datetime import datetime,timezone\nimport hashlib,json,shutil\nsrc=Path('/workspace/submission'); root=Path('/workspace/finalization'); dst=root/'selected-package'\nroot.mkdir(parents=True,exist_ok=True)\nassert not dst.exists()\ndef sha(p):\n h=hashlib.sha256()\n with p.open('rb') as f:\n for b in iter(lambda:f.read(1<<20),b''):h.update(b)\n return h.hexdigest()\ndef inventory(p):\n return {str(f.relative_to(p)):sha(f) for f in sorted(p.rglob('*')) if f.is_file() and '__pycache__' not in f.parts and f.suffix\"'!='\"'.pyc'}\nbefore=inventory(src)\nassert not any(p.is_symlink() for p in src.rglob('*'))\nassert before['generator.ckpt']=='e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779'\nshutil.copytree(src,dst,ignore=shutil.ignore_patterns('__pycache__','*.pyc'))\nassert inventory(dst)==before\nreplay=Path('/workspace/research/experiments/001-contract-final.log')\nlog=replay.read_text()\nassert '240/240 requests have a valid design' in log\nserved=[line for line in log.splitlines() if line.startswith('SERVED ')]\nassert len(served)==240 and all(': 2/2 ' in line for line in served)\n(dst/'RESULTS.md').write_text('''# Results for the submitted package\n\nThis package contains the 32-update, 12,445,554-parameter shared RFdiffusion3 model\nidentified in harness.json. These are its own development measurements.\n\n| Track | Pass rate | Diversity | Returned / requested |\n|---|---:|---:|---:|\n| unconditional | 0/20 | 0 | 2/20 |\n| sm_binder | 0/20 | 0 | 2/20 |\n| ppi_binder | 0/20 | 0 | 2/20 |\n| enzyme | 0/20 | 0 | 2/20 |\n\nEach row uses the first-ID tune target for that track. All eight emitted structures\nwere contract-valid, but none passed designability. The eighteen missing designs\nper target remain in the denominator. This small diagnostic screen is not a\nfull-output pass-rate estimate. MEASUREMENTS.json retains the detailed results.\n\nThe existing full check_package.py replay served all 240 tune requests with two\ndesigns each and reported 240/240 requests with a valid design. Contract replay\nestablishes invocation and output validity; it does not establish designability.\n\nLater completed deployable experiments did not demonstrate a pass-rate improvement.\nThe positive research hybrids require pretrained inference assets that are absent\nfrom /pretrained and were never fully replayed for deployment. The final teacher-data\ncontinuation was interrupted before its registered evaluations. None replaces this\npreviously replayed package during finalization.\n\nNo inference, evaluation, simulation or training was run in the submission-only\nwindow. Only documentation was updated; model weights, inference source, sampler\nand harness are unchanged. FINALIZATION.json records static verification and the\nexisting replay evidence. Reported author-baseline numbers are not results of this\nsubmitted checkpoint.\n''')\np=dst/'README.md'\np.write_text(p.read_text()+'''\nFinal selection: this previously replayed package is retained using existing\nresearch results. Finalization changed documentation only. No new training,\ninference or evaluation was performed; see RESULTS.md and FINALIZATION.json.\n''')\nafter=inventory(dst)\nchanged=sorted(k for k in before if before[k]\"'!=after[k])\nassert changed==['\"'README.md','RESULTS.md']\nrecord={'utc':datetime.now(timezone.utc).isoformat(),'selected_kind':'trained_generator','checkpoint_sha256':before['generator.ckpt'],'checkpoint_optimizer_steps':32,'selection':'Retain the existing fully replayed portable package; no measured stronger deployable replacement is available.','scientific_method_changed':False,'weights_runtime_sampler_harness_unchanged':True,'changed_existing_files':changed,'new_training_inference_evaluations_simulations':0,'existing_replay':{'source':'research/experiments/001-contract-final.log','sha256':sha(replay),'requests':240,'served_two_designs_each':240,'valid_requests':240,'final_line':'240/240 requests have a valid design'},'existing_measurements_sha256':before['MEASUREMENTS.json'],'source_package_files_sha256':before,'finalization_policy':'Reuse existing replay evidence for unchanged scientific code and weights; current submission-only instruction prohibits a new replay.','pretrained_assets':[]}\n(dst/'FINALIZATION.json').write_text(json.dumps(record,indent=2)+'\\\\n')\n(root/'selected-package-files.json').write_text(json.dumps(inventory(dst),indent=2)+'\\\\n')\nprint(json.dumps({'staged':str(dst),'files':len(inventory(dst)),'changed_existing_files':changed,'checkpoint_sha256':before['generator.ckpt'],'existing_replay_valid_requests':240}))\nPY\"","aggregated_output":"{\"staged\": \"/workspace/finalization/selected-package\", \"files\": 310, \"changed_existing_files\": [\"README.md\", \"RESULTS.md\"], \"checkpoint_sha256\": \"e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779\", \"existing_replay_valid_requests\": 240}\n","exit_code":0,"status":"completed"}}
40
+ {"type":"item.started","item":{"id":"item_20","type":"command_execution","command":"/bin/sh -lc 'python /workspace/baseline/rfd3-small/publish.py /workspace/finalization/selected-package --check'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
41
+ {"type":"item.completed","item":{"id":"item_20","type":"command_execution","command":"/bin/sh -lc 'python /workspace/baseline/rfd3-small/publish.py /workspace/finalization/selected-package --check'","aggregated_output":"published /workspace/finalization/selected-package -> /workspace/submission\n","exit_code":0,"status":"completed"}}
42
+ {"type":"item.completed","item":{"id":"item_21","type":"agent_message","text":"The package has been atomically published to `/workspace/submission`. Its weights, inference code, sampler, and harness are unchanged from the package that passed the 240-request replay. I’m checking the published file digests now; no new inference or evaluation was run.\n"}}
43
+ {"type":"item.started","item":{"id":"item_22","type":"command_execution","command":"/bin/sh -lc 'bash -n /workspace/submission/infer.sh'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
44
+ {"type":"item.completed","item":{"id":"item_22","type":"command_execution","command":"/bin/sh -lc 'bash -n /workspace/submission/infer.sh'","aggregated_output":"","exit_code":0,"status":"completed"}}
45
+ {"type":"item.started","item":{"id":"item_23","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nfrom pathlib import Path\nimport hashlib,json,stat\nroot=Path('/workspace/submission')\nexpected=json.loads(Path('/workspace/finalization/selected-package-files.json').read_text())\ndef sha(p):\n h=hashlib.sha256()\n with p.open('rb') as f:\n for b in iter(lambda:f.read(1<<20),b''):h.update(b)\n return h.hexdigest()\nactual={str(p.relative_to(root)):sha(p) for p in sorted(root.rglob('*')) if p.is_file() and '__pycache__' not in p.parts and p.suffix\"'!='\"'.pyc'}\nassert actual==expected\nassert not any(p.is_symlink() for p in root.rglob('*'))\nassert all(p.stat().st_mode & stat.S_IROTH for p in root.rglob('*') if p.is_file())\nassert all(p.stat().st_mode & stat.S_IXOTH for p in [root,*[q for q in root.rglob('*') if q.is_dir()]])\nh=json.loads((root/'harness.json').read_text())\nassert h['pretrained_assets']==[]\nassert actual[h['learned_components'][0]['path']]==h['learned_components'][0]['sha256']\nreport={'published_package':'/workspace/submission','files_verified':len(actual),'static_checks':'passed','weights_runtime_sampler_harness_unchanged':True,'new_experiments':0,'checkpoint_sha256':h['learned_components'][0]['sha256']}\nPath('/workspace/finalization/publication-verification.json').write_text(json.dumps(report,indent=2)+'\\\\n')\nprint(json.dumps(report))\nPY\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
46
+ {"type":"item.completed","item":{"id":"item_23","type":"command_execution","command":"/bin/sh -lc \"python - <<'PY'\nfrom pathlib import Path\nimport hashlib,json,stat\nroot=Path('/workspace/submission')\nexpected=json.loads(Path('/workspace/finalization/selected-package-files.json').read_text())\ndef sha(p):\n h=hashlib.sha256()\n with p.open('rb') as f:\n for b in iter(lambda:f.read(1<<20),b''):h.update(b)\n return h.hexdigest()\nactual={str(p.relative_to(root)):sha(p) for p in sorted(root.rglob('*')) if p.is_file() and '__pycache__' not in p.parts and p.suffix\"'!='\"'.pyc'}\nassert actual==expected\nassert not any(p.is_symlink() for p in root.rglob('*'))\nassert all(p.stat().st_mode & stat.S_IROTH for p in root.rglob('*') if p.is_file())\nassert all(p.stat().st_mode & stat.S_IXOTH for p in [root,*[q for q in root.rglob('*') if q.is_dir()]])\nh=json.loads((root/'harness.json').read_text())\nassert h['pretrained_assets']==[]\nassert actual[h['learned_components'][0]['path']]==h['learned_components'][0]['sha256']\nreport={'published_package':'/workspace/submission','files_verified':len(actual),'static_checks':'passed','weights_runtime_sampler_harness_unchanged':True,'new_experiments':0,'checkpoint_sha256':h['learned_components'][0]['sha256']}\nPath('/workspace/finalization/publication-verification.json').write_text(json.dumps(report,indent=2)+'\\\\n')\nprint(json.dumps(report))\nPY\"","aggregated_output":"{\"published_package\": \"/workspace/submission\", \"files_verified\": 310, \"static_checks\": \"passed\", \"weights_runtime_sampler_harness_unchanged\": true, \"new_experiments\": 0, \"checkpoint_sha256\": \"e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779\"}\n","exit_code":0,"status":"completed"}}
47
+ {"type":"item.completed","item":{"id":"item_24","type":"agent_message","text":"Published [the package](/workspace/submission/README.md) atomically. Static checks passed; the existing replay validated all 240 requests. No new experiments were run.\n\nThe retained development screen recorded zero passing designs across all four tracks, documented in [RESULTS.md](/workspace/submission/RESULTS.md)."}}
48
+ {"type":"turn.completed","usage":{"input_tokens":734107806,"cached_input_tokens":722095327,"cache_write_input_tokens":11692426,"output_tokens":3590214,"reasoning_output_tokens":1972465}}
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/index.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/codex.stderr ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-10-22T03:02:48.457954Z ERROR codex_core::tools::router: error=apply_patch verification failed: invalid patch: multiple operations target /workspace/research/shared_rfd3/infer.sh
2
+ 2026-10-22T03:04:10.649595Z ERROR codex_core::tools::router: error=apply_patch verification failed: invalid patch: multiple operations target /workspace/research/shared_rfd3/README.md
3
+ 2026-10-22T03:27:49.631184Z ERROR codex_core::tools::router: error=apply_patch verification failed: Failed to find expected lines in /workspace/research/NOTES.md:
4
+ enzyme result with the three unaffected initial track results. This is a small
5
+ 2026-10-22T03:35:19.900912Z ERROR codex_core::tools::router: error=apply_patch verification failed: Failed to find expected lines in /workspace/research/NOTES.md:
6
+ More denoising steps alone
7
+ 2026-10-22T05:02:12.308861Z ERROR codex_models_manager::manager: failed to refresh available models: request timed out
8
+ 2026-10-24T22:45:04.291445Z ERROR codex_models_manager::manager: failed to refresh available models: request timed out
9
+ 2026-10-25T21:01:47.057633Z ERROR codex_models_manager::manager: failed to refresh available models: request timed out
10
+ 2026-10-26T03:34:26.766771Z ERROR codex_core::util: Custom tool call output is missing for call id: call_iGwMB7s1JRqPB4GvUyyVBt33
11
+ 2026-10-26T03:34:37.312604Z ERROR codex_core::tools::router: error=write_stdin failed: Unknown process id 7914
12
+ 2026-10-26T03:34:37.313294Z ERROR codex_core::tools::router: error=write_stdin failed: Unknown process id 5098
13
+ 2026-10-26T03:34:37.570868Z ERROR codex_core::util: Custom tool call output is missing for call id: call_iGwMB7s1JRqPB4GvUyyVBt33
14
+ 2026-10-26T03:34:49.764965Z ERROR codex_core::util: Custom tool call output is missing for call id: call_iGwMB7s1JRqPB4GvUyyVBt33
15
+ 2026-10-26T06:47:32.180947Z ERROR codex_core::util: Custom tool call output is missing for call id: call_QnECbXnGTJXAuzaqD01dc3dI
16
+ 2026-10-26T06:47:43.552606Z ERROR codex_core::tools::router: error=write_stdin failed: Unknown process id 38473
17
+ 2026-10-26T06:47:43.820806Z ERROR codex_core::util: Custom tool call output is missing for call id: call_QnECbXnGTJXAuzaqD01dc3dI
18
+ 2026-10-26T06:50:10.411194Z ERROR codex_core::tools::router: error=write_stdin failed: Unknown process id 38473
19
+ 2026-10-26T10:10:15.555933Z ERROR codex_core::tools::router: error=write_stdin failed: Unknown process id 44604
20
+ 2026-10-26T16:01:47.671801Z ERROR codex_core::session: failed to record rollout items: thread 01a1618d-8956-7b80-9cc4-d67245b7663a not found
21
+ 2026-10-26T16:02:31.003966Z ERROR codex_core::tools::router: error=write_stdin failed: Unknown process id 72390
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/preflight.jsonl ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {"type":"thread.started","thread_id":"01a177af-d7d2-7ea3-aeef-071dcf0fdca6"}
2
+ {"type":"item.completed","item":{"id":"item_0","type":"error","message":"`[features].use_legacy_landlock` is deprecated and will be removed soon. (Remove this setting to stop opting into the legacy Linux sandbox behavior.)"}}
3
+ {"type":"turn.started"}
4
+ {"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"I’ll run the environment check.\n"}}
5
+ {"type":"item.started","item":{"id":"item_2","type":"command_execution","command":"/bin/sh -lc 'python /opt/speedrun/probe.py'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
6
+ {"type":"item.completed","item":{"id":"item_2","type":"command_execution","command":"/bin/sh -lc 'python /opt/speedrun/probe.py'","aggregated_output":"Environment variable CCD_MIRROR_PATH not set. Will not be able to use function requiring this variable. To set it you may:\n (1) add the line 'export VAR_NAME=path/to/variable' to your .bashrc or .zshrc file\n (2) set it in your current shell with 'export VAR_NAME=path/to/variable'\n (3) write it to a .env file in the root of the atomworks.io repository\nEnvironment variable PDB_MIRROR_PATH not set. Will not be able to use function requiring this variable. To set it you may:\n (1) add the line 'export VAR_NAME=path/to/variable' to your .bashrc or .zshrc file\n (2) set it in your current shell with 'export VAR_NAME=path/to/variable'\n (3) write it to a .env file in the root of the atomworks.io repository\n{\"gpu_name\": \"NVIDIA H100 80GB HBM3\", \"visible_gpus\": 1, \"cuda_ok\": true, \"imports_ok\": true, \"network_blocked\": true, \"ipv4_blocked\": true, \"ipv6_blocked\": true, \"unix_ipc_ok\": true, \"network_error\": \"[Errno 1] Operation not permitted\", \"task\": \"protein-design\", \"development_data_ok\": true, \"data_readonly\": true, \"development_mounts\": [\"fit\", \"tune\"], \"evaluation_roles_absent\": true, \"research_storage_free_bytes\": 8691251236864, \"cpu_affinity_count\": 180, \"atomic_exchange_ok\": true, \"gpu_device_access_isolated\": true, \"denied_gpu_device_count\": 0}\n","exit_code":0,"status":"completed"}}
7
+ {"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"PREFLIGHT_OK"}}
8
+ {"type":"turn.completed","usage":{"input_tokens":21846,"cached_input_tokens":10674,"cache_write_input_tokens":11166,"output_tokens":70,"reasoning_output_tokens":0}}
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/preflight.stderr ADDED
File without changes
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/sessions/2026/10/22/rollout-2026-10-22T03-00-28-01a1618d-8956-7b80-9cc4-d67245b7663a.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17607efe54a5c46e4ebd1d4bea366a536a5541d1cb9fdf8e35d20778d3208870
3
+ size 111948226
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/logs/trajectory.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e63b4b1514bf173359b83072398cc301fd211beb74d8cb130606ca32a86b5189
3
+ size 25933501
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/LICENSE.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, Institute for Protein Design, University of Washington
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ * Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ * Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ * Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/MEASUREMENTS.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "protocol": "First-ID tune target per track; two emitted designs, twenty requested per target. Missing eighteen designs remain failures. Diagnostic screen, not a full-rate estimate.",
3
+ "checkpoint_steps": 32,
4
+ "weight_selection": "online",
5
+ "postprocessing": "input-frame restoration and residue-constrained unindexed motif assignment",
6
+ "tracks": {
7
+ "enzyme": {
8
+ "designs_requested": 20,
9
+ "designs_returned": 2,
10
+ "designs_valid": 2,
11
+ "designs_designable": 0,
12
+ "conditioning_satisfied": 2,
13
+ "failures": {
14
+ "not designable (scRMSD 26.27, ipTM 0.48, PAE 8.23, motif 21.95, no sequence satisfied the criterion)": 1,
15
+ "not designable (scRMSD 53.47, ipTM 0.38, PAE 9.65, motif 45.15, no sequence satisfied the criterion)": 1
16
+ },
17
+ "designs_novel": 0,
18
+ "pass_rate": 0.0,
19
+ "diversity": 0.0,
20
+ "invalid_reason": null
21
+ },
22
+ "ppi_binder": {
23
+ "conditioning_satisfied": 2,
24
+ "designs_designable": 0,
25
+ "designs_novel": 0,
26
+ "designs_requested": 20,
27
+ "designs_returned": 2,
28
+ "designs_valid": 2,
29
+ "diversity": 0.0,
30
+ "failures": {
31
+ "not designable (scRMSD 11.77, ipTM 0.21, PAE 14.18, no sequence satisfied the criterion)": 1,
32
+ "not designable (scRMSD 13.47, ipTM 0.11, PAE 19.94, no sequence satisfied the criterion)": 1
33
+ },
34
+ "invalid_reason": null,
35
+ "pass_rate": 0.0
36
+ },
37
+ "sm_binder": {
38
+ "conditioning_satisfied": 2,
39
+ "designs_designable": 0,
40
+ "designs_novel": 0,
41
+ "designs_requested": 20,
42
+ "designs_returned": 2,
43
+ "designs_valid": 2,
44
+ "diversity": 0.0,
45
+ "failures": {
46
+ "not designable (scRMSD 83.21, ipTM 0.27, PAE 12.71, ligRMSD 127.52, no sequence satisfied the criterion)": 1,
47
+ "not designable (scRMSD 83.58, ipTM 0.34, PAE 11.58, ligRMSD 38.29, no sequence satisfied the criterion)": 1
48
+ },
49
+ "invalid_reason": null,
50
+ "pass_rate": 0.0
51
+ },
52
+ "unconditional": {
53
+ "conditioning_satisfied": 2,
54
+ "designs_designable": 0,
55
+ "designs_novel": 0,
56
+ "designs_requested": 20,
57
+ "designs_returned": 2,
58
+ "designs_valid": 2,
59
+ "diversity": 0.0,
60
+ "failures": {
61
+ "not designable (scRMSD 10.85, ipTM 0.00, no sequence satisfied the criterion)": 1,
62
+ "not designable (scRMSD 11.00, ipTM 0.00, no sequence satisfied the criterion)": 1
63
+ },
64
+ "invalid_reason": null,
65
+ "pass_rate": 0.0
66
+ }
67
+ }
68
+ }
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/README.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared all-atom conditional diffusion
2
+
3
+ Run `bash infer.sh INPUT_ROOT OUTPUT_ROOT`. The package owns all imported model
4
+ source and its checkpoint; it needs the image's Python dependencies and one GPU.
5
+ No network, training corpus, external cache, or pretrained weights are used at
6
+ inference. The exact checkpoint digest is in `harness.json`.
7
+
8
+ One 12,445,554-parameter RFdiffusion3 network serves every track. Unconditional
9
+ requests supply only length. Small-molecule requests supply a bare ligand. PPI
10
+ requests supply a target and hotspot features, with the diffusion origin near the
11
+ hotspots. Enzyme requests supply unindexed catalytic residues and ligand atoms;
12
+ RFD3 chooses motif placement during all-atom diffusion. All use the same network,
13
+ featurization, losses, and sampler. There are no per-track models or retrieved folds.
14
+
15
+ Source derives from the mounted rfd3-small starter (Foundry b02eed6a). RF3 source
16
+ utilities are included because a shared logging module imports them. No RF3 or
17
+ LigandMPNN checkpoint is included or used by the generator.
18
+
19
+ The model is initialized randomly and trained in this session on fit structures
20
+ with the upstream all-atom EDM and sequence losses, PPI conditioning enabled,
21
+ 128-token crops, eight noise draws per structure, one structure per optimizer
22
+ step, a 100-step warmup, and peak learning rate 0.001. Training uses one H100.
23
+ `training_record.json` states the actual optimizer-step count and whether online
24
+ or moving-average weights were exported. Optimizer state is excluded.
25
+
26
+ `sampling.json` records sampler settings. The initial research candidate uses 24
27
+ diffusion steps and one recycle to make full-suite contract replay affordable.
28
+ The explicit diffusion-origin translation is restored before writing each design.
29
+ Guidepost insertion is constrained to distinct generated protein residues, fixing
30
+ an upstream atomwise-assignment failure. Generated coordinates outside the
31
+ inserted guideposts are preserved; unknown sequence
32
+ head outputs are represented as glycine backbone atoms for inverse folding.
33
+ Each request receives its requested sample count, unless a documented sample or
34
+ request error occurs. Errors are written to the output's failures.jsonl and do not
35
+ abort the remaining batch. Ranking is neutral (0.0); no native structures are used.
36
+
37
+ Limitations: the initial 32-step checkpoint is a pipeline smoke test, not a claim
38
+ of designability or improvement over the reported reference. Contract replay and
39
+ scientific evaluation are separate. Only the official LigandMPNN/RoseTTAFold3
40
+ criteria plus Foldseek novelty establish passing designs. The initial
41
+ measured screen has zero passing designs on every track (two designs emitted and
42
+ twenty requested per target); see MEASUREMENTS.json. This is a diagnostic screen,
43
+ not a full-rate estimate. Early training is severely underfit.
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/RESULTS.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # rfd3-small: results
2
+
3
+ The reproduced numbers for this baseline. The criteria behind them, the enzyme-target
4
+ distribution and the full write-up of how the graded and operator paths were reconciled are
5
+ in [../../evaluation/RESULTS.md](../../evaluation/RESULTS.md).
6
+
7
+ ## What this baseline is
8
+
9
+ Upstream RFdiffusion3, vendored at `rfd3/` from
10
+ [RosettaCommons/foundry](https://github.com/RosettaCommons/foundry) `b02eed6a` and reduced in
11
+ **layer widths only** to **12,445,554** parameters against upstream `pretrain`'s 168,038,994
12
+ (7.4 %). Every depth is upstream's — 18 diffusion transformer blocks, 2 + 2 pairformer,
13
+ 3 + 3 atom encoder/decoder, `n_recycle` 2 — as are the crop, the losses, the AF-3
14
+ optimizer/schedule and EMA. See [README.md](README.md) for the eight width leaves that change
15
+ and how to run it.
16
+
17
+ ## Transfer (verifier, 51-target evaluation view)
18
+
19
+ Checkpoint `epoch-0100.ckpt`, the real protocol of 51 targets × 100 designs.
20
+ `conditioning_satisfied` is 100 % on all four tracks.
21
+
22
+ | track | `pass_rate` | `diversity` | operator harness |
23
+ |---|---:|---:|---:|
24
+ | enzyme | 0.0624 | 0.341 | 0.054 |
25
+ | sm_binder | 0.0275 | 0.750 | 0.030 |
26
+ | ppi_binder | 0.002 | 0.200 | 0.004 |
27
+ | unconditional | 0.420 | 1.000 | 0.410 |
28
+
29
+ The two paths agree within sampling noise, on counts of 12 vs 11, 1 vs 2, 220 vs 256 and
30
+ 41 vs 42 passing designs. Reaching that agreement required fixing five divergences in which
31
+ the graded path posed a different problem from the published specs; `input.yaml` is the source
32
+ of truth and residue renumbering is the only licensed difference. The five are written up in
33
+ [../../evaluation/RESULTS.md](../../evaluation/RESULTS.md).
34
+
35
+ **This row is accepted from the task author's report rather than reproduced in this setup**,
36
+ because the checkpoint is not distributable.
37
+
38
+ ## Anchors
39
+
40
+ | system | enzyme | sm_binder | ppi_binder | unconditional |
41
+ |---|---:|---:|---:|---:|
42
+ | trivial generator (extended backbone, reduced view) | 0.000 | 0.000 | 0.000 | 0.000 |
43
+ | `rfd3-small` above | 0.0624 | 0.0275 | 0.002 | 0.420 |
44
+
45
+ The trivial row is a **partial** null system: one target per track and two designs each, run
46
+ through the real scorer, where nothing was designable on any track. The full
47
+ null row over all 51 targets is still open, and matters most on `enzyme`, where 28 of 41
48
+ targets score exactly 0.
49
+
50
+ ## Reading the numbers
51
+
52
+ - `ppi_binder` is measurable, not good: 1 of 500 is not distinguishable from zero
53
+ (P(0 of 500 | true rate 0.004) ≈ 13 %). What the cross-check establishes is that the number
54
+ is produced by the model rather than by a spec bug, which was not true of any earlier run.
55
+ - Thresholds come from RFdiffusion3's `success.txt`, which was calibrated with AlphaFold;
56
+ scoring here uses RoseTTAFold3. Numbers are internally comparable and **not** comparable with
57
+ the published table.
58
+ - 5 designs of 5,100 never reached the grader, each carrying a single `UNK` residue that
59
+ `rfd3_collect.py` rejects. They count as failed designs, which shifts pass rates by ≤ 0.1 %.
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/TRAINING_DATA.md ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training data for the vendored RFdiffusion3
2
+
3
+ The starter is upstream RFdiffusion3 (`starter/rfd3/`, pinned at `b02eed6a`), reduced in
4
+ layer width and nothing else. This page is about the one thing that could not be
5
+ vendored with it: **the data contract**.
6
+
7
+ Upstream's own documentation stops short here. `models/rfd3/README.md` devotes two
8
+ paragraphs to data - "update the path configs to point to the correct base directories
9
+ for the metadata parquets" for the PDB case, and a single sentence for custom datasets
10
+ that defers to a URL you cannot reach offline. The page that URL points at is vendored
11
+ at `references/atomworks-datasets.md`, and it is genuinely useful: it explains
12
+ `PandasDataset`, the loader factories, `ConcatDatasetWithID` and the weighted sampler.
13
+ What it does not explain is the *schema* - which columns must exist, what `cluster`
14
+ means, how interface clusters are keyed. That is what follows.
15
+
16
+ **If you have network access, read §0 first.** Upstream publishes the real metadata
17
+ tables, and downloading them is both faster and more faithful than rebuilding them.
18
+ §1-§6 describe the offline path, which is what the graded image has.
19
+
20
+ ---
21
+
22
+ ## 0. With network: download the real corpus, do not rebuild it
23
+
24
+ Upstream's metadata is a **public artifact**, which is not obvious from the rfd3 README -
25
+ it only says "update the path configs". The download lives in the atomworks CLI, which is
26
+ already installed alongside the vendored rfd3:
27
+
28
+ ```sh
29
+ # 1. the two metadata tables (~975 MB archive -> ~3.8 GB of parquet)
30
+ atomworks setup metadata /data/upstream/metadata
31
+
32
+ # 2. the structures: RCSB divided mmCIF mirror (~100 GB), or a subset
33
+ atomworks pdb sync /data/upstream/pdb
34
+ atomworks pdb sync /data/upstream/pdb --pdb-ids-file ids.txt # subset
35
+
36
+ # 3. the chemical component dictionary (~2 GB)
37
+ atomworks ccd sync /data/upstream/ccd
38
+ ```
39
+
40
+ `output_dir` is a **positional argument** on `setup metadata`; the command's own docstring
41
+ shows `--output-dir`, which does not exist and will error. Mirroring uses rsync to
42
+ `rsync.wwpdb.org::ftp/data/structures/divided/mmCIF/` on **port 33444** (CCD:
43
+ `rsync://ftp.ebi.ac.uk/pub/databases/msd/pdbechem_v2/ccd/`), so a site that blocks
44
+ outbound rsync can fetch the metadata but not the structures.
45
+
46
+ Verified 2026-09-22: `https://files.ipd.uw.edu/pub/atomworks/pdb_metadata_latest.tar.gz`,
47
+ 975,084,126 bytes, last-modified 2025-08-10, sha256
48
+ `8f77156c978135bf5fb5cfff8595103c05dccbafa38c85f3e27385869b9db1a0`. It is a `_latest`
49
+ URL, so treat that digest as a record of what was checked, not a pin that must hold.
50
+ Same host and `/pub/` tree as the scorer weights in
51
+ `environment/fetch_designability_weights.sh`.
52
+
53
+ ### Point the configs at it
54
+
55
+ ```yaml
56
+ # configs/paths/data/<your>.yaml
57
+ pdb_parquet_dir: /data/upstream/metadata
58
+ pdb_data_dir: /data/upstream/pdb
59
+ ```
60
+
61
+ and export `PDB_MIRROR_PATH` / `CCD_MIRROR_PATH` for the atomworks side.
62
+
63
+ **The mirror layout already matches.** `atomworks pdb sync` writes
64
+ `a0/1a0i.cif.gz` - characters 2-3 of the id - which is exactly what
65
+ `PNUnitsDFParser`'s default `path_template` resolves (§1) and the same layout IPD's own
66
+ frozen PDB copy uses. These are plain asymmetric-unit mmCIFs; atomworks builds the
67
+ assembly at load time, so **nothing needs pre-expanding** - unlike the offline path,
68
+ which stages `-assembly1.cif.gz` files.
69
+
70
+ **One filename mismatch to fix.** The archive ships `pn_units_df.parquet`, but
71
+ `datasets/train/pdb/af3_train_pn_unit.yaml` reads
72
+ `${paths.data.pdb_parquet_dir}/pn_units_df_train.parquet`. Symlink it, or override
73
+ `dataset.dataset.data`. The interfaces name matches as shipped.
74
+
75
+ ### What you get, and how it differs from a local rebuild
76
+
77
+ | | downloaded | `build_training_index.py` |
78
+ | --- | --- | --- |
79
+ | `pn_units_df` rows | 3,813,611 (whole PDB) | whatever you staged |
80
+ | `interfaces_df` rows | 6,875,066 | derived |
81
+ | required `columns_to_load` | **all present**, both tables | all present |
82
+ | `cluster` | upstream's own 40% MMseqs2 hash | 30% RCSB substitute (§3) |
83
+ | `q_pn_unit_is_loi` | populated, 7.1% True | always False (§4) |
84
+ | entry dates / resolution | in the table | need `entries.idx` (§4) |
85
+
86
+ So the download **retires every compromise in §3 and §4** for PDB data. Rebuild only for
87
+ structures that are not in the PDB.
88
+
89
+ ### The split and the target holdout are filters, not files
90
+
91
+ The published tables are whole-PDB (max deposition date 2025-06-24). Train/val and the
92
+ benchmark holdout are `filters` in the dataset configs, so they are reproducible from the
93
+ repo alone. `datasets/train/pdb/rfd3_train_{pn_unit,interface}.yaml` carry
94
+
95
+ ```yaml
96
+ - 'pdb_id not in ["7rte", "7m5w", "7n5u"]'
97
+ - 'pdb_id not in ["3di3", "5o45", "1z92", "2gy5", "4zxb"]' # the five ppi eval targets
98
+ - "deposition_date < '2024-12-16'"
99
+ ```
100
+
101
+ while `af3_train_*.yaml` cut at `2021-09-30`. Applying RFD3's own filters to the
102
+ downloaded tables gives:
103
+
104
+ | cut | pn_units | interfaces | total examples |
105
+ | --- | ---: | ---: | ---: |
106
+ | `< 2021-09-30` | 2,395,525 | 4,045,470 | **6,440,995** |
107
+ | `< 2024-12-16` | 3,258,883 | 5,632,469 | **8,891,352** |
108
+
109
+ **Beware a trap if you compare against runs on IPD paths.** Their `pn_units_df_train.parquet`
110
+ already has the 2021 cut baked in (max date 2021-09-20), so `rfd3_train_*`'s
111
+ `< '2024-12-16'` is a **no-op there** - those runs saw a 2021 corpus. Use the 2021 cut to
112
+ reproduce them, and expect a ~10% superset anyway from the newer snapshot.
113
+
114
+ Cluster **labels** are not portable across snapshots: on the 2.41M example ids shared with
115
+ the IPD tables the string matches for 86%, the rest being hash relabelings as new members
116
+ join a cluster. The partition is the same scheme; the ids are not join keys.
117
+
118
+ ---
119
+
120
+ ## 1. What RFD3 actually trains on
121
+
122
+ Not design requests. The four per-track `.npz` contexts under `/data/*/contexts/` are
123
+ inference inputs - a length, a motif, a ligand. Upstream trains on **whole structures**
124
+ and samples its own crops and conditioning from them. That is where the tipatom regime
125
+ (53% of pretraining) and the unindexed regime come from: they are re-rolled on every
126
+ draw, not stored.
127
+
128
+ So training needs two things:
129
+
130
+ | what | where | who makes it |
131
+ | --- | --- | --- |
132
+ | mmCIF assemblies | `/data/development/fit/structures/<xx>/<id>.cif.gz` | operator (`materialize.py --corpus-targets`) |
133
+ | two index tables | `/data/development/fit/index/*.parquet` | `data/build_training_index.py` |
134
+
135
+ The `<xx>` shard is characters 2-3 of the PDB id (`1a0i` -> `a0/1a0i.cif.gz`). That is
136
+ the RCSB divided layout, which is what `PNUnitsDFParser`'s default `path_template`
137
+ (`{base_dir}/{pdb_id[1:3]}/{pdb_id}{file_extension}`) already resolves - so no path
138
+ override is needed.
139
+
140
+ **An example is a row, not a file.** `pn_units_df_train.parquet` has one row per PN unit
141
+ (one polymer or non-polymer unit of one assembly); `interfaces_df_train.parquet` has one
142
+ row per contacting pair. A single entry therefore contributes several examples.
143
+
144
+ ---
145
+
146
+ ## 2. The schema
147
+
148
+ Three consumers fix it, and every column below exists because one of them reads it.
149
+
150
+ ### `pn_units_df_train.parquet`
151
+
152
+ | column | dtype | meaning |
153
+ | --- | --- | --- |
154
+ | `example_id` | str | `{['pdb', 'pn_units']}{1owi}{1}{['A_1']}` - build it with `atomworks.ml.example_id.generate_example_id`, never by hand |
155
+ | `pdb_id` | str | lower-case, resolves the file through the path template |
156
+ | `assembly_id` | str | which assembly to build |
157
+ | `deposition_date` | datetime64 | read by the `filters` |
158
+ | `resolution` | float | read by the `filters`; NaN is allowed and passes `< 9.0` as False |
159
+ | `num_polymer_pn_units` | int | read by the `filters` (`<= 300`) |
160
+ | `method` | str | `X-RAY_DIFFRACTION`, underscored |
161
+ | `cluster` | str | see §3 - the sampler's homology balance |
162
+ | `n_prot`, `n_nuc`, `n_ligand`, `n_peptide` | int | AF-3 composition weights; exactly one is 1 |
163
+ | `total_num_atoms_in_unprocessed_assembly` | int | loaded by the config, not filtered on |
164
+ | `q_pn_unit_iid` | str | **the query unit - this is what the crop is centred on** |
165
+ | `q_pn_unit_non_polymer_res_names` | str or None | CCD codes; the AF-3 excluded-ligand filter matches on it |
166
+ | `all_pn_unit_iids_after_processing` | JSON str | which units survive clash resolution |
167
+ | `q_pn_unit_is_loi` | bool | ligand of interest; see §4 |
168
+
169
+ ### `interfaces_df_train.parquet`
170
+
171
+ Same common columns, then `pn_unit_1_iid` / `pn_unit_2_iid` (both query units - the crop
172
+ is centred on the interface), `pn_unit_1_non_polymer_res_names` /
173
+ `pn_unit_2_non_polymer_res_names`, `is_inter_molecule` (bool, filtered on) and
174
+ `involves_loi`. The composition counts are summed over **both** units, so a
175
+ protein-ligand interface is `n_prot=1, n_ligand=1`.
176
+
177
+ The consumers:
178
+
179
+ * `atomworks.ml.datasets.parsers.PNUnitsDFParser` / `InterfacesDFParser` - find the file,
180
+ pick the assembly, choose the crop centre.
181
+ * `atomworks.ml.samplers.calculate_af3_example_weights` - **asserts** on
182
+ `["n_prot", "n_nuc", "n_ligand", "cluster_size"]`. `cluster_size` is not a column you
183
+ write: the sampler derives it from `cluster` and asserts it is never NaN.
184
+ * the dataset configs' `filters` - `deposition_date`, `resolution`,
185
+ `num_polymer_pn_units`, `cluster.notnull()`, the `*_non_polymer_res_names` regex, and
186
+ `is_inter_molecule` for interfaces.
187
+
188
+ ### How the weights use it
189
+
190
+ ```
191
+ w ∝ (β / N_cluster) · (a_prot·n_prot + a_peptide·n_peptide + a_nuc·n_nuc
192
+ + a_ligand·n_ligand + a_loi·is_loi)
193
+ ```
194
+
195
+ with `beta: 0.5` and `a_prot 3.0 / a_nuc 0.0 / a_ligand 1.0 / a_loi 5.0`
196
+ (`datasets/train/pdb/base.yaml`). The two tables are concatenated, their weight vectors
197
+ are concatenated with them, and one `WeightedRandomSampler(..., replacement=True)`
198
+ covers the whole thing. There is **no fixed interface:pn_unit ratio** - the mix falls
199
+ out of the weights.
200
+
201
+ Two consequences worth internalising:
202
+
203
+ 1. **Sampling is with replacement and an "epoch" is just a counter**
204
+ (`n_examples_per_epoch`). Nothing is exhausted, so a small corpus needs no structural
205
+ change - it is revisited sooner, and each revisit re-rolls the crop and the
206
+ conditioning, so a repeat is not the same example.
207
+ 2. **`cluster` is the only thing clustering feeds**, and it enters as a scalar divisor.
208
+ Without it, `datasets/train/pdb/base_no_weights.yaml` gives uniform sampling.
209
+ Training still runs; you lose homology balancing.
210
+
211
+ ---
212
+
213
+ ## 3. The cluster conventions
214
+
215
+ Nothing documents these and nothing errors if you get them wrong - the weights just come
216
+ out wrong, silently. All three were established by reading upstream's parquets.
217
+
218
+ 1. **Polymers are keyed by a clustering, not by the entity.** Upstream uses a
219
+ representative-sequence hash from a 40%-identity MMseqs2 clustering
220
+ (`3ad9e8af6a4`). This task substitutes **RCSB's 30% entity clusters**
221
+ (`rcsb30:57016`), because that is a public, digest-pinned input the task already
222
+ downloads *and* it is the partition the fit/evaluation split is made disjoint on -
223
+ so the sampler's balancing and the split agree instead of fighting. Where an entity
224
+ is missing from the cluster file we fall back to atomworks' exact-sequence hash,
225
+ which under-clusters but never collides.
226
+ 2. **Non-polymers are keyed by CCD code.** A bare ligand unit's cluster is literally
227
+ `426` or `HEM`. So all heme sites in the PDB are one cluster and are damped together.
228
+ 3. **Interface clusters are the two sides joined by `+`** - `2eeec33883b+SPM`,
229
+ `HEM+rcsb30:57016`. Sorted, so the key does not depend on which side was listed
230
+ first. Get this wrong and interface homology silently collapses to single-chain
231
+ clustering.
232
+
233
+ Why MMseqs2 is not an option here: it is not in the image, `PIP_NO_INDEX=1` and no
234
+ network mean it cannot be installed, and clustering ~16k entries by pairwise alignment
235
+ does not fit the budget. The RCSB clusters are already a task input
236
+ (`data/sources.json`, `rcsb_clusters_30`), pinned by digest.
237
+
238
+ ---
239
+
240
+ ## 4. Building the index offline
241
+
242
+ This is the path for the graded image, which has no network, and for structures that are
243
+ not in the PDB. **For PDB data with network access, §0 is both cheaper and more faithful.**
244
+
245
+ ```sh
246
+ python /workspace/data/build_training_index.py \
247
+ --structures /data/development/fit/structures \
248
+ --clusters /data/sources/clusters-by-entity-30.txt \
249
+ --entry-index /data/sources/entries.idx \
250
+ --output /data/development/fit/index \
251
+ --workers $(nproc)
252
+ ```
253
+
254
+ Four things that will bite if you write your own instead:
255
+
256
+ 1. **`DataPreprocessor(from_rcsb=False)` is mandatory offline.** The default
257
+ (`from_rcsb=True`) POSTs to `data.rcsb.org/graphql` for ligand validity scores with
258
+ **no try/except around the request**, so it raises `ConnectionError` rather than
259
+ degrading. The cost of `False` is that `is_loi` is False everywhere, which switches
260
+ off the `a_loi: 5.0` term - about 2.9% of upstream's rows carry it.
261
+ 2. **An `-assembly1.cif.gz` download carries no entry metadata.** Its `metadata.id` is
262
+ the literal `xxxx`, and deposition date, release date and resolution all parse as
263
+ None. They have to come from `entries.idx`, which is why `--entry-index` exists. Skip
264
+ it and every date filter drops every row.
265
+ 3. **Give each structure a timeout.** Cost is not proportional to file size: `4nlm` is
266
+ 175 KB and ran for over ten minutes, while the median entry is ~2 s. The builder
267
+ budgets 120 s per structure and records the skips in `index_report.json`.
268
+ 4. **Cast the PN unit ids to `str`.** atomworks returns numpy `str_`, and
269
+ `generate_example_id` formats the list with `repr`, so a numpy scalar is written into
270
+ the id as `np.str_('A_1')` - and `parse_example_id`, which `eval`s that field, then
271
+ fails on it.
272
+
273
+ To build a corpus of your own from scratch, the preprocessing half is
274
+ `atomworks.ml.preprocessing.get_pn_unit_data_from_structure` - pure Python over biotite,
275
+ no binaries, no network. It gives you per-unit records (sequences, sequence hashes,
276
+ contacting units, residue counts, clash severity); the cluster join and the interface
277
+ derivation are what `build_training_index.py` adds on top.
278
+
279
+ ### Measured cost
280
+
281
+ On one core, preprocessing runs at **~2 s per structure** (median; mean is higher
282
+ because of a long tail). The transform pipeline that runs at *training* time - parse,
283
+ assembly build, crop, condition sampling, featurisation - costs a **median 2.05 s and
284
+ mean 2.50 s per drawn example** on one core, measured through upstream's own loader at
285
+ crop 256 with 16 noise draws.
286
+
287
+ That sets the shape of the problem: eight
288
+ loader workers deliver roughly 3 examples/s, so the CPUs are not obviously the binding
289
+ constraint, and the honest answer is that **you should measure GPU utilisation before
290
+ assuming either side is**. Turning on `save_to_cache` for the parsed-CIF cache
291
+ (`paths.data.cif_cache_dir`, see `configs/paths/data/task.yaml`) moves parse cost off
292
+ the critical path on every revisit, which matters because sampling is with replacement.
293
+
294
+ ---
295
+
296
+ ## 5. Training
297
+
298
+ ```sh
299
+ python /workspace/baseline/rfd3-small/rfd3/models/rfd3/src/rfd3/train.py experiment=pretrain_small_ppi
300
+ ```
301
+
302
+ `pretrain_small_ppi` is upstream's recipe with the widths reduced and PPI conditioning
303
+ on, and it already points at this container's data by default - there is nothing to
304
+ override. It changes no other recipe leaf: 18 diffusion blocks, the condition mix
305
+ (tipatom 5.0 / unconditional 2.0 / island 2.0 / sequence_design 0.5), the unindexed
306
+ regime at `p_unindex_motif_tokens: 0.5` on island and tipatom, crop 256, the AF-3
307
+ optimizer, schedule and EMA, and every loss weight.
308
+
309
+ What it does change, and why:
310
+
311
+ | change | reason |
312
+ | --- | --- |
313
+ | `paths/data: task` | upstream's defaults are IPD mounts that do not exist here |
314
+ | parquet filenames + date filter | match what the index builder writes and the task's own split boundary |
315
+ | `datasets.val: null` | upstream's validation sets read design-benchmark JSON that is not redistributed; a missing file fails at dataset construction. Score with `evaluation/score.py` on the tune view instead |
316
+ | `calculate_hbonds: 0` | HBPLUS is not installed, and 0.2 raises at runtime. It is a free download - install it and restore 0.2 to get the channel back |
317
+ | `grad_accum_steps: 3`, `devices_per_node: 1` | one GPU, so upstream's 3-structures-per-optimizer-step has to come from accumulation. Keeping it is what makes the AF-3 warmup and decay mean the same thing per unit of data |
318
+
319
+ ### Verified end to end
320
+
321
+ Run 2026-09-17 on one RTX A4000, from an index this pipeline built over task-cache
322
+ assemblies. `train.py` on this experiment reached 2 optimizer steps over 6 batches and
323
+ saved a checkpoint, with:
324
+
325
+ * **12,445,554 trainable parameters** - identical to the reference reduced run;
326
+ * examples drawn from **both** tables (`pdb/pn_units` 66.7%, `pdb/interfaces` 33.3%) by
327
+ the weighted sampler, e.g. `{['pdb', 'interfaces']}{1a31}{1}{['B_1', 'C_1']}`;
328
+ * `Mse Loss Mean` **1.0126** at step 0, which is what an EDM-preconditioned loss should
329
+ read for an untrained network - 1.0 is exactly a zero predictor;
330
+ * **`lp_norm_unindexed_diffused` 0.6489, nonzero** - the unindexed regime is live and
331
+ contributing gradient, which is the whole reason for training upstream rather than the
332
+ port;
333
+ * validation correctly skipped ("No validation datasets provided").
334
+
335
+ Diffing the checkpoint's own resolved `train_cfg` against a fresh
336
+ `compose(experiment=pretrain)` leaves **three** unexplained differing leaves once width
337
+ cuts, data re-pointing, removed validation and the smoke run's own `max_epochs` /
338
+ `n_examples_per_epoch` / `diffusion_batch_size_train` are set aside: two dataloader knobs
339
+ passed on the command line, and `calculate_hbonds` (§5). Crop 256, `max_atoms_in_crop`
340
+ 2560, `grad_accum_steps` 3, 18 diffusion blocks, tipatom frequency 5.0 and
341
+ `p_unindex_motif_tokens` 0.5 on both island and tipatom all match upstream exactly.
342
+
343
+ ### Known departures from upstream, all deliberate
344
+
345
+ * **30% RCSB clusters instead of 40% MMseqs2** (§3) - a different, stricter partition.
346
+ Avoidable with network: the downloaded tables carry upstream's own clusters (§0).
347
+ * **`is_loi` always False** (§4) - the `a_loi` term never fires. Also avoidable via §0,
348
+ where the column is populated.
349
+ * **No hydrogen-bond conditioning** - HBPLUS absent.
350
+ * **No MACE embedding cache** - `residue_cache_dir` starts empty and atomworks falls
351
+ back to RDKit reference conformers. Upstream hits the same fallback on this cluster
352
+ for any component its shared cache lacks.
353
+ * **No validation loop** - the task's grader is the metric.
354
+
355
+ ---
356
+
357
+ ## 6. From checkpoint to submission
358
+
359
+ `rfd3_infer.sh` closes the loop:
360
+
361
+ ```sh
362
+ # 100 designs per target by default (N_BATCHES=25 x 4 diffusion samples); lower
363
+ # N_BATCHES for a quicker, noisier read.
364
+ bash rfd3_infer.sh <ckpt> /data/tune /workspace/research/run
365
+ python /workspace/evaluation/score.py --input /data/tune \
366
+ --designs /workspace/research/run/submission --tracks enzyme
367
+ ```
368
+
369
+ Three stages, with upstream's inference untouched in the middle:
370
+
371
+ | stage | what |
372
+ | --- | --- |
373
+ | `rfd3_inputs.py` | request `.npz` -> `InputSpecification` + a conditioning structure rebuilt from the context |
374
+ | `rfd3 design` | upstream, unmodified. Reduced widths come from the checkpoint's own `train_cfg` |
375
+ | `rfd3_collect.py` | output mmCIF -> one PDB per design plus `<track>.jsonl`, with `motif_map` recovered for enzyme |
376
+
377
+ `rfd3_inputs.py` works on **fit and tune**, which is what an agent has - the container
378
+ mounts only `development`. It rebuilds the conditioning rather than reusing upstream's
379
+ published benchmark specs, which exist only for the evaluation view the verifier holds
380
+ (that path is `environment/evaluation/benchmark/` in the repo, operator-side). All 160 tune specs across the
381
+ four tracks pass upstream's own CPU-only `DesignInputSpecification.safe_init`.
382
+
383
+ Two details worth knowing before you modify it:
384
+
385
+ * **Ligand atom names are reconstructed.** A context stores ligand coordinates and
386
+ elements but no names, and RFD3 needs names that match the chemical component or bonds
387
+ and the reference conformer will not resolve. Materialization keeps deposition order,
388
+ which follows the CCD, so the observed element sequence is embedded into the CCD's
389
+ heavy-atom sequence, earliest match first. 22 of 24 sampled ligands match
390
+ element-for-element; the other two have *fewer* atoms than the CCD (unresolved
391
+ density), which is exactly why a subsequence embedding is used rather than positional
392
+ assignment.
393
+ * **Enzyme goes through `unindex`, not a contig.** The request gives motif geometry with
394
+ no positions, so the model chooses placement and `motif_map` reports it back. That is
395
+ upstream's guidepost setting and the reason for training upstream at all.
396
+
397
+ Three bugs this path already cost, kept here so they are not rediscovered:
398
+
399
+ 1. A pinned contig of `150` parses as **residue index 150**, not a 150-residue design.
400
+ Write `150-150`.
401
+ 2. `diffused_index_map` keys come back **truncated** (`B1029` -> `B102`), so exact lookup
402
+ silently drops designs; match on unique prefix.
403
+ 3. The coordinate fallback must not demand all four backbone atoms - an enzyme context
404
+ carries only 2-3 fixed tip atoms per motif residue, so a four-atom requirement can
405
+ never fire.
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/design.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One shared, trained all-atom diffusion network for every conditioning track."""
2
+ import gc
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+ import tempfile
8
+ import time
9
+ import traceback
10
+
11
+ import numpy as np
12
+ import torch
13
+ from omegaconf import OmegaConf
14
+
15
+ from rfd3.engine import RFD3InferenceConfig, RFD3InferenceEngine
16
+ from rfd3.inference.datasets import ContigJsonDataset
17
+ from rfd3.transforms.pipelines import build_atom14_base_pipeline
18
+ from rfd3_collect import to_atom14, recover_motif_map, write_pdb
19
+ from rfd3_inputs import BUILDERS
20
+ from residues import ATOM14
21
+
22
+ TRACKS = ('unconditional', 'sm_binder', 'ppi_binder', 'enzyme')
23
+ HERE = Path(__file__).resolve().parent
24
+
25
+
26
+ class SharedEngine(RFD3InferenceEngine):
27
+ def _construct_pipeline(self, cfg):
28
+ # Training has no validation dataset; inference uses its own transform and
29
+ # resolves no corpus, training log, benchmark or cached conformer paths.
30
+ self.inference_cfg = cfg
31
+ self.set_batch_size(self.transform_overrides['diffusion_batch_size'])
32
+
33
+ def set_batch_size(self, count):
34
+ cfg = self.inference_cfg
35
+ args = OmegaConf.to_container(cfg.datasets.global_transform_args, resolve=True)
36
+ args.pop('train_conditions', None)
37
+ args.pop('meta_conditioning_probabilities', None)
38
+ args.update(is_inference=True, return_atom_array=True,
39
+ diffusion_batch_size=count, residue_cache_dir=None,
40
+ sigma_data=float(cfg.model.net.diffusion_module.sigma_data),
41
+ atom_1d_features=OmegaConf.to_container(
42
+ cfg.model.net.token_initializer.atom_1d_features, resolve=True),
43
+ token_1d_features=OmegaConf.to_container(
44
+ cfg.model.net.token_initializer.token_1d_features, resolve=True))
45
+ self.pipeline = build_atom14_base_pipeline(**args)
46
+
47
+
48
+ def conditioning_origin(track, context):
49
+ """An explicit diffusion origin whose translation is restored on output."""
50
+ if track == 'unconditional':
51
+ return np.zeros(3)
52
+ if track == 'ppi_binder':
53
+ target = context['target_coords']
54
+ mask = context['target_mask'].astype(bool)
55
+ points = []
56
+ for k, row in enumerate(context['hotspot_indices']):
57
+ row = int(row)
58
+ keep = mask[row].copy()
59
+ if 'hotspot_atoms' in context:
60
+ atoms = str(context['hotspot_atoms'][k]).split(',')
61
+ names = ATOM14[str(context['target_restypes'][row])]
62
+ selected = [a in atoms for a in names] + [False] * (14 - len(names))
63
+ keep &= np.array(selected, dtype=bool)
64
+ points.extend(target[row][keep])
65
+ hotspots = np.asarray(points)
66
+ atoms = target[mask]
67
+ nearby = ((atoms[:, None] - hotspots[None]) ** 2).sum(-1).min(-1) <= 144.
68
+ center = hotspots.mean(0)
69
+ normal = center - atoms[nearby].mean(0)
70
+ size = np.linalg.norm(normal)
71
+ return center + 10. * normal / max(size, 1e-8)
72
+ if track == 'sm_binder':
73
+ return context['ligand_coords'].mean(0)
74
+ pieces = [context['motif_coords'][context['motif_mask'].astype(bool)]]
75
+ if len(context.get('ligand_coords', [])):
76
+ lig = context['ligand_coords']
77
+ keep = context.get('ligand_fixed_mask', np.ones(len(lig), dtype=bool)).astype(bool)
78
+ pieces.append(lig[keep])
79
+ return np.concatenate(pieces).mean(0)
80
+
81
+
82
+ def extract_design(output, request, context, origin):
83
+ arr = output.atom_array
84
+ chains = {}
85
+ for atom in arr:
86
+ if atom.element == 'H':
87
+ continue
88
+ res = chains.setdefault(str(atom.chain_id), {})
89
+ entry = res.setdefault(int(atom.res_id), [str(atom.res_name), {}])
90
+ entry[1][str(atom.atom_name)] = tuple(float(v) for v in atom.coord)
91
+ candidates = []
92
+ for chain, entries in chains.items():
93
+ if len(entries) != request['design_length']:
94
+ continue
95
+ residues = []
96
+ for number, (name, atoms) in entries.items():
97
+ if name == 'UNK' and all(a in atoms for a in ('N', 'CA', 'C', 'O')):
98
+ # MPNN supplies the scored sequence; no coordinates are rebuilt.
99
+ name, atoms = 'GLY', {a: atoms[a] for a in ('N', 'CA', 'C', 'O')}
100
+ residues.append((number, name, atoms))
101
+ if not all(name in ATOM14 for _, name, _ in residues):
102
+ continue
103
+ chosen = arr.chain_id == chain
104
+ fixed = (arr.is_motif_atom_with_fixed_coord[chosen].astype(bool).mean()
105
+ if 'is_motif_atom_with_fixed_coord' in arr.get_annotation_categories()
106
+ else 0.0)
107
+ candidates.append((float(fixed), chain, sorted(residues)))
108
+ if not candidates:
109
+ raise ValueError('no generated protein chain of the requested length')
110
+ _, _, residues = min(candidates, key=lambda v: (v[0], v[1]))
111
+ coords, mask, names = to_atom14(residues)
112
+ coords += origin
113
+ if not mask[:, :4].all() or not np.isfinite(coords[mask]).all():
114
+ raise ValueError('incomplete or nonfinite generated backbone')
115
+ mapping = None
116
+ if request['track'] == 'enzyme':
117
+ mapping = recover_motif_map(output.metadata, names, context, coords, mask)
118
+ if mapping is None:
119
+ raise ValueError('could not identify generated motif residues')
120
+ return coords, mask, names, mapping
121
+
122
+
123
+ def main():
124
+ input_root, output_root = map(lambda p: Path(p).resolve(), sys.argv[1:3])
125
+ settings = json.loads((HERE / 'sampling.json').read_text())
126
+ torch.set_num_threads(4)
127
+ torch.set_float32_matmul_precision('high')
128
+ config = RFD3InferenceConfig(
129
+ ckpt_path=HERE / 'generator.ckpt', diffusion_batch_size=settings['batch_size'],
130
+ inference_sampler={'num_timesteps': settings['timesteps'],
131
+ 'step_scale': settings['step_scale'],
132
+ 'n_recycle': settings['recycles']},
133
+ seed=settings['seed'], prevalidate_inputs=False, global_prefix='',
134
+ )
135
+ engine = SharedEngine(**dict(config))
136
+ engine.initialize()
137
+ pred = output_root / 'predictions'
138
+ structures = pred / 'structures'
139
+ structures.mkdir(parents=True, exist_ok=True)
140
+ errors = output_root / 'failures.jsonl'
141
+ with tempfile.TemporaryDirectory(prefix='shared-rfd3-') as temporary:
142
+ temporary = Path(temporary)
143
+ for track in TRACKS:
144
+ source = input_root / f'{track}.jsonl'
145
+ if not source.exists():
146
+ continue
147
+ with (pred / f'{track}.jsonl').open('w') as index:
148
+ for line in source.read_text().splitlines():
149
+ if not line.strip():
150
+ continue
151
+ request = json.loads(line)
152
+ example, records = request['example_id'], []
153
+ start = time.monotonic()
154
+ try:
155
+ context = dict(np.load(input_root / request['context_path'], allow_pickle=False))
156
+ safe_name = hashlib.sha256(example.encode()).hexdigest()[:20]
157
+ if track == 'unconditional':
158
+ spec = {'length': f"{request['design_length']}-{request['design_length']}"}
159
+ else:
160
+ spec = BUILDERS[track](context, request['design_length'],
161
+ temporary / f'{safe_name}.pdb')
162
+ if spec is None:
163
+ raise ValueError('conditioning chemistry could not be resolved')
164
+ origin = conditioning_origin(track, context)
165
+ if track != 'unconditional':
166
+ spec['ori_token'] = origin.tolist()
167
+ spec.pop('infer_ori_strategy', None)
168
+ count = int(request['num_designs'])
169
+ for offset in range(0, count, settings['batch_size']):
170
+ batch_size = min(count - offset, settings['batch_size'])
171
+ engine.set_batch_size(batch_size)
172
+ dataset = ContigJsonDataset(
173
+ data={f'{safe_name}_{offset}': dict(spec)},
174
+ cif_parser_args=None, transform=engine.pipeline,
175
+ name=track, subset_to_keys=None, eval_every_n=1)
176
+ pipeline_input = dataset[0]
177
+ outputs = engine._model_forward(pipeline_input)
178
+ for sample, output in enumerate(outputs):
179
+ number = offset + sample
180
+ try:
181
+ coords, mask, names, mapping = extract_design(output, request, context, origin)
182
+ name = f'{safe_name}-{number}.pdb'
183
+ write_pdb(structures / name, coords, mask, names)
184
+ rec = {'design_index': number, 'ranking_score': 0.0,
185
+ 'structure_path': name}
186
+ if mapping is not None:
187
+ rec['motif_map'] = mapping
188
+ records.append(rec)
189
+ except (ValueError, KeyError, IndexError) as error:
190
+ with errors.open('a') as log:
191
+ log.write(json.dumps({'example_id': example,
192
+ 'design_index': number, 'error': str(error)}) + '\n')
193
+ del outputs, pipeline_input, dataset
194
+ except Exception as error:
195
+ traceback.print_exc()
196
+ with errors.open('a') as log:
197
+ log.write(json.dumps({'example_id': example, 'error': repr(error)}) + '\n')
198
+ gc.collect()
199
+ torch.cuda.empty_cache()
200
+ index.write(json.dumps({'example_id': example, 'designs': records}) + '\n')
201
+ index.flush()
202
+ print(f"SERVED {track} {example}: {len(records)}/{request['num_designs']} "
203
+ f"in {time.monotonic() - start:.1f}s", flush=True)
204
+
205
+
206
+ if __name__ == '__main__':
207
+ main()
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/harness.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "protein-design-harness/v1",
3
+ "kind": "trained_generator",
4
+ "entry_point": "infer.sh",
5
+ "pretrained_assets": [],
6
+ "learned_components": [
7
+ {
8
+ "path": "generator.ckpt",
9
+ "sha256": "e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779",
10
+ "parameters": 12445554,
11
+ "trained_in_session": true
12
+ }
13
+ ]
14
+ }
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/infer.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ if [[ $# -ne 2 ]]; then
4
+ echo 'usage: infer.sh INPUT_ROOT OUTPUT_ROOT' >&2
5
+ exit 2
6
+ fi
7
+ here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
8
+ export PROJECT_ROOT="$here/rfd3"
9
+ export PYTHONPATH="$here:$here/rfd3/src:$here/rfd3/models/rfd3/src:$here/rfd3/models/rf3/src"
10
+ export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1
11
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
12
+ exec python "$here/design.py" "$1" "$2"
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/publish.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Publish a package directory to /workspace/submission atomically.
3
+
4
+ python /workspace/baseline/rfd3-small/publish.py SRC [--exclude GLOB ...] [--check]
5
+
6
+ The verifier may snapshot /workspace/submission at any moment, so the package must never be
7
+ half-written. This copies SRC into a staging directory next to the target (training-only
8
+ files excluded), optionally checks the harness manifest the way the verifier does, then swaps
9
+ it in with one rename.
10
+ """
11
+ import argparse
12
+ import errno
13
+ import fnmatch
14
+ import os
15
+ import shutil
16
+ import sys
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+ DEFAULT_EXCLUDES = ["__pycache__", "*.pyc", "*.ckpt.tmp", "optimizer.pt", "events.out.tfevents.*"]
21
+
22
+
23
+ def ignore_for(source: Path, patterns: list[str]):
24
+ def ignore(directory: str, names: list[str]) -> set[str]:
25
+ relative = Path(directory).relative_to(source)
26
+ return {name for name in names
27
+ if any(fnmatch.fnmatch(name, p) or fnmatch.fnmatch((relative / name).as_posix(), p)
28
+ for p in patterns)}
29
+ return ignore
30
+
31
+
32
+ def swap_into(staged: Path, final: Path) -> None:
33
+ old = final.with_name(f".{final.name}.old-{os.getpid()}")
34
+ if final.exists():
35
+ try:
36
+ os.replace(final, old)
37
+ except OSError as error:
38
+ # A directory from a lower image layer cannot be renamed on overlayfs (EXDEV): move
39
+ # its contents aside instead; the swap below is still a single rename.
40
+ if error.errno != errno.EXDEV:
41
+ raise
42
+ shutil.copytree(final, old, symlinks=True)
43
+ shutil.rmtree(final)
44
+ os.replace(staged, final)
45
+ shutil.rmtree(old, ignore_errors=True)
46
+
47
+
48
+ def main() -> None:
49
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
50
+ parser.add_argument("source", type=Path)
51
+ parser.add_argument("--output", type=Path, default=Path("/workspace/submission"))
52
+ parser.add_argument("--exclude", action="append", default=[],
53
+ help=f"glob (name or path relative to SRC) to leave out; always excluded: {DEFAULT_EXCLUDES}")
54
+ parser.add_argument("--check", action="store_true",
55
+ help="validate harness.json against the staged copy, as the verifier does")
56
+ args = parser.parse_args()
57
+ source, final = args.source.resolve(), args.output.resolve()
58
+ for required in ("infer.sh", "harness.json", "README.md"):
59
+ if not (source / required).is_file():
60
+ sys.exit(f"{source} has no {required} (see /workspace/contract.md)")
61
+ final.parent.mkdir(parents=True, exist_ok=True)
62
+ staged = Path(tempfile.mkdtemp(prefix=f".{final.name}.stage-", dir=final.parent))
63
+ try:
64
+ shutil.copytree(source, staged, symlinks=False, dirs_exist_ok=True,
65
+ ignore=ignore_for(source, DEFAULT_EXCLUDES + args.exclude))
66
+ if args.check:
67
+ sys.path.insert(0, "/workspace/evaluation/lib")
68
+ from common import validate_harness # the verifier's own check
69
+ validate_harness(staged, Path("/pretrained"))
70
+ staged.chmod(0o755)
71
+ swap_into(staged, final)
72
+ except BaseException:
73
+ shutil.rmtree(staged, ignore_errors=True)
74
+ raise
75
+ print(f"published {source} -> {final}")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/residues.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Atom14 residue constants.
2
+
3
+ Each residue is represented by up to 14 heavy atoms in a residue-type-specific order,
4
+ the representation RFdiffusion3 uses. Slots 0-3 are always the backbone N, CA, C, O,
5
+ so backbone-only logic stays valid on an all-atom array. Tryptophan fills all 14.
6
+ """
7
+
8
+ ATOM14 = {
9
+ "ALA": ["N", "CA", "C", "O", "CB"],
10
+ "ARG": ["N", "CA", "C", "O", "CB", "CG", "CD", "NE", "CZ", "NH1", "NH2"],
11
+ "ASN": ["N", "CA", "C", "O", "CB", "CG", "OD1", "ND2"],
12
+ "ASP": ["N", "CA", "C", "O", "CB", "CG", "OD1", "OD2"],
13
+ "CYS": ["N", "CA", "C", "O", "CB", "SG"],
14
+ "GLN": ["N", "CA", "C", "O", "CB", "CG", "CD", "OE1", "NE2"],
15
+ "GLU": ["N", "CA", "C", "O", "CB", "CG", "CD", "OE1", "OE2"],
16
+ "GLY": ["N", "CA", "C", "O"],
17
+ "HIS": ["N", "CA", "C", "O", "CB", "CG", "ND1", "CD2", "CE1", "NE2"],
18
+ "ILE": ["N", "CA", "C", "O", "CB", "CG1", "CG2", "CD1"],
19
+ "LEU": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2"],
20
+ "LYS": ["N", "CA", "C", "O", "CB", "CG", "CD", "CE", "NZ"],
21
+ "MET": ["N", "CA", "C", "O", "CB", "CG", "SD", "CE"],
22
+ "PHE": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ"],
23
+ "PRO": ["N", "CA", "C", "O", "CB", "CG", "CD"],
24
+ "SER": ["N", "CA", "C", "O", "CB", "OG"],
25
+ "THR": ["N", "CA", "C", "O", "CB", "OG1", "CG2"],
26
+ "TRP": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "NE1", "CE2", "CE3",
27
+ "CZ2", "CZ3", "CH2"],
28
+ "TYR": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "OH"],
29
+ "VAL": ["N", "CA", "C", "O", "CB", "CG1", "CG2"],
30
+ }
31
+
32
+ # OXT, the C-terminal carboxyl oxygen, is deliberately absent: it occurs once per
33
+ # chain and AlphaFold's atom14 layout omits it too. Parsers skip it rather than fail.
34
+ IGNORED_ATOMS = {"OXT"}
35
+
36
+ ATOM14_WIDTH = 14
37
+ BACKBONE_SLOTS = (0, 1, 2, 3)
38
+ BACKBONE_ATOMS = ("N", "CA", "C", "O")
39
+
40
+ RESTYPES = tuple(sorted(ATOM14))
41
+ RESTYPE_INDEX = {name: index for index, name in enumerate(RESTYPES)}
42
+
43
+ THREE_TO_ONE = {
44
+ "ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C", "GLN": "Q",
45
+ "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I", "LEU": "L", "LYS": "K",
46
+ "MET": "M", "PHE": "F", "PRO": "P", "SER": "S", "THR": "T", "TRP": "W",
47
+ "TYR": "Y", "VAL": "V",
48
+ }
49
+
50
+ # Alternative naming for symmetric sidechain tips: these pairs are indistinguishable
51
+ # by the physics, so a motif RMSD must take the better of the two assignments.
52
+ SYMMETRIC_SWAPS = {
53
+ "ARG": [("NH1", "NH2")],
54
+ "ASP": [("OD1", "OD2")],
55
+ "GLU": [("OE1", "OE2")],
56
+ "PHE": [("CD1", "CD2"), ("CE1", "CE2")],
57
+ "TYR": [("CD1", "CD2"), ("CE1", "CE2")],
58
+ }
59
+
60
+
61
+ def atom_slot(residue_name, atom_name):
62
+ """Index of `atom_name` within the residue's atom14 layout, or None."""
63
+ names = ATOM14.get(residue_name)
64
+ if names is None or atom_name not in names:
65
+ return None
66
+ return names.index(atom_name)
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/LICENSE.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, Institute for Protein Design, University of Washington
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ * Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ * Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ * Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/default.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ defaults:
2
+ - train_logging
3
+ - metrics_logging
4
+ - dump_validation_structures
5
+ - _self_
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/dump_validation_structures.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ dump_validation_structures_callback:
2
+ _target_: rf3.callbacks.dump_validation_structures.DumpValidationStructuresCallback
3
+ save_dir: ${paths.output_dir}/val_structures
4
+ dump_predictions: True
5
+ one_model_per_file: False
6
+ dump_trajectories: False
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/metrics_logging.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ store_validation_metrics_in_df_callback:
2
+ _target_: rf3.callbacks.metrics_logging.StoreValidationMetricsInDFCallback
3
+ save_dir: ${paths.output_dir}/val_metrics
4
+ metrics_to_save: "all"
5
+
6
+ log_af3_validation_metrics_callback:
7
+ _target_: rf3.callbacks.metrics_logging.LogAF3ValidationMetricsCallback
8
+ # Only logs if present in the metric output dictionary
9
+ # Must be subset of metrics_to_save
10
+ metrics_to_log: "all"
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/callbacks/train_logging.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ log_af3_training_losses_callback:
2
+ _target_: foundry.callbacks.train_logging.LogAF3TrainingLossesCallback
3
+ log_every_n: 10
4
+ log_full_batch_losses: true
5
+
6
+ log_learning_rate_callback:
7
+ _target_: foundry.callbacks.train_logging.LogLearningRateCallback
8
+ log_every_n: 10
9
+
10
+ log_model_parameters_callback:
11
+ _target_: foundry.callbacks.train_logging.LogModelParametersCallback
12
+
13
+ log_dataset_sampling_ratios_callback:
14
+ _target_: foundry.callbacks.train_logging.LogDatasetSamplingRatiosCallback
15
+
16
+
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/dataloader/default.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train:
2
+ dataloader_params:
3
+ # These parameters will be unpacked as kwargs for the DataLoader
4
+ batch_size: 1
5
+ num_workers: 2
6
+ prefetch_factor: 3
7
+ n_fallback_retries: 4
8
+
9
+ val:
10
+ dataloader_params:
11
+ # These parameters will be unpacked as kwargs for the DataLoader
12
+ batch_size: 1
13
+ num_workers: 2
14
+ prefetch_factor: 3
15
+ n_fallback_retries: 0 # Disable fallback retries for validation
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/datasets/base.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base Transform defaults
2
+ diffusion_batch_size_train: 48
3
+ diffusion_batch_size_inference: 5
4
+
5
+ n_recycles_train: 4
6
+ n_recycles_validation: 10
7
+
8
+ run_confidence_head: false
9
+
10
+ # Conditioning
11
+ p_unconditional: 0.9
12
+
13
+ # Embeddings
14
+ p_dropout_atom_level_embeddings: 0.5
15
+
16
+ n_msa: 1024
17
+ crop_size: 384
18
+ max_atoms_in_crop: 5000
19
+
20
+ key_to_balance: n_tokens_total
21
+
22
+ take_first_chiral_subordering: false
23
+ use_element_for_atom_names_of_atomized_tokens: true
24
+ mirror_prob: 0.02
25
+ atomization_prob: 0.02
26
+ ligand_dropout_prob: 0.0
27
+
28
+ add_residue_is_paired_feature: true
29
+
30
+ add_cyclic_bonds: true
31
+
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/datasets/pdb_and_distillation.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AF3 dataset configuration with monomer distillation
2
+
3
+ defaults:
4
+ - base
5
+ # The @ symbol specifies the tree under which the item will be attached to the config
6
+ - train/pdb/train_interface@train.pdb.sub_datasets.interface
7
+ - train/pdb/train_pn_unit@train.pdb.sub_datasets.pn_unit
8
+ - train:
9
+ - monomer_distillation
10
+ - na_complex_distillation
11
+ - disorder_distillation
12
+ # - rna_monomer_distillation
13
+ - val/af3_validation@val.af3_validation
14
+ - val/af3_validation@val.quick_af3_validation_with_templating
15
+ - _self_
16
+
17
+ # Dataloading pipeline to use
18
+ pipeline_target: rf3.data.pipelines.build_af3_transform_pipeline
19
+
20
+ # Dataset weighting
21
+ train:
22
+ pdb:
23
+ probability: 0.50
24
+ monomer_distillation:
25
+ probability: 0.46
26
+ na_complex_distillation:
27
+ probability: 0.02
28
+ disorder_distillation:
29
+ probability: 0.02
30
+ # rna_monomer_distillation:
31
+ # probability: 0.04
32
+
33
+ val:
34
+ quick_af3_validation_with_templating:
35
+ dataset:
36
+ dataset:
37
+ filters:
38
+ # Only score examples with protein-ligand interfaces
39
+ - "interfaces_to_score.str.contains('protein-ligand')"
40
+ # Small examples only - very fast
41
+ - "n_tokens_total < 400"
42
+ transform:
43
+ # +-- Conditioning --+
44
+ p_unconditional: 0.0 # Always show conditioning
45
+ # (Templates)
46
+ template_noise_scales:
47
+ not_atomized: 1e-4 # No noise on polymer atoms (epsilon to avoid division by zero)
48
+ atomized: 1e-4 # No noise on ligand atoms (epsilon to avoid division by zero)
49
+ allowed_chain_types_for_conditioning:
50
+ _target_: atomworks.enums.ChainType.get_all_types
51
+ p_condition_per_token: 1.0 # Always condition
52
+ p_provide_inter_molecule_distances: 0.0 # No inter-chain distances
53
+ # (Reference conformer)
54
+ p_give_non_polymer_ref_conf: 1.0 # Always give non-polymer reference conformers
55
+ p_give_polymer_ref_conf: 1.0 # Always give polymer reference conformers
tasks/protein-design/protein-design-astra-xhigh-1h100-48h-20261022a/submissions/S001/rfd3/models/rf3/configs/datasets/pdb_only.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AF3 dataset configuration with monomer distillation
2
+
3
+ defaults:
4
+ - base
5
+ # The @ symbol specifies the tree under which the item will be attached to the config
6
+ - train/pdb/train_interface@train.pdb.sub_datasets.interface
7
+ - train/pdb/train_pn_unit@train.pdb.sub_datasets.pn_unit
8
+ - val/af3_validation@val.af3_validation
9
+ - _self_
10
+
11
+ # Dataloading pipeline to use
12
+ pipeline_target: rf3.data.pipelines.build_af3_transform_pipeline
13
+
14
+ # Dataset weighting
15
+ train:
16
+ pdb:
17
+ probability: 1.0