File size: 11,054 Bytes
db32e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable, List, Optional

import numpy as np
from tqdm import tqdm
from .io import chunked


def l2_normalize(x: np.ndarray, eps: float = 1e-8) -> np.ndarray:
    norm = np.linalg.norm(x, axis=-1, keepdims=True)
    return x / (norm + eps)


@dataclass
class SMILESEmbedder:
    model_name: str
    device: str = "cpu"
    pooling: str = "cls"  # "cls" or "mean"
    batch_size: int = 64
    max_length: int = 256
    normalize: bool = True

    def _load(self):
        from transformers import AutoModel, AutoTokenizer

        tokenizer = AutoTokenizer.from_pretrained(self.model_name)
        # Use safetensors to avoid torch.load CVE (CVE-2025-32434) when torch < 2.6
        try:
            model = AutoModel.from_pretrained(self.model_name, use_safetensors=True)
        except Exception as e:
            raise RuntimeError(
                "Loading ChemBERTa failed (transformers require torch>=2.6 or safetensors). "
                "Upgrade with: pip install 'torch>=2.6', or ensure the model has .safetensors on the Hub."
            ) from e
        import torch
        if self.device == "cuda" and torch.cuda.device_count() > 1:
            model = torch.nn.DataParallel(model, device_ids=list(range(torch.cuda.device_count())))
        model.to(self.device)
        model.eval()
        return tokenizer, model

    def encode(self, smiles: Iterable[str]) -> np.ndarray:
        smiles_list = list(smiles)
        if not smiles_list:
            return np.zeros((0, 0), dtype=np.float32)
        tokenizer, model = self._load()
        outputs: List[np.ndarray] = []
        import torch

        n_batches = (len(smiles_list) + self.batch_size - 1) // self.batch_size
        with torch.no_grad():
            for _, batch in tqdm(
                chunked(smiles_list, self.batch_size),
                total=n_batches,
                desc="Encoding SMILES",
                unit="batch",
            ):
                toks = tokenizer(
                    batch,
                    padding=True,
                    truncation=True,
                    max_length=self.max_length,
                    return_tensors="pt",
                ).to(self.device)
                h = model(**toks).last_hidden_state
                if self.pooling == "mean":
                    mask = toks["attention_mask"].unsqueeze(-1).float()
                    pooled = (h * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1.0)
                else:
                    pooled = h[:, 0]
                outputs.append(pooled.detach().cpu().numpy())
        arr = np.concatenate(outputs, axis=0).astype(np.float32)
        if self.normalize:
            arr = l2_normalize(arr)
        return arr


@dataclass
class SpectrumEmbedder:
    specbridge_ckpt: str
    dreams_ckpt: Optional[str] = None
    d_out: int = 512
    mapper_hidden: int = 512
    n_blocks: int = 4
    chemberta_model: str = "seyonec/ChemBERTa-zinc-base-v1"
    device: str = "cpu"
    normalize: bool = True
    use_lightweight: bool = False

    def _load(self):
        import torch
        from argparse import Namespace
        from pathlib import PosixPath
        from pathlib import Path
        import sys
        import types

        specbridge_root = Path(__file__).resolve().parents[2] / "SpecBridge"
        dreams_root = specbridge_root / "DreaMS"
        for p in (specbridge_root, dreams_root):
            if p.exists() and str(p) not in sys.path:
                sys.path.insert(0, str(p))
        try:
            torch.serialization.add_safe_globals([Namespace, PosixPath])
        except Exception:
            pass

        from specbridge.adapters.dreams_adapter import load_dreams_encoder

        try:
            state = torch.load(self.specbridge_ckpt, map_location="cpu", weights_only=False)
        except TypeError:
            state = torch.load(self.specbridge_ckpt, map_location="cpu")
        model_state = state.get("model", state)
        ckpt_args = state.get("args", {}) if isinstance(state, dict) else {}

        d_out = self.d_out
        mapper_hidden = self.mapper_hidden
        n_blocks = self.n_blocks
        chemberta_model = self.chemberta_model
        spec_bins = 2048
        if isinstance(ckpt_args, dict):
            if ckpt_args.get("cond_dim") is not None:
                d_out = int(ckpt_args["cond_dim"])
            if ckpt_args.get("mapper_hidden") is not None:
                mapper_hidden = int(ckpt_args["mapper_hidden"])
            if ckpt_args.get("n_blocks") is not None:
                n_blocks = int(ckpt_args["n_blocks"])
            if ckpt_args.get("chemberta_model"):
                chemberta_model = str(ckpt_args["chemberta_model"])
            if ckpt_args.get("spec_bins") is not None:
                spec_bins = int(ckpt_args["spec_bins"])

        dreams_d_out = 1024
        if isinstance(model_state, dict) and "spec.proj.0.0.weight" in model_state:
            dreams_d_out = int(model_state["spec.proj.0.0.weight"].shape[1])
        dreams = load_dreams_encoder(self.dreams_ckpt, d_in=spec_bins, d_out=dreams_d_out)
        self._dreams_is_dummy = dreams.__class__.__name__ == "DummyDreams"

        if self.use_lightweight:
            if isinstance(model_state, dict):
                if "spec.proj.0.0.weight" in model_state:
                    d_out = int(model_state["spec.proj.0.0.weight"].shape[0])
                elif "mapB.W.weight" in model_state:
                    d_out = int(model_state["mapB.W.weight"].shape[1])
                if "mapB.blocks.0.fc1.weight" in model_state:
                    mapper_hidden = int(model_state["mapB.blocks.0.fc1.weight"].shape[0])
                block_ids = set()
                for key in model_state.keys():
                    if key.startswith("mapB.blocks."):
                        parts = key.split(".")
                        if len(parts) > 2 and parts[2].isdigit():
                            block_ids.add(int(parts[2]))
                if block_ids:
                    n_blocks = max(block_ids) + 1

            from transformers import AutoConfig
            from specbridge.adapters.dreams_adapter import DreamsAdapter
            from specbridge.models.mapper import ProcrustesResidualMapper

            hid = int(AutoConfig.from_pretrained(chemberta_model).hidden_size)
            spec = DreamsAdapter(
                dreams_encoder=dreams,
                d_out=d_out,
                hidden=mapper_hidden,
                freeze_backbone=True,
            )
            mapB = ProcrustesResidualMapper(
                d_in=d_out,
                d_out=hid,
                n_blocks=n_blocks,
                hidden=mapper_hidden,
                gaussian=True,
                random_init=False,
            )

            class _LightSpecBridge(torch.nn.Module):
                def __init__(self, spec, mapB):
                    super().__init__()
                    self.spec = spec
                    self.mapB = mapB

            model = _LightSpecBridge(spec, mapB)
            model._dreams_is_dummy = self._dreams_is_dummy
            model.load_state_dict(model_state, strict=False)
            model.to(self.device)
            model.eval()
            return model

        from specbridge.models.mapper import DreamsToMolCondition

        model = DreamsToMolCondition(
            dreams_encoder=dreams,
            d_out=d_out,
            mapper_hidden=mapper_hidden,
            gaussian=True,
            mol_space="chemberta",
            chemberta_model=chemberta_model,
            args=type("Args", (), {"n_blocks": n_blocks, "random_mapper_init": False})(),
            freeze_backbone=True,
        )
        model.load_state_dict(model_state, strict=False)
        model._dreams_is_dummy = self._dreams_is_dummy
        model.to(self.device)
        model.eval()
        return model

    def encode(self, spectra_binned, meta: dict, batch_size: int | None = None) -> np.ndarray:
        import torch

        model = self._load()
        if not isinstance(spectra_binned, torch.Tensor):
            spectra_binned = torch.tensor(spectra_binned, dtype=torch.float32)
        total = spectra_binned.shape[0]
        if batch_size is None or batch_size <= 0:
            batch_size = total
        outputs = []
        use_peaks = not getattr(model, "_dreams_is_dummy", False)
        with torch.no_grad():
            for start in tqdm(range(0, total, batch_size)):
                end = min(total, start + batch_size)
                batch = spectra_binned[start:end].to(self.device)
                batch_meta = meta
                if isinstance(meta, dict):
                    batch_meta = {}
                    for k, v in meta.items():
                        if k == "peaks" and not use_peaks:
                            continue
                        if isinstance(v, torch.Tensor) and v.shape[0] == total:
                            batch_meta[k] = v[start:end].to(self.device)
                        else:
                            batch_meta[k] = v
                z_s = model.spec(batch, batch_meta)
                mu_s, _ = model.mapB(z_s)
                outputs.append(mu_s.detach().cpu().numpy().astype(np.float32))
        emb = np.concatenate(outputs, axis=0) if outputs else np.zeros((0, 0), dtype=np.float32)
        if self.normalize:
            emb = l2_normalize(emb)
        return emb

    def encode_spec_only(
        self, spectra_binned, meta: dict, batch_size: int | None = None
    ) -> np.ndarray:
        """Return E_mist(spec): spectrum embedding before mapper (d_spec), for mapper training."""
        import torch

        model = self._load()
        if not isinstance(spectra_binned, torch.Tensor):
            spectra_binned = torch.tensor(spectra_binned, dtype=torch.float32)
        total = spectra_binned.shape[0]
        if batch_size is None or batch_size <= 0:
            batch_size = total
        outputs = []
        use_peaks = not getattr(model, "_dreams_is_dummy", False)
        with torch.no_grad():
            for start in range(0, total, batch_size):
                end = min(total, start + batch_size)
                batch = spectra_binned[start:end].to(self.device)
                batch_meta = meta
                if isinstance(meta, dict):
                    batch_meta = {}
                    for k, v in meta.items():
                        if k == "peaks" and not use_peaks:
                            continue
                        if isinstance(v, torch.Tensor) and v.shape[0] == total:
                            batch_meta[k] = v[start:end].to(self.device)
                        else:
                            batch_meta[k] = v
                z_s = model.spec(batch, batch_meta)
                outputs.append(z_s.detach().cpu().numpy().astype(np.float32))
        return (
            np.concatenate(outputs, axis=0)
            if outputs
            else np.zeros((0, 0), dtype=np.float32)
        )