molgpf 1.0.0__tar.gz

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.
@@ -0,0 +1,20 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ build/
4
+ dist/
5
+ *.egg-info/
6
+ .venv/
7
+ .pytest_cache/
8
+ .DS_Store
9
+ *.pt
10
+ *.pth
11
+ *.ckpt
12
+ *.safetensors
13
+ *.fm118
14
+ *.mgpf
15
+ pretrained/
16
+ weights/
17
+ paper/*.aux
18
+ paper/*.blg
19
+ paper/*.log
20
+ paper/*.out
molgpf-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shangqian Chen, Guojiang Zhao, Zheng Cheng, Jiankun Wang, Hongshuai Wang, Zhifeng Gao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
molgpf-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: molgpf
3
+ Version: 1.0.0
4
+ Summary: MolGPF: Periodic-Table-Wide Generative Pre-trained Flow Foundation Model for 3D Molecules and Transition-Metal Complexes
5
+ Project-URL: Homepage, https://github.com/ShangChien/molgpf
6
+ Project-URL: Repository, https://github.com/ShangChien/molgpf
7
+ Project-URL: Issues, https://github.com/ShangChien/molgpf/issues
8
+ Author: Guojiang Zhao, Zheng Cheng, Jiankun Wang, Hongshuai Wang, Zhifeng Gao
9
+ Author-email: Shangqian Chen <chensq@dp.tech>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: 3d-molecular-generation,chemistry,flow-matching,foundation-model,gvp,periodic-table,se3-equivariant,transition-metal-complexes
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
20
+ Requires-Python: <3.13,>=3.11
21
+ Requires-Dist: numpy<2.0.0,>=1.26.0
22
+ Requires-Dist: rdkit>=2022.9.5
23
+ Requires-Dist: scipy>=1.11.0
24
+ Requires-Dist: torch>=2.5.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # MolGPF (`MolGPF-118`)
28
+
29
+ **MolGPF: A Periodic-Table-Wide Generative Pre-trained Flow Foundation Model for 3D Molecules and Transition-Metal Complexes**
30
+
31
+ `MolGPF` (*Molecular Generative Pre-trained Flow*) is a standalone, pure-PyTorch (DGL-free) $SE(3)$-equivariant continuous--discrete flow-matching foundation model spanning the full 118-element periodic table (`Z=1..118`), 11 formal-charge states (`-4..+6`), and 6 explicit bond classes including organometallic coordinate (`DATIVE L->M`) bonds.
32
+
33
+ ## Model Family (Pre-trained to `180M` Samples Each; Clean `1×A800` Calibrated)
34
+
35
+ | Model | Layers | Params | Clean `1×A800` Heun-25 | Val Loss (`14,891` mols) | `tmQM` Val Loss | `All Euler-100` Valid / Conn. | `Open-118 H25` Valid / Conn. |
36
+ | :--- | :---: | ---: | ---: | ---: | ---: | :---: | :---: |
37
+ | **`MolGPF-Small`** | `6` | `4.23M` | **`36.1 mol/s`** | `1.2353` | `1.2024` | **`96.2% / 90.8%`** | `88.5% / 78.9%` |
38
+ | **`MolGPF-Base`** | `9` | `12.74M` | `18.8 mol/s` | `1.1890` | `1.1112` | `95.3% / 90.9%` | **`89.3% / 79.7%`** |
39
+ | **`MolGPF-Large`** | `12` | **`40.19M`** | `10.3 mol/s` | **`1.1546`** | **`1.0456`** | `94.7% / 89.6%` | `87.9% / 79.1%` |
40
+
41
+ ## Downstream Zero-Leakage Conditional Adaptation (`tmQM` Transition Metals & Official `PropMolFlow` `QM9`)
42
+
43
+ | Benchmark | Method (`Solver / CFG`) | Clean `A800` GPU-h | Valid / Conn. | Key Quantum Control Result |
44
+ | :--- | :--- | :---: | :---: | :--- |
45
+ | **`tmQM`** (`4` DFT props, `44` elem) | `MolGPF-Large` From-Scratch (`H25`) | `4.07 h` | `5.5% / 1.6%` | Catastrophic collapse (`94.5%` invalid) |
46
+ | **`tmQM`** (`4` DFT props, `44` elem) | **`MolGPF-Large + LoRA`** (`E100`, `1.5`) | **`4.78 h`** | **`76.8% / 62.9%`** | **`74.5%`** valid TM complexes (`39.3×` conn.); HL gap `0.791 eV` (`-57.6%`) |
47
+ | **`QM9`** (`6` props, rapid LoRA) | **`MolGPF-Base / Large + LoRA`** | **`2.60–3.37 h`** | **`98.4% / 98.0%`** | `46×–60×` cheaper than `PropMolFlow` (`156 h`); beats `EDM`/`GeoLDM` on $\mu$ (`1.08 D`) |
48
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF-Base 1×K=6 SFT`** (`E100`, `N=1`) | `6.12 h` | `95.4% / 94.7%` | 1 unified model beats `EDM` on 4/6 props + **2-prop joint control** (`-42.7%` to `-49.9%` z-MAE) |
49
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF 6×K=1 Specialist SFT`** (`E100`, `N=1`) | `12.22 h` | `93.9% / 92.6%` | Pure `N=1` (`1.87 / 499 / 320 / 443 / 0.93 / 0.96`) **beats `EDM` & `GeoLDM` on all 6 props** |
50
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF-Base 1×K=6 + Bo8`** (Zero-Leak) | **`6.46 h`** | **`100% / 100%`** | **1 unified model beats 6-model `PropMolFlow` by `44.7%–59.3%`** (`24.1×` cheaper) |
51
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF 6×K=1 Specialist + Bo8`** (Zero-Leak) | `12.56 h` | **`100% / 100%`** | **`0.61 / 181 / 116 / 140 / 0.24 / 0.28`** (**beats `PropMolFlow` by `53.3%–61.2%`**, `12.4×` cheaper) |
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install molgpf
57
+ ```
58
+
59
+ ## Quick Start
60
+
61
+ ```python
62
+ from molgpf import MolGPFModel
63
+
64
+ model, meta = MolGPFModel.from_pretrained("pretrained/best_ema.pt", device="cuda")
65
+ n_atoms = MolGPFModel.sample_empirical_sizes(meta, n_mols=16, domain="tmqm")
66
+ mols = model.sample(
67
+ n_atoms,
68
+ n_steps=25,
69
+ solver="heun",
70
+ allowed_elements=meta["active_elements"],
71
+ )
72
+ ```
73
+
74
+ ## Repository Structure
75
+
76
+ - `src/molgpf/`: Standalone pure-PyTorch $SE(3)$-GVP flow foundation package (`MolGPFModel`, `MolGPFConfig`, `MolGPFConditioner`, `ToggleableLoRALinear`).
77
+ - `scripts/`: 5-source corpus builder (`4.86M` conformers, persisted at Wenyon `flowmol-corpus-118:1`), `16×A100` pre-training, `N=1,024×7` evaluation, single-node `8×A100` downstream LoRA benchmark, and paper figure generation.
78
+ - `results/`: Verified pre-training curves, corpus metadata, precision audit, Scaling Law summaries, and downstream LoRA transfer metrics.
79
+ - `paper/`: Complete arXiv manuscript (`main_molgpf.tex`, `main_molgpf.pdf`, `MolGPF_Paper.md`, vector figures, `MolGPF_arXiv_Submission.tar.gz`).
80
+ - `tests/`: Unit test suite (`pytest -q`).
81
+
82
+ ## Related Repositories
83
+
84
+ - **[`molgpao`](https://github.com/ShangChien/molgpao)**: Standalone `MolGPAO` speculative autoregressive octree 3D generator & paper (`pip install molgpao`).
85
+ - **[`ai-loom`](https://github.com/ShangChien/loom)**: Cross-paradigm `Loom` 3D molecular weaving & Grounded RSI platform & paper (`pip install ai-loom`).
86
+ - **[`molgen-rs`](https://github.com/ShangChien/molgen-rs)**: Unified client-side Rust + `wgpu` (`molgpf-rs`, `molgpao-rs`, `dpa4-rs`, `hyff-rs`, `loom-rs`, unified CLI & single-bundle WebGPU WASM).
molgpf-1.0.0/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # MolGPF (`MolGPF-118`)
2
+
3
+ **MolGPF: A Periodic-Table-Wide Generative Pre-trained Flow Foundation Model for 3D Molecules and Transition-Metal Complexes**
4
+
5
+ `MolGPF` (*Molecular Generative Pre-trained Flow*) is a standalone, pure-PyTorch (DGL-free) $SE(3)$-equivariant continuous--discrete flow-matching foundation model spanning the full 118-element periodic table (`Z=1..118`), 11 formal-charge states (`-4..+6`), and 6 explicit bond classes including organometallic coordinate (`DATIVE L->M`) bonds.
6
+
7
+ ## Model Family (Pre-trained to `180M` Samples Each; Clean `1×A800` Calibrated)
8
+
9
+ | Model | Layers | Params | Clean `1×A800` Heun-25 | Val Loss (`14,891` mols) | `tmQM` Val Loss | `All Euler-100` Valid / Conn. | `Open-118 H25` Valid / Conn. |
10
+ | :--- | :---: | ---: | ---: | ---: | ---: | :---: | :---: |
11
+ | **`MolGPF-Small`** | `6` | `4.23M` | **`36.1 mol/s`** | `1.2353` | `1.2024` | **`96.2% / 90.8%`** | `88.5% / 78.9%` |
12
+ | **`MolGPF-Base`** | `9` | `12.74M` | `18.8 mol/s` | `1.1890` | `1.1112` | `95.3% / 90.9%` | **`89.3% / 79.7%`** |
13
+ | **`MolGPF-Large`** | `12` | **`40.19M`** | `10.3 mol/s` | **`1.1546`** | **`1.0456`** | `94.7% / 89.6%` | `87.9% / 79.1%` |
14
+
15
+ ## Downstream Zero-Leakage Conditional Adaptation (`tmQM` Transition Metals & Official `PropMolFlow` `QM9`)
16
+
17
+ | Benchmark | Method (`Solver / CFG`) | Clean `A800` GPU-h | Valid / Conn. | Key Quantum Control Result |
18
+ | :--- | :--- | :---: | :---: | :--- |
19
+ | **`tmQM`** (`4` DFT props, `44` elem) | `MolGPF-Large` From-Scratch (`H25`) | `4.07 h` | `5.5% / 1.6%` | Catastrophic collapse (`94.5%` invalid) |
20
+ | **`tmQM`** (`4` DFT props, `44` elem) | **`MolGPF-Large + LoRA`** (`E100`, `1.5`) | **`4.78 h`** | **`76.8% / 62.9%`** | **`74.5%`** valid TM complexes (`39.3×` conn.); HL gap `0.791 eV` (`-57.6%`) |
21
+ | **`QM9`** (`6` props, rapid LoRA) | **`MolGPF-Base / Large + LoRA`** | **`2.60–3.37 h`** | **`98.4% / 98.0%`** | `46×–60×` cheaper than `PropMolFlow` (`156 h`); beats `EDM`/`GeoLDM` on $\mu$ (`1.08 D`) |
22
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF-Base 1×K=6 SFT`** (`E100`, `N=1`) | `6.12 h` | `95.4% / 94.7%` | 1 unified model beats `EDM` on 4/6 props + **2-prop joint control** (`-42.7%` to `-49.9%` z-MAE) |
23
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF 6×K=1 Specialist SFT`** (`E100`, `N=1`) | `12.22 h` | `93.9% / 92.6%` | Pure `N=1` (`1.87 / 499 / 320 / 443 / 0.93 / 0.96`) **beats `EDM` & `GeoLDM` on all 6 props** |
24
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF-Base 1×K=6 + Bo8`** (Zero-Leak) | **`6.46 h`** | **`100% / 100%`** | **1 unified model beats 6-model `PropMolFlow` by `44.7%–59.3%`** (`24.1×` cheaper) |
25
+ | **`QM9`** (`N=1,000` official `rQM9`) | **`MolGPF 6×K=1 Specialist + Bo8`** (Zero-Leak) | `12.56 h` | **`100% / 100%`** | **`0.61 / 181 / 116 / 140 / 0.24 / 0.28`** (**beats `PropMolFlow` by `53.3%–61.2%`**, `12.4×` cheaper) |
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pip install molgpf
31
+ ```
32
+
33
+ ## Quick Start
34
+
35
+ ```python
36
+ from molgpf import MolGPFModel
37
+
38
+ model, meta = MolGPFModel.from_pretrained("pretrained/best_ema.pt", device="cuda")
39
+ n_atoms = MolGPFModel.sample_empirical_sizes(meta, n_mols=16, domain="tmqm")
40
+ mols = model.sample(
41
+ n_atoms,
42
+ n_steps=25,
43
+ solver="heun",
44
+ allowed_elements=meta["active_elements"],
45
+ )
46
+ ```
47
+
48
+ ## Repository Structure
49
+
50
+ - `src/molgpf/`: Standalone pure-PyTorch $SE(3)$-GVP flow foundation package (`MolGPFModel`, `MolGPFConfig`, `MolGPFConditioner`, `ToggleableLoRALinear`).
51
+ - `scripts/`: 5-source corpus builder (`4.86M` conformers, persisted at Wenyon `flowmol-corpus-118:1`), `16×A100` pre-training, `N=1,024×7` evaluation, single-node `8×A100` downstream LoRA benchmark, and paper figure generation.
52
+ - `results/`: Verified pre-training curves, corpus metadata, precision audit, Scaling Law summaries, and downstream LoRA transfer metrics.
53
+ - `paper/`: Complete arXiv manuscript (`main_molgpf.tex`, `main_molgpf.pdf`, `MolGPF_Paper.md`, vector figures, `MolGPF_arXiv_Submission.tar.gz`).
54
+ - `tests/`: Unit test suite (`pytest -q`).
55
+
56
+ ## Related Repositories
57
+
58
+ - **[`molgpao`](https://github.com/ShangChien/molgpao)**: Standalone `MolGPAO` speculative autoregressive octree 3D generator & paper (`pip install molgpao`).
59
+ - **[`ai-loom`](https://github.com/ShangChien/loom)**: Cross-paradigm `Loom` 3D molecular weaving & Grounded RSI platform & paper (`pip install ai-loom`).
60
+ - **[`molgen-rs`](https://github.com/ShangChien/molgen-rs)**: Unified client-side Rust + `wgpu` (`molgpf-rs`, `molgpao-rs`, `dpa4-rs`, `hyff-rs`, `loom-rs`, unified CLI & single-bundle WebGPU WASM).
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "molgpf"
7
+ version = "1.0.0"
8
+ description = "MolGPF: Periodic-Table-Wide Generative Pre-trained Flow Foundation Model for 3D Molecules and Transition-Metal Complexes"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11,<3.13"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ keywords = [
14
+ "3d-molecular-generation",
15
+ "flow-matching",
16
+ "foundation-model",
17
+ "periodic-table",
18
+ "transition-metal-complexes",
19
+ "se3-equivariant",
20
+ "gvp",
21
+ "chemistry",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Intended Audience :: Science/Research",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Topic :: Scientific/Engineering :: Chemistry",
30
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
31
+ ]
32
+ authors = [
33
+ { name = "Shangqian Chen", email = "chensq@dp.tech" },
34
+ { name = "Guojiang Zhao" },
35
+ { name = "Zheng Cheng" },
36
+ { name = "Jiankun Wang" },
37
+ { name = "Hongshuai Wang" },
38
+ { name = "Zhifeng Gao" },
39
+ ]
40
+ dependencies = [
41
+ "numpy>=1.26.0,<2.0.0",
42
+ "scipy>=1.11.0",
43
+ "torch>=2.5.0",
44
+ "rdkit>=2022.9.5",
45
+ ]
46
+
47
+ [project.urls]
48
+ Homepage = "https://github.com/ShangChien/molgpf"
49
+ Repository = "https://github.com/ShangChien/molgpf"
50
+ Issues = "https://github.com/ShangChien/molgpf/issues"
51
+
52
+ [tool.hatch.build.targets.sdist]
53
+ include = [
54
+ "/src/molgpf",
55
+ "/tests",
56
+ "/README.md",
57
+ "/LICENSE",
58
+ "/pyproject.toml",
59
+ ]
60
+
61
+ [tool.hatch.build.targets.wheel]
62
+ packages = ["src/molgpf"]
63
+
64
+ [tool.pytest.ini_options]
65
+ testpaths = ["tests"]
66
+ pythonpath = [".", "src"]
@@ -0,0 +1,96 @@
1
+ """MolGPF: Molecular Generative Pre-trained Flow (Periodic-Table-Wide 118-Element 3D Foundation Model)."""
2
+
3
+ from .conditioner import LoomConditioner, MolGPFConditioner
4
+ from .constants import (
5
+ ATOM_MASK_IDX,
6
+ ATOM_TO_IDX,
7
+ BOND_MASK_IDX,
8
+ CHARGE_MASK_IDX,
9
+ CHARGE_TO_IDX,
10
+ FLOWMOL_ATOM_TYPES,
11
+ FLOWMOL_BOND_TYPES,
12
+ FLOWMOL_FORMAL_CHARGES,
13
+ LEGACY_5_BOND_TYPES,
14
+ LEGACY_6_FORMAL_CHARGES,
15
+ N_ATOM_TYPES,
16
+ N_BOND_TYPES,
17
+ N_CHARGES,
18
+ ORGANIC_16_ATOM_TYPES,
19
+ PERIODIC_FEATURE_DIM,
20
+ build_allowed_charge_mask,
21
+ build_allowed_element_mask,
22
+ build_periodic_feature_tensor,
23
+ evaluate_sampled_molecules,
24
+ mol_to_sparse_record,
25
+ tensors_to_rdkit_mol,
26
+ )
27
+ from .data import (
28
+ DynamicEdgeBudgetBatchSampler,
29
+ FlatMoleculeCorpus,
30
+ FlowMolBatch,
31
+ build_complete_graph_batch,
32
+ collate_flowmol_batch,
33
+ write_flat_corpus,
34
+ )
35
+ from .gvp import (
36
+ EdgeUpdate,
37
+ GVP,
38
+ GVPConv,
39
+ ToggleableLoRALinear,
40
+ compute_edge_geometry_fp32,
41
+ disable_lora,
42
+ inject_flowmol_lora,
43
+ )
44
+ from .model import FlowMolConfig, FlowMolModel, MolGPFConfig, MolGPFModel
45
+ from .priors import (
46
+ apply_train_geometry_distortion_fp32,
47
+ coord_prior_std_for_size,
48
+ proper_kabsch_align_fp32,
49
+ remove_com_fp32,
50
+ sample_aligned_coord_prior_np,
51
+ )
52
+ from .scheduler import FlowInterpolantScheduler, build_inference_tspan, sample_train_timesteps
53
+ InterpolantScheduler = FlowInterpolantScheduler
54
+
55
+ # Clean MolGPF aliases
56
+ MOLGPF_ATOM_TYPES = FLOWMOL_ATOM_TYPES
57
+ MOLGPF_FORMAL_CHARGES = FLOWMOL_FORMAL_CHARGES
58
+ MOLGPF_BOND_TYPES = FLOWMOL_BOND_TYPES
59
+ MolGPFBatch = FlowMolBatch
60
+ inject_molgpf_lora = inject_flowmol_lora
61
+ collate_molgpf_batch = collate_flowmol_batch
62
+
63
+ __version__ = "1.0.0"
64
+
65
+ __all__ = [
66
+ "MolGPFConfig",
67
+ "MolGPFModel",
68
+ "MolGPFBatch",
69
+ "MolGPFConditioner",
70
+ "MOLGPF_ATOM_TYPES",
71
+ "MOLGPF_FORMAL_CHARGES",
72
+ "MOLGPF_BOND_TYPES",
73
+ "inject_molgpf_lora",
74
+ "collate_molgpf_batch",
75
+ "ToggleableLoRALinear",
76
+ "disable_lora",
77
+ "FlatMoleculeCorpus",
78
+ "DynamicEdgeBudgetBatchSampler",
79
+ "FlowInterpolantScheduler",
80
+ "InterpolantScheduler",
81
+ "evaluate_sampled_molecules",
82
+ "mol_to_sparse_record",
83
+ "tensors_to_rdkit_mol",
84
+ # Backward-compatible aliases
85
+ "FlowMolConfig",
86
+ "FlowMolModel",
87
+ "FlowMolBatch",
88
+ "LoomConditioner",
89
+ "FLOWMOL_ATOM_TYPES",
90
+ "FLOWMOL_FORMAL_CHARGES",
91
+ "FLOWMOL_BOND_TYPES",
92
+ "LEGACY_5_BOND_TYPES",
93
+ "LEGACY_6_FORMAL_CHARGES",
94
+ "inject_flowmol_lora",
95
+ "collate_flowmol_batch",
96
+ ]
@@ -0,0 +1,318 @@
1
+ """High-capacity property conditioner combining Gaussian RBF + Fourier expansion,
2
+ multi-token attention prefixes, and unclamped AdaLN-Zero modulation.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+
12
+ class MolGPFConditioner(nn.Module):
13
+ """High-bandwidth continuous scalar / multi-property conditioner for 3D generators.
14
+
15
+ Addresses the three bottlenecks identified in historical point-conditioning:
16
+ 1. Replaces bare `Linear(1, D)` with multi-scale Gaussian RBF + log-spaced Fourier features.
17
+ 2. Injects `num_prefix_tokens` dedicated condition KV tokens at the start of the causal sequence
18
+ (plus zero-initialized root residual when `num_prefix_tokens == 0`).
19
+ 3. Uses DiT-style zero-initialized AdaLN-Zero without the `0.08 * tanh` ceiling.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ emb_dim: int = 768,
25
+ num_props: int = 2,
26
+ num_layers: int = 12,
27
+ num_rbf: int = 32,
28
+ rbf_min: float = -4.5,
29
+ rbf_max: float = 4.5,
30
+ num_freqs: int = 16,
31
+ num_prefix_tokens: int = 0,
32
+ modulation_cap: float = 4.0,
33
+ edge_dim: int = 0,
34
+ vec_dim: int = 0,
35
+ use_size_context: bool = False,
36
+ use_time_context: bool = False,
37
+ size_mean: float = 18.0,
38
+ size_std: float = 5.0,
39
+ ) -> None:
40
+ super().__init__()
41
+ self.emb_dim = int(emb_dim)
42
+ self.num_props = int(num_props)
43
+ self.num_layers = int(num_layers)
44
+ self.num_rbf = int(num_rbf)
45
+ self.num_freqs = int(num_freqs)
46
+ self.num_prefix_tokens = int(num_prefix_tokens)
47
+ self.modulation_cap = float(modulation_cap)
48
+ self.edge_dim = int(edge_dim)
49
+ self.vec_dim = int(vec_dim)
50
+ self.use_size_context = bool(use_size_context)
51
+ self.use_time_context = bool(use_time_context)
52
+ self.size_mean = float(size_mean)
53
+ self.size_std = float(max(size_std, 1e-3))
54
+
55
+ centers = torch.linspace(rbf_min, rbf_max, num_rbf, dtype=torch.float32)
56
+ spacing = (rbf_max - rbf_min) / max(num_rbf - 1, 1)
57
+ self.register_buffer("rbf_centers", centers)
58
+ self.rbf_gamma = 1.0 / (2.0 * (spacing ** 2))
59
+
60
+ freqs = (2.0 ** torch.linspace(-1.0, 4.0, num_freqs, dtype=torch.float32)) * math.pi
61
+ self.register_buffer("fourier_freqs", freqs)
62
+
63
+ # Per-property feature vector: [val, active_flag] + RBF(num_rbf) + sin/cos(2 * num_freqs)
64
+ in_dim = 2 + num_rbf + 2 * num_freqs
65
+ self.prop_encoders = nn.ModuleList(
66
+ [
67
+ nn.Sequential(
68
+ nn.Linear(in_dim, emb_dim),
69
+ nn.LayerNorm(emb_dim),
70
+ nn.SiLU(),
71
+ nn.Linear(emb_dim, emb_dim),
72
+ nn.LayerNorm(emb_dim),
73
+ nn.SiLU(),
74
+ )
75
+ for _ in range(num_props)
76
+ ]
77
+ )
78
+ self.prop_id_emb = nn.Embedding(num_props, emb_dim)
79
+ self.inactive_prop_emb = nn.Parameter(torch.zeros(num_props, emb_dim))
80
+
81
+ extra_slots = 0
82
+ if self.use_size_context:
83
+ self.size_encoder: nn.Module | None = nn.Sequential(
84
+ nn.Linear(in_dim, emb_dim),
85
+ nn.LayerNorm(emb_dim),
86
+ nn.SiLU(),
87
+ nn.Linear(emb_dim, emb_dim),
88
+ nn.LayerNorm(emb_dim),
89
+ nn.SiLU(),
90
+ )
91
+ extra_slots += 1
92
+ else:
93
+ self.size_encoder = None
94
+
95
+ if self.use_time_context:
96
+ self.time_encoder: nn.Module | None = nn.Sequential(
97
+ nn.Linear(in_dim, emb_dim),
98
+ nn.LayerNorm(emb_dim),
99
+ nn.SiLU(),
100
+ nn.Linear(emb_dim, emb_dim),
101
+ nn.LayerNorm(emb_dim),
102
+ nn.SiLU(),
103
+ )
104
+ extra_slots += 1
105
+ else:
106
+ self.time_encoder = None
107
+
108
+ mlp_in_dim = (num_props + extra_slots) * emb_dim
109
+
110
+ self.global_mlp = nn.Sequential(
111
+ nn.Linear(mlp_in_dim, emb_dim * 2),
112
+ nn.LayerNorm(emb_dim * 2),
113
+ nn.SiLU(),
114
+ nn.Linear(emb_dim * 2, emb_dim),
115
+ nn.LayerNorm(emb_dim),
116
+ nn.SiLU(),
117
+ )
118
+
119
+ # Multi-token causal prefix embeddings: [B, P, emb_dim] (zero-initialized when enabled)
120
+ if self.num_prefix_tokens > 0:
121
+ self.prefix_queries = nn.Parameter(torch.randn(self.num_prefix_tokens, emb_dim) * 0.02)
122
+ proj_out = nn.Linear(emb_dim, emb_dim)
123
+ nn.init.zeros_(proj_out.weight)
124
+ nn.init.zeros_(proj_out.bias)
125
+ self.prefix_proj = nn.Sequential(
126
+ nn.Linear(emb_dim * 2, emb_dim),
127
+ nn.LayerNorm(emb_dim),
128
+ nn.SiLU(),
129
+ proj_out,
130
+ )
131
+ self.null_prefix = nn.Parameter(torch.randn(self.num_prefix_tokens, emb_dim) * 0.02)
132
+ else:
133
+ self.prefix_queries = None
134
+ self.prefix_proj = None
135
+ self.null_prefix = None
136
+
137
+ # Root residual injection (zero-initialized gate)
138
+ self.root_proj = nn.Linear(emb_dim, emb_dim, bias=False)
139
+ nn.init.normal_(self.root_proj.weight, mean=0.0, std=0.02)
140
+ self.root_gate = nn.Parameter(torch.zeros((), dtype=torch.float32))
141
+
142
+ # Unclamped AdaLN-Zero per-layer & final-norm modulations (exact zero init)
143
+ self.layer_mods = nn.ModuleList(
144
+ [nn.Sequential(nn.SiLU(), nn.Linear(emb_dim, 2 * emb_dim, bias=True)) for _ in range(num_layers)]
145
+ )
146
+ for mod in self.layer_mods:
147
+ nn.init.zeros_(mod[1].weight)
148
+ nn.init.zeros_(mod[1].bias)
149
+
150
+ self.out_mod = nn.Sequential(nn.SiLU(), nn.Linear(emb_dim, 2 * emb_dim, bias=True))
151
+ nn.init.zeros_(self.out_mod[1].weight)
152
+ nn.init.zeros_(self.out_mod[1].bias)
153
+
154
+ if self.edge_dim > 0:
155
+ self.edge_layer_mods: nn.ModuleList | None = nn.ModuleList(
156
+ [nn.Sequential(nn.SiLU(), nn.Linear(emb_dim, 2 * self.edge_dim, bias=True)) for _ in range(num_layers)]
157
+ )
158
+ for emod in self.edge_layer_mods:
159
+ nn.init.zeros_(emod[1].weight)
160
+ nn.init.zeros_(emod[1].bias)
161
+ self.edge_out_mod: nn.Sequential | None = nn.Sequential(
162
+ nn.SiLU(), nn.Linear(emb_dim, 2 * self.edge_dim, bias=True)
163
+ )
164
+ nn.init.zeros_(self.edge_out_mod[1].weight)
165
+ nn.init.zeros_(self.edge_out_mod[1].bias)
166
+ else:
167
+ self.edge_layer_mods = None
168
+ self.edge_out_mod = None
169
+
170
+ # SO(3)-equivariant vector channel scale gates (2 * vec_dim per block: pre-conv & pre-pos-update)
171
+ if self.vec_dim > 0:
172
+ self.vec_layer_mods: nn.ModuleList | None = nn.ModuleList(
173
+ [nn.Sequential(nn.SiLU(), nn.Linear(emb_dim, 2 * self.vec_dim, bias=True)) for _ in range(num_layers)]
174
+ )
175
+ for vmod in self.vec_layer_mods:
176
+ nn.init.zeros_(vmod[1].weight)
177
+ nn.init.zeros_(vmod[1].bias)
178
+ else:
179
+ self.vec_layer_mods = None
180
+
181
+ def _expand_scalar(self, val: torch.Tensor, active: torch.Tensor) -> torch.Tensor:
182
+ """Expand normalized scalar `val` `(B,)` and boolean `active` `(B,)` to `(B, in_dim)`."""
183
+ val_clean = torch.where(active, val.float(), torch.zeros_like(val, dtype=torch.float32))
184
+ diff = val_clean.unsqueeze(-1) - self.rbf_centers.unsqueeze(0)
185
+ rbf = torch.exp(-self.rbf_gamma * diff.square())
186
+ angles = val_clean.unsqueeze(-1) * self.fourier_freqs.unsqueeze(0)
187
+ sin_cos = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
188
+ act_f = active.float().unsqueeze(-1)
189
+ raw = torch.cat([val_clean.unsqueeze(-1), rbf, sin_cos], dim=-1) * act_f
190
+ return torch.cat([raw, act_f], dim=-1)
191
+
192
+ def encode_condition(
193
+ self,
194
+ values: torch.Tensor,
195
+ active_mask: torch.Tensor,
196
+ *,
197
+ n_atoms: torch.Tensor | None = None,
198
+ t: torch.Tensor | None = None,
199
+ ) -> tuple[torch.Tensor, torch.Tensor]:
200
+ """Return `(global_c, has_any)` where `global_c` is `(B, emb_dim)` and `has_any` is `(B, 1)` bool."""
201
+ active = active_mask.any(dim=-1) if active_mask.ndim == 3 else active_mask.bool()
202
+ bsz = values.shape[0]
203
+ device = values.device
204
+ per_prop = []
205
+ for k in range(self.num_props):
206
+ act_k = active[:, k]
207
+ feat_k = self._expand_scalar(values[:, k], act_k)
208
+ enc_k = self.prop_encoders[k](feat_k) + self.prop_id_emb(
209
+ torch.full((bsz,), k, dtype=torch.long, device=device)
210
+ )
211
+ emb_k = torch.where(act_k.unsqueeze(-1), enc_k, self.inactive_prop_emb[k].unsqueeze(0))
212
+ per_prop.append(emb_k)
213
+ if self.use_size_context and self.size_encoder is not None:
214
+ if n_atoms is not None:
215
+ n_z = ((n_atoms.to(device=device, dtype=torch.float32) - self.size_mean) / self.size_std).clamp(-4.5, 4.5)
216
+ s_act = torch.ones((bsz,), dtype=torch.bool, device=device)
217
+ else:
218
+ n_z = torch.zeros((bsz,), dtype=torch.float32, device=device)
219
+ s_act = torch.zeros((bsz,), dtype=torch.bool, device=device)
220
+ per_prop.append(self.size_encoder(self._expand_scalar(n_z, s_act)))
221
+ if self.use_time_context and self.time_encoder is not None:
222
+ if t is not None:
223
+ # Map t in [0, 1] to [-3.0, +3.0] across the Gaussian RBF + Fourier basis
224
+ t_z = (t.to(device=device, dtype=torch.float32).view(-1) * 6.0 - 3.0).clamp(-4.5, 4.5)
225
+ t_act = torch.ones((bsz,), dtype=torch.bool, device=device)
226
+ else:
227
+ t_z = torch.zeros((bsz,), dtype=torch.float32, device=device)
228
+ t_act = torch.zeros((bsz,), dtype=torch.bool, device=device)
229
+ per_prop.append(self.time_encoder(self._expand_scalar(t_z, t_act)))
230
+ fused = self.global_mlp(torch.cat(per_prop, dim=-1))
231
+ has_any = active.any(dim=-1, keepdim=True)
232
+ global_c = fused * has_any.to(fused.dtype)
233
+ return global_c, has_any
234
+
235
+ def forward(self, values: torch.Tensor, unused_upper: torch.Tensor | None, active_mask: torch.Tensor) -> torch.Tensor:
236
+ global_c, _ = self.encode_condition(values, active_mask)
237
+ return global_c
238
+
239
+ def build_prefix_tokens(self, global_c: torch.Tensor, has_any: torch.Tensor) -> torch.Tensor | None:
240
+ """Build `(B, P, emb_dim)` condition prefix tokens; uses learned `null_prefix` when unconditional."""
241
+ if self.num_prefix_tokens <= 0:
242
+ return None
243
+ bsz = global_c.shape[0]
244
+ queries = self.prefix_queries.unsqueeze(0).expand(bsz, -1, -1)
245
+ c_rep = global_c.float().unsqueeze(1).expand(-1, self.num_prefix_tokens, -1)
246
+ cond_prefix = queries + self.prefix_proj(torch.cat([queries, c_rep], dim=-1))
247
+ null_prefix = self.null_prefix.unsqueeze(0).expand(bsz, -1, -1)
248
+ mask_3d = has_any.view(bsz, 1, 1)
249
+ return torch.where(mask_3d, cond_prefix, null_prefix)
250
+
251
+ def forward_root_prefix(self, global_c: torch.Tensor) -> torch.Tensor:
252
+ return self.root_gate * self.root_proj(global_c.float())
253
+
254
+ def _apply_mod(self, mod_net: nn.Module, h: torch.Tensor, global_c: torch.Tensor) -> torch.Tensor:
255
+ raw = mod_net(global_c.float())
256
+ if self.modulation_cap > 0:
257
+ raw = self.modulation_cap * torch.tanh(raw / self.modulation_cap)
258
+ scale, shift = raw.to(h.dtype).chunk(2, dim=-1)
259
+ return h * (1.0 + scale) + shift
260
+
261
+ def modulate_layer(self, layer_idx: int, h: torch.Tensor, global_c: torch.Tensor) -> torch.Tensor:
262
+ return self._apply_mod(self.layer_mods[layer_idx], h, global_c)
263
+
264
+ def modulate_out(self, h: torch.Tensor, global_c: torch.Tensor) -> torch.Tensor:
265
+ return self._apply_mod(self.out_mod, h, global_c)
266
+
267
+ def precompute_modulations(
268
+ self, global_c: torch.Tensor, dtype: torch.dtype
269
+ ) -> tuple[list[tuple[torch.Tensor, torch.Tensor]], tuple[torch.Tensor, torch.Tensor]]:
270
+ """Precompute `(1 + scale, shift)` across all layers + output norm once per trajectory."""
271
+ c_fp32 = global_c.float()
272
+
273
+ def _one(mod_net: nn.Module) -> tuple[torch.Tensor, torch.Tensor]:
274
+ raw = mod_net(c_fp32)
275
+ if self.modulation_cap > 0:
276
+ raw = self.modulation_cap * torch.tanh(raw / self.modulation_cap)
277
+ scale, shift = raw.to(dtype).chunk(2, dim=-1)
278
+ return (1.0 + scale), shift
279
+
280
+ layer_pairs = [_one(mod) for mod in self.layer_mods]
281
+ out_pair = _one(self.out_mod)
282
+ return layer_pairs, out_pair
283
+
284
+ def precompute_edge_modulations(
285
+ self, global_c: torch.Tensor, dtype: torch.dtype
286
+ ) -> tuple[list[tuple[torch.Tensor, torch.Tensor]], tuple[torch.Tensor, torch.Tensor]] | None:
287
+ """Precompute `(1 + e_scale, e_shift)` across all edge layers + final edge readout when `edge_dim > 0`."""
288
+ if self.edge_layer_mods is None or self.edge_out_mod is None:
289
+ return None
290
+ c_fp32 = global_c.float()
291
+
292
+ def _one(mod_net: nn.Module) -> tuple[torch.Tensor, torch.Tensor]:
293
+ raw = mod_net(c_fp32)
294
+ if self.modulation_cap > 0:
295
+ raw = self.modulation_cap * torch.tanh(raw / self.modulation_cap)
296
+ scale, shift = raw.to(dtype).chunk(2, dim=-1)
297
+ return (1.0 + scale), shift
298
+
299
+ return [_one(mod) for mod in self.edge_layer_mods], _one(self.edge_out_mod)
300
+
301
+ def precompute_vec_modulations(
302
+ self, global_c: torch.Tensor
303
+ ) -> list[tuple[torch.Tensor, torch.Tensor]] | None:
304
+ """Precompute FP32 `(1 + v_scale_conv, 1 + v_scale_pos)` SO(3)-equivariant vector gates when `vec_dim > 0`."""
305
+ if self.vec_layer_mods is None:
306
+ return None
307
+ c_fp32 = global_c.float()
308
+ out: list[tuple[torch.Tensor, torch.Tensor]] = []
309
+ for vmod in self.vec_layer_mods:
310
+ raw = vmod(c_fp32)
311
+ if self.modulation_cap > 0:
312
+ raw = self.modulation_cap * torch.tanh(raw / self.modulation_cap)
313
+ s_conv, s_pos = raw.chunk(2, dim=-1)
314
+ out.append((1.0 + s_conv, 1.0 + s_pos))
315
+ return out
316
+
317
+ # Backward-compatible alias
318
+ LoomConditioner = MolGPFConditioner