File size: 15,988 Bytes
839a5b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da903c2
 
 
 
 
 
 
 
 
 
 
839a5b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Standalone modality-aware tokenizer for HuggingFace AutoTokenizer (trust_remote_code=True)."""

from __future__ import annotations

import json
import re
from pathlib import Path
from typing import Any

from tokenizers import Tokenizer

BOS_TOKEN = '<|bos|>'
EOS_TOKEN = '<|eos|>'
PAD_TOKEN = '<|pad|>'
SPECIAL_TOKENS = ['<|bos|>', '<|eos|>', '<|pad|>', '<|fim_prefix|>', '<|fim_middle|>', '<|fim_suffix|>', '<|im_start|>', '<|im_end|>', '<|think|>', '<|/think|>', '<|tool_call|>', '<|/tool_call|>', '<|tool_response|>', '<|/tool_response|>', '<|code_exec|>', '<|/code_exec|>', '[START_SMILES]', '[END_SMILES]', '[START_SELFIES]', '[END_SELFIES]', '[START_IUPAC]', '[END_IUPAC]', '[START_AMINO]', '[END_AMINO]', '[START_DNA]', '[END_DNA]', '[START_REF]', '[END_REF]', '<|reserved_0|>', '<|reserved_1|>', '<|reserved_2|>', '<|reserved_3|>', '<|reserved_4|>', '<|reserved_5|>', '<|reserved_6|>', '<|reserved_7|>', '<|reserved_8|>', '<|reserved_9|>', '<|reserved_10|>', '<|reserved_11|>', '<|reserved_12|>', '<|reserved_13|>', '<|reserved_14|>', '<|reserved_15|>', '<|reserved_16|>', '<|reserved_17|>', '<|reserved_18|>', '<|reserved_19|>', '<|reserved_20|>', '<|reserved_21|>', '<|reserved_22|>', '<|reserved_23|>', '<|reserved_24|>', '<|reserved_25|>', '<|reserved_26|>', '<|reserved_27|>', '<|reserved_28|>', '<|reserved_29|>', '<|reserved_30|>', '<|reserved_31|>']
ATOMIC_MODALITY_ENTRIES = [('[AA:A]', 'A'), ('[AA:B]', 'B'), ('[AA:C]', 'C'), ('[AA:D]', 'D'), ('[AA:E]', 'E'), ('[AA:F]', 'F'), ('[AA:G]', 'G'), ('[AA:H]', 'H'), ('[AA:I]', 'I'), ('[AA:J]', 'J'), ('[AA:K]', 'K'), ('[AA:L]', 'L'), ('[AA:M]', 'M'), ('[AA:N]', 'N'), ('[AA:O]', 'O'), ('[AA:P]', 'P'), ('[AA:Q]', 'Q'), ('[AA:R]', 'R'), ('[AA:S]', 'S'), ('[AA:T]', 'T'), ('[AA:U]', 'U'), ('[AA:V]', 'V'), ('[AA:W]', 'W'), ('[AA:X]', 'X'), ('[AA:Y]', 'Y'), ('[AA:Z]', 'Z'), ('[AA:*]', '*'), ('[DNA:A]', 'A'), ('[DNA:C]', 'C'), ('[DNA:G]', 'G'), ('[DNA:T]', 'T'), ('[DNA:U]', 'U'), ('[DNA:N]', 'N'), ('[SMI:C]', 'C'), ('[SMI:c]', 'c'), ('[SMI:N]', 'N'), ('[SMI:n]', 'n'), ('[SMI:O]', 'O'), ('[SMI:o]', 'o'), ('[SMI:S]', 'S'), ('[SMI:s]', 's'), ('[SMI:P]', 'P'), ('[SMI:p]', 'p'), ('[SMI:F]', 'F'), ('[SMI:Cl]', 'Cl'), ('[SMI:Br]', 'Br'), ('[SMI:I]', 'I'), ('[SMI:B]', 'B'), ('[SMI:b]', 'b'), ('[SMI:Si]', 'Si'), ('[SMI:Se]', 'Se'), ('[SMI:(]', '('), ('[SMI:)]', ')'), ('[SMI:[]', '['), ('[SMI:]]', ']'), ('[SMI:=]', '='), ('[SMI:#]', '#'), ('[SMI:-]', '-'), ('[SMI:+]', '+'), ('[SMI:\\]', '\\'), ('[SMI:/]', '/'), ('[SMI::]', ':'), ('[SMI:~]', '~'), ('[SMI:@]', '@'), ('[SMI:@@]', '@@'), ('[SMI:.]', '.'), ('[SMI:*]', '*'), ('[SMI:?]', '?'), ('[SMI:0]', '0'), ('[SMI:1]', '1'), ('[SMI:2]', '2'), ('[SMI:3]', '3'), ('[SMI:4]', '4'), ('[SMI:5]', '5'), ('[SMI:6]', '6'), ('[SMI:7]', '7'), ('[SMI:8]', '8'), ('[SMI:9]', '9'), ('[SMI:%10]', '%10'), ('[SMI:%11]', '%11'), ('[SMI:%12]', '%12'), ('[SMI:%13]', '%13'), ('[SMI:%14]', '%14'), ('[SMI:%15]', '%15'), ('[SMI:%16]', '%16'), ('[SMI:%17]', '%17'), ('[SMI:%18]', '%18'), ('[SMI:%19]', '%19'), ('[SMI:[nH]]', '[nH]'), ('[SMI:[NH]]', '[NH]'), ('[SMI:[NH2+]]', '[NH2+]'), ('[SMI:[NH3+]]', '[NH3+]'), ('[SMI:[NH+]]', '[NH+]'), ('[SMI:[N+]]', '[N+]'), ('[SMI:[N-]]', '[N-]'), ('[SMI:[n+]]', '[n+]'), ('[SMI:[O-]]', '[O-]'), ('[SMI:[O+]]', '[O+]'), ('[SMI:[OH]]', '[OH]'), ('[SMI:[S+]]', '[S+]'), ('[SMI:[S-]]', '[S-]'), ('[SMI:[P+]]', '[P+]'), ('[SMI:[C@H]]', '[C@H]'), ('[SMI:[C@@H]]', '[C@@H]'), ('[SMI:[C@]]', '[C@]'), ('[SMI:[C@@]]', '[C@@]'), ('[SMI:[cH]]', '[cH]'), ('[SMI:[CH]]', '[CH]'), ('[SMI:[CH2]]', '[CH2]'), ('[SMI:[CH3]]', '[CH3]'), ('[SMI:[H]]', '[H]'), ('[SMI:[Na+]]', '[Na+]'), ('[SMI:[K+]]', '[K+]'), ('[SMI:[Ca+2]]', '[Ca+2]'), ('[SMI:[Mg+2]]', '[Mg+2]'), ('[SMI:[Fe+2]]', '[Fe+2]'), ('[SMI:[Fe+3]]', '[Fe+3]'), ('[SMI:[Zn+2]]', '[Zn+2]'), ('[SMI:[Cl-]]', '[Cl-]'), ('[SMI:[Br-]]', '[Br-]'), ('[SMI:[F-]]', '[F-]'), ('[SMI:[I-]]', '[I-]'), ('[SF:[C]]', '[C]'), ('[SF:[=C]]', '[=C]'), ('[SF:[#C]]', '[#C]'), ('[SF:[N]]', '[N]'), ('[SF:[=N]]', '[=N]'), ('[SF:[#N]]', '[#N]'), ('[SF:[O]]', '[O]'), ('[SF:[=O]]', '[=O]'), ('[SF:[S]]', '[S]'), ('[SF:[=S]]', '[=S]'), ('[SF:[P]]', '[P]'), ('[SF:[=P]]', '[=P]'), ('[SF:[F]]', '[F]'), ('[SF:[Cl]]', '[Cl]'), ('[SF:[Br]]', '[Br]'), ('[SF:[I]]', '[I]'), ('[SF:[B]]', '[B]'), ('[SF:[Si]]', '[Si]'), ('[SF:[H]]', '[H]'), ('[SF:[#Branch1]]', '[#Branch1]'), ('[SF:[Branch1]]', '[Branch1]'), ('[SF:[Branch2]]', '[Branch2]'), ('[SF:[Branch3]]', '[Branch3]'), ('[SF:[=Branch1]]', '[=Branch1]'), ('[SF:[=Branch2]]', '[=Branch2]'), ('[SF:[=Branch3]]', '[=Branch3]'), ('[SF:[Ring1]]', '[Ring1]'), ('[SF:[Ring2]]', '[Ring2]'), ('[SF:[Ring3]]', '[Ring3]'), ('[SF:[=Ring1]]', '[=Ring1]'), ('[SF:[=Ring2]]', '[=Ring2]'), ('[SF:[#Ring1]]', '[#Ring1]'), ('[SF:[C@H1]]', '[C@H1]'), ('[SF:[C@@H1]]', '[C@@H1]'), ('[SF:[C@]]', '[C@]'), ('[SF:[C@@]]', '[C@@]'), ('[SF:[NH1]]', '[NH1]'), ('[SF:[NH2+1]]', '[NH2+1]'), ('[SF:[NH3+1]]', '[NH3+1]'), ('[SF:[N+1]]', '[N+1]'), ('[SF:[N-1]]', '[N-1]'), ('[SF:[O-1]]', '[O-1]'), ('[SF:[OH0]]', '[OH0]'), ('[SF:[S+1]]', '[S+1]'), ('[SF:[S-1]]', '[S-1]'), ('[SF:[P+1]]', '[P+1]'), ('[SF:[CH0]]', '[CH0]'), ('[SF:[CH1]]', '[CH1]'), ('[SF:[CH2]]', '[CH2]'), ('[SF:[=CH1]]', '[=CH1]'), ('[SF:[=N+1]]', '[=N+1]'), ('[SF:[=O+1]]', '[=O+1]'), ('[SF:[C+1]]', '[C+1]'), ('[SF:[C-1]]', '[C-1]'), ('[SF:[B-1]]', '[B-1]'), ('[SF:[Fe]]', '[Fe]'), ('[SF:[Zn]]', '[Zn]'), ('[SF:[Mg]]', '[Mg]'), ('[SF:[Ca]]', '[Ca]'), ('[SF:[Na]]', '[Na]'), ('[SF:[K]]', '[K]'), ('[SF:[Cl-1]]', '[Cl-1]'), ('[SF:[Br-1]]', '[Br-1]'), ('[SF:[F-1]]', '[F-1]'), ('[SF:[I-1]]', '[I-1]'), ('[SF:[=C-1]]', '[=C-1]'), ('[SF:[=N-1]]', '[=N-1]'), ('[SF:[#C-1]]', '[#C-1]'), ('[SF:[S@@]]', '[S@@]'), ('[SF:[S@]]', '[S@]'), ('[SF:[P@@]]', '[P@@]'), ('[SF:[P@]]', '[P@]'), ('[SF:[nop]]', '[nop]'), ('[SF:.]', '.')]

try:
    from transformers import PreTrainedTokenizerBase as _BaseHFTokenizer
except ImportError:  # pragma: no cover

    class _BaseHFTokenizer:  # type: ignore[no-redef]
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)

_SPAN_RE = re.compile(
    r"(\[START_SMILES\].*?\[END_SMILES\]"
    r"|\[START_SELFIES\].*?\[END_SELFIES\]"
    r"|\[START_AMINO\].*?\[END_AMINO\]"
    r"|\[START_DNA\].*?\[END_DNA\])",
    re.DOTALL,
)
_SMILES_TOKEN_RE = re.compile(
    r"(\[[^\]]+\]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
)
_SELFIES_TOKEN_RE = re.compile(r"(\[[^\]]+\]|.)")


class FemtoScienceHFTokenizer(_BaseHFTokenizer):
    """HuggingFace-compatible wrapper preserving FemtoScience modality span tokenization."""

    vocab_files_names = {"tokenizer_file": "tokenizer.json"}

    def __init__(self, tokenizer_object: Tokenizer, mode: str = "modality_aware", **kwargs: Any) -> None:
        self._tok = tokenizer_object
        self.mode = mode
        self._special_id_map = {t: tid for t in SPECIAL_TOKENS if (tid := self._tok.token_to_id(t)) is not None}
        self._special_ids = set(self._special_id_map.values())
        self._atomic_str_to_id: dict[str, int] = {}
        self._atomic_id_to_literal: dict[int, str] = {}
        if mode == "modality_aware":
            for tok_str, literal in ATOMIC_MODALITY_ENTRIES:
                tid = self._tok.token_to_id(tok_str)
                if tid is not None:
                    self._atomic_str_to_id[tok_str] = tid
                    self._atomic_id_to_literal[tid] = literal

        self._bos_id = self._tok.token_to_id(BOS_TOKEN)
        self._eos_id = self._tok.token_to_id(EOS_TOKEN)
        self._pad_id = self._tok.token_to_id(PAD_TOKEN)
        kwargs.setdefault("bos_token", BOS_TOKEN)
        kwargs.setdefault("eos_token", EOS_TOKEN)
        kwargs.setdefault("pad_token", PAD_TOKEN)
        super().__init__(**kwargs)

    @property
    def vocab_size(self) -> int:
        return int(self._tok.get_vocab_size())

    @property
    def bos_token_id(self) -> int:
        return int(self._bos_id)

    @property
    def eos_token_id(self) -> int:
        return int(self._eos_id)

    @property
    def pad_token_id(self) -> int:
        return int(self._pad_id)

    def get_vocab(self) -> dict[str, int]:
        return dict(self._tok.get_vocab())

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: str | Path, **kwargs: Any) -> "FemtoScienceHFTokenizer":
        p = Path(pretrained_model_name_or_path)
        if not (p / "tokenizer.json").is_file():  # a Hub repo id, not a local export: fetch the tokenizer files
            from huggingface_hub import snapshot_download

            p = Path(snapshot_download(
                str(pretrained_model_name_or_path),
                revision=kwargs.get("revision"),
                cache_dir=kwargs.get("cache_dir"),
                token=kwargs.get("token"),
                local_files_only=kwargs.get("local_files_only", False),
                allow_patterns=["tokenizer.json", "tokenizer_config.json"],
            ))
        tok = Tokenizer.from_file(str(p / "tokenizer.json"))
        cfg_file = p / "tokenizer_config.json"
        mode = "modality_aware"
        if cfg_file.exists():
            cfg = json.loads(cfg_file.read_text())
            mode = cfg.get("femtoscience_mode", mode)
            kwargs.setdefault("chat_template", cfg.get("chat_template"))
        return cls(tok, mode=mode, **kwargs)

    def save_pretrained(self, save_directory: str | Path, **kwargs: Any) -> tuple[str, ...]:
        del kwargs
        out = Path(save_directory)
        out.mkdir(parents=True, exist_ok=True)
        tok_file = out / "tokenizer.json"
        self._tok.save(str(tok_file))
        return (str(tok_file),)

    def _encode_bpe(self, text: str) -> list[int]:
        return self._tok.encode(text, add_special_tokens=False).ids if text else []

    def _encode_span_body(self, kind: str, body: str) -> list[int]:
        if not body:
            return []
        if kind in {"AMINO", "DNA"}:
            prefix = "AA" if kind == "AMINO" else "DNA"
            ids: list[int] = []
            for ch in body:
                tid = self._atomic_str_to_id.get(f"[{prefix}:{ch}]")
                if tid is not None:
                    ids.append(tid)
                else:
                    ids.extend(self._encode_bpe(ch))
            return ids
        if kind == "SMILES":
            ids = []
            pos = 0
            for m in _SMILES_TOKEN_RE.finditer(body):
                if m.start() > pos:
                    ids.extend(self._encode_bpe(body[pos : m.start()]))
                sym = m.group(0)
                tid = self._atomic_str_to_id.get(f"[SMI:{sym}]")
                ids.extend([tid] if tid is not None else self._encode_bpe(sym))
                pos = m.end()
            if pos < len(body):
                ids.extend(self._encode_bpe(body[pos:]))
            return ids
        if kind == "SELFIES":
            ids = []
            for m in _SELFIES_TOKEN_RE.finditer(body):
                sym = m.group(0)
                tid = self._atomic_str_to_id.get(f"[SF:{sym}]")
                ids.extend([tid] if tid is not None else self._encode_bpe(sym))
            return ids
        return self._encode_bpe(body)

    def encode(self, text: str, add_special_tokens: bool = False, **kwargs: Any) -> list[int]:
        del add_special_tokens, kwargs
        ids: list[int] = []
        if self.mode == "plain_bpe":
            return self._encode_bpe(text)
        pos = 0
        for m in _SPAN_RE.finditer(text):
            if m.start() > pos:
                ids.extend(self._encode_bpe(text[pos : m.start()]))
            span = m.group(0)
            if span.startswith("[START_SMILES]"):
                kind, s_tag, e_tag = "SMILES", "[START_SMILES]", "[END_SMILES]"
            elif span.startswith("[START_SELFIES]"):
                kind, s_tag, e_tag = "SELFIES", "[START_SELFIES]", "[END_SELFIES]"
            elif span.startswith("[START_AMINO]"):
                kind, s_tag, e_tag = "AMINO", "[START_AMINO]", "[END_AMINO]"
            else:
                kind, s_tag, e_tag = "DNA", "[START_DNA]", "[END_DNA]"
            body = span[len(s_tag) : len(span) - len(e_tag)]
            ids.append(self._special_id_map[s_tag])
            ids.extend(self._encode_span_body(kind, body))
            ids.append(self._special_id_map[e_tag])
            pos = m.end()
        if pos < len(text):
            ids.extend(self._encode_bpe(text[pos:]))
        return ids

    def decode(self, token_ids: list[int], skip_special_tokens: bool = False, **kwargs: Any) -> str:
        del kwargs
        out_parts: list[str] = []
        buf: list[int] = []

        def _flush() -> None:
            if buf:
                out_parts.append(self._tok.decode(buf, skip_special_tokens=False))
                buf.clear()

        for raw_tid in token_ids:
            tid = int(raw_tid)
            if skip_special_tokens and tid in self._special_ids:
                _flush()
                continue
            literal = self._atomic_id_to_literal.get(tid)
            if literal is not None:
                _flush()
                out_parts.append(literal)
            else:
                buf.append(tid)
        _flush()
        return "".join(out_parts)

    def batch_decode(self, sequences: list[list[int]], skip_special_tokens: bool = False, **kwargs: Any) -> list[str]:
        return [self.decode(seq, skip_special_tokens=skip_special_tokens, **kwargs) for seq in sequences]

    def tokenize(self, text: str, **kwargs: Any) -> list[str]:
        del kwargs
        return [self._tok.id_to_token(tid) or "" for tid in self.encode(text)]

    def convert_tokens_to_ids(self, tokens: str | list[str]) -> int | list[int]:
        if isinstance(tokens, str):
            tid = self._tok.token_to_id(tokens)
            return int(self._eos_id if tid is None else tid)
        return [int(self._eos_id if (tid := self._tok.token_to_id(t)) is None else tid) for t in tokens]

    def convert_ids_to_tokens(self, ids: int | list[int], skip_special_tokens: bool = False) -> str | list[str]:
        del skip_special_tokens
        if isinstance(ids, int):
            return self._tok.id_to_token(ids) or ""
        return [self._tok.id_to_token(int(i)) or "" for i in ids]

    def __call__(
        self,
        text: str | list[str],
        *,
        padding: bool = False,
        return_tensors: str | None = None,
        **kwargs: Any,
    ) -> dict[str, Any]:
        del kwargs
        single = isinstance(text, str)
        texts = [text] if single else list(text)
        encoded = [self.encode(t) for t in texts]
        if padding or (return_tensors and len(encoded) > 1):
            width = max((len(seq) for seq in encoded), default=0)
            input_ids = [seq + [self.pad_token_id] * (width - len(seq)) for seq in encoded]
            attn_mask = [[1] * len(seq) + [0] * (width - len(seq)) for seq in encoded]
        else:
            input_ids = encoded[0] if (single and return_tensors is None) else encoded
            attn_mask = [1] * len(encoded[0]) if (single and return_tensors is None) else [[1] * len(seq) for seq in encoded]
        if return_tensors == "pt":
            import torch

            return {
                "input_ids": torch.tensor(input_ids, dtype=torch.long),
                "attention_mask": torch.tensor(attn_mask, dtype=torch.long),
            }
        return {"input_ids": input_ids, "attention_mask": attn_mask}

    def apply_chat_template(
        self,
        messages: list[dict[str, str]],
        *,
        add_generation_prompt: bool = False,
        tokenize: bool = False,
        **kwargs: Any,
    ) -> str | list[int]:
        del kwargs
        chunks = [f"<|im_start|>{m.get('role', 'user')}\n{m.get('content', '')}<|im_end|>\n" for m in messages]
        if add_generation_prompt:
            chunks.append("<|im_start|>assistant\n")
        rendered = "".join(chunks)
        return self.encode(rendered) if tokenize else rendered