kfold 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. kfold/__init__.py +14 -0
  2. kfold/cli/__init__.py +15 -0
  3. kfold/cli/main.py +48 -0
  4. kfold/cli/multigpu.py +98 -0
  5. kfold/cli/predict.py +336 -0
  6. kfold/cli/predict_complex.py +365 -0
  7. kfold/cli/prepare_apo.py +389 -0
  8. kfold/constants/__init__.py +38 -0
  9. kfold/constants/atom.py +329 -0
  10. kfold/constants/bond.py +41 -0
  11. kfold/constants/ccd.py +461 -0
  12. kfold/constants/chain.py +95 -0
  13. kfold/constants/residue.py +308 -0
  14. kfold/constants/sequence.py +127 -0
  15. kfold/constants/training.py +90 -0
  16. kfold/data/__init__.py +13 -0
  17. kfold/data/layout.py +339 -0
  18. kfold/data/pipelines/__init__.py +13 -0
  19. kfold/data/pipelines/featurization.py +221 -0
  20. kfold/data/pipelines/prior_sampling.py +640 -0
  21. kfold/data/pipelines/structure_preparation.py +265 -0
  22. kfold/data/pipelines/tokenization.py +743 -0
  23. kfold/data/types/__init__.py +19 -0
  24. kfold/data/types/ccd.py +829 -0
  25. kfold/data/types/metadata.py +278 -0
  26. kfold/data/types/model_input.py +1004 -0
  27. kfold/data/types/structure.py +928 -0
  28. kfold/data/types/tokenized.py +875 -0
  29. kfold/data/utils/__init__.py +13 -0
  30. kfold/data/utils/io/__init__.py +13 -0
  31. kfold/data/utils/io/fasta.py +129 -0
  32. kfold/data/utils/io/structure.py +172 -0
  33. kfold/data/utils/rdkit_utils.py +172 -0
  34. kfold/data/utils/simulation/__init__.py +13 -0
  35. kfold/data/utils/simulation/bioprior.py +188 -0
  36. kfold/data/utils/simulation/langevin_dynamics.py +317 -0
  37. kfold/data/utils/writer/__init__.py +19 -0
  38. kfold/data/utils/writer/gemmi_utils.py +507 -0
  39. kfold/data/utils/writer/writer.py +220 -0
  40. kfold/inference/__init__.py +13 -0
  41. kfold/inference/apo_runner.py +457 -0
  42. kfold/inference/data_pipeline.py +338 -0
  43. kfold/inference/query.py +536 -0
  44. kfold/inference/runner.py +639 -0
  45. kfold/inference/utils.py +142 -0
  46. kfold/kernels/__init__.py +13 -0
  47. kfold/kernels/triton/__init__.py +31 -0
  48. kfold/kernels/triton/_common/__init__.py +25 -0
  49. kfold/kernels/triton/_common/dtypes.py +35 -0
  50. kfold/kernels/triton/_common/layouts.py +47 -0
  51. kfold/kernels/triton/attention_pair_bias/__init__.py +24 -0
  52. kfold/kernels/triton/attention_pair_bias/dispatch.py +472 -0
  53. kfold/kernels/triton/attention_pair_bias/kernels.py +606 -0
  54. kfold/kernels/triton/attention_pair_bias/ops.py +284 -0
  55. kfold/kernels/triton/cdist.py +342 -0
  56. kfold/kernels/triton/triangle_attention/__init__.py +18 -0
  57. kfold/kernels/triton/triangle_attention/kernels.py +471 -0
  58. kfold/kernels/triton/triangle_attention/ops.py +184 -0
  59. kfold/kernels/triton/triangle_multiplication/__init__.py +24 -0
  60. kfold/kernels/triton/triangle_multiplication/kernels.py +383 -0
  61. kfold/kernels/triton/triangle_multiplication/ops.py +110 -0
  62. kfold/model/__init__.py +16 -0
  63. kfold/model/layers/__init__.py +13 -0
  64. kfold/model/layers/folding/__init__.py +13 -0
  65. kfold/model/layers/folding/atom_transformer.py +484 -0
  66. kfold/model/layers/folding/attention_pair_bias.py +260 -0
  67. kfold/model/layers/folding/diffusion.py +592 -0
  68. kfold/model/layers/folding/diffusion_transformer.py +597 -0
  69. kfold/model/layers/folding/embeddings.py +308 -0
  70. kfold/model/layers/folding/input_encoder.py +118 -0
  71. kfold/model/layers/folding/transition.py +68 -0
  72. kfold/model/layers/folding/utils.py +188 -0
  73. kfold/model/layers/seq_enc/__init__.py +13 -0
  74. kfold/model/layers/seq_enc/attention.py +89 -0
  75. kfold/model/layers/seq_enc/blocks.py +89 -0
  76. kfold/model/layers/seq_enc/moe.py +219 -0
  77. kfold/model/layers/seq_enc/nn.py +37 -0
  78. kfold/model/layers/seq_enc/rotary.py +97 -0
  79. kfold/model/layers/seq_enc/transformer_stack.py +70 -0
  80. kfold/model/layers/struct_enc/__init__.py +3 -0
  81. kfold/model/layers/struct_enc/backbone.py +125 -0
  82. kfold/model/layers/struct_enc/bb_tokenizer.py +160 -0
  83. kfold/model/layers/struct_enc/bb_vqvae/__init__.py +0 -0
  84. kfold/model/layers/struct_enc/bb_vqvae/affine_utils.py +622 -0
  85. kfold/model/layers/struct_enc/bb_vqvae/encoder.py +179 -0
  86. kfold/model/layers/struct_enc/bb_vqvae/quantizer.py +46 -0
  87. kfold/model/layers/struct_enc/bb_vqvae/rotary.py +186 -0
  88. kfold/model/layers/struct_enc/bb_vqvae/transformer.py +350 -0
  89. kfold/model/layers/struct_enc/fa_tokenizer.py +203 -0
  90. kfold/model/layers/struct_enc/fa_vqvae/__init__.py +0 -0
  91. kfold/model/layers/struct_enc/fa_vqvae/encoder.py +316 -0
  92. kfold/model/layers/struct_enc/fa_vqvae/pair_bias_attn.py +199 -0
  93. kfold/model/layers/struct_enc/fa_vqvae/pair_update.py +84 -0
  94. kfold/model/layers/struct_enc/fa_vqvae/quantizer.py +46 -0
  95. kfold/model/layers/struct_enc/fa_vqvae/tri_mul.py +150 -0
  96. kfold/model/layers/struct_enc/fa_vqvae/utils/__init__.py +0 -0
  97. kfold/model/layers/struct_enc/fa_vqvae/utils/coords_utils.py +148 -0
  98. kfold/model/layers/struct_enc/fa_vqvae/utils/data_transforms.py +200 -0
  99. kfold/model/layers/struct_enc/fa_vqvae/utils/residue_constants.py +214 -0
  100. kfold/model/layers/struct_enc/fa_vqvae/utils/rigid_utils.py +1454 -0
  101. kfold/model/layers/struct_enc/nn.py +23 -0
  102. kfold/model/layers/struct_enc/transformer_layers.py +103 -0
  103. kfold/model/model.py +683 -0
  104. kfold/model/model_train.py +554 -0
  105. kfold/model/modules/__init__.py +27 -0
  106. kfold/model/modules/apo_module.py +393 -0
  107. kfold/model/modules/confidence_head.py +470 -0
  108. kfold/model/modules/distogram_head.py +105 -0
  109. kfold/model/modules/ecsi.py +1502 -0
  110. kfold/model/modules/input_embedder.py +167 -0
  111. kfold/model/modules/patch_geometry.py +386 -0
  112. kfold/model/modules/prot_seq_encoder.py +151 -0
  113. kfold/model/modules/prot_struct_encoder.py +351 -0
  114. kfold/model/modules/rna_seq_encoder.py +189 -0
  115. kfold/model/modules/score_model.py +306 -0
  116. kfold/model/modules/tri_stack.py +151 -0
  117. kfold/model/primitives/__init__.py +38 -0
  118. kfold/model/primitives/activation.py +29 -0
  119. kfold/model/primitives/attention.py +334 -0
  120. kfold/model/primitives/dropout.py +89 -0
  121. kfold/model/primitives/initialize.py +129 -0
  122. kfold/model/primitives/linear.py +126 -0
  123. kfold/model/primitives/normalization.py +125 -0
  124. kfold/model/primitives/triangle_attention.py +465 -0
  125. kfold/model/primitives/triangle_multiplication.py +313 -0
  126. kfold/model/primitives/utils.py +128 -0
  127. kfold/training/__init__.py +13 -0
  128. kfold/training/dataset/__init__.py +15 -0
  129. kfold/training/dataset/cropper/__init__.py +31 -0
  130. kfold/training/dataset/cropper/alphafold.py +370 -0
  131. kfold/training/dataset/cropper/base.py +222 -0
  132. kfold/training/dataset/cropper/multi_anchor.py +581 -0
  133. kfold/training/dataset/cropper/utils.py +269 -0
  134. kfold/training/dataset/datamodule.py +283 -0
  135. kfold/training/dataset/datasets/__init__.py +30 -0
  136. kfold/training/dataset/datasets/base.py +898 -0
  137. kfold/training/dataset/datasets/distillation.py +37 -0
  138. kfold/training/dataset/datasets/rcsb.py +39 -0
  139. kfold/training/dataset/datasets/train_dataset.py +700 -0
  140. kfold/training/dataset/datasets/val_dataset.py +70 -0
  141. kfold/training/dataset/dl_sampler.py +120 -0
  142. kfold/training/dataset/sampler/__init__.py +31 -0
  143. kfold/training/dataset/sampler/base.py +64 -0
  144. kfold/training/dataset/sampler/cluster.py +222 -0
  145. kfold/training/dataset/sampler/uniform.py +64 -0
  146. kfold/training/dataset/utils/__init__.py +13 -0
  147. kfold/training/dataset/utils/apo_io.py +234 -0
  148. kfold/training/dataset/utils/apo_perturbation.py +107 -0
  149. kfold/training/dataset/utils/pre_crop.py +198 -0
  150. kfold/training/loss/__init__.py +15 -0
  151. kfold/training/loss/confidence.py +547 -0
  152. kfold/training/loss/diffusion.py +422 -0
  153. kfold/training/loss/distogram.py +68 -0
  154. kfold/training/loss/patch_geometry.py +48 -0
  155. kfold/training/metrics/__init__.py +13 -0
  156. kfold/training/metrics/structure_metrics.py +558 -0
  157. kfold/training/optim/__init__.py +13 -0
  158. kfold/training/optim/ema.py +182 -0
  159. kfold/training/optim/lr_scheduler.py +115 -0
  160. kfold/training/preprocess/__init__.py +15 -0
  161. kfold/training/preprocess/apo_lmdb.py +280 -0
  162. kfold/training/preprocess/apo_preparation.py +172 -0
  163. kfold/training/preprocess/atlasfold_prediction.py +283 -0
  164. kfold/training/preprocess/cif_factory.py +1187 -0
  165. kfold/training/preprocess/prepared_sequences.py +50 -0
  166. kfold/training/preprocess/structure_cleaning.py +140 -0
  167. kfold/training/preprocess/structure_tokenizers.py +46 -0
  168. kfold/training/training_module.py +1084 -0
  169. kfold/training/utils/__init__.py +13 -0
  170. kfold/training/utils/gradient_logging.py +39 -0
  171. kfold/training/utils/permutation_alignment/__init__.py +13 -0
  172. kfold/training/utils/permutation_alignment/align_train.py +622 -0
  173. kfold/training/utils/permutation_alignment/align_val.py +422 -0
  174. kfold/training/utils/permutation_alignment/symmetry.py +283 -0
  175. kfold/utils/__init__.py +13 -0
  176. kfold/utils/checkpointing.py +99 -0
  177. kfold/utils/confidence_metrics.py +522 -0
  178. kfold/utils/config.py +171 -0
  179. kfold/utils/geometry/__init__.py +13 -0
  180. kfold/utils/geometry/random_augment.py +519 -0
  181. kfold/utils/geometry/rigid_align.py +771 -0
  182. kfold/utils/misc.py +96 -0
  183. kfold/utils/mmseqs2.py +211 -0
  184. kfold/utils/rcsb_api.py +92 -0
  185. kfold/utils/registry.py +229 -0
  186. kfold/utils/runtime.py +69 -0
  187. kfold-1.0.0.dist-info/METADATA +325 -0
  188. kfold-1.0.0.dist-info/RECORD +192 -0
  189. kfold-1.0.0.dist-info/WHEEL +5 -0
  190. kfold-1.0.0.dist-info/entry_points.txt +2 -0
  191. kfold-1.0.0.dist-info/licenses/LICENSE +201 -0
  192. kfold-1.0.0.dist-info/top_level.txt +1 -0
kfold/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ # Copyright 2026 Korea Advanced Institute of Science and Technology (KAIST)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ __version__ = "1.0.0"
kfold/cli/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ # Copyright 2026 Korea Advanced Institute of Science and Technology (KAIST)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Command-line entry points for KFold."""
kfold/cli/main.py ADDED
@@ -0,0 +1,48 @@
1
+ # Copyright 2026 Korea Advanced Institute of Science and Technology (KAIST)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Run structure prediction from the installed kfold command."""
16
+
17
+ import argparse
18
+ import logging
19
+
20
+ from kfold.cli.predict import add_arguments, dry_run, run
21
+
22
+
23
+ def create_parser() -> argparse.ArgumentParser:
24
+ parser = argparse.ArgumentParser(
25
+ prog="kfold", description="K-Fold structure prediction", allow_abbrev=False
26
+ )
27
+ add_arguments(parser)
28
+ return parser
29
+
30
+
31
+ def main(argv=None) -> None:
32
+ # Parse the command and configure logging before running prediction stages.
33
+ parser = create_parser()
34
+ args = parser.parse_args(argv)
35
+ logging.basicConfig(
36
+ level=logging.INFO,
37
+ format="%(asctime)s | %(name)s | %(message)s",
38
+ datefmt="%y/%m/%d %H:%M:%S",
39
+ )
40
+ logging.getLogger("httpx").setLevel(logging.WARNING)
41
+ if args.dry_run:
42
+ dry_run(args)
43
+ else:
44
+ run(args)
45
+
46
+
47
+ if __name__ == "__main__":
48
+ main()
kfold/cli/multigpu.py ADDED
@@ -0,0 +1,98 @@
1
+ # Copyright 2026 Korea Advanced Institute of Science and Technology (KAIST)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Run one prediction stage in isolated GPU processes."""
16
+
17
+ import logging
18
+ import multiprocessing
19
+ from multiprocessing.connection import wait
20
+
21
+
22
+ def distribute(costs: list[int], num_workers: int, method: str) -> list[list[int]]:
23
+ """Assign job indices round-robin or balance their estimated costs."""
24
+ if method == "round-robin":
25
+ return [list(range(rank, len(costs), num_workers)) for rank in range(num_workers)]
26
+ groups: list[list[int]] = [[] for _ in range(num_workers)]
27
+ loads = [0] * num_workers
28
+ for index in sorted(range(len(costs)), key=lambda index: costs[index], reverse=True):
29
+ rank = min(range(num_workers), key=lambda rank: loads[rank])
30
+ groups[rank].append(index)
31
+ loads[rank] += costs[index]
32
+ # Preserve the stage's original processing order within each worker.
33
+ return [sorted(group) for group in groups]
34
+
35
+
36
+ def launch(worker, args, worker_jobs, *, stage: str):
37
+ """Launch one GPU process for each preassigned group of jobs."""
38
+ import torch
39
+
40
+ # Validate GPU selection and launch the preassigned jobs in isolated workers.
41
+ num_visible = torch.cuda.device_count()
42
+ if any(gpu_id >= num_visible for gpu_id in args.gpu_ids):
43
+ raise ValueError(
44
+ f"Requested GPU IDs {args.gpu_ids}; visible GPU count: {num_visible}."
45
+ )
46
+ workers = len(worker_jobs)
47
+ context = multiprocessing.get_context("spawn")
48
+ processes = [
49
+ context.Process(
50
+ target=_worker_entry,
51
+ args=(worker, args.gpu_ids[rank], args, jobs, workers),
52
+ )
53
+ for rank, jobs in enumerate(worker_jobs)
54
+ ]
55
+ # Start workers and stop the stage as soon as one reports a failure.
56
+ try:
57
+ for process in processes:
58
+ process.start()
59
+ pending = {
60
+ process.sentinel: (process, gpu_id)
61
+ for process, gpu_id in zip(processes, args.gpu_ids, strict=False)
62
+ }
63
+ while pending:
64
+ for sentinel in wait(pending):
65
+ process, gpu_id = pending.pop(sentinel)
66
+ process.join()
67
+ if process.exitcode:
68
+ raise SystemExit(
69
+ f"{stage} stopped: GPU {gpu_id} worker failed "
70
+ f"(exit {process.exitcode})."
71
+ )
72
+ finally:
73
+ # Reap remaining workers when the stage fails or is interrupted.
74
+ for process in processes:
75
+ if process.is_alive():
76
+ process.terminate()
77
+ process.join()
78
+
79
+
80
+ def _worker_entry(worker, gpu_id, args, jobs, num_workers):
81
+ """Configure a GPU process and show inference logs and library warnings."""
82
+ import torch
83
+ from huggingface_hub.utils import disable_progress_bars
84
+
85
+ # Spawned workers do not inherit the parent's progress-bar settings.
86
+ disable_progress_bars()
87
+ # Configure process-local logging and CUDA before entering the stage worker.
88
+ gpu_label = f" | gpu-{gpu_id}" if num_workers > 1 else ""
89
+ logging.basicConfig(
90
+ level=logging.INFO,
91
+ format=f"%(asctime)s | %(name)s{gpu_label} | %(message)s",
92
+ datefmt="%y/%m/%d %H:%M:%S",
93
+ )
94
+ logging.getLogger("cli").setLevel(logging.INFO)
95
+ logging.getLogger("httpx").setLevel(logging.WARNING)
96
+ torch.cuda.set_device(gpu_id)
97
+ torch.set_float32_matmul_precision("highest")
98
+ worker(gpu_id, args, jobs)
kfold/cli/predict.py ADDED
@@ -0,0 +1,336 @@
1
+ # Copyright 2026 Korea Advanced Institute of Science and Technology (KAIST)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Run predictions for each query and seed."""
16
+
17
+ import argparse
18
+ import logging
19
+ import os
20
+ from pathlib import Path
21
+
22
+ from kfold.inference.query import Query
23
+
24
+ logger = logging.getLogger("cli")
25
+
26
+
27
+ def add_arguments(parser: argparse.ArgumentParser) -> None:
28
+ # Stage selection, query paths, and generation seeds.
29
+ parser.add_argument(
30
+ "--stage",
31
+ choices=("all", "apo", "complex"),
32
+ default="all",
33
+ help="Run all stages, prepare apos, or predict complexes from --out-dir.",
34
+ )
35
+ parser.add_argument(
36
+ "-i",
37
+ "--input",
38
+ type=Path,
39
+ required=True,
40
+ help="Query JSON/YAML file or directory.",
41
+ )
42
+ parser.add_argument(
43
+ "-o",
44
+ "--out-dir",
45
+ type=Path,
46
+ required=True,
47
+ help="Output directory.",
48
+ )
49
+ parser.add_argument(
50
+ "--seeds",
51
+ type=int,
52
+ nargs="+",
53
+ default=[1],
54
+ help="Complex inference seeds (default: [1]).",
55
+ )
56
+ # Apo generation settings.
57
+ parser.add_argument(
58
+ "--apo-config",
59
+ type=Path,
60
+ help="YAML settings for apo batching and AtlasFold prediction.",
61
+ )
62
+ parser.add_argument(
63
+ "--num-apos",
64
+ type=int,
65
+ default=1,
66
+ help="Generated apos per protein entry per inference seed "
67
+ "without shared seeds (1–5; default: 1).",
68
+ )
69
+ parser.add_argument(
70
+ "--share-apo-seeds",
71
+ type=int,
72
+ nargs="+",
73
+ help="Generate apos with these unique positive seeds "
74
+ "and reuse them across inference seeds.",
75
+ )
76
+ # Complex prediction settings.
77
+ parser.add_argument(
78
+ "--num-shared-apos",
79
+ type=int,
80
+ default=5,
81
+ help="Maximum apo candidates per protein entry with shared seeds "
82
+ "(1–5; default: 5).",
83
+ )
84
+ parser.add_argument(
85
+ "--num-samples",
86
+ type=int,
87
+ default=5,
88
+ help="Predictions per query/seed (default: 5).",
89
+ )
90
+ parser.add_argument(
91
+ "--num-recycles",
92
+ type=int,
93
+ default=10,
94
+ help="Number of recycling iterations (default: 10).",
95
+ )
96
+ parser.add_argument(
97
+ "--num-steps",
98
+ type=int,
99
+ default=100,
100
+ help="Number of diffusion steps (default: 100).",
101
+ )
102
+ # Devices, model components, and model cache.
103
+ parser.add_argument(
104
+ "--kernel",
105
+ dest="kernel_backend",
106
+ type=str,
107
+ default="auto",
108
+ choices=("auto", "torch", "triton", "cuequiv"),
109
+ help="Kernel backend for K-Fold and AtlasFold apo preparation.",
110
+ )
111
+ parser.add_argument(
112
+ "--gpu-ids",
113
+ type=int,
114
+ nargs="+",
115
+ default=[0],
116
+ help="Visible CUDA device IDs (default: [0]).",
117
+ )
118
+ parser.add_argument(
119
+ "--distribution",
120
+ choices=("size", "round-robin"),
121
+ default="size",
122
+ help="Multi-GPU job distribution",
123
+ )
124
+ parser.add_argument(
125
+ "--disable-struct-encoder",
126
+ action="store_true",
127
+ help="Disable the apo structure encoder to save ~6 GB of GPU memory.",
128
+ )
129
+ parser.add_argument(
130
+ "--disable-rna-encoder",
131
+ action="store_true",
132
+ help="Disable the RNA encoder; only for queries without RNA.",
133
+ )
134
+ parser.add_argument(
135
+ "--cpu-offload",
136
+ action="store_true",
137
+ help="Offload pretrained encoders to CPU to save GPU memory (slower).",
138
+ )
139
+ parser.add_argument(
140
+ "--cache-dir",
141
+ type=Path,
142
+ help="Hugging Face cache directory for models and CCD.",
143
+ )
144
+ # Execution control and optional output files.
145
+ parser.add_argument(
146
+ "--dry-run",
147
+ action="store_true",
148
+ help="Check query files and paths; count pending jobs without loading models.",
149
+ )
150
+ parser.add_argument(
151
+ "--overwrite",
152
+ action="store_true",
153
+ help="Rerun completed query/seed jobs.",
154
+ )
155
+ parser.add_argument(
156
+ "--save-confidence",
157
+ action="store_true",
158
+ help="Save per-atom and token-pair confidence arrays.",
159
+ )
160
+ parser.add_argument(
161
+ "--save-embeddings",
162
+ action="store_true",
163
+ help="Save internal trunk embeddings.",
164
+ )
165
+ parser.add_argument(
166
+ "--save-distogram",
167
+ action="store_true",
168
+ help="Save distogram.",
169
+ )
170
+ parser.add_argument(
171
+ "--save-trajectory",
172
+ action="store_true",
173
+ help="Save diffusion trajectories.",
174
+ )
175
+
176
+
177
+ def _download_models(cache_dir: Path | None) -> None:
178
+ """Cache all model weights and assets."""
179
+ from huggingface_hub import snapshot_download
180
+ from huggingface_hub.utils import tqdm
181
+
182
+ progress_bars = []
183
+
184
+ class DownloadProgress(tqdm):
185
+ def __init__(self, *args, **kwargs):
186
+ kwargs.update(leave=False, dynamic_ncols=True)
187
+ super().__init__(*args, **kwargs)
188
+ progress_bars.append(self)
189
+
190
+ logger.info("Downloading all model weights and assets.")
191
+ if cache_dir is not None:
192
+ logger.info("Cache directory: %s", cache_dir.resolve())
193
+
194
+ for repo_id in (
195
+ "SeonghwanSeo/atlaslm-3b-base",
196
+ "SeonghwanSeo/atlasfold-260703",
197
+ "SeonghwanSeo/atlasfold-m-260725",
198
+ "kaist-ai-bio/kfold-assets",
199
+ "kaist-ai-bio/kfold",
200
+ ):
201
+ try:
202
+ snapshot_download(
203
+ repo_id,
204
+ cache_dir=cache_dir,
205
+ tqdm_class=DownloadProgress,
206
+ )
207
+ finally:
208
+ for bar in reversed(progress_bars):
209
+ bar.close()
210
+ progress_bars.clear()
211
+ logger.info("All model weights and assets are cached.")
212
+
213
+
214
+ def _load_queries(args: argparse.Namespace) -> list[Query]:
215
+ """Validate runtime arguments and load queries in prediction order."""
216
+ # Validate all runtime arguments, regardless of the selected stages.
217
+ # GPU selection and generation seeds.
218
+ if not args.gpu_ids or any(gpu_id < 0 for gpu_id in args.gpu_ids):
219
+ raise ValueError("--gpu-ids must be a non-empty list of non-negative indices.")
220
+ if len(set(args.gpu_ids)) != len(args.gpu_ids):
221
+ raise ValueError("--gpu-ids values must be unique.")
222
+ for name in ("seeds", "share_apo_seeds"):
223
+ seeds = getattr(args, name)
224
+ if seeds is not None and (
225
+ not seeds or any(seed < 1 for seed in seeds) or len(set(seeds)) != len(seeds)
226
+ ):
227
+ raise ValueError(
228
+ f"--{name.replace('_', '-')} requires one or more unique positive seeds."
229
+ )
230
+
231
+ # Apo and complex sampling counts.
232
+ for name in ("num_apos", "num_shared_apos"):
233
+ if not 1 <= getattr(args, name) <= 5:
234
+ raise ValueError(f"--{name.replace('_', '-')} must be between 1 and 5.")
235
+ for name in ("num_samples", "num_recycles", "num_steps"):
236
+ if getattr(args, name) < 1:
237
+ raise ValueError(f"--{name.replace('_', '-')} must be positive.")
238
+
239
+ # Discover query files from a single file or directory.
240
+ if args.input.is_dir():
241
+ paths = sorted(
242
+ path
243
+ for path in args.input.iterdir()
244
+ if path.is_file() and path.suffix in {".json", ".yaml", ".yml"}
245
+ )
246
+ else:
247
+ paths = [args.input]
248
+ if not paths:
249
+ raise ValueError(f"No JSON/YAML query files found in {args.input}.")
250
+
251
+ # Load queries and reject names that would share an output directory.
252
+ queries = [Query.load(path) for path in paths]
253
+ names = set()
254
+ for query in queries:
255
+ if query.name in names:
256
+ raise ValueError(f"Duplicate query name: {query.name!r}.")
257
+ names.add(query.name)
258
+
259
+ queries.sort(key=lambda query: query.priority)
260
+ return queries
261
+
262
+
263
+ def dry_run(args: argparse.Namespace) -> None:
264
+ """Validate selected queries and report pending work without writing outputs."""
265
+ from huggingface_hub import snapshot_download
266
+
267
+ from kfold.cli.predict_complex import dry_run as predict_complex
268
+ from kfold.cli.prepare_apo import dry_run as prepare_apo
269
+ from kfold.data.types.ccd import CCD
270
+ from kfold.inference.runner import ASSETS_REPO_ID
271
+
272
+ queries = _load_queries(args)
273
+
274
+ logger.info("Checking query CCD codes.")
275
+ ccd_path = (
276
+ Path(snapshot_download(ASSETS_REPO_ID, cache_dir=args.cache_dir))
277
+ / "assets/ccd.pkl"
278
+ )
279
+ ccd = CCD.load(ccd_path)
280
+ for query in queries:
281
+ query.validate_ccd_codes(ccd.keys())
282
+
283
+ logger.info("Input: %s; output: %s.", args.input, args.out_dir)
284
+ if args.stage in ("all", "apo"):
285
+ prepare_apo(args, queries)
286
+ if args.stage in ("all", "complex"):
287
+ predict_complex(args, queries)
288
+ logger.info("Dry run complete; no models loaded or outputs written.")
289
+
290
+
291
+ def run(args: argparse.Namespace) -> None:
292
+ """Validate arguments, load queries, and run the selected prediction stages."""
293
+ from huggingface_hub.utils import disable_progress_bars
294
+
295
+ from kfold.cli.predict_complex import run as predict_complex
296
+ from kfold.cli.prepare_apo import run as prepare_apo
297
+ from kfold.utils.runtime import select_kernel_backend
298
+
299
+ if os.environ.get("OMP_NUM_THREADS") != "1":
300
+ logger.warning(
301
+ "OMP_NUM_THREADS is not set to 1; model initialization may be slow. "
302
+ "Set OMP_NUM_THREADS=1 to avoid this slowdown."
303
+ )
304
+
305
+ # Populate the shared cache before any GPU worker loads a model.
306
+ _download_models(args.cache_dir)
307
+
308
+ input_path = args.input.resolve()
309
+ output_path = args.out_dir.resolve()
310
+ if not input_path.exists():
311
+ raise FileNotFoundError(f"Input path {input_path} does not exist.")
312
+
313
+ # Print the resolved input and output paths for clarity.
314
+ logger.info("Input path: %s", input_path)
315
+ logger.info("Output path: %s", output_path)
316
+
317
+ # Resolve the kernel backend, preferring Triton when unspecified.
318
+ args.kernel_backend = select_kernel_backend(args.kernel_backend)
319
+ logger.info("Kernel backend: %s.", args.kernel_backend)
320
+
321
+ # Load queries
322
+ queries = _load_queries(args)
323
+
324
+ # Disable Hugging Face progress bars to avoid cluttering the output.
325
+ disable_progress_bars()
326
+
327
+ # Prepare provided and generated apo structures.
328
+ if args.stage in ("all", "apo"):
329
+ prepare_apo(args, queries)
330
+
331
+ # Predict complexes from prepared apo structures.
332
+ if args.stage in ("all", "complex"):
333
+ predict_complex(args, queries)
334
+
335
+ # Report completion after all selected stages finish.
336
+ logger.info("Output path: %s", output_path)