Upload base files
Browse files- ChemQ3MTP/FastChemTokenizerHF.py +539 -0
- ChemQ3MTP/__init__.py +14 -0
- ChemQ3MTP/configuration_chemq3mtp.py +27 -0
- ChemQ3MTP/misc_utils.py +98 -0
- ChemQ3MTP/modeling_chemq3mtp.py +467 -0
- ChemQ3MTP/rl_utils.py +1070 -0
- ChemQ3MTP/trainer.py +72 -0
- ChemQ3MTP/training_utils.py +157 -0
- FastChemTokenizerHF.py +539 -0
ChemQ3MTP/FastChemTokenizerHF.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from typing import List, Union, Optional, Tuple, Dict, Any
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from collections.abc import Mapping
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ------------------------------
|
| 10 |
+
# BatchEncoding
|
| 11 |
+
# ------------------------------
|
| 12 |
+
class BatchEncoding(dict, Mapping):
|
| 13 |
+
"""Minimal BatchEncoding compatible wrapper."""
|
| 14 |
+
|
| 15 |
+
def __init__(self, data: dict, tensor_type: Optional[str] = None):
|
| 16 |
+
data = {} if data is None else {k: v for k, v in data.items()}
|
| 17 |
+
super().__init__(data)
|
| 18 |
+
self.data = data
|
| 19 |
+
self.tensor_type = tensor_type
|
| 20 |
+
for k, v in data.items():
|
| 21 |
+
setattr(self, k, v)
|
| 22 |
+
|
| 23 |
+
def __getitem__(self, key): return self.data[key]
|
| 24 |
+
def __iter__(self): return iter(self.data)
|
| 25 |
+
def __len__(self): return len(self.data)
|
| 26 |
+
def keys(self): return self.data.keys()
|
| 27 |
+
def values(self): return self.data.values()
|
| 28 |
+
def items(self): return self.data.items()
|
| 29 |
+
def get(self, key, default=None): return self.data.get(key, default)
|
| 30 |
+
|
| 31 |
+
def to(self, device):
|
| 32 |
+
if self.tensor_type in ("pt", "torch"):
|
| 33 |
+
for k, v in list(self.data.items()):
|
| 34 |
+
if torch.is_tensor(v):
|
| 35 |
+
self.data[k] = v.to(device)
|
| 36 |
+
setattr(self, k, self.data[k])
|
| 37 |
+
return self
|
| 38 |
+
|
| 39 |
+
def cpu(self): return self.to("cpu")
|
| 40 |
+
def cuda(self): return self.to("cuda")
|
| 41 |
+
def detach(self):
|
| 42 |
+
if self.tensor_type in ("pt", "torch"):
|
| 43 |
+
for k, v in list(self.data.items()):
|
| 44 |
+
if torch.is_tensor(v):
|
| 45 |
+
self.data[k] = v.detach()
|
| 46 |
+
setattr(self, k, self.data[k])
|
| 47 |
+
return self
|
| 48 |
+
|
| 49 |
+
def __repr__(self):
|
| 50 |
+
keys = ", ".join(list(self.data.keys())[:10])
|
| 51 |
+
return f"BatchEncoding(keys=[{keys}], tensor_type={self.tensor_type})"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ------------------------------
|
| 55 |
+
# Base class
|
| 56 |
+
# ------------------------------
|
| 57 |
+
class PreTrainedTokenizerBase:
|
| 58 |
+
def __init__(self, **kwargs):
|
| 59 |
+
for key, value in kwargs.items():
|
| 60 |
+
if key.endswith('_token'):
|
| 61 |
+
setattr(self, f"_{key}", value)
|
| 62 |
+
setattr(self, f"{key}_id", None)
|
| 63 |
+
self.model_max_length = kwargs.get('model_max_length', 512)
|
| 64 |
+
self.padding_side = kwargs.get('padding_side', 'right')
|
| 65 |
+
self.truncation_side = kwargs.get('truncation_side', 'right')
|
| 66 |
+
self.chat_template = kwargs.get('chat_template')
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ------------------------------
|
| 70 |
+
# Trie node
|
| 71 |
+
# ------------------------------
|
| 72 |
+
class TrieNode:
|
| 73 |
+
__slots__ = ['children', 'token_id']
|
| 74 |
+
def __init__(self):
|
| 75 |
+
self.children = {}
|
| 76 |
+
self.token_id = None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ------------------------------
|
| 80 |
+
# FastChemTokenizer
|
| 81 |
+
# ------------------------------
|
| 82 |
+
|
| 83 |
+
class FastChemTokenizer(PreTrainedTokenizerBase):
|
| 84 |
+
def __init__(self, token_to_id=None, vocab_file=None, **kwargs):
|
| 85 |
+
if vocab_file is not None:
|
| 86 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 87 |
+
token_to_id = json.load(f)
|
| 88 |
+
token_to_id = {str(k): int(v) for k, v in token_to_id.items()}
|
| 89 |
+
|
| 90 |
+
self.token_to_id = token_to_id
|
| 91 |
+
self.id_to_token = {v: k for k, v in token_to_id.items()}
|
| 92 |
+
|
| 93 |
+
# Build trie
|
| 94 |
+
self.trie_root = self._build_trie(self.token_to_id)
|
| 95 |
+
|
| 96 |
+
# ✅ Call parent (sets token *strings*, may reset *_id to None)
|
| 97 |
+
super().__init__(
|
| 98 |
+
bos_token="<s>",
|
| 99 |
+
eos_token="</s>",
|
| 100 |
+
unk_token="<unk>",
|
| 101 |
+
pad_token="<pad>",
|
| 102 |
+
mask_token="<mask>",
|
| 103 |
+
model_max_length=kwargs.get("model_max_length", 512),
|
| 104 |
+
padding_side=kwargs.get("padding_side", "right"),
|
| 105 |
+
truncation_side=kwargs.get("truncation_side", "right"),
|
| 106 |
+
**kwargs,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# ✅ Re-map token strings → IDs from vocab
|
| 110 |
+
self.bos_token_id = self.token_to_id.get("<s>", 0)
|
| 111 |
+
self.eos_token_id = self.token_to_id.get("</s>", 1)
|
| 112 |
+
self.pad_token_id = self.token_to_id.get("<pad>", 2)
|
| 113 |
+
self.unk_token_id = self.token_to_id.get("<unk>", 3)
|
| 114 |
+
self.mask_token_id = self.token_to_id.get("<mask>", 4)
|
| 115 |
+
|
| 116 |
+
# Ensure reverse mapping always valid
|
| 117 |
+
self.id_to_token[self.bos_token_id] = "<s>"
|
| 118 |
+
self.id_to_token[self.eos_token_id] = "</s>"
|
| 119 |
+
self.id_to_token[self.pad_token_id] = "<pad>"
|
| 120 |
+
self.id_to_token[self.unk_token_id] = "<unk>"
|
| 121 |
+
self.id_to_token[self.mask_token_id] = "<mask>"
|
| 122 |
+
|
| 123 |
+
# Debug
|
| 124 |
+
print("✅ Special tokens bound:",
|
| 125 |
+
self.bos_token_id, self.eos_token_id, self.pad_token_id,
|
| 126 |
+
self.unk_token_id, self.mask_token_id)
|
| 127 |
+
|
| 128 |
+
# ✅ Ensure token *strings* also exist (for decode fallback)
|
| 129 |
+
self.bos_token = "<s>"
|
| 130 |
+
self.eos_token = "</s>"
|
| 131 |
+
self.pad_token = "<pad>"
|
| 132 |
+
self.unk_token = "<unk>"
|
| 133 |
+
self.mask_token = "<mask>"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _build_trie(self, token_to_id):
|
| 137 |
+
root = TrieNode()
|
| 138 |
+
for token, tid in token_to_id.items():
|
| 139 |
+
node = root
|
| 140 |
+
for char in token:
|
| 141 |
+
if char not in node.children:
|
| 142 |
+
node.children[char] = TrieNode()
|
| 143 |
+
node = node.children[char]
|
| 144 |
+
node.token_id = tid
|
| 145 |
+
return root
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def vocab_size(self): return len(self.token_to_id)
|
| 149 |
+
def __len__(self): return len(self.token_to_id)
|
| 150 |
+
def get_vocab(self) -> Dict[str, int]: return self.token_to_id.copy()
|
| 151 |
+
|
| 152 |
+
@lru_cache(maxsize=10000)
|
| 153 |
+
def _cached_encode_str(self, s: str) -> Tuple[int, ...]:
|
| 154 |
+
return tuple(self._encode_core(s))
|
| 155 |
+
|
| 156 |
+
def _encode_core(self, text: str) -> List[int]:
|
| 157 |
+
tokens, result_ids = text, []
|
| 158 |
+
i, n = 0, len(tokens)
|
| 159 |
+
while i < n:
|
| 160 |
+
node, j = self.trie_root, i
|
| 161 |
+
last_match_id, last_match_end = None, i
|
| 162 |
+
while j < n and tokens[j] in node.children:
|
| 163 |
+
node = node.children[tokens[j]]
|
| 164 |
+
j += 1
|
| 165 |
+
if node.token_id is not None:
|
| 166 |
+
last_match_id, last_match_end = node.token_id, j
|
| 167 |
+
if last_match_id is not None:
|
| 168 |
+
result_ids.append(last_match_id)
|
| 169 |
+
i = last_match_end
|
| 170 |
+
else:
|
| 171 |
+
tid = self.token_to_id.get(tokens[i], self.unk_token_id)
|
| 172 |
+
result_ids.append(tid)
|
| 173 |
+
i += 1
|
| 174 |
+
return result_ids
|
| 175 |
+
|
| 176 |
+
# ------------------------------
|
| 177 |
+
# Converters
|
| 178 |
+
# ------------------------------
|
| 179 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 180 |
+
return self.token_to_id.get(token, self.unk_token_id)
|
| 181 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 182 |
+
return self.id_to_token.get(index, self.unk_token)
|
| 183 |
+
|
| 184 |
+
def convert_tokens_to_ids(self, tokens: Union[str, List[str]]):
|
| 185 |
+
if isinstance(tokens, str): return self._convert_token_to_id(tokens)
|
| 186 |
+
return [self._convert_token_to_id(tok) for tok in tokens]
|
| 187 |
+
|
| 188 |
+
def convert_ids_to_tokens(self, ids: Union[int, List[int]]):
|
| 189 |
+
if isinstance(ids, int): return self._convert_id_to_token(ids)
|
| 190 |
+
return [self._convert_id_to_token(i) for i in ids]
|
| 191 |
+
|
| 192 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str: return "".join(tokens)
|
| 193 |
+
|
| 194 |
+
# ------------------------------
|
| 195 |
+
# Encoding / Decoding
|
| 196 |
+
# ------------------------------
|
| 197 |
+
# ------------------------------
|
| 198 |
+
# Convenience wrappers
|
| 199 |
+
# ------------------------------
|
| 200 |
+
def encode(
|
| 201 |
+
self,
|
| 202 |
+
text: str,
|
| 203 |
+
text_pair: Optional[str] = None,
|
| 204 |
+
add_special_tokens: bool = True,
|
| 205 |
+
padding: bool = False,
|
| 206 |
+
truncation: bool = False,
|
| 207 |
+
max_length: Optional[int] = None,
|
| 208 |
+
return_tensors: Optional[str] = None,
|
| 209 |
+
) -> List[int]:
|
| 210 |
+
encoded = self.encode_plus(
|
| 211 |
+
text=text,
|
| 212 |
+
text_pair=text_pair,
|
| 213 |
+
add_special_tokens=add_special_tokens,
|
| 214 |
+
padding=padding,
|
| 215 |
+
truncation=truncation,
|
| 216 |
+
max_length=max_length,
|
| 217 |
+
return_tensors=return_tensors,
|
| 218 |
+
)
|
| 219 |
+
input_ids = encoded["input_ids"]
|
| 220 |
+
if isinstance(input_ids, torch.Tensor):
|
| 221 |
+
if input_ids.dim() > 1:
|
| 222 |
+
input_ids = input_ids.squeeze(0)
|
| 223 |
+
input_ids = input_ids.tolist()
|
| 224 |
+
return input_ids
|
| 225 |
+
|
| 226 |
+
def __call__(
|
| 227 |
+
self,
|
| 228 |
+
text: Union[str, List[str]],
|
| 229 |
+
text_pair: Optional[Union[str, List[str]]] = None,
|
| 230 |
+
add_special_tokens: bool = True,
|
| 231 |
+
padding: Union[bool, str] = False,
|
| 232 |
+
truncation: Union[bool, str] = False,
|
| 233 |
+
max_length: Optional[int] = None,
|
| 234 |
+
stride: int = 0,
|
| 235 |
+
is_split_into_words: bool = False,
|
| 236 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 237 |
+
return_tensors: Optional[Union[str, Any]] = None,
|
| 238 |
+
return_token_type_ids: Optional[bool] = None,
|
| 239 |
+
return_attention_mask: Optional[bool] = None,
|
| 240 |
+
return_overflowing_tokens: bool = False,
|
| 241 |
+
return_special_tokens_mask: bool = False,
|
| 242 |
+
return_offsets_mapping: bool = False,
|
| 243 |
+
return_length: bool = False,
|
| 244 |
+
verbose: bool = True,
|
| 245 |
+
**kwargs
|
| 246 |
+
) -> BatchEncoding:
|
| 247 |
+
"""HuggingFace-compatible: one string → encode_plus, list → batch_encode_plus"""
|
| 248 |
+
if return_token_type_ids is None:
|
| 249 |
+
return_token_type_ids = True
|
| 250 |
+
if return_attention_mask is None:
|
| 251 |
+
return_attention_mask = True
|
| 252 |
+
|
| 253 |
+
if isinstance(text, list):
|
| 254 |
+
if text_pair is not None:
|
| 255 |
+
batch = [(t, p) for t, p in zip(text, text_pair)]
|
| 256 |
+
else:
|
| 257 |
+
batch = text
|
| 258 |
+
return self.batch_encode_plus(
|
| 259 |
+
batch,
|
| 260 |
+
add_special_tokens=add_special_tokens,
|
| 261 |
+
padding=padding,
|
| 262 |
+
truncation=truncation,
|
| 263 |
+
max_length=max_length,
|
| 264 |
+
stride=stride,
|
| 265 |
+
is_split_into_words=is_split_into_words,
|
| 266 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 267 |
+
return_tensors=return_tensors,
|
| 268 |
+
return_token_type_ids=return_token_type_ids,
|
| 269 |
+
return_attention_mask=return_attention_mask,
|
| 270 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 271 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 272 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 273 |
+
return_length=return_length,
|
| 274 |
+
verbose=verbose,
|
| 275 |
+
**kwargs
|
| 276 |
+
)
|
| 277 |
+
else:
|
| 278 |
+
return self.encode_plus(
|
| 279 |
+
text=text,
|
| 280 |
+
text_pair=text_pair,
|
| 281 |
+
add_special_tokens=add_special_tokens,
|
| 282 |
+
padding=padding,
|
| 283 |
+
truncation=truncation,
|
| 284 |
+
max_length=max_length,
|
| 285 |
+
stride=stride,
|
| 286 |
+
is_split_into_words=is_split_into_words,
|
| 287 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 288 |
+
return_tensors=return_tensors,
|
| 289 |
+
return_token_type_ids=return_token_type_ids,
|
| 290 |
+
return_attention_mask=return_attention_mask,
|
| 291 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 292 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 293 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 294 |
+
return_length=return_length,
|
| 295 |
+
verbose=verbose,
|
| 296 |
+
**kwargs
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
def encode_plus(
|
| 300 |
+
self,
|
| 301 |
+
text: str,
|
| 302 |
+
text_pair: Optional[str] = None,
|
| 303 |
+
add_special_tokens: bool = True,
|
| 304 |
+
padding: Union[bool, str] = False,
|
| 305 |
+
truncation: Union[bool, str] = False,
|
| 306 |
+
max_length: Optional[int] = None,
|
| 307 |
+
stride: int = 0,
|
| 308 |
+
is_split_into_words: bool = False,
|
| 309 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 310 |
+
return_tensors: Optional[Union[str, Any]] = None,
|
| 311 |
+
return_token_type_ids: Optional[bool] = True,
|
| 312 |
+
return_attention_mask: Optional[bool] = True,
|
| 313 |
+
return_overflowing_tokens: bool = False,
|
| 314 |
+
return_special_tokens_mask: bool = False,
|
| 315 |
+
return_offsets_mapping: bool = False,
|
| 316 |
+
return_length: bool = False,
|
| 317 |
+
verbose: bool = True,
|
| 318 |
+
**kwargs
|
| 319 |
+
) -> BatchEncoding:
|
| 320 |
+
if max_length is None: max_length = self.model_max_length
|
| 321 |
+
ids_a = list(self._cached_encode_str(text.strip()))
|
| 322 |
+
ids_b = list(self._cached_encode_str(text_pair.strip())) if text_pair else None
|
| 323 |
+
|
| 324 |
+
input_ids, token_type_ids = [], []
|
| 325 |
+
if add_special_tokens:
|
| 326 |
+
input_ids.append(self.bos_token_id); token_type_ids.append(0)
|
| 327 |
+
input_ids.extend(ids_a); token_type_ids.extend([0] * len(ids_a))
|
| 328 |
+
input_ids.append(self.eos_token_id); token_type_ids.append(0)
|
| 329 |
+
if ids_b is not None:
|
| 330 |
+
input_ids.extend(ids_b); token_type_ids.extend([1] * len(ids_b))
|
| 331 |
+
input_ids.append(self.eos_token_id); token_type_ids.append(1)
|
| 332 |
+
else:
|
| 333 |
+
input_ids = ids_a.copy(); token_type_ids = [0] * len(input_ids)
|
| 334 |
+
if ids_b is not None:
|
| 335 |
+
input_ids.extend(ids_b); token_type_ids.extend([1] * len(ids_b))
|
| 336 |
+
|
| 337 |
+
if truncation and len(input_ids) > max_length:
|
| 338 |
+
input_ids, token_type_ids = input_ids[:max_length], token_type_ids[:max_length]
|
| 339 |
+
|
| 340 |
+
encoded_dict = {"input_ids": input_ids}
|
| 341 |
+
if return_attention_mask:
|
| 342 |
+
if padding == True or padding == "max_length":
|
| 343 |
+
pad_len = max_length - len(input_ids)
|
| 344 |
+
if pad_len > 0:
|
| 345 |
+
if self.padding_side == "right":
|
| 346 |
+
input_ids.extend([self.pad_token_id] * pad_len)
|
| 347 |
+
token_type_ids.extend([0] * pad_len)
|
| 348 |
+
else:
|
| 349 |
+
input_ids = [self.pad_token_id] * pad_len + input_ids
|
| 350 |
+
token_type_ids = [0] * pad_len + token_type_ids
|
| 351 |
+
attention_mask = [0 if tid == self.pad_token_id else 1 for tid in input_ids]
|
| 352 |
+
encoded_dict["attention_mask"] = attention_mask
|
| 353 |
+
if return_token_type_ids: encoded_dict["token_type_ids"] = token_type_ids
|
| 354 |
+
if return_special_tokens_mask:
|
| 355 |
+
encoded_dict["special_tokens_mask"] = [
|
| 356 |
+
1 if tid in {self.bos_token_id, self.eos_token_id, self.pad_token_id, self.mask_token_id} else 0
|
| 357 |
+
for tid in input_ids
|
| 358 |
+
]
|
| 359 |
+
if return_length:
|
| 360 |
+
encoded_dict["length"] = len([tid for tid in input_ids if tid != self.pad_token_id])
|
| 361 |
+
|
| 362 |
+
if return_tensors in ["pt", "torch"]:
|
| 363 |
+
out = {}
|
| 364 |
+
for k, v in encoded_dict.items():
|
| 365 |
+
if isinstance(v, list):
|
| 366 |
+
tensor = torch.tensor(
|
| 367 |
+
[self.unk_token_id if x is None else int(x) for x in v], dtype=torch.long
|
| 368 |
+
).unsqueeze(0)
|
| 369 |
+
out[k] = tensor
|
| 370 |
+
else:
|
| 371 |
+
out[k] = v
|
| 372 |
+
return BatchEncoding(out, tensor_type=return_tensors)
|
| 373 |
+
return BatchEncoding(encoded_dict, tensor_type=None)
|
| 374 |
+
|
| 375 |
+
def batch_encode_plus(
|
| 376 |
+
self,
|
| 377 |
+
batch_text_or_text_pairs: List[Union[str, Tuple[str, str]]],
|
| 378 |
+
add_special_tokens: bool = True,
|
| 379 |
+
padding: Union[bool, str] = False,
|
| 380 |
+
truncation: Union[bool, str] = False,
|
| 381 |
+
max_length: Optional[int] = None,
|
| 382 |
+
stride: int = 0,
|
| 383 |
+
is_split_into_words: bool = False,
|
| 384 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 385 |
+
return_tensors: Optional[Union[str, Any]] = None,
|
| 386 |
+
return_token_type_ids: Optional[bool] = True,
|
| 387 |
+
return_attention_mask: Optional[bool] = True,
|
| 388 |
+
return_overflowing_tokens: bool = False,
|
| 389 |
+
return_special_tokens_mask: bool = False,
|
| 390 |
+
return_offsets_mapping: bool = False,
|
| 391 |
+
return_length: bool = False,
|
| 392 |
+
verbose: bool = True,
|
| 393 |
+
**kwargs
|
| 394 |
+
) -> BatchEncoding:
|
| 395 |
+
if padding is True: padding = "longest"
|
| 396 |
+
if padding == "max_length" and max_length is None: max_length = self.model_max_length
|
| 397 |
+
|
| 398 |
+
all_input_ids, all_token_type_ids, all_attention_masks = [], [], []
|
| 399 |
+
all_special_masks, all_lengths = [], []
|
| 400 |
+
for item in batch_text_or_text_pairs:
|
| 401 |
+
t, tp = item if isinstance(item, tuple) else (item, None)
|
| 402 |
+
enc = self.encode_plus(
|
| 403 |
+
text=t, text_pair=tp, add_special_tokens=add_special_tokens,
|
| 404 |
+
padding=False, truncation=truncation, max_length=max_length,
|
| 405 |
+
return_tensors=None, return_token_type_ids=return_token_type_ids,
|
| 406 |
+
return_attention_mask=return_attention_mask,
|
| 407 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 408 |
+
return_length=return_length, **kwargs
|
| 409 |
+
)
|
| 410 |
+
ids, tt, am = enc["input_ids"], enc.get("token_type_ids", [0]*len(enc["input_ids"])), enc.get("attention_mask",[1]*len(enc["input_ids"]))
|
| 411 |
+
sm, ln = enc.get("special_tokens_mask",[0]*len(ids)), enc.get("length", len([x for x in ids if x != self.pad_token_id]))
|
| 412 |
+
all_input_ids.append(ids); all_token_type_ids.append(tt); all_attention_masks.append(am)
|
| 413 |
+
all_special_masks.append(sm); all_lengths.append(ln)
|
| 414 |
+
|
| 415 |
+
pad_to = max(len(x) for x in all_input_ids) if padding == "longest" else (max_length if padding == "max_length" else None)
|
| 416 |
+
batched = {
|
| 417 |
+
"input_ids": all_input_ids,
|
| 418 |
+
"token_type_ids": all_token_type_ids if return_token_type_ids else None,
|
| 419 |
+
"attention_mask": all_attention_masks if return_attention_mask else None,
|
| 420 |
+
"special_tokens_mask": all_special_masks if return_special_tokens_mask else None,
|
| 421 |
+
"length": all_lengths if return_length else None,
|
| 422 |
+
}
|
| 423 |
+
if pad_to is not None:
|
| 424 |
+
for key in ["input_ids","token_type_ids","attention_mask","special_tokens_mask"]:
|
| 425 |
+
if batched.get(key) is None: continue
|
| 426 |
+
padded = []
|
| 427 |
+
for seq in batched[key]:
|
| 428 |
+
pad_len = pad_to - len(seq)
|
| 429 |
+
pad_val = self.pad_token_id if key=="input_ids" else 0
|
| 430 |
+
if pad_len > 0:
|
| 431 |
+
seq = seq+[pad_val]*pad_len if self.padding_side=="right" else [pad_val]*pad_len+seq
|
| 432 |
+
padded.append(seq)
|
| 433 |
+
batched[key] = padded
|
| 434 |
+
|
| 435 |
+
if return_tensors in ["pt", "torch"]:
|
| 436 |
+
def to_tensor(lst, pad_val=0):
|
| 437 |
+
return torch.tensor([[self.unk_token_id if x is None else int(x) for x in row] for row in lst], dtype=torch.long)
|
| 438 |
+
out = {}
|
| 439 |
+
if batched.get("input_ids") is not None: out["input_ids"] = to_tensor(batched["input_ids"], self.pad_token_id)
|
| 440 |
+
if batched.get("attention_mask") is not None: out["attention_mask"] = to_tensor(batched["attention_mask"],0)
|
| 441 |
+
if batched.get("token_type_ids") is not None: out["token_type_ids"] = to_tensor(batched["token_type_ids"],0)
|
| 442 |
+
if batched.get("special_tokens_mask") is not None: out["special_tokens_mask"] = to_tensor(batched["special_tokens_mask"],0)
|
| 443 |
+
if return_length and batched.get("length") is not None: out["length"] = torch.tensor([int(x) for x in batched["length"]], dtype=torch.long)
|
| 444 |
+
return BatchEncoding(out, tensor_type=return_tensors)
|
| 445 |
+
return BatchEncoding({k:v for k,v in batched.items() if v is not None}, tensor_type=None)
|
| 446 |
+
|
| 447 |
+
# ------------------------------
|
| 448 |
+
# Decoding
|
| 449 |
+
# ------------------------------
|
| 450 |
+
def decode(self, token_ids, skip_special_tokens=False, **kwargs):
|
| 451 |
+
if isinstance(token_ids, torch.Tensor): token_ids = token_ids.tolist()
|
| 452 |
+
special_ids = {self.bos_token_id,self.eos_token_id,self.pad_token_id,self.mask_token_id} if skip_special_tokens else set()
|
| 453 |
+
tokens = [self.id_to_token.get(tid,self.unk_token) for tid in token_ids if tid not in special_ids]
|
| 454 |
+
return "".join(tokens)
|
| 455 |
+
|
| 456 |
+
def batch_decode(self, sequences, skip_special_tokens=False, **kwargs):
|
| 457 |
+
if isinstance(sequences, torch.Tensor): sequences = sequences.tolist()
|
| 458 |
+
return [self.decode(seq, skip_special_tokens=skip_special_tokens, **kwargs) for seq in sequences]
|
| 459 |
+
|
| 460 |
+
def decode_with_trace(self, token_ids: List[int]):
|
| 461 |
+
print(f"\n🔍 Decoding {len(token_ids)} tokens:")
|
| 462 |
+
for i, tid in enumerate(token_ids):
|
| 463 |
+
token = self.id_to_token.get(tid, self.unk_token)
|
| 464 |
+
tid_str = "None" if tid is None else f"{tid:5d}"
|
| 465 |
+
print(f" [{i:03d}] ID={tid_str} → '{token}'")
|
| 466 |
+
|
| 467 |
+
# ------------------------------
|
| 468 |
+
# Save / Load
|
| 469 |
+
# ------------------------------
|
| 470 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 471 |
+
if not os.path.isdir(save_directory): os.makedirs(save_directory)
|
| 472 |
+
vocab_file = os.path.join(save_directory,(filename_prefix+"-" if filename_prefix else "")+"vocab.json")
|
| 473 |
+
with open(vocab_file,"w",encoding="utf-8") as f: json.dump(self.token_to_id,f,ensure_ascii=False,indent=2)
|
| 474 |
+
return (vocab_file,)
|
| 475 |
+
|
| 476 |
+
def save_pretrained(self, save_directory: Union[str, os.PathLike], filename_prefix: Optional[str]=None, **kwargs):
|
| 477 |
+
if not os.path.exists(save_directory): os.makedirs(save_directory)
|
| 478 |
+
self.save_vocabulary(save_directory, filename_prefix)
|
| 479 |
+
config_file = os.path.join(save_directory,"tokenizer_config.json")
|
| 480 |
+
with open(config_file,"w",encoding="utf-8") as f:
|
| 481 |
+
json.dump({
|
| 482 |
+
"tokenizer_class": self.__class__.__name__,
|
| 483 |
+
"model_max_length": self.model_max_length,
|
| 484 |
+
"padding_side": self.padding_side,
|
| 485 |
+
"truncation_side": self.truncation_side,
|
| 486 |
+
"special_tokens": {
|
| 487 |
+
"bos_token": self.bos_token,
|
| 488 |
+
"eos_token": self.eos_token,
|
| 489 |
+
"pad_token": self.pad_token,
|
| 490 |
+
"unk_token": self.unk_token,
|
| 491 |
+
"mask_token": self.mask_token,
|
| 492 |
+
}
|
| 493 |
+
},f,ensure_ascii=False,indent=2)
|
| 494 |
+
return (save_directory,)
|
| 495 |
+
|
| 496 |
+
@classmethod
|
| 497 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 498 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 499 |
+
vocab_file = os.path.join(pretrained_model_name_or_path,"vocab.json")
|
| 500 |
+
config_file = os.path.join(pretrained_model_name_or_path,"tokenizer_config.json")
|
| 501 |
+
config = {}
|
| 502 |
+
if os.path.exists(config_file):
|
| 503 |
+
with open(config_file,"r",encoding="utf-8") as f: config=json.load(f)
|
| 504 |
+
return cls(vocab_file=vocab_file, **{**config,**kwargs})
|
| 505 |
+
else:
|
| 506 |
+
raise NotImplementedError("Loading from Hub not implemented yet")
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# ------------------------------
|
| 510 |
+
# SELFIES variant
|
| 511 |
+
# ------------------------------
|
| 512 |
+
class FastChemTokenizerSelfies(FastChemTokenizer):
|
| 513 |
+
def __init__(self, *args, **kwargs):
|
| 514 |
+
super().__init__(*args, **kwargs) # ✅ ensures BOS/EOS etc. are set
|
| 515 |
+
|
| 516 |
+
"""SELFIES variant that handles whitespace-separated tokens."""
|
| 517 |
+
|
| 518 |
+
def _encode_core(self, text: str) -> List[int]:
|
| 519 |
+
result_ids, i, n = [], 0, len(text)
|
| 520 |
+
while i < n:
|
| 521 |
+
if text[i].isspace(): i += 1; continue
|
| 522 |
+
node, j = self.trie_root, i
|
| 523 |
+
last_match_id, last_match_end = None, i
|
| 524 |
+
while j < n and text[j] in node.children:
|
| 525 |
+
node = node.children[text[j]]; j += 1
|
| 526 |
+
if node.token_id is not None:
|
| 527 |
+
last_match_id, last_match_end = node.token_id, j
|
| 528 |
+
if last_match_id is not None:
|
| 529 |
+
result_ids.append(last_match_id); i = last_match_end
|
| 530 |
+
else:
|
| 531 |
+
result_ids.append(self.token_to_id.get(text[i], self.unk_token_id)); i += 1
|
| 532 |
+
return result_ids
|
| 533 |
+
|
| 534 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str: return " ".join(tokens)
|
| 535 |
+
def decode(self, token_ids, skip_special_tokens=False, **kwargs):
|
| 536 |
+
if isinstance(token_ids, torch.Tensor): token_ids = token_ids.tolist()
|
| 537 |
+
special_ids = {self.bos_token_id,self.eos_token_id,self.pad_token_id,self.mask_token_id} if skip_special_tokens else set()
|
| 538 |
+
tokens = [self.id_to_token.get(tid,self.unk_token) for tid in token_ids if tid not in special_ids]
|
| 539 |
+
return " ".join(tokens)
|
ChemQ3MTP/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# __init__.py
|
| 2 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
from .configuration_chemq3mtp import ChemQ3MTPConfig
|
| 4 |
+
from .modeling_chemq3mtp import ChemQ3MTPForCausalLM
|
| 5 |
+
from .FastChemTokenizerHF import FastChemTokenizerSelfies
|
| 6 |
+
|
| 7 |
+
# Register the model
|
| 8 |
+
AutoConfig.register("chemq3_mtp", ChemQ3MTPConfig)
|
| 9 |
+
AutoModelForCausalLM.register(ChemQ3MTPConfig, ChemQ3MTPForCausalLM)
|
| 10 |
+
|
| 11 |
+
# Register the tokenizer
|
| 12 |
+
AutoTokenizer.register(ChemQ3MTPConfig, FastChemTokenizerSelfies)
|
| 13 |
+
|
| 14 |
+
__all__ = ["ChemQ3MTPConfig", "ChemQ3MTPForCausalLM", "FastChemTokenizerSelfies"]
|
ChemQ3MTP/configuration_chemq3mtp.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# configuration_chemq3mtp.py
|
| 2 |
+
from transformers import Qwen2Config
|
| 3 |
+
|
| 4 |
+
class ChemQ3MTPConfig(Qwen2Config):
|
| 5 |
+
"""
|
| 6 |
+
Configuration class for ChemQ3MTP model.
|
| 7 |
+
"""
|
| 8 |
+
model_type = "chemq3_mtp"
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
num_future_tokens: int = 3,
|
| 13 |
+
horizon_weights = None,
|
| 14 |
+
use_mtp_training: bool = True,
|
| 15 |
+
entropy_controller_config = None,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
super().__init__(**kwargs)
|
| 19 |
+
self.num_future_tokens = num_future_tokens
|
| 20 |
+
self.horizon_weights = horizon_weights or [0.9 ** i for i in range(num_future_tokens)]
|
| 21 |
+
self.use_mtp_training = use_mtp_training
|
| 22 |
+
self.entropy_controller_config = entropy_controller_config or {
|
| 23 |
+
"min_entropy": 0.5,
|
| 24 |
+
"max_entropy": 3.0,
|
| 25 |
+
"target_entropy": 1.5,
|
| 26 |
+
"adaptation_rate": 0.01
|
| 27 |
+
}
|
ChemQ3MTP/misc_utils.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# src/misc_utils.py
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
import shutil
|
| 5 |
+
import os
|
| 6 |
+
import datetime
|
| 7 |
+
from transformers import TrainerCallback
|
| 8 |
+
|
| 9 |
+
def load_config(config_path: str = "config.json") -> dict:
|
| 10 |
+
with open(config_path, "r") as f:
|
| 11 |
+
return json.load(f)
|
| 12 |
+
|
| 13 |
+
def get_training_config(config: dict) -> dict:
|
| 14 |
+
return config["training"]
|
| 15 |
+
|
| 16 |
+
def get_model_config(config: dict) -> dict:
|
| 17 |
+
return {k: v for k, v in config.items()
|
| 18 |
+
if k not in ["training", "generation", "model_type", "architectures"]}
|
| 19 |
+
|
| 20 |
+
def get_generation_config(config: dict) -> dict:
|
| 21 |
+
return config.get("generation", {})
|
| 22 |
+
|
| 23 |
+
def clear_cache():
|
| 24 |
+
print("Clearing PyTorch and CUDA caches...")
|
| 25 |
+
if torch.cuda.is_available():
|
| 26 |
+
torch.cuda.empty_cache()
|
| 27 |
+
torch.cuda.synchronize()
|
| 28 |
+
print("CUDA cache cleared")
|
| 29 |
+
torch.backends.cudnn.benchmark = True
|
| 30 |
+
print("PyTorch cache cleared")
|
| 31 |
+
|
| 32 |
+
def clear_datasets_cache():
|
| 33 |
+
from datasets import get_cache_directory
|
| 34 |
+
try:
|
| 35 |
+
cache_dir = get_cache_directory()
|
| 36 |
+
print(f"Clearing datasets cache at: {cache_dir}")
|
| 37 |
+
if os.path.exists(cache_dir):
|
| 38 |
+
shutil.rmtree(cache_dir)
|
| 39 |
+
print("Datasets cache cleared")
|
| 40 |
+
except:
|
| 41 |
+
print("Could not clear datasets cache (may not exist)")
|
| 42 |
+
|
| 43 |
+
class LossLoggerCallback(TrainerCallback):
|
| 44 |
+
def __init__(self, log_file="training_losses.txt", with_timestamp=False):
|
| 45 |
+
self.log_file = log_file
|
| 46 |
+
self.with_timestamp = with_timestamp
|
| 47 |
+
with open(self.log_file, "w") as f:
|
| 48 |
+
if self.with_timestamp:
|
| 49 |
+
f.write("time\tstep\tloss\teval_loss\n")
|
| 50 |
+
else:
|
| 51 |
+
f.write("step\tloss\teval_loss\n")
|
| 52 |
+
|
| 53 |
+
def on_log(self, args, state, control, logs=None, **kwargs):
|
| 54 |
+
if logs is None:
|
| 55 |
+
return
|
| 56 |
+
step = state.global_step
|
| 57 |
+
loss = logs.get("loss")
|
| 58 |
+
eval_loss = logs.get("eval_loss")
|
| 59 |
+
|
| 60 |
+
with open(self.log_file, "a") as f:
|
| 61 |
+
if self.with_timestamp:
|
| 62 |
+
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 63 |
+
f.write(f"{ts}\t{step}\t{loss if loss is not None else ''}\t{eval_loss if eval_loss is not None else ''}\n")
|
| 64 |
+
else:
|
| 65 |
+
f.write(f"{step}\t{loss if loss is not None else ''}\t{eval_loss if eval_loss is not None else ''}\n")
|
| 66 |
+
|
| 67 |
+
class CheckpointEvery10PercentCallback(TrainerCallback):
|
| 68 |
+
def __init__(self, save_dir, total_steps):
|
| 69 |
+
self.save_dir = save_dir
|
| 70 |
+
self.total_steps = total_steps
|
| 71 |
+
self.checkpoint_intervals = []
|
| 72 |
+
for i in range(1, 11):
|
| 73 |
+
checkpoint_step = int(total_steps * i * 0.1)
|
| 74 |
+
self.checkpoint_intervals.append(checkpoint_step)
|
| 75 |
+
self.saved_checkpoints = set()
|
| 76 |
+
print(f"Checkpoint intervals: {self.checkpoint_intervals}")
|
| 77 |
+
|
| 78 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 79 |
+
current_step = state.global_step
|
| 80 |
+
for checkpoint_step in self.checkpoint_intervals:
|
| 81 |
+
if current_step == checkpoint_step and checkpoint_step not in self.saved_checkpoints:
|
| 82 |
+
checkpoint_dir = f"{self.save_dir}/checkpoint_10percent_{current_step}"
|
| 83 |
+
print(f"Saving 10% progress checkpoint at step {current_step} to {checkpoint_dir}")
|
| 84 |
+
|
| 85 |
+
model = kwargs.get('model')
|
| 86 |
+
tokenizer = kwargs.get('processing_class')
|
| 87 |
+
|
| 88 |
+
if model is not None:
|
| 89 |
+
model.save_pretrained(checkpoint_dir)
|
| 90 |
+
if tokenizer is not None:
|
| 91 |
+
tokenizer.save_pretrained(checkpoint_dir)
|
| 92 |
+
|
| 93 |
+
if hasattr(kwargs.get('trainer'), 'save_state'):
|
| 94 |
+
kwargs['trainer'].save_state()
|
| 95 |
+
|
| 96 |
+
self.saved_checkpoints.add(checkpoint_step)
|
| 97 |
+
print(f"Checkpoint saved at step {current_step} ({current_step/self.total_steps*100:.1f}% completion)")
|
| 98 |
+
break
|
ChemQ3MTP/modeling_chemq3mtp.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Version
|
| 3 |
+
# MODEL COMPONENTS
|
| 4 |
+
# by gbyuvd
|
| 5 |
+
# ========================
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch.distributions import Categorical
|
| 12 |
+
from typing import List, Union, Optional, Tuple, Dict, Any
|
| 13 |
+
from transformers import Qwen2Config, Qwen2ForCausalLM, AutoTokenizer
|
| 14 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 15 |
+
from transformers.utils import logging
|
| 16 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 17 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 18 |
+
from rdkit import Chem
|
| 19 |
+
from rdkit.Chem import Descriptors, Lipinski
|
| 20 |
+
import selfies as sf
|
| 21 |
+
from rdkit import RDLogger
|
| 22 |
+
RDLogger.DisableLog('rdApp.*')
|
| 23 |
+
import json
|
| 24 |
+
import numpy as np
|
| 25 |
+
from collections import Counter
|
| 26 |
+
from rdkit.Chem import rdMolDescriptors
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
# ========================
|
| 31 |
+
# CONFIGURATION CLASS
|
| 32 |
+
# ========================
|
| 33 |
+
|
| 34 |
+
class ChemQ3MTPConfig(Qwen2Config):
|
| 35 |
+
"""
|
| 36 |
+
Configuration class for ChemQ3MTP model.
|
| 37 |
+
"""
|
| 38 |
+
model_type = "chemq3_mtp"
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
num_future_tokens: int = 3,
|
| 43 |
+
horizon_weights: Optional[List[float]] = None,
|
| 44 |
+
use_mtp_training: bool = True,
|
| 45 |
+
entropy_controller_config: Optional[Dict[str, Any]] = None,
|
| 46 |
+
**kwargs
|
| 47 |
+
):
|
| 48 |
+
super().__init__(**kwargs)
|
| 49 |
+
self.num_future_tokens = num_future_tokens
|
| 50 |
+
self.horizon_weights = horizon_weights or [0.9 ** i for i in range(num_future_tokens)]
|
| 51 |
+
self.use_mtp_training = use_mtp_training
|
| 52 |
+
self.entropy_controller_config = entropy_controller_config or {
|
| 53 |
+
"min_entropy": 0.5,
|
| 54 |
+
"max_entropy": 3.0,
|
| 55 |
+
"target_entropy": 1.5,
|
| 56 |
+
"adaptation_rate": 0.01
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# ========================
|
| 60 |
+
# UTILITY FUNCTIONS (kept minimal for HF compatibility)
|
| 61 |
+
# ========================
|
| 62 |
+
|
| 63 |
+
def selfies_to_smiles(selfies_str: str) -> str | None:
|
| 64 |
+
"""Convert SELFIES string to SMILES, handling tokenizer artifacts."""
|
| 65 |
+
try:
|
| 66 |
+
clean_selfies = selfies_str.replace(" ", "")
|
| 67 |
+
return sf.decoder(clean_selfies)
|
| 68 |
+
except Exception:
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
def is_valid_smiles(smiles: str) -> bool:
|
| 72 |
+
if not isinstance(smiles, str) or len(smiles.strip()) == 0:
|
| 73 |
+
return False
|
| 74 |
+
return Chem.MolFromSmiles(smiles.strip()) is not None
|
| 75 |
+
|
| 76 |
+
# ========================
|
| 77 |
+
# MODEL COMPONENTS
|
| 78 |
+
# ========================
|
| 79 |
+
|
| 80 |
+
class MTPHead(nn.Module):
|
| 81 |
+
"""Multi-Token Prediction Head for predicting future tokens."""
|
| 82 |
+
|
| 83 |
+
def __init__(self, hidden_size: int, vocab_size: int, num_future_tokens: int = 3):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.num_future_tokens = num_future_tokens
|
| 86 |
+
self.vocab_size = vocab_size
|
| 87 |
+
self.prediction_heads = nn.ModuleList([
|
| 88 |
+
nn.Linear(hidden_size, vocab_size, bias=False)
|
| 89 |
+
for _ in range(num_future_tokens)
|
| 90 |
+
])
|
| 91 |
+
self.position_embeddings = nn.Embedding(num_future_tokens, hidden_size)
|
| 92 |
+
self.layer_norm = nn.LayerNorm(hidden_size)
|
| 93 |
+
|
| 94 |
+
def forward(self, hidden_states: torch.Tensor) -> Dict[str, torch.Tensor]:
|
| 95 |
+
batch_size, seq_len, hidden_size = hidden_states.shape
|
| 96 |
+
outputs = {}
|
| 97 |
+
|
| 98 |
+
for i in range(self.num_future_tokens):
|
| 99 |
+
pos_emb = self.position_embeddings(torch.tensor(i, device=hidden_states.device))
|
| 100 |
+
enhanced_hidden = self.layer_norm(hidden_states + pos_emb)
|
| 101 |
+
logits = self.prediction_heads[i](enhanced_hidden)
|
| 102 |
+
outputs[f'logits_t{i+1}'] = logits
|
| 103 |
+
|
| 104 |
+
return outputs
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class HorizonLoss(nn.Module):
|
| 108 |
+
"""Loss function for multi-horizon prediction."""
|
| 109 |
+
|
| 110 |
+
def __init__(self, num_future_tokens: int = 3, horizon_weights: Optional[List[float]] = None):
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.num_future_tokens = num_future_tokens
|
| 113 |
+
if horizon_weights is None:
|
| 114 |
+
self.horizon_weights = [0.9 ** i for i in range(num_future_tokens)]
|
| 115 |
+
else:
|
| 116 |
+
self.horizon_weights = horizon_weights
|
| 117 |
+
self.log_weights = nn.Parameter(torch.log(torch.tensor(self.horizon_weights)))
|
| 118 |
+
|
| 119 |
+
def forward(
|
| 120 |
+
self,
|
| 121 |
+
mtp_outputs: Dict[str, torch.Tensor],
|
| 122 |
+
input_ids: torch.Tensor,
|
| 123 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 124 |
+
) -> Dict[str, torch.Tensor]:
|
| 125 |
+
|
| 126 |
+
batch_size, seq_len = input_ids.shape
|
| 127 |
+
device = input_ids.device
|
| 128 |
+
weights = F.softmax(self.log_weights, dim=0)
|
| 129 |
+
total_loss = 0.0
|
| 130 |
+
horizon_losses = {}
|
| 131 |
+
|
| 132 |
+
for i in range(self.num_future_tokens):
|
| 133 |
+
logits_key = f'logits_t{i+1}'
|
| 134 |
+
if logits_key not in mtp_outputs:
|
| 135 |
+
continue
|
| 136 |
+
|
| 137 |
+
logits = mtp_outputs[logits_key]
|
| 138 |
+
shift = i + 1
|
| 139 |
+
if seq_len <= shift:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
shifted_logits = logits[:, :-shift, :].contiguous()
|
| 143 |
+
shifted_targets = input_ids[:, shift:].contiguous()
|
| 144 |
+
|
| 145 |
+
if attention_mask is not None:
|
| 146 |
+
shifted_mask = attention_mask[:, shift:].contiguous()
|
| 147 |
+
mask_expanded = shifted_mask.view(-1)
|
| 148 |
+
valid_indices = mask_expanded == 1
|
| 149 |
+
if valid_indices.sum() == 0:
|
| 150 |
+
continue
|
| 151 |
+
flat_logits = shifted_logits.view(-1, logits.size(-1))[valid_indices]
|
| 152 |
+
flat_targets = shifted_targets.view(-1)[valid_indices]
|
| 153 |
+
else:
|
| 154 |
+
flat_logits = shifted_logits.view(-1, logits.size(-1))
|
| 155 |
+
flat_targets = shifted_targets.view(-1)
|
| 156 |
+
|
| 157 |
+
horizon_loss = F.cross_entropy(flat_logits, flat_targets, reduction='mean')
|
| 158 |
+
horizon_losses[f'horizon_loss_t{i+1}'] = horizon_loss
|
| 159 |
+
total_loss += weights[i] * horizon_loss
|
| 160 |
+
|
| 161 |
+
return {'loss': total_loss, 'horizon_weights': weights, **horizon_losses}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class EnhancedEntropyController:
|
| 165 |
+
"""Enhanced entropy controller for adaptive training."""
|
| 166 |
+
|
| 167 |
+
def __init__(self, min_entropy: float = 0.5, max_entropy: float = 3.0,
|
| 168 |
+
target_entropy: float = 1.5, adaptation_rate: float = 0.01):
|
| 169 |
+
self.min_entropy = min_entropy
|
| 170 |
+
self.max_entropy = max_entropy
|
| 171 |
+
self.target_entropy = target_entropy
|
| 172 |
+
self.adaptation_rate = adaptation_rate
|
| 173 |
+
self.entropy_history = []
|
| 174 |
+
self.entropy_weight = 0.01
|
| 175 |
+
|
| 176 |
+
def update_entropy_weight(self, current_entropy: float) -> float:
|
| 177 |
+
"""Dynamically adjust entropy weight based on current entropy levels."""
|
| 178 |
+
self.entropy_history.append(current_entropy)
|
| 179 |
+
|
| 180 |
+
if len(self.entropy_history) > 100:
|
| 181 |
+
self.entropy_history = self.entropy_history[-100:]
|
| 182 |
+
|
| 183 |
+
if len(self.entropy_history) >= 10:
|
| 184 |
+
avg_entropy = np.mean(self.entropy_history[-10:])
|
| 185 |
+
|
| 186 |
+
if avg_entropy < self.target_entropy * 0.8:
|
| 187 |
+
self.entropy_weight = min(0.05, self.entropy_weight * 1.1)
|
| 188 |
+
elif avg_entropy > self.target_entropy * 1.2:
|
| 189 |
+
self.entropy_weight = max(0.001, self.entropy_weight * 0.95)
|
| 190 |
+
|
| 191 |
+
return self.entropy_weight
|
| 192 |
+
|
| 193 |
+
# ========================
|
| 194 |
+
# MAIN MODEL CLASS
|
| 195 |
+
# ========================
|
| 196 |
+
|
| 197 |
+
class ChemQ3MTPForCausalLM(Qwen2ForCausalLM):
|
| 198 |
+
"""
|
| 199 |
+
ChemQ3MTP model for causal language modeling with multi-token prediction.
|
| 200 |
+
|
| 201 |
+
This model extends Qwen2ForCausalLM with additional capabilities for
|
| 202 |
+
multi-token prediction and chemistry-specific training.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
config_class = ChemQ3MTPConfig
|
| 206 |
+
_supports_flash_attn_2 = True
|
| 207 |
+
_supports_sdpa = True
|
| 208 |
+
_supports_cache_class = True
|
| 209 |
+
|
| 210 |
+
def __init__(self, config: ChemQ3MTPConfig):
|
| 211 |
+
super().__init__(config)
|
| 212 |
+
|
| 213 |
+
# Initialize MTP components
|
| 214 |
+
self.mtp_head = MTPHead(
|
| 215 |
+
config.hidden_size,
|
| 216 |
+
config.vocab_size,
|
| 217 |
+
config.num_future_tokens
|
| 218 |
+
)
|
| 219 |
+
self.horizon_loss = HorizonLoss(
|
| 220 |
+
num_future_tokens=config.num_future_tokens,
|
| 221 |
+
horizon_weights=config.horizon_weights
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# Training configuration
|
| 225 |
+
self.use_mtp_training = config.use_mtp_training
|
| 226 |
+
|
| 227 |
+
# Initialize entropy controller
|
| 228 |
+
self.entropy_controller = EnhancedEntropyController(
|
| 229 |
+
**config.entropy_controller_config
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# Initialize weights and apply final processing
|
| 233 |
+
self.post_init()
|
| 234 |
+
|
| 235 |
+
def forward(
|
| 236 |
+
self,
|
| 237 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 238 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 239 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 240 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 241 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 242 |
+
labels: Optional[torch.LongTensor] = None,
|
| 243 |
+
use_cache: Optional[bool] = None,
|
| 244 |
+
output_attentions: Optional[bool] = None,
|
| 245 |
+
output_hidden_states: Optional[bool] = None,
|
| 246 |
+
return_dict: Optional[bool] = None,
|
| 247 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 248 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 249 |
+
"""
|
| 250 |
+
Forward pass of the ChemQ3MTP model.
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 254 |
+
output_hidden_states = (
|
| 255 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 256 |
+
)
|
| 257 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 258 |
+
|
| 259 |
+
# Default attention mask if not provided
|
| 260 |
+
if attention_mask is None and input_ids is not None:
|
| 261 |
+
# Handle case where pad_token_id is None
|
| 262 |
+
if hasattr(self.config, 'pad_token_id') and self.config.pad_token_id is not None:
|
| 263 |
+
attention_mask = (input_ids != self.config.pad_token_id).long()
|
| 264 |
+
else:
|
| 265 |
+
# Default to all 1s if no pad_token_id is defined
|
| 266 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.long)
|
| 267 |
+
|
| 268 |
+
# Call parent forward with required hidden states
|
| 269 |
+
outputs = super().forward(
|
| 270 |
+
input_ids=input_ids,
|
| 271 |
+
attention_mask=attention_mask,
|
| 272 |
+
position_ids=position_ids,
|
| 273 |
+
past_key_values=past_key_values,
|
| 274 |
+
inputs_embeds=inputs_embeds,
|
| 275 |
+
labels=None, # Handle labels manually
|
| 276 |
+
use_cache=use_cache,
|
| 277 |
+
output_attentions=output_attentions,
|
| 278 |
+
output_hidden_states=True, # Always need hidden states for MTP
|
| 279 |
+
return_dict=True,
|
| 280 |
+
cache_position=cache_position,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# Rest of your forward method...
|
| 284 |
+
hidden_states = outputs.hidden_states[-1]
|
| 285 |
+
lm_logits = outputs.logits
|
| 286 |
+
loss = None
|
| 287 |
+
|
| 288 |
+
# Compute loss if labels are provided
|
| 289 |
+
if labels is not None:
|
| 290 |
+
if self.training and self.use_mtp_training:
|
| 291 |
+
# Multi-token prediction training
|
| 292 |
+
mtp_outputs = self.mtp_head(hidden_states)
|
| 293 |
+
horizon_loss_dict = self.horizon_loss(mtp_outputs, input_ids, attention_mask)
|
| 294 |
+
|
| 295 |
+
# Standard causal LM loss
|
| 296 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 297 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 298 |
+
|
| 299 |
+
if attention_mask is not None:
|
| 300 |
+
shift_mask = attention_mask[..., 1:].contiguous()
|
| 301 |
+
loss_mask = shift_mask.view(-1) == 1
|
| 302 |
+
if loss_mask.sum() == 0:
|
| 303 |
+
causal_lm_loss = torch.tensor(0.0, device=lm_logits.device)
|
| 304 |
+
else:
|
| 305 |
+
flat_logits = shift_logits.view(-1, shift_logits.size(-1))[loss_mask]
|
| 306 |
+
flat_labels = shift_labels.view(-1)[loss_mask]
|
| 307 |
+
causal_lm_loss = F.cross_entropy(flat_logits, flat_labels, reduction='mean')
|
| 308 |
+
else:
|
| 309 |
+
flat_logits = shift_logits.view(-1, shift_logits.size(-1))
|
| 310 |
+
flat_labels = shift_labels.view(-1)
|
| 311 |
+
causal_lm_loss = F.cross_entropy(flat_logits, flat_labels, reduction='mean')
|
| 312 |
+
|
| 313 |
+
# Combine losses
|
| 314 |
+
loss = 0.7 * horizon_loss_dict['loss'] + 0.3 * causal_lm_loss
|
| 315 |
+
|
| 316 |
+
else:
|
| 317 |
+
# Standard causal LM training
|
| 318 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 319 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 320 |
+
loss = F.cross_entropy(
|
| 321 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 322 |
+
shift_labels.view(-1),
|
| 323 |
+
ignore_index=-100
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
if not return_dict:
|
| 327 |
+
output = (lm_logits,) + outputs[1:]
|
| 328 |
+
return (loss,) + output if loss is not None else output
|
| 329 |
+
|
| 330 |
+
return CausalLMOutputWithPast(
|
| 331 |
+
loss=loss,
|
| 332 |
+
logits=lm_logits,
|
| 333 |
+
past_key_values=outputs.past_key_values,
|
| 334 |
+
hidden_states=outputs.hidden_states,
|
| 335 |
+
attentions=outputs.attentions,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
def set_mtp_training(self, use_mtp: bool):
|
| 339 |
+
"""Enable or disable multi-token prediction training."""
|
| 340 |
+
self.use_mtp_training = use_mtp
|
| 341 |
+
|
| 342 |
+
def prepare_inputs_for_generation(
|
| 343 |
+
self,
|
| 344 |
+
input_ids,
|
| 345 |
+
past_key_values=None,
|
| 346 |
+
attention_mask=None,
|
| 347 |
+
inputs_embeds=None,
|
| 348 |
+
cache_position=None,
|
| 349 |
+
**kwargs
|
| 350 |
+
):
|
| 351 |
+
"""
|
| 352 |
+
Prepare inputs for generation. This method is required for compatibility
|
| 353 |
+
with HuggingFace's generation utilities.
|
| 354 |
+
"""
|
| 355 |
+
# This delegates to the parent class implementation
|
| 356 |
+
return super().prepare_inputs_for_generation(
|
| 357 |
+
input_ids=input_ids,
|
| 358 |
+
past_key_values=past_key_values,
|
| 359 |
+
attention_mask=attention_mask,
|
| 360 |
+
inputs_embeds=inputs_embeds,
|
| 361 |
+
cache_position=cache_position,
|
| 362 |
+
**kwargs
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
def generate_with_logprobs(
|
| 366 |
+
self,
|
| 367 |
+
input_ids: torch.LongTensor,
|
| 368 |
+
max_new_tokens: int = 50,
|
| 369 |
+
temperature: float = 1.0,
|
| 370 |
+
top_k: Optional[int] = None,
|
| 371 |
+
top_p: Optional[float] = None,
|
| 372 |
+
do_sample: bool = True,
|
| 373 |
+
return_probs: bool = True,
|
| 374 |
+
tokenizer=None,
|
| 375 |
+
) -> Tuple[List[str], torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
|
| 376 |
+
"""
|
| 377 |
+
Generate sequences with log probabilities for RL training.
|
| 378 |
+
|
| 379 |
+
FIXED VERSION: Corrects log probability calculation to avoid numerical issues.
|
| 380 |
+
Changes:
|
| 381 |
+
1. Use log_softmax instead of log(softmax) to avoid log(0) issues
|
| 382 |
+
2. Correct the gather operation for non-sampling case
|
| 383 |
+
3. Handle the case where filtered logits become -inf properly
|
| 384 |
+
"""
|
| 385 |
+
self.eval()
|
| 386 |
+
device = input_ids.device
|
| 387 |
+
|
| 388 |
+
# Normalize input shapes
|
| 389 |
+
if input_ids.dim() == 1:
|
| 390 |
+
input_ids = input_ids.unsqueeze(0)
|
| 391 |
+
if input_ids.dim() == 3 and input_ids.size(1) == 1:
|
| 392 |
+
input_ids = input_ids.squeeze(1)
|
| 393 |
+
assert input_ids.dim() == 2, f"input_ids must be 2-D, got {input_ids.shape}"
|
| 394 |
+
|
| 395 |
+
batch_size, seq_len = input_ids.shape
|
| 396 |
+
current_input = input_ids
|
| 397 |
+
|
| 398 |
+
generated_tokens, generated_logprobs, generated_probs = [], [], []
|
| 399 |
+
|
| 400 |
+
with torch.no_grad():
|
| 401 |
+
for _ in range(max_new_tokens):
|
| 402 |
+
outputs = self(current_input, use_cache=False)
|
| 403 |
+
logits = outputs.logits[:, -1, :] / temperature
|
| 404 |
+
|
| 405 |
+
# Apply top-k filtering
|
| 406 |
+
if top_k is not None:
|
| 407 |
+
values, indices = torch.topk(logits, k=top_k)
|
| 408 |
+
logits = torch.full_like(logits, float("-inf"))
|
| 409 |
+
logits.scatter_(1, indices, values)
|
| 410 |
+
|
| 411 |
+
# Apply top-p filtering
|
| 412 |
+
if top_p is not None and top_p < 1.0:
|
| 413 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 414 |
+
cumprobs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 415 |
+
mask = cumprobs > top_p
|
| 416 |
+
mask[..., 1:] = mask[..., :-1].clone()
|
| 417 |
+
mask[..., 0] = False
|
| 418 |
+
logits[mask.scatter(1, sorted_indices, mask)] = float("-inf")
|
| 419 |
+
|
| 420 |
+
# FIX: Calculate log probabilities using log_softmax for numerical stability
|
| 421 |
+
log_probs = F.log_softmax(logits, dim=-1)
|
| 422 |
+
probs = F.softmax(logits, dim=-1)
|
| 423 |
+
|
| 424 |
+
if do_sample:
|
| 425 |
+
dist = Categorical(probs)
|
| 426 |
+
next_token = dist.sample()
|
| 427 |
+
# FIX: Get log prob directly from log_probs tensor
|
| 428 |
+
log_p = torch.gather(log_probs, 1, next_token.unsqueeze(1)).squeeze(1)
|
| 429 |
+
else:
|
| 430 |
+
next_token = torch.argmax(probs, dim=-1)
|
| 431 |
+
# FIX: Use log_probs instead of log(probs) to avoid numerical issues
|
| 432 |
+
log_p = torch.gather(log_probs, 1, next_token.unsqueeze(1)).squeeze(1)
|
| 433 |
+
|
| 434 |
+
generated_tokens.append(next_token.unsqueeze(1))
|
| 435 |
+
generated_logprobs.append(log_p.unsqueeze(1))
|
| 436 |
+
if return_probs:
|
| 437 |
+
generated_probs.append(probs.unsqueeze(1))
|
| 438 |
+
|
| 439 |
+
current_input = torch.cat([current_input, next_token.unsqueeze(1)], dim=1)
|
| 440 |
+
|
| 441 |
+
generated_tokens = torch.cat(generated_tokens, dim=1)
|
| 442 |
+
generated_logprobs = torch.cat(generated_logprobs, dim=1)
|
| 443 |
+
generated_probs = torch.cat(generated_probs, dim=1) if return_probs else None
|
| 444 |
+
|
| 445 |
+
# Decode generated tokens
|
| 446 |
+
if tokenizer is None:
|
| 447 |
+
tokenizer = getattr(self, "tokenizer", None)
|
| 448 |
+
if tokenizer is None:
|
| 449 |
+
raise ValueError("Tokenizer must be provided to decode generated tokens.")
|
| 450 |
+
|
| 451 |
+
decoded_list = [
|
| 452 |
+
tokenizer.decode(tok_ids, skip_special_tokens=True)
|
| 453 |
+
for tok_ids in generated_tokens
|
| 454 |
+
]
|
| 455 |
+
|
| 456 |
+
return decoded_list, generated_logprobs, generated_tokens, generated_probs
|
| 457 |
+
|
| 458 |
+
# ========================
|
| 459 |
+
# REGISTRATION
|
| 460 |
+
# ========================
|
| 461 |
+
|
| 462 |
+
# Register the configuration and model classes
|
| 463 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 464 |
+
|
| 465 |
+
# Register the configuration and model classes
|
| 466 |
+
AutoConfig.register("chemq3_mtp", ChemQ3MTPConfig)
|
| 467 |
+
AutoModelForCausalLM.register(ChemQ3MTPConfig, ChemQ3MTPForCausalLM)
|
ChemQ3MTP/rl_utils.py
ADDED
|
@@ -0,0 +1,1070 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ========================
|
| 2 |
+
# RL_UTILS.PY
|
| 3 |
+
# v3
|
| 4 |
+
# Chemistry RL Training Utilities for ChemQ3-MTP
|
| 5 |
+
# by gbyuvd
|
| 6 |
+
# Patched: reward normalization, KL/entropy reset per phase,
|
| 7 |
+
# entropy target annealing, and symmetric curriculum
|
| 8 |
+
# and now with Durrant's Lab's filtering included
|
| 9 |
+
# ========================
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from torch.distributions import Categorical
|
| 15 |
+
from typing import List, Union, Optional, Tuple, Dict, Any
|
| 16 |
+
import numpy as np
|
| 17 |
+
from collections import Counter, deque
|
| 18 |
+
|
| 19 |
+
# Chemistry imports
|
| 20 |
+
from rdkit import Chem
|
| 21 |
+
from rdkit.Chem import Descriptors, Lipinski, rdMolDescriptors
|
| 22 |
+
import selfies as sf
|
| 23 |
+
from rdkit import RDLogger
|
| 24 |
+
RDLogger.DisableLog('rdApp.*')
|
| 25 |
+
|
| 26 |
+
# Optional: HuggingFace for SA classifier
|
| 27 |
+
try:
|
| 28 |
+
from transformers import pipeline, AutoTokenizer
|
| 29 |
+
HF_AVAILABLE = True
|
| 30 |
+
except ImportError:
|
| 31 |
+
HF_AVAILABLE = False
|
| 32 |
+
print("Warning: transformers not available, SA classifier will not work")
|
| 33 |
+
|
| 34 |
+
# ========================
|
| 35 |
+
# CHEMISTRY UTILITIES
|
| 36 |
+
# ========================
|
| 37 |
+
|
| 38 |
+
def selfies_to_smiles(selfies_str: str) -> str | None:
|
| 39 |
+
"""Convert SELFIES string to SMILES, handling tokenizer artifacts."""
|
| 40 |
+
try:
|
| 41 |
+
clean_selfies = selfies_str.replace(" ", "")
|
| 42 |
+
return sf.decoder(clean_selfies)
|
| 43 |
+
except Exception:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
def is_valid_smiles(smiles: str) -> bool:
|
| 47 |
+
"""
|
| 48 |
+
Check if a SMILES string represents a valid molecule.
|
| 49 |
+
FIXED: Now properly checks for heavy atoms (non-hydrogens) >= 3
|
| 50 |
+
and rejects disconnected/separated molecules
|
| 51 |
+
"""
|
| 52 |
+
if not isinstance(smiles, str) or len(smiles.strip()) == 0:
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
smiles = smiles.strip()
|
| 56 |
+
|
| 57 |
+
# FAST CHECK: Reject separated molecules (contains dots)
|
| 58 |
+
if '.' in smiles:
|
| 59 |
+
return False # Disconnected components indicated by dots
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 63 |
+
if mol is None:
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
# CRITICAL FIX: Check heavy atoms (non-hydrogens), not total atoms
|
| 67 |
+
heavy_atoms = mol.GetNumHeavyAtoms() # This excludes hydrogens
|
| 68 |
+
if heavy_atoms < 3:
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
return True
|
| 72 |
+
except Exception:
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
def passes_durrant_lab_filter(smiles: str) -> bool:
|
| 76 |
+
"""
|
| 77 |
+
Apply Durrant's lab filter to remove improbable substructures.
|
| 78 |
+
FIXED: More robust error handling, pattern checking, and disconnected molecule rejection.
|
| 79 |
+
Returns True if molecule passes the filter (is acceptable), False otherwise.
|
| 80 |
+
"""
|
| 81 |
+
if not smiles or not isinstance(smiles, str) or len(smiles.strip()) == 0:
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
mol = Chem.MolFromSmiles(smiles.strip())
|
| 86 |
+
if mol is None:
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
# Check heavy atoms again (belt and suspenders approach)
|
| 90 |
+
if mol.GetNumHeavyAtoms() < 3:
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
# REJECT SEPARATED/DISCONNECTED MOLECULES (double check here too)
|
| 94 |
+
fragments = Chem.rdmolops.GetMolFrags(mol, asMols=False)
|
| 95 |
+
if len(fragments) > 1:
|
| 96 |
+
return False # Reject molecules with multiple disconnected parts
|
| 97 |
+
|
| 98 |
+
# Define SMARTS patterns for problematic substructures
|
| 99 |
+
problematic_patterns = [
|
| 100 |
+
"C=[N-]", # Carbon double bonded to negative nitrogen
|
| 101 |
+
"[N-]C=[N+]", # Nitrogen anion bonded to nitrogen cation
|
| 102 |
+
"[nH+]c[n-]", # Aromatic nitrogen cation adjacent to nitrogen anion
|
| 103 |
+
"[#7+]~[#7+]", # Positive nitrogen connected to positive nitrogen
|
| 104 |
+
"[#7-]~[#7-]", # Negative nitrogen connected to negative nitrogen
|
| 105 |
+
"[!#7]~[#7+]~[#7-]~[!#7]", # Bridge: non-nitrogen - pos nitrogen - neg nitrogen - non-nitrogen
|
| 106 |
+
"[#5]", # Boron atoms
|
| 107 |
+
"O=[PH](=O)([#8])([#8])", # Phosphoryl with hydroxyls
|
| 108 |
+
"N=c1cc[#7]c[#7]1", # Nitrogen in aromatic ring with another nitrogen
|
| 109 |
+
"[$([NX2H1]),$([NX3H2])]=C[$([OH]),$([O-])]", # N=CH-OH or N=CH-O-
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
# Check for metals (excluding common biologically relevant ions)
|
| 113 |
+
metal_exclusions = {11, 12, 19, 20} # Na, Mg, K, Ca
|
| 114 |
+
for atom in mol.GetAtoms():
|
| 115 |
+
atomic_num = atom.GetAtomicNum()
|
| 116 |
+
# More precise metal detection
|
| 117 |
+
if atomic_num > 20 and atomic_num not in metal_exclusions:
|
| 118 |
+
return False
|
| 119 |
+
|
| 120 |
+
# Check for each problematic pattern
|
| 121 |
+
for pattern in problematic_patterns:
|
| 122 |
+
try:
|
| 123 |
+
patt_mol = Chem.MolFromSmarts(pattern)
|
| 124 |
+
if patt_mol is not None:
|
| 125 |
+
matches = mol.GetSubstructMatches(patt_mol)
|
| 126 |
+
if matches:
|
| 127 |
+
return False # Found problematic substructure
|
| 128 |
+
except Exception:
|
| 129 |
+
# If SMARTS parsing fails, continue to next pattern
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
return True # Passed all checks
|
| 133 |
+
|
| 134 |
+
except Exception:
|
| 135 |
+
return False
|
| 136 |
+
# ========================
|
| 137 |
+
# SA CLASSIFIER
|
| 138 |
+
# ========================
|
| 139 |
+
|
| 140 |
+
# Global classifier instance for lazy loading
|
| 141 |
+
_sa_classifier = None
|
| 142 |
+
|
| 143 |
+
def get_sa_classifier():
|
| 144 |
+
"""Get or initialize the synthetic accessibility classifier."""
|
| 145 |
+
global _sa_classifier
|
| 146 |
+
if not HF_AVAILABLE:
|
| 147 |
+
raise ImportError("transformers package required for SA classifier")
|
| 148 |
+
|
| 149 |
+
if _sa_classifier is None:
|
| 150 |
+
try:
|
| 151 |
+
sa_tokenizer = AutoTokenizer.from_pretrained("gbyuvd/synthaccess-chemselfies")
|
| 152 |
+
_sa_classifier = pipeline(
|
| 153 |
+
"text-classification",
|
| 154 |
+
model="gbyuvd/synthaccess-chemselfies",
|
| 155 |
+
tokenizer=sa_tokenizer
|
| 156 |
+
)
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"Warning: Could not load SA classifier: {e}")
|
| 159 |
+
return None
|
| 160 |
+
return _sa_classifier
|
| 161 |
+
|
| 162 |
+
def compute_sa_reward(selfies_str: str) -> float:
|
| 163 |
+
"""Reward molecules with easy synthetic accessibility (SA)."""
|
| 164 |
+
try:
|
| 165 |
+
classifier = get_sa_classifier()
|
| 166 |
+
if classifier is None:
|
| 167 |
+
return 0.0
|
| 168 |
+
|
| 169 |
+
result = classifier(selfies_str, truncation=True, max_length=128)[0]
|
| 170 |
+
if result["label"].lower() == "easy":
|
| 171 |
+
return result["score"]
|
| 172 |
+
else:
|
| 173 |
+
return -result["score"] # penalize "Hard"
|
| 174 |
+
except Exception:
|
| 175 |
+
return 0.0
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# ========================
|
| 179 |
+
# MOLECULAR REWARD COMPONENTS
|
| 180 |
+
# ========================
|
| 181 |
+
|
| 182 |
+
def compute_biological_diversity_score(mol) -> float:
|
| 183 |
+
"""Reward molecules with diverse CHONP atoms, normalized to [0,1]."""
|
| 184 |
+
if mol is None:
|
| 185 |
+
return 0.0
|
| 186 |
+
try:
|
| 187 |
+
atoms = [atom.GetSymbol() for atom in mol.GetAtoms()]
|
| 188 |
+
atom_counts = Counter(atoms)
|
| 189 |
+
bio_elements = {"C", "H", "O", "N", "P"}
|
| 190 |
+
present_bio_elements = set(atoms) & bio_elements
|
| 191 |
+
|
| 192 |
+
if len(present_bio_elements) < 2:
|
| 193 |
+
return 0.0
|
| 194 |
+
|
| 195 |
+
base_score = 0.3
|
| 196 |
+
diversity_bonus = (len(present_bio_elements) - 2) / 3 * 0.4
|
| 197 |
+
|
| 198 |
+
total_bio_atoms = sum(atom_counts.get(e, 0) for e in present_bio_elements)
|
| 199 |
+
if total_bio_atoms > 0:
|
| 200 |
+
bio_probs = [atom_counts.get(e, 0) / total_bio_atoms for e in present_bio_elements]
|
| 201 |
+
if len(bio_probs) > 1:
|
| 202 |
+
entropy = -sum(p * np.log2(p) for p in bio_probs if p > 0)
|
| 203 |
+
max_entropy = np.log2(len(bio_probs))
|
| 204 |
+
entropy_bonus = (entropy / max_entropy) * 0.3
|
| 205 |
+
else:
|
| 206 |
+
entropy_bonus = 0.0
|
| 207 |
+
else:
|
| 208 |
+
entropy_bonus = 0.0
|
| 209 |
+
|
| 210 |
+
return min(1.0, base_score + diversity_bonus + entropy_bonus)
|
| 211 |
+
except Exception:
|
| 212 |
+
return 0.0
|
| 213 |
+
|
| 214 |
+
def compute_charge_neutrality_score(mol) -> float:
|
| 215 |
+
"""Reward if molecule is globally neutral (formal charge = 0)."""
|
| 216 |
+
if mol is None:
|
| 217 |
+
return 0.0
|
| 218 |
+
try:
|
| 219 |
+
return 1.0 if Chem.rdmolops.GetFormalCharge(mol) == 0 else 0.0
|
| 220 |
+
except Exception:
|
| 221 |
+
return 0.0
|
| 222 |
+
|
| 223 |
+
def compute_local_charge_penalty(mol) -> float:
|
| 224 |
+
"""
|
| 225 |
+
Penalize carbocations/anions.
|
| 226 |
+
Returns 1.0 if no charged atoms, decreases with fraction charged.
|
| 227 |
+
"""
|
| 228 |
+
if mol is None:
|
| 229 |
+
return 0.0
|
| 230 |
+
try:
|
| 231 |
+
charges = [atom.GetFormalCharge() for atom in mol.GetAtoms()]
|
| 232 |
+
if not charges:
|
| 233 |
+
return 1.0
|
| 234 |
+
charged_atoms = sum(1 for c in charges if c != 0)
|
| 235 |
+
total_atoms = len(charges)
|
| 236 |
+
return max(0.0, 1.0 - (charged_atoms / total_atoms))
|
| 237 |
+
except Exception:
|
| 238 |
+
return 0.0
|
| 239 |
+
|
| 240 |
+
def compute_enhanced_lipinski_reward(mol) -> float:
|
| 241 |
+
"""Soft Lipinski scoring with partial credit."""
|
| 242 |
+
if mol is None:
|
| 243 |
+
return 0.0
|
| 244 |
+
try:
|
| 245 |
+
mw = Descriptors.MolWt(mol)
|
| 246 |
+
logp = Descriptors.MolLogP(mol)
|
| 247 |
+
hbd = Lipinski.NumHDonors(mol)
|
| 248 |
+
hba = Lipinski.NumHAcceptors(mol)
|
| 249 |
+
scores = []
|
| 250 |
+
|
| 251 |
+
# Molecular Weight
|
| 252 |
+
if 250 <= mw <= 500:
|
| 253 |
+
scores.append(1.0)
|
| 254 |
+
elif 150 <= mw < 250:
|
| 255 |
+
scores.append(0.5)
|
| 256 |
+
elif 500 < mw <= 600:
|
| 257 |
+
scores.append(0.7)
|
| 258 |
+
else:
|
| 259 |
+
scores.append(0.0)
|
| 260 |
+
|
| 261 |
+
# LogP
|
| 262 |
+
if -1 <= logp <= 5:
|
| 263 |
+
scores.append(1.0)
|
| 264 |
+
elif -2 <= logp < -1 or 5 < logp <= 6:
|
| 265 |
+
scores.append(0.5)
|
| 266 |
+
else:
|
| 267 |
+
scores.append(0.0)
|
| 268 |
+
|
| 269 |
+
# Hydrogen bond donors
|
| 270 |
+
scores.append(1.0 if hbd <= 5 else max(0.0, 1.0 - 0.2 * (hbd - 5)))
|
| 271 |
+
|
| 272 |
+
# Hydrogen bond acceptors
|
| 273 |
+
scores.append(1.0 if hba <= 10 else max(0.0, 1.0 - 0.1 * (hba - 10)))
|
| 274 |
+
|
| 275 |
+
return sum(scores) / len(scores)
|
| 276 |
+
except Exception:
|
| 277 |
+
return 0.0
|
| 278 |
+
|
| 279 |
+
def compute_structural_complexity_reward(mol) -> float:
|
| 280 |
+
"""Reward moderate complexity: 1–3 rings and some flexibility."""
|
| 281 |
+
if mol is None:
|
| 282 |
+
return 0.0
|
| 283 |
+
try:
|
| 284 |
+
ring_count = rdMolDescriptors.CalcNumRings(mol)
|
| 285 |
+
if 1 <= ring_count <= 3:
|
| 286 |
+
ring_score = 1.0
|
| 287 |
+
elif ring_count == 0:
|
| 288 |
+
ring_score = 0.3
|
| 289 |
+
elif ring_count <= 5:
|
| 290 |
+
ring_score = 0.7
|
| 291 |
+
else:
|
| 292 |
+
ring_score = 0.1
|
| 293 |
+
|
| 294 |
+
rot_bonds = Descriptors.NumRotatableBonds(mol)
|
| 295 |
+
if 2 <= rot_bonds <= 8:
|
| 296 |
+
flex_score = 1.0
|
| 297 |
+
elif rot_bonds <= 12:
|
| 298 |
+
flex_score = 0.7
|
| 299 |
+
elif rot_bonds in (0, 1):
|
| 300 |
+
flex_score = 0.5
|
| 301 |
+
else:
|
| 302 |
+
flex_score = 0.2
|
| 303 |
+
|
| 304 |
+
return (ring_score + flex_score) / 2
|
| 305 |
+
except Exception:
|
| 306 |
+
return 0.0
|
| 307 |
+
|
| 308 |
+
def compute_lipinski_reward(mol) -> float:
|
| 309 |
+
"""Simple Lipinski rule compliance scoring."""
|
| 310 |
+
if mol is None:
|
| 311 |
+
return 0.0
|
| 312 |
+
try:
|
| 313 |
+
mw = Descriptors.MolWt(mol)
|
| 314 |
+
logp = Descriptors.MolLogP(mol)
|
| 315 |
+
hbd = Lipinski.NumHDonors(mol)
|
| 316 |
+
hba = Lipinski.NumHAcceptors(mol)
|
| 317 |
+
|
| 318 |
+
# We don't want too small fragments, so MW > 250
|
| 319 |
+
rules = [250 < mw <= 500, logp <= 5, hbd <= 5, hba <= 10]
|
| 320 |
+
return sum(rules) / 4.0
|
| 321 |
+
except Exception:
|
| 322 |
+
return 0.0
|
| 323 |
+
|
| 324 |
+
# ========================
|
| 325 |
+
# COMPREHENSIVE REWARD SYSTEM
|
| 326 |
+
# ========================
|
| 327 |
+
|
| 328 |
+
def compute_comprehensive_reward(selfies_str: str) -> Dict[str, float]:
|
| 329 |
+
"""
|
| 330 |
+
Compute comprehensive reward for a SELFIES string.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
selfies_str: SELFIES representation of molecule
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
Dictionary containing individual reward components and total
|
| 337 |
+
"""
|
| 338 |
+
smiles = selfies_to_smiles(selfies_str)
|
| 339 |
+
|
| 340 |
+
# Check validity first
|
| 341 |
+
is_valid = (smiles is not None and
|
| 342 |
+
is_valid_smiles(smiles) and
|
| 343 |
+
passes_durrant_lab_filter(smiles))
|
| 344 |
+
|
| 345 |
+
if is_valid:
|
| 346 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 347 |
+
else:
|
| 348 |
+
mol = None
|
| 349 |
+
|
| 350 |
+
rewards = {
|
| 351 |
+
"validity": 1.0 if is_valid else 0.0,
|
| 352 |
+
"biological_diversity": compute_biological_diversity_score(mol),
|
| 353 |
+
"charge_neutrality": compute_charge_neutrality_score(mol),
|
| 354 |
+
"local_charge_penalty": compute_local_charge_penalty(mol),
|
| 355 |
+
"lipinski": compute_enhanced_lipinski_reward(mol),
|
| 356 |
+
"structural_complexity": compute_structural_complexity_reward(mol),
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
if not is_valid:
|
| 360 |
+
# If not valid, set all chemistry-based rewards to 0
|
| 361 |
+
for key in rewards:
|
| 362 |
+
if key != "validity":
|
| 363 |
+
rewards[key] = 0.0
|
| 364 |
+
rewards["total"] = 0.0
|
| 365 |
+
else:
|
| 366 |
+
# Weighted combination of rewards
|
| 367 |
+
weights = {
|
| 368 |
+
"validity": 1.0,
|
| 369 |
+
"biological_diversity": 2.0,
|
| 370 |
+
"charge_neutrality": 1.5,
|
| 371 |
+
"local_charge_penalty": 1.0,
|
| 372 |
+
"lipinski": 1.0,
|
| 373 |
+
"structural_complexity": 0.5,
|
| 374 |
+
}
|
| 375 |
+
weighted_sum = sum(rewards[k] * weights[k] for k in weights)
|
| 376 |
+
rewards["total"] = weighted_sum / sum(weights.values())
|
| 377 |
+
|
| 378 |
+
return rewards
|
| 379 |
+
|
| 380 |
+
def selfies_to_lipinski_reward(selfies_str: str) -> float:
|
| 381 |
+
"""Convert SELFIES to SMILES, then compute Lipinski reward."""
|
| 382 |
+
smiles = selfies_to_smiles(selfies_str)
|
| 383 |
+
if smiles is None or not is_valid_smiles(smiles) or not passes_durrant_lab_filter(smiles):
|
| 384 |
+
return 0.0
|
| 385 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 386 |
+
return compute_lipinski_reward(mol)
|
| 387 |
+
|
| 388 |
+
# ========================
|
| 389 |
+
# PARETO-STYLE DYNAMIC REWARD CONTROLLER
|
| 390 |
+
# ========================
|
| 391 |
+
|
| 392 |
+
class ParetoRewardController:
|
| 393 |
+
"""
|
| 394 |
+
Dynamic reward mixing based on Pareto optimality principles.
|
| 395 |
+
Adapts reward weights based on current population performance.
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
def __init__(
|
| 399 |
+
self,
|
| 400 |
+
objectives: List[str] = None,
|
| 401 |
+
history_size: int = 500,
|
| 402 |
+
adaptation_rate: float = 0.1,
|
| 403 |
+
min_weight: float = 0.05,
|
| 404 |
+
max_weight: float = 0.95,
|
| 405 |
+
pareto_pressure: float = 1.0,
|
| 406 |
+
exploration_phase_length: int = 100
|
| 407 |
+
):
|
| 408 |
+
"""
|
| 409 |
+
Args:
|
| 410 |
+
objectives: List of objective names to track
|
| 411 |
+
history_size: Size of rolling history for Pareto analysis
|
| 412 |
+
adaptation_rate: How quickly weights adapt (0-1)
|
| 413 |
+
min_weight: Minimum weight for any objective
|
| 414 |
+
max_weight: Maximum weight for any objective
|
| 415 |
+
pareto_pressure: Higher = more aggressive toward Pareto front
|
| 416 |
+
exploration_phase_length: Steps of pure exploration before adaptation
|
| 417 |
+
"""
|
| 418 |
+
self.objectives = objectives or ["total", "sa", "validity", "diversity"]
|
| 419 |
+
self.history_size = history_size
|
| 420 |
+
self.adaptation_rate = adaptation_rate
|
| 421 |
+
self.min_weight = min_weight
|
| 422 |
+
self.max_weight = max_weight
|
| 423 |
+
self.pareto_pressure = pareto_pressure
|
| 424 |
+
self.exploration_phase_length = exploration_phase_length
|
| 425 |
+
|
| 426 |
+
# Initialize weights equally
|
| 427 |
+
n_objectives = len(self.objectives)
|
| 428 |
+
self.weights = {obj: 1.0/n_objectives for obj in self.objectives}
|
| 429 |
+
|
| 430 |
+
# History tracking
|
| 431 |
+
self.objective_history = deque(maxlen=history_size)
|
| 432 |
+
self.pareto_history = deque(maxlen=100) # Track Pareto front evolution
|
| 433 |
+
self.step_count = 0
|
| 434 |
+
|
| 435 |
+
# Performance tracking
|
| 436 |
+
self.objective_trends = {obj: deque(maxlen=50) for obj in self.objectives}
|
| 437 |
+
self.stagnation_counters = {obj: 0 for obj in self.objectives}
|
| 438 |
+
|
| 439 |
+
def update(self, batch_objectives: Dict[str, torch.Tensor]) -> Dict[str, float]:
|
| 440 |
+
"""
|
| 441 |
+
Update weights based on current batch performance.
|
| 442 |
+
|
| 443 |
+
Args:
|
| 444 |
+
batch_objectives: Dict of objective_name -> tensor of scores
|
| 445 |
+
|
| 446 |
+
Returns:
|
| 447 |
+
Updated weights dictionary
|
| 448 |
+
"""
|
| 449 |
+
self.step_count += 1
|
| 450 |
+
|
| 451 |
+
# Convert to numpy for easier manipulation
|
| 452 |
+
batch_data = {}
|
| 453 |
+
for obj_name, tensor_vals in batch_objectives.items():
|
| 454 |
+
if obj_name in self.objectives:
|
| 455 |
+
batch_data[obj_name] = tensor_vals.detach().cpu().numpy()
|
| 456 |
+
|
| 457 |
+
# Store in history
|
| 458 |
+
if len(batch_data) > 0:
|
| 459 |
+
batch_size = len(batch_data[next(iter(batch_data))])
|
| 460 |
+
for i in range(batch_size):
|
| 461 |
+
point = {obj: batch_data[obj][i] for obj in self.objectives if obj in batch_data}
|
| 462 |
+
if len(point) == len(self.objectives): # Only store complete points
|
| 463 |
+
self.objective_history.append(point)
|
| 464 |
+
|
| 465 |
+
# Skip adaptation during exploration phase
|
| 466 |
+
if self.step_count <= self.exploration_phase_length:
|
| 467 |
+
return self.weights.copy()
|
| 468 |
+
|
| 469 |
+
# Compute current Pareto front
|
| 470 |
+
current_front = self._compute_pareto_front()
|
| 471 |
+
if len(current_front) > 0:
|
| 472 |
+
self.pareto_history.append(len(current_front))
|
| 473 |
+
|
| 474 |
+
# Adapt weights based on multiple criteria
|
| 475 |
+
self._adapt_weights_pareto_driven(batch_data)
|
| 476 |
+
self._adapt_weights_stagnation_driven(batch_data)
|
| 477 |
+
self._adapt_weights_diversity_driven()
|
| 478 |
+
|
| 479 |
+
# Ensure constraints
|
| 480 |
+
self._normalize_weights()
|
| 481 |
+
|
| 482 |
+
return self.weights.copy()
|
| 483 |
+
|
| 484 |
+
def _compute_pareto_front(self) -> List[Dict[str, float]]:
|
| 485 |
+
"""Compute current Pareto front from history."""
|
| 486 |
+
if len(self.objective_history) < 10:
|
| 487 |
+
return []
|
| 488 |
+
|
| 489 |
+
points = list(self.objective_history)
|
| 490 |
+
pareto_front = []
|
| 491 |
+
|
| 492 |
+
for i, point1 in enumerate(points):
|
| 493 |
+
is_dominated = False
|
| 494 |
+
for j, point2 in enumerate(points):
|
| 495 |
+
if i != j and self._dominates(point2, point1):
|
| 496 |
+
is_dominated = True
|
| 497 |
+
break
|
| 498 |
+
if not is_dominated:
|
| 499 |
+
pareto_front.append(point1)
|
| 500 |
+
|
| 501 |
+
return pareto_front
|
| 502 |
+
|
| 503 |
+
def _dominates(self, point1: Dict[str, float], point2: Dict[str, float]) -> bool:
|
| 504 |
+
"""Check if point1 dominates point2 (higher is better for all objectives)."""
|
| 505 |
+
better_in_all = True
|
| 506 |
+
strictly_better_in_one = False
|
| 507 |
+
|
| 508 |
+
for obj in self.objectives:
|
| 509 |
+
if obj in point1 and obj in point2:
|
| 510 |
+
if point1[obj] < point2[obj]:
|
| 511 |
+
better_in_all = False
|
| 512 |
+
break
|
| 513 |
+
elif point1[obj] > point2[obj]:
|
| 514 |
+
strictly_better_in_one = True
|
| 515 |
+
|
| 516 |
+
return better_in_all and strictly_better_in_one
|
| 517 |
+
|
| 518 |
+
def _adapt_weights_pareto_driven(self, batch_data: Dict[str, np.ndarray]):
|
| 519 |
+
"""Adapt weights based on distance to Pareto front."""
|
| 520 |
+
if len(self.objective_history) < 50:
|
| 521 |
+
return
|
| 522 |
+
|
| 523 |
+
pareto_front = self._compute_pareto_front()
|
| 524 |
+
if len(pareto_front) == 0:
|
| 525 |
+
return
|
| 526 |
+
|
| 527 |
+
# Compute average distance to Pareto front for each objective
|
| 528 |
+
obj_distances = {obj: [] for obj in self.objectives}
|
| 529 |
+
|
| 530 |
+
for point in list(self.objective_history)[-100:]: # Recent history
|
| 531 |
+
min_distance = float('inf')
|
| 532 |
+
closest_front_point = None
|
| 533 |
+
|
| 534 |
+
for front_point in pareto_front:
|
| 535 |
+
distance = sum((point[obj] - front_point[obj])**2
|
| 536 |
+
for obj in self.objectives if obj in point and obj in front_point)
|
| 537 |
+
if distance < min_distance:
|
| 538 |
+
min_distance = distance
|
| 539 |
+
closest_front_point = front_point
|
| 540 |
+
|
| 541 |
+
if closest_front_point:
|
| 542 |
+
for obj in self.objectives:
|
| 543 |
+
if obj in point and obj in closest_front_point:
|
| 544 |
+
obj_distances[obj].append(abs(point[obj] - closest_front_point[obj]))
|
| 545 |
+
|
| 546 |
+
# Increase weight for objectives with larger gaps to Pareto front
|
| 547 |
+
for obj in self.objectives:
|
| 548 |
+
if obj_distances[obj]:
|
| 549 |
+
avg_distance = np.mean(obj_distances[obj])
|
| 550 |
+
# Higher distance = increase weight
|
| 551 |
+
weight_adjustment = avg_distance * self.adaptation_rate * self.pareto_pressure
|
| 552 |
+
self.weights[obj] = self.weights[obj] * (1 + weight_adjustment)
|
| 553 |
+
|
| 554 |
+
def _adapt_weights_stagnation_driven(self, batch_data: Dict[str, np.ndarray]):
|
| 555 |
+
"""Increase weights for stagnating objectives."""
|
| 556 |
+
for obj in self.objectives:
|
| 557 |
+
if obj in batch_data:
|
| 558 |
+
current_mean = np.mean(batch_data[obj])
|
| 559 |
+
self.objective_trends[obj].append(current_mean)
|
| 560 |
+
|
| 561 |
+
if len(self.objective_trends[obj]) >= 20:
|
| 562 |
+
recent_trend = np.array(list(self.objective_trends[obj])[-20:])
|
| 563 |
+
# Check for stagnation (low variance)
|
| 564 |
+
if np.std(recent_trend) < 0.01: # Adjust threshold as needed
|
| 565 |
+
self.stagnation_counters[obj] += 1
|
| 566 |
+
# Boost weight for stagnating objectives
|
| 567 |
+
boost = min(0.1, self.stagnation_counters[obj] * 0.02)
|
| 568 |
+
self.weights[obj] += boost
|
| 569 |
+
else:
|
| 570 |
+
self.stagnation_counters[obj] = max(0, self.stagnation_counters[obj] - 1)
|
| 571 |
+
|
| 572 |
+
def _adapt_weights_diversity_driven(self):
|
| 573 |
+
"""Adapt weights based on Pareto front diversity."""
|
| 574 |
+
if len(self.pareto_history) < 10:
|
| 575 |
+
return
|
| 576 |
+
|
| 577 |
+
recent_front_sizes = list(self.pareto_history)[-10:]
|
| 578 |
+
front_diversity = np.std(recent_front_sizes)
|
| 579 |
+
|
| 580 |
+
# If diversity is low, boost exploration objectives
|
| 581 |
+
if front_diversity < 1.0: # Adjust threshold
|
| 582 |
+
exploration_objectives = ["sa", "diversity"] # Objectives that promote exploration
|
| 583 |
+
for obj in exploration_objectives:
|
| 584 |
+
if obj in self.weights:
|
| 585 |
+
self.weights[obj] += 0.05 * self.adaptation_rate
|
| 586 |
+
|
| 587 |
+
def _normalize_weights(self):
|
| 588 |
+
"""Ensure weights are normalized and within bounds."""
|
| 589 |
+
# Apply bounds
|
| 590 |
+
for obj in self.weights:
|
| 591 |
+
self.weights[obj] = np.clip(self.weights[obj], self.min_weight, self.max_weight)
|
| 592 |
+
|
| 593 |
+
# Normalize to sum to 1
|
| 594 |
+
total = sum(self.weights.values())
|
| 595 |
+
if total > 0:
|
| 596 |
+
for obj in self.weights:
|
| 597 |
+
self.weights[obj] /= total
|
| 598 |
+
else:
|
| 599 |
+
# Fallback to equal weights
|
| 600 |
+
n = len(self.weights)
|
| 601 |
+
for obj in self.weights:
|
| 602 |
+
self.weights[obj] = 1.0 / n
|
| 603 |
+
|
| 604 |
+
def get_mixed_reward(self, rewards_dict: Dict[str, torch.Tensor]) -> torch.Tensor:
|
| 605 |
+
"""
|
| 606 |
+
Compute mixed reward using current weights.
|
| 607 |
+
|
| 608 |
+
Args:
|
| 609 |
+
rewards_dict: Dictionary of reward tensors
|
| 610 |
+
|
| 611 |
+
Returns:
|
| 612 |
+
Mixed reward tensor
|
| 613 |
+
"""
|
| 614 |
+
mixed_reward = None
|
| 615 |
+
|
| 616 |
+
for obj_name, weight in self.weights.items():
|
| 617 |
+
if obj_name in rewards_dict:
|
| 618 |
+
weighted_reward = weight * rewards_dict[obj_name]
|
| 619 |
+
if mixed_reward is None:
|
| 620 |
+
mixed_reward = weighted_reward
|
| 621 |
+
else:
|
| 622 |
+
mixed_reward += weighted_reward
|
| 623 |
+
|
| 624 |
+
return mixed_reward if mixed_reward is not None else torch.zeros_like(list(rewards_dict.values())[0])
|
| 625 |
+
|
| 626 |
+
def get_status(self) -> Dict[str, any]:
|
| 627 |
+
"""Get current status for logging."""
|
| 628 |
+
pareto_front = self._compute_pareto_front()
|
| 629 |
+
|
| 630 |
+
return {
|
| 631 |
+
"weights": self.weights.copy(),
|
| 632 |
+
"step_count": self.step_count,
|
| 633 |
+
"pareto_front_size": len(pareto_front),
|
| 634 |
+
"stagnation_counters": self.stagnation_counters.copy(),
|
| 635 |
+
"history_size": len(self.objective_history),
|
| 636 |
+
"avg_pareto_size": np.mean(list(self.pareto_history)) if self.pareto_history else 0
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
# ========================
|
| 641 |
+
# RL TRAINING CONTROLLERS
|
| 642 |
+
# ========================
|
| 643 |
+
|
| 644 |
+
class AdaptiveKLController:
|
| 645 |
+
"""
|
| 646 |
+
Adaptive KL controller with hard clipping and EMA smoothing.
|
| 647 |
+
Prevents runaway beta values and exploding KL penalties.
|
| 648 |
+
"""
|
| 649 |
+
|
| 650 |
+
def __init__(
|
| 651 |
+
self,
|
| 652 |
+
init_kl_coef: float = 0.2,
|
| 653 |
+
target_kl: float = 6.0,
|
| 654 |
+
horizon: int = 10000,
|
| 655 |
+
max_kl_coef: float = 10.0,
|
| 656 |
+
max_inc_factor: float = 2.0,
|
| 657 |
+
ema_alpha: float = 0.9,
|
| 658 |
+
kl_penalty_cap: float = 10.0,
|
| 659 |
+
):
|
| 660 |
+
self.value = init_kl_coef
|
| 661 |
+
self.target = target_kl
|
| 662 |
+
self.horizon = horizon
|
| 663 |
+
self.max_kl_coef = max_kl_coef
|
| 664 |
+
self.max_inc_factor = max_inc_factor
|
| 665 |
+
self.ema_alpha = ema_alpha
|
| 666 |
+
self.kl_penalty_cap = kl_penalty_cap
|
| 667 |
+
|
| 668 |
+
# Exponential moving average of KL
|
| 669 |
+
self.ema_kl = None
|
| 670 |
+
|
| 671 |
+
def update(self, current_kl: float, n_steps: int) -> None:
|
| 672 |
+
# update EMA
|
| 673 |
+
if self.ema_kl is None:
|
| 674 |
+
self.ema_kl = current_kl
|
| 675 |
+
else:
|
| 676 |
+
self.ema_kl = (
|
| 677 |
+
self.ema_alpha * self.ema_kl + (1 - self.ema_alpha) * current_kl
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
proportional_error = np.clip(
|
| 681 |
+
(self.ema_kl - self.target) / self.target, -1.0, 1.0
|
| 682 |
+
)
|
| 683 |
+
mult = 1.0 + proportional_error * (n_steps / self.horizon)
|
| 684 |
+
|
| 685 |
+
# cap growth
|
| 686 |
+
if mult > self.max_inc_factor:
|
| 687 |
+
mult = self.max_inc_factor
|
| 688 |
+
|
| 689 |
+
# update beta
|
| 690 |
+
new_val = self.value * mult
|
| 691 |
+
self.value = min(new_val, self.max_kl_coef)
|
| 692 |
+
|
| 693 |
+
def __call__(self) -> float:
|
| 694 |
+
return self.value
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def compute_kl_penalty(kl_vals: torch.Tensor, kl_coef: float, kl_penalty_cap: float):
|
| 698 |
+
"""
|
| 699 |
+
Compute KL penalty with clipping.
|
| 700 |
+
Returns (clipped_penalty, raw_penalty, kl_mean).
|
| 701 |
+
"""
|
| 702 |
+
kl_mean = kl_vals.mean()
|
| 703 |
+
raw_penalty = kl_coef * kl_mean
|
| 704 |
+
clipped_penalty = torch.clamp(raw_penalty, max=kl_penalty_cap)
|
| 705 |
+
return clipped_penalty, raw_penalty, kl_mean
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
class EnhancedEntropyController:
|
| 709 |
+
def __init__(self, min_entropy: float = 0.5, max_entropy: float = 3.0,
|
| 710 |
+
target_entropy: float = 1.5):
|
| 711 |
+
self.min_entropy = min_entropy
|
| 712 |
+
self.max_entropy = max_entropy
|
| 713 |
+
self.target_entropy = target_entropy
|
| 714 |
+
self.entropy_history: List[float] = []
|
| 715 |
+
self.entropy_weight = 0.01
|
| 716 |
+
|
| 717 |
+
def update_entropy_weight(self, current_entropy: float) -> float:
|
| 718 |
+
self.entropy_history.append(float(current_entropy))
|
| 719 |
+
if len(self.entropy_history) > 100:
|
| 720 |
+
self.entropy_history = self.entropy_history[-100:]
|
| 721 |
+
if len(self.entropy_history) >= 10:
|
| 722 |
+
avg_entropy = np.mean(self.entropy_history[-10:])
|
| 723 |
+
if avg_entropy < self.target_entropy * 0.8:
|
| 724 |
+
self.entropy_weight = min(0.05, self.entropy_weight * 1.1)
|
| 725 |
+
elif avg_entropy > self.target_entropy * 1.2:
|
| 726 |
+
self.entropy_weight = max(0.001, self.entropy_weight * 0.95)
|
| 727 |
+
return float(self.entropy_weight)
|
| 728 |
+
|
| 729 |
+
def adjust_for_seq_len(self, seq_len: int, base_entropy: float = 1.5):
|
| 730 |
+
seq_len = max(1, int(seq_len))
|
| 731 |
+
self.target_entropy = float(base_entropy * np.log1p(seq_len) / np.log1p(10))
|
| 732 |
+
self.target_entropy = float(np.clip(self.target_entropy, self.min_entropy, self.max_entropy))
|
| 733 |
+
|
| 734 |
+
def reset(self):
|
| 735 |
+
self.entropy_history.clear()
|
| 736 |
+
self.entropy_weight = 0.01
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
class CurriculumManager:
|
| 740 |
+
"""Symmetric curriculum: 10→15→20→25→20→15→10→..."""
|
| 741 |
+
def __init__(self, start_len: int = 10, max_len: int = 25,
|
| 742 |
+
step_increase: int = 5, steps_per_level: int = 30):
|
| 743 |
+
self.start_len = start_len
|
| 744 |
+
self.max_len = max_len
|
| 745 |
+
self.step_increase = step_increase
|
| 746 |
+
self.steps_per_level = steps_per_level
|
| 747 |
+
self.current_max_len = start_len
|
| 748 |
+
self.step_counter = 0
|
| 749 |
+
self.direction = +1
|
| 750 |
+
|
| 751 |
+
def get_max_new_tokens(self) -> int:
|
| 752 |
+
return self.current_max_len
|
| 753 |
+
|
| 754 |
+
def step(self) -> int:
|
| 755 |
+
self.step_counter += 1
|
| 756 |
+
if self.step_counter % self.steps_per_level == 0:
|
| 757 |
+
if self.direction == +1:
|
| 758 |
+
if self.current_max_len < self.max_len:
|
| 759 |
+
self.current_max_len += self.step_increase
|
| 760 |
+
else:
|
| 761 |
+
self.direction = -1
|
| 762 |
+
self.current_max_len -= self.step_increase
|
| 763 |
+
else:
|
| 764 |
+
if self.current_max_len > self.start_len:
|
| 765 |
+
self.current_max_len -= self.step_increase
|
| 766 |
+
else:
|
| 767 |
+
self.direction = +1
|
| 768 |
+
self.current_max_len += self.step_increase
|
| 769 |
+
print(f"📈 Curriculum Update: max_new_tokens = {self.current_max_len}")
|
| 770 |
+
return self.current_max_len
|
| 771 |
+
|
| 772 |
+
# ========================
|
| 773 |
+
# HELPERS
|
| 774 |
+
# ========================
|
| 775 |
+
|
| 776 |
+
def normalize_rewards(rewards: torch.Tensor, seq_len: int, mode: str = "sqrt") -> torch.Tensor:
|
| 777 |
+
if seq_len <= 1 or mode == "none":
|
| 778 |
+
return rewards
|
| 779 |
+
if mode == "per_token":
|
| 780 |
+
return rewards / float(seq_len)
|
| 781 |
+
elif mode == "sqrt":
|
| 782 |
+
return rewards / float(np.sqrt(seq_len))
|
| 783 |
+
else:
|
| 784 |
+
raise ValueError(f"Unknown normalization mode: {mode}")
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def reset_controllers_on_phase_change(prev_len: Optional[int], new_len: int,
|
| 788 |
+
kl_controller: Optional[AdaptiveKLController] = None,
|
| 789 |
+
entropy_controller: Optional[EnhancedEntropyController] = None,
|
| 790 |
+
entropy_base: float = 1.5):
|
| 791 |
+
if prev_len is None or prev_len == new_len:
|
| 792 |
+
return
|
| 793 |
+
if kl_controller is not None:
|
| 794 |
+
kl_controller.reset()
|
| 795 |
+
if entropy_controller is not None:
|
| 796 |
+
entropy_controller.reset()
|
| 797 |
+
entropy_controller.adjust_for_seq_len(new_len, base_entropy=entropy_base)
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
# ========================
|
| 801 |
+
# PPO LOSS
|
| 802 |
+
# ========================
|
| 803 |
+
|
| 804 |
+
def compute_ppo_loss(old_log_probs: torch.Tensor, new_log_probs: torch.Tensor,
|
| 805 |
+
rewards: torch.Tensor, clip_epsilon: float = 0.2,
|
| 806 |
+
baseline: Optional[torch.Tensor] = None,
|
| 807 |
+
seq_len: int = 1, reward_norm: str = "sqrt",
|
| 808 |
+
adv_clip: Optional[float] = None) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 809 |
+
normed_rewards = normalize_rewards(rewards, seq_len, mode=reward_norm)
|
| 810 |
+
if baseline is not None:
|
| 811 |
+
advantage = normed_rewards - baseline.detach()
|
| 812 |
+
else:
|
| 813 |
+
advantage = normed_rewards
|
| 814 |
+
if adv_clip is not None:
|
| 815 |
+
advantage = torch.clamp(advantage, -float(adv_clip), float(adv_clip))
|
| 816 |
+
else:
|
| 817 |
+
default_clip = 2.0 * np.sqrt(max(1, seq_len))
|
| 818 |
+
advantage = torch.clamp(advantage, -default_clip, default_clip)
|
| 819 |
+
log_ratio = torch.clamp(new_log_probs - old_log_probs, -10.0, 10.0)
|
| 820 |
+
ratio = torch.exp(log_ratio)
|
| 821 |
+
adv_expanded = advantage.unsqueeze(1) if advantage.dim() == 1 else advantage
|
| 822 |
+
surr1 = ratio * adv_expanded
|
| 823 |
+
surr2 = torch.clamp(ratio, 1 - clip_epsilon, 1 + clip_epsilon) * adv_expanded
|
| 824 |
+
ppo_loss = -torch.min(surr1, surr2).sum(dim=1).mean()
|
| 825 |
+
return ppo_loss, advantage.detach()
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def compute_kl_divergence(old_action_probs: torch.Tensor, new_action_probs: torch.Tensor) -> torch.Tensor:
|
| 829 |
+
old_probs = old_action_probs.clamp_min(1e-12)
|
| 830 |
+
new_probs = new_action_probs.clamp_min(1e-12)
|
| 831 |
+
kl_per_step = (old_probs * (torch.log(old_probs) - torch.log(new_probs))).sum(dim=-1)
|
| 832 |
+
return kl_per_step.sum(dim=1)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def compute_entropy_bonus(action_probs: torch.Tensor) -> torch.Tensor:
|
| 836 |
+
probs = action_probs.clamp_min(1e-12)
|
| 837 |
+
entropy_per_step = -(probs * torch.log(probs)).sum(dim=-1)
|
| 838 |
+
return entropy_per_step.sum(dim=1)
|
| 839 |
+
|
| 840 |
+
# ========================
|
| 841 |
+
# BATCH REWARD COMPUTATION
|
| 842 |
+
# ========================
|
| 843 |
+
|
| 844 |
+
def batch_compute_rewards_pareto(
|
| 845 |
+
selfies_list: List[str],
|
| 846 |
+
reward_mode: str = "mix",
|
| 847 |
+
reward_mix: float = 0.5,
|
| 848 |
+
pareto_controller: Optional[ParetoRewardController] = None
|
| 849 |
+
) -> Dict[str, torch.Tensor]:
|
| 850 |
+
"""
|
| 851 |
+
Drop-in replacement for batch_compute_rewards with Pareto support.
|
| 852 |
+
|
| 853 |
+
Args:
|
| 854 |
+
selfies_list: List of SELFIES strings
|
| 855 |
+
reward_mode: "chemq3", "sa", "mix", or "pareto"
|
| 856 |
+
reward_mix: Weight for comprehensive rewards when mixing (0-1)
|
| 857 |
+
pareto_controller: ParetoRewardController instance for "pareto" mode
|
| 858 |
+
|
| 859 |
+
Returns:
|
| 860 |
+
Dictionary containing reward tensors (same format as original)
|
| 861 |
+
"""
|
| 862 |
+
batch_size = len(selfies_list)
|
| 863 |
+
|
| 864 |
+
validity_vals = []
|
| 865 |
+
lipinski_vals = []
|
| 866 |
+
total_rewards = []
|
| 867 |
+
sa_rewards = []
|
| 868 |
+
|
| 869 |
+
# Compute all individual rewards
|
| 870 |
+
for selfies_str in selfies_list:
|
| 871 |
+
smiles = selfies_to_smiles(selfies_str)
|
| 872 |
+
|
| 873 |
+
# Check validity comprehensively
|
| 874 |
+
is_valid = (smiles is not None and
|
| 875 |
+
is_valid_smiles(smiles) and
|
| 876 |
+
passes_durrant_lab_filter(smiles))
|
| 877 |
+
|
| 878 |
+
if reward_mode in ["chemq3", "mix", "pareto"]:
|
| 879 |
+
r = compute_comprehensive_reward(selfies_str)
|
| 880 |
+
validity_vals.append(r.get('validity', 0.0))
|
| 881 |
+
lipinski_vals.append(r.get('lipinski', 0.0))
|
| 882 |
+
|
| 883 |
+
if reward_mode in ["sa", "mix", "pareto"]:
|
| 884 |
+
sa = compute_sa_reward(selfies_str) if is_valid else 0.0
|
| 885 |
+
sa_rewards.append(sa)
|
| 886 |
+
|
| 887 |
+
# Store individual comprehensive reward for pareto mode
|
| 888 |
+
if reward_mode in ["chemq3", "pareto"]:
|
| 889 |
+
total_rewards.append(r.get('total', 0.0))
|
| 890 |
+
elif reward_mode == "sa":
|
| 891 |
+
total_rewards.append(sa)
|
| 892 |
+
elif reward_mode == "mix":
|
| 893 |
+
r_total = r.get("total", 0.0) if 'r' in locals() else 0.0
|
| 894 |
+
sa_val = sa if 'sa' in locals() else 0.0
|
| 895 |
+
mixed = reward_mix * r_total + (1.0 - reward_mix) * sa_val
|
| 896 |
+
total_rewards.append(mixed)
|
| 897 |
+
|
| 898 |
+
# Convert to tensors
|
| 899 |
+
result = {
|
| 900 |
+
"total_rewards": torch.tensor(total_rewards, dtype=torch.float32),
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
if validity_vals:
|
| 904 |
+
result["validity_rewards"] = torch.tensor(validity_vals, dtype=torch.float32)
|
| 905 |
+
if lipinski_vals:
|
| 906 |
+
result["lipinski_rewards"] = torch.tensor(lipinski_vals, dtype=torch.float32)
|
| 907 |
+
if sa_rewards:
|
| 908 |
+
result["sa_rewards"] = torch.tensor(sa_rewards, dtype=torch.float32)
|
| 909 |
+
|
| 910 |
+
# Compute diversity reward
|
| 911 |
+
valid_smiles = []
|
| 912 |
+
for selfies_str in selfies_list:
|
| 913 |
+
smiles = selfies_to_smiles(selfies_str)
|
| 914 |
+
if smiles and is_valid_smiles(smiles) and passes_durrant_lab_filter(smiles):
|
| 915 |
+
valid_smiles.append(smiles)
|
| 916 |
+
|
| 917 |
+
diversity_score = len(set(valid_smiles)) / max(1, len(valid_smiles))
|
| 918 |
+
result["diversity_rewards"] = torch.full((batch_size,), diversity_score, dtype=torch.float32)
|
| 919 |
+
|
| 920 |
+
# Apply Pareto mixing if requested
|
| 921 |
+
if reward_mode == "pareto" and pareto_controller is not None:
|
| 922 |
+
# Prepare objectives for controller update
|
| 923 |
+
batch_objectives = {
|
| 924 |
+
"total": result["total_rewards"],
|
| 925 |
+
"validity": result.get("validity_rewards", torch.zeros(batch_size)),
|
| 926 |
+
"diversity": result["diversity_rewards"]
|
| 927 |
+
}
|
| 928 |
+
|
| 929 |
+
if "sa_rewards" in result:
|
| 930 |
+
batch_objectives["sa"] = result["sa_rewards"]
|
| 931 |
+
|
| 932 |
+
# Update controller and get new weights
|
| 933 |
+
updated_weights = pareto_controller.update(batch_objectives)
|
| 934 |
+
|
| 935 |
+
# Compute mixed reward using adaptive weights
|
| 936 |
+
mixed_reward = pareto_controller.get_mixed_reward(batch_objectives)
|
| 937 |
+
result["total_rewards"] = mixed_reward
|
| 938 |
+
|
| 939 |
+
# Store weights for logging
|
| 940 |
+
result["pareto_weights"] = updated_weights
|
| 941 |
+
|
| 942 |
+
return result
|
| 943 |
+
|
| 944 |
+
# Legacy
|
| 945 |
+
def batch_compute_rewards(
|
| 946 |
+
selfies_list: List[str],
|
| 947 |
+
reward_mode: str = "chemq3",
|
| 948 |
+
reward_mix: float = 0.5
|
| 949 |
+
) -> Dict[str, torch.Tensor]:
|
| 950 |
+
"""
|
| 951 |
+
Compute rewards for a batch of SELFIES strings.
|
| 952 |
+
|
| 953 |
+
Args:
|
| 954 |
+
selfies_list: List of SELFIES strings
|
| 955 |
+
reward_mode: "chemq3", "sa", or "mix"
|
| 956 |
+
reward_mix: Weight for chemq3 rewards when mixing (0-1)
|
| 957 |
+
|
| 958 |
+
Returns:
|
| 959 |
+
Dictionary containing reward tensors
|
| 960 |
+
"""
|
| 961 |
+
batch_size = len(selfies_list)
|
| 962 |
+
|
| 963 |
+
validity_vals = []
|
| 964 |
+
lipinski_vals = []
|
| 965 |
+
total_rewards = []
|
| 966 |
+
sa_rewards = []
|
| 967 |
+
|
| 968 |
+
for selfies_str in selfies_list:
|
| 969 |
+
smiles = selfies_to_smiles(selfies_str)
|
| 970 |
+
|
| 971 |
+
# Check validity comprehensively
|
| 972 |
+
is_valid = (smiles is not None and
|
| 973 |
+
is_valid_smiles(smiles) and
|
| 974 |
+
passes_durrant_lab_filter(smiles))
|
| 975 |
+
|
| 976 |
+
if reward_mode == "chemq3":
|
| 977 |
+
r = compute_comprehensive_reward(selfies_str)
|
| 978 |
+
validity_vals.append(r.get('validity', 0.0))
|
| 979 |
+
lipinski_vals.append(r.get('lipinski', 0.0))
|
| 980 |
+
total_rewards.append(r.get('total', 0.0))
|
| 981 |
+
|
| 982 |
+
elif reward_mode == "sa":
|
| 983 |
+
sa = compute_sa_reward(selfies_str) if is_valid else 0.0
|
| 984 |
+
sa_rewards.append(sa)
|
| 985 |
+
total_rewards.append(sa)
|
| 986 |
+
|
| 987 |
+
elif reward_mode == "mix":
|
| 988 |
+
r = compute_comprehensive_reward(selfies_str)
|
| 989 |
+
sa = compute_sa_reward(selfies_str) if is_valid else 0.0
|
| 990 |
+
mixed = reward_mix * r.get("total", 0.0) + (1.0 - reward_mix) * sa
|
| 991 |
+
|
| 992 |
+
total_rewards.append(mixed)
|
| 993 |
+
sa_rewards.append(sa)
|
| 994 |
+
validity_vals.append(r.get('validity', 0.0))
|
| 995 |
+
lipinski_vals.append(r.get('lipinski', 0.0))
|
| 996 |
+
|
| 997 |
+
else:
|
| 998 |
+
# Unknown mode -> default to zero reward
|
| 999 |
+
total_rewards.append(0.0)
|
| 1000 |
+
validity_vals.append(0.0)
|
| 1001 |
+
lipinski_vals.append(0.0)
|
| 1002 |
+
|
| 1003 |
+
# Convert to tensors
|
| 1004 |
+
result = {
|
| 1005 |
+
"total_rewards": torch.tensor(total_rewards, dtype=torch.float32),
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
if validity_vals:
|
| 1009 |
+
result["validity_rewards"] = torch.tensor(validity_vals, dtype=torch.float32)
|
| 1010 |
+
if lipinski_vals:
|
| 1011 |
+
result["lipinski_rewards"] = torch.tensor(lipinski_vals, dtype=torch.float32)
|
| 1012 |
+
if sa_rewards:
|
| 1013 |
+
result["sa_rewards"] = torch.tensor(sa_rewards, dtype=torch.float32)
|
| 1014 |
+
|
| 1015 |
+
return result
|
| 1016 |
+
|
| 1017 |
+
# ========================
|
| 1018 |
+
# TRAINING METRICS
|
| 1019 |
+
# ========================
|
| 1020 |
+
|
| 1021 |
+
def compute_training_metrics(
|
| 1022 |
+
rewards: Dict[str, torch.Tensor],
|
| 1023 |
+
selfies_list: List[str],
|
| 1024 |
+
loss_dict: Dict[str, float]
|
| 1025 |
+
) -> Dict[str, float]:
|
| 1026 |
+
"""
|
| 1027 |
+
Compute comprehensive training metrics.
|
| 1028 |
+
|
| 1029 |
+
Args:
|
| 1030 |
+
rewards: Dictionary of reward tensors
|
| 1031 |
+
selfies_list: List of generated SELFIES
|
| 1032 |
+
loss_dict: Dictionary containing loss components
|
| 1033 |
+
|
| 1034 |
+
Returns:
|
| 1035 |
+
Dictionary of computed metrics
|
| 1036 |
+
"""
|
| 1037 |
+
metrics = {}
|
| 1038 |
+
|
| 1039 |
+
# Basic reward metrics
|
| 1040 |
+
if "total_rewards" in rewards:
|
| 1041 |
+
metrics["avg_reward"] = float(rewards["total_rewards"].mean())
|
| 1042 |
+
metrics["max_reward"] = float(rewards["total_rewards"].max())
|
| 1043 |
+
metrics["min_reward"] = float(rewards["total_rewards"].min())
|
| 1044 |
+
metrics["reward_std"] = float(rewards["total_rewards"].std())
|
| 1045 |
+
|
| 1046 |
+
if "validity_rewards" in rewards:
|
| 1047 |
+
metrics["validity_rate"] = float(rewards["validity_rewards"].mean())
|
| 1048 |
+
|
| 1049 |
+
if "lipinski_rewards" in rewards:
|
| 1050 |
+
metrics["lipinski_score"] = float(rewards["lipinski_rewards"].mean())
|
| 1051 |
+
|
| 1052 |
+
if "sa_rewards" in rewards:
|
| 1053 |
+
metrics["sa_score"] = float(rewards["sa_rewards"].mean())
|
| 1054 |
+
|
| 1055 |
+
# Molecular diversity metrics
|
| 1056 |
+
valid_smiles = []
|
| 1057 |
+
for selfies_str in selfies_list:
|
| 1058 |
+
smiles = selfies_to_smiles(selfies_str)
|
| 1059 |
+
if smiles and is_valid_smiles(smiles) and passes_durrant_lab_filter(smiles):
|
| 1060 |
+
valid_smiles.append(smiles)
|
| 1061 |
+
|
| 1062 |
+
metrics["num_valid"] = len(valid_smiles)
|
| 1063 |
+
metrics["num_unique"] = len(set(valid_smiles))
|
| 1064 |
+
metrics["diversity_ratio"] = len(set(valid_smiles)) / max(1, len(valid_smiles))
|
| 1065 |
+
|
| 1066 |
+
# Add loss components
|
| 1067 |
+
metrics.update(loss_dict)
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
return metrics
|
ChemQ3MTP/trainer.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# trainer.py
|
| 2 |
+
from transformers import Trainer, TrainingArguments
|
| 3 |
+
from torch.utils.data import DataLoader
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
class MTPTrainer(Trainer):
|
| 8 |
+
"""
|
| 9 |
+
Custom trainer for Multi-Token Prediction training.
|
| 10 |
+
"""
|
| 11 |
+
def __init__(self, model, args=None, train_dataset=None, eval_dataset=None, **kwargs):
|
| 12 |
+
super().__init__(
|
| 13 |
+
model=model,
|
| 14 |
+
args=args,
|
| 15 |
+
train_dataset=train_dataset,
|
| 16 |
+
eval_dataset=eval_dataset,
|
| 17 |
+
**kwargs
|
| 18 |
+
)
|
| 19 |
+
self.use_mtp_training = True
|
| 20 |
+
|
| 21 |
+
def compute_loss(self, model, inputs, return_outputs=False):
|
| 22 |
+
"""
|
| 23 |
+
Compute loss during training - handles both MTP and standard LM training.
|
| 24 |
+
"""
|
| 25 |
+
labels = inputs.get("labels")
|
| 26 |
+
outputs = model(**inputs, labels=labels, use_mtp_training=self.use_mtp_training)
|
| 27 |
+
loss = outputs.loss
|
| 28 |
+
|
| 29 |
+
return (loss, outputs) if return_outputs else loss
|
| 30 |
+
|
| 31 |
+
def train_step_with_mtp(self, model, inputs):
|
| 32 |
+
"""
|
| 33 |
+
Specialized training step for MTP training.
|
| 34 |
+
"""
|
| 35 |
+
model.set_mtp_training(True)
|
| 36 |
+
return self.training_step(model, inputs)
|
| 37 |
+
|
| 38 |
+
def train_step_with_lm(self, model, inputs):
|
| 39 |
+
"""
|
| 40 |
+
Standard language modeling training step.
|
| 41 |
+
"""
|
| 42 |
+
model.set_mtp_training(False)
|
| 43 |
+
return self.training_step(model, inputs)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class RLTrainer:
|
| 47 |
+
"""
|
| 48 |
+
Separate trainer class for Reinforcement Learning training.
|
| 49 |
+
This can use the generate_with_logprobs method from your model.
|
| 50 |
+
"""
|
| 51 |
+
def __init__(self, model, tokenizer, rl_config=None):
|
| 52 |
+
self.model = model
|
| 53 |
+
self.tokenizer = tokenizer
|
| 54 |
+
self.rl_config = rl_config or {}
|
| 55 |
+
|
| 56 |
+
def rl_training_step(self, input_ids, old_log_probs, old_action_probs, **kwargs):
|
| 57 |
+
"""
|
| 58 |
+
Perform an RL training step using the model's generate_with_logprobs method
|
| 59 |
+
and the reward functions from rl_utils.
|
| 60 |
+
"""
|
| 61 |
+
# Import RL utilities
|
| 62 |
+
from .rl_utils import (
|
| 63 |
+
batch_compute_rewards,
|
| 64 |
+
compute_ppo_loss,
|
| 65 |
+
compute_kl_divergence,
|
| 66 |
+
compute_entropy_bonus,
|
| 67 |
+
AdaptiveKLController
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# This would call the generate_with_logprobs method from your model
|
| 71 |
+
# and then compute RL-specific losses
|
| 72 |
+
pass
|
ChemQ3MTP/training_utils.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# training_utils.py
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers import Trainer, TrainingArguments
|
| 5 |
+
from datasets import load_dataset, Dataset
|
| 6 |
+
from ranger21 import Ranger21
|
| 7 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 8 |
+
import os
|
| 9 |
+
from typing import Dict, Any, Tuple
|
| 10 |
+
from transformers import TrainerCallback
|
| 11 |
+
|
| 12 |
+
class EnhancedDataCollator:
|
| 13 |
+
def __init__(self, tokenizer, pad_to_multiple_of=8):
|
| 14 |
+
self.tokenizer = tokenizer
|
| 15 |
+
self.pad_to_multiple_of = pad_to_multiple_of
|
| 16 |
+
|
| 17 |
+
def __call__(self, features):
|
| 18 |
+
max_length = max(len(f["input_ids"]) for f in features)
|
| 19 |
+
if self.pad_to_multiple_of:
|
| 20 |
+
max_length = ((max_length + self.pad_to_multiple_of - 1) // self.pad_to_multiple_of) * self.pad_to_multiple_of
|
| 21 |
+
|
| 22 |
+
batch = {"input_ids": [], "attention_mask": [], "labels": []}
|
| 23 |
+
for feature in features:
|
| 24 |
+
input_ids = feature["input_ids"]
|
| 25 |
+
attention_mask = feature["attention_mask"]
|
| 26 |
+
labels = feature["labels"]
|
| 27 |
+
padding_length = max_length - len(input_ids)
|
| 28 |
+
padded_input_ids = input_ids + [self.tokenizer.pad_token_id] * padding_length
|
| 29 |
+
padded_attention_mask = attention_mask + [0] * padding_length
|
| 30 |
+
padded_labels = labels + [-100] * padding_length
|
| 31 |
+
batch["input_ids"].append(padded_input_ids)
|
| 32 |
+
batch["attention_mask"].append(padded_attention_mask)
|
| 33 |
+
batch["labels"].append(padded_labels)
|
| 34 |
+
|
| 35 |
+
batch = {k: torch.tensor(v, dtype=torch.long) for k, v in batch.items()}
|
| 36 |
+
return batch
|
| 37 |
+
|
| 38 |
+
def tokenize_function(examples, tokenizer, max_length):
|
| 39 |
+
smiles_list = examples['SELFIES']
|
| 40 |
+
batch_results = {"input_ids": [], "attention_mask": [], "labels": []}
|
| 41 |
+
for smiles in smiles_list:
|
| 42 |
+
tokenized = tokenizer(
|
| 43 |
+
smiles,
|
| 44 |
+
truncation=True,
|
| 45 |
+
padding=False,
|
| 46 |
+
max_length=max_length,
|
| 47 |
+
return_tensors=None,
|
| 48 |
+
add_special_tokens=True
|
| 49 |
+
)
|
| 50 |
+
input_ids = tokenized["input_ids"]
|
| 51 |
+
attention_mask = tokenized["attention_mask"]
|
| 52 |
+
labels = input_ids.copy()
|
| 53 |
+
batch_results["input_ids"].append(input_ids)
|
| 54 |
+
batch_results["attention_mask"].append(attention_mask)
|
| 55 |
+
batch_results["labels"].append(labels)
|
| 56 |
+
return batch_results
|
| 57 |
+
|
| 58 |
+
def load_and_tokenize_dataset(data_path: str, tokenizer, max_length: int, tokenize_batch_size: int,
|
| 59 |
+
train_split_ratio: float, val_split_ratio: float, test_split_ratio: float):
|
| 60 |
+
dataset = load_dataset('csv', data_files=data_path, split='train')
|
| 61 |
+
dataset = dataset.shuffle(seed=42)
|
| 62 |
+
|
| 63 |
+
total_lines = len(dataset)
|
| 64 |
+
test_size = int(test_split_ratio * total_lines)
|
| 65 |
+
val_size = int(val_split_ratio * total_lines)
|
| 66 |
+
train_size = total_lines - test_size - val_size
|
| 67 |
+
|
| 68 |
+
train_dataset = dataset.select(range(0, train_size))
|
| 69 |
+
val_dataset = dataset.select(range(train_size, train_size + val_size))
|
| 70 |
+
test_dataset = dataset.select(range(train_size + val_size, total_lines))
|
| 71 |
+
|
| 72 |
+
def tokenize_train(examples):
|
| 73 |
+
return tokenize_function(examples, tokenizer, max_length)
|
| 74 |
+
|
| 75 |
+
def tokenize_val(examples):
|
| 76 |
+
return tokenize_function(examples, tokenizer, max_length)
|
| 77 |
+
|
| 78 |
+
train_dataset = train_dataset.map(
|
| 79 |
+
tokenize_train,
|
| 80 |
+
batched=True,
|
| 81 |
+
batch_size=tokenize_batch_size,
|
| 82 |
+
remove_columns=["SELFIES"],
|
| 83 |
+
desc="Tokenizing train"
|
| 84 |
+
)
|
| 85 |
+
val_dataset = val_dataset.map(
|
| 86 |
+
tokenize_val,
|
| 87 |
+
batched=True,
|
| 88 |
+
batch_size=tokenize_batch_size,
|
| 89 |
+
remove_columns=["SELFIES"],
|
| 90 |
+
desc="Tokenizing val"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
return train_dataset, val_dataset, test_dataset
|
| 94 |
+
|
| 95 |
+
def create_enhanced_optimizer(model_params, lr, weight_decay, num_epochs, train_dataset_len, batch_size):
|
| 96 |
+
num_batches_per_epoch = train_dataset_len // batch_size
|
| 97 |
+
optimizer_params = {
|
| 98 |
+
'lr': lr,
|
| 99 |
+
'weight_decay': weight_decay,
|
| 100 |
+
'use_adabelief': True,
|
| 101 |
+
'use_madgrad': True,
|
| 102 |
+
'using_gc': True,
|
| 103 |
+
'warmdown_active': True,
|
| 104 |
+
'num_epochs': num_epochs,
|
| 105 |
+
'num_batches_per_epoch': num_batches_per_epoch,
|
| 106 |
+
'use_warmup': True,
|
| 107 |
+
'use_cheb': False
|
| 108 |
+
}
|
| 109 |
+
return Ranger21(model_params, **optimizer_params)
|
| 110 |
+
|
| 111 |
+
class EnhancedCustomTrainer(Trainer):
|
| 112 |
+
def create_optimizer(self):
|
| 113 |
+
self.optimizer = create_enhanced_optimizer(
|
| 114 |
+
self.model.parameters(),
|
| 115 |
+
self.args.learning_rate,
|
| 116 |
+
self.args.weight_decay,
|
| 117 |
+
self.args.num_train_epochs,
|
| 118 |
+
len(self.train_dataset),
|
| 119 |
+
self.args.per_device_train_batch_size
|
| 120 |
+
)
|
| 121 |
+
return self.optimizer
|
| 122 |
+
|
| 123 |
+
def create_scheduler(self, num_training_steps, optimizer=None):
|
| 124 |
+
self.lr_scheduler = LambdaLR(optimizer or self.optimizer, lr_lambda=lambda step: 1.0)
|
| 125 |
+
return self.lr_scheduler
|
| 126 |
+
|
| 127 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 128 |
+
outputs = model(**inputs)
|
| 129 |
+
loss = outputs.loss
|
| 130 |
+
return (loss, outputs) if return_outputs else loss
|
| 131 |
+
|
| 132 |
+
def setup_training_args(output_dir: str, total_steps: int, batch_size: int, gradient_accumulation_steps: int,
|
| 133 |
+
steps_per_epoch: int, include_for_metrics: list):
|
| 134 |
+
return TrainingArguments(
|
| 135 |
+
output_dir=output_dir,
|
| 136 |
+
max_steps=total_steps,
|
| 137 |
+
per_device_train_batch_size=batch_size,
|
| 138 |
+
per_device_eval_batch_size=batch_size,
|
| 139 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
| 140 |
+
logging_dir='./logs',
|
| 141 |
+
logging_strategy="steps",
|
| 142 |
+
logging_steps=max(1, steps_per_epoch // 4),
|
| 143 |
+
eval_strategy="steps",
|
| 144 |
+
eval_steps=max(1, steps_per_epoch // 4),
|
| 145 |
+
save_strategy="steps",
|
| 146 |
+
save_steps=steps_per_epoch,
|
| 147 |
+
save_total_limit=1,
|
| 148 |
+
dataloader_num_workers=0,
|
| 149 |
+
dataloader_pin_memory=False,
|
| 150 |
+
remove_unused_columns=False,
|
| 151 |
+
prediction_loss_only=False,
|
| 152 |
+
fp16=torch.cuda.is_available(),
|
| 153 |
+
gradient_checkpointing=True,
|
| 154 |
+
dataloader_drop_last=True,
|
| 155 |
+
report_to=None,
|
| 156 |
+
include_for_metrics=include_for_metrics,
|
| 157 |
+
)
|
FastChemTokenizerHF.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from typing import List, Union, Optional, Tuple, Dict, Any
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from collections.abc import Mapping
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ------------------------------
|
| 10 |
+
# BatchEncoding
|
| 11 |
+
# ------------------------------
|
| 12 |
+
class BatchEncoding(dict, Mapping):
|
| 13 |
+
"""Minimal BatchEncoding compatible wrapper."""
|
| 14 |
+
|
| 15 |
+
def __init__(self, data: dict, tensor_type: Optional[str] = None):
|
| 16 |
+
data = {} if data is None else {k: v for k, v in data.items()}
|
| 17 |
+
super().__init__(data)
|
| 18 |
+
self.data = data
|
| 19 |
+
self.tensor_type = tensor_type
|
| 20 |
+
for k, v in data.items():
|
| 21 |
+
setattr(self, k, v)
|
| 22 |
+
|
| 23 |
+
def __getitem__(self, key): return self.data[key]
|
| 24 |
+
def __iter__(self): return iter(self.data)
|
| 25 |
+
def __len__(self): return len(self.data)
|
| 26 |
+
def keys(self): return self.data.keys()
|
| 27 |
+
def values(self): return self.data.values()
|
| 28 |
+
def items(self): return self.data.items()
|
| 29 |
+
def get(self, key, default=None): return self.data.get(key, default)
|
| 30 |
+
|
| 31 |
+
def to(self, device):
|
| 32 |
+
if self.tensor_type in ("pt", "torch"):
|
| 33 |
+
for k, v in list(self.data.items()):
|
| 34 |
+
if torch.is_tensor(v):
|
| 35 |
+
self.data[k] = v.to(device)
|
| 36 |
+
setattr(self, k, self.data[k])
|
| 37 |
+
return self
|
| 38 |
+
|
| 39 |
+
def cpu(self): return self.to("cpu")
|
| 40 |
+
def cuda(self): return self.to("cuda")
|
| 41 |
+
def detach(self):
|
| 42 |
+
if self.tensor_type in ("pt", "torch"):
|
| 43 |
+
for k, v in list(self.data.items()):
|
| 44 |
+
if torch.is_tensor(v):
|
| 45 |
+
self.data[k] = v.detach()
|
| 46 |
+
setattr(self, k, self.data[k])
|
| 47 |
+
return self
|
| 48 |
+
|
| 49 |
+
def __repr__(self):
|
| 50 |
+
keys = ", ".join(list(self.data.keys())[:10])
|
| 51 |
+
return f"BatchEncoding(keys=[{keys}], tensor_type={self.tensor_type})"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ------------------------------
|
| 55 |
+
# Base class
|
| 56 |
+
# ------------------------------
|
| 57 |
+
class PreTrainedTokenizerBase:
|
| 58 |
+
def __init__(self, **kwargs):
|
| 59 |
+
for key, value in kwargs.items():
|
| 60 |
+
if key.endswith('_token'):
|
| 61 |
+
setattr(self, f"_{key}", value)
|
| 62 |
+
setattr(self, f"{key}_id", None)
|
| 63 |
+
self.model_max_length = kwargs.get('model_max_length', 512)
|
| 64 |
+
self.padding_side = kwargs.get('padding_side', 'right')
|
| 65 |
+
self.truncation_side = kwargs.get('truncation_side', 'right')
|
| 66 |
+
self.chat_template = kwargs.get('chat_template')
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ------------------------------
|
| 70 |
+
# Trie node
|
| 71 |
+
# ------------------------------
|
| 72 |
+
class TrieNode:
|
| 73 |
+
__slots__ = ['children', 'token_id']
|
| 74 |
+
def __init__(self):
|
| 75 |
+
self.children = {}
|
| 76 |
+
self.token_id = None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ------------------------------
|
| 80 |
+
# FastChemTokenizer
|
| 81 |
+
# ------------------------------
|
| 82 |
+
|
| 83 |
+
class FastChemTokenizer(PreTrainedTokenizerBase):
|
| 84 |
+
def __init__(self, token_to_id=None, vocab_file=None, **kwargs):
|
| 85 |
+
if vocab_file is not None:
|
| 86 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 87 |
+
token_to_id = json.load(f)
|
| 88 |
+
token_to_id = {str(k): int(v) for k, v in token_to_id.items()}
|
| 89 |
+
|
| 90 |
+
self.token_to_id = token_to_id
|
| 91 |
+
self.id_to_token = {v: k for k, v in token_to_id.items()}
|
| 92 |
+
|
| 93 |
+
# Build trie
|
| 94 |
+
self.trie_root = self._build_trie(self.token_to_id)
|
| 95 |
+
|
| 96 |
+
# ✅ Call parent (sets token *strings*, may reset *_id to None)
|
| 97 |
+
super().__init__(
|
| 98 |
+
bos_token="<s>",
|
| 99 |
+
eos_token="</s>",
|
| 100 |
+
unk_token="<unk>",
|
| 101 |
+
pad_token="<pad>",
|
| 102 |
+
mask_token="<mask>",
|
| 103 |
+
model_max_length=kwargs.get("model_max_length", 512),
|
| 104 |
+
padding_side=kwargs.get("padding_side", "right"),
|
| 105 |
+
truncation_side=kwargs.get("truncation_side", "right"),
|
| 106 |
+
**kwargs,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# ✅ Re-map token strings → IDs from vocab
|
| 110 |
+
self.bos_token_id = self.token_to_id.get("<s>", 0)
|
| 111 |
+
self.eos_token_id = self.token_to_id.get("</s>", 1)
|
| 112 |
+
self.pad_token_id = self.token_to_id.get("<pad>", 2)
|
| 113 |
+
self.unk_token_id = self.token_to_id.get("<unk>", 3)
|
| 114 |
+
self.mask_token_id = self.token_to_id.get("<mask>", 4)
|
| 115 |
+
|
| 116 |
+
# Ensure reverse mapping always valid
|
| 117 |
+
self.id_to_token[self.bos_token_id] = "<s>"
|
| 118 |
+
self.id_to_token[self.eos_token_id] = "</s>"
|
| 119 |
+
self.id_to_token[self.pad_token_id] = "<pad>"
|
| 120 |
+
self.id_to_token[self.unk_token_id] = "<unk>"
|
| 121 |
+
self.id_to_token[self.mask_token_id] = "<mask>"
|
| 122 |
+
|
| 123 |
+
# Debug
|
| 124 |
+
print("✅ Special tokens bound:",
|
| 125 |
+
self.bos_token_id, self.eos_token_id, self.pad_token_id,
|
| 126 |
+
self.unk_token_id, self.mask_token_id)
|
| 127 |
+
|
| 128 |
+
# ✅ Ensure token *strings* also exist (for decode fallback)
|
| 129 |
+
self.bos_token = "<s>"
|
| 130 |
+
self.eos_token = "</s>"
|
| 131 |
+
self.pad_token = "<pad>"
|
| 132 |
+
self.unk_token = "<unk>"
|
| 133 |
+
self.mask_token = "<mask>"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _build_trie(self, token_to_id):
|
| 137 |
+
root = TrieNode()
|
| 138 |
+
for token, tid in token_to_id.items():
|
| 139 |
+
node = root
|
| 140 |
+
for char in token:
|
| 141 |
+
if char not in node.children:
|
| 142 |
+
node.children[char] = TrieNode()
|
| 143 |
+
node = node.children[char]
|
| 144 |
+
node.token_id = tid
|
| 145 |
+
return root
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def vocab_size(self): return len(self.token_to_id)
|
| 149 |
+
def __len__(self): return len(self.token_to_id)
|
| 150 |
+
def get_vocab(self) -> Dict[str, int]: return self.token_to_id.copy()
|
| 151 |
+
|
| 152 |
+
@lru_cache(maxsize=10000)
|
| 153 |
+
def _cached_encode_str(self, s: str) -> Tuple[int, ...]:
|
| 154 |
+
return tuple(self._encode_core(s))
|
| 155 |
+
|
| 156 |
+
def _encode_core(self, text: str) -> List[int]:
|
| 157 |
+
tokens, result_ids = text, []
|
| 158 |
+
i, n = 0, len(tokens)
|
| 159 |
+
while i < n:
|
| 160 |
+
node, j = self.trie_root, i
|
| 161 |
+
last_match_id, last_match_end = None, i
|
| 162 |
+
while j < n and tokens[j] in node.children:
|
| 163 |
+
node = node.children[tokens[j]]
|
| 164 |
+
j += 1
|
| 165 |
+
if node.token_id is not None:
|
| 166 |
+
last_match_id, last_match_end = node.token_id, j
|
| 167 |
+
if last_match_id is not None:
|
| 168 |
+
result_ids.append(last_match_id)
|
| 169 |
+
i = last_match_end
|
| 170 |
+
else:
|
| 171 |
+
tid = self.token_to_id.get(tokens[i], self.unk_token_id)
|
| 172 |
+
result_ids.append(tid)
|
| 173 |
+
i += 1
|
| 174 |
+
return result_ids
|
| 175 |
+
|
| 176 |
+
# ------------------------------
|
| 177 |
+
# Converters
|
| 178 |
+
# ------------------------------
|
| 179 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 180 |
+
return self.token_to_id.get(token, self.unk_token_id)
|
| 181 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 182 |
+
return self.id_to_token.get(index, self.unk_token)
|
| 183 |
+
|
| 184 |
+
def convert_tokens_to_ids(self, tokens: Union[str, List[str]]):
|
| 185 |
+
if isinstance(tokens, str): return self._convert_token_to_id(tokens)
|
| 186 |
+
return [self._convert_token_to_id(tok) for tok in tokens]
|
| 187 |
+
|
| 188 |
+
def convert_ids_to_tokens(self, ids: Union[int, List[int]]):
|
| 189 |
+
if isinstance(ids, int): return self._convert_id_to_token(ids)
|
| 190 |
+
return [self._convert_id_to_token(i) for i in ids]
|
| 191 |
+
|
| 192 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str: return "".join(tokens)
|
| 193 |
+
|
| 194 |
+
# ------------------------------
|
| 195 |
+
# Encoding / Decoding
|
| 196 |
+
# ------------------------------
|
| 197 |
+
# ------------------------------
|
| 198 |
+
# Convenience wrappers
|
| 199 |
+
# ------------------------------
|
| 200 |
+
def encode(
|
| 201 |
+
self,
|
| 202 |
+
text: str,
|
| 203 |
+
text_pair: Optional[str] = None,
|
| 204 |
+
add_special_tokens: bool = True,
|
| 205 |
+
padding: bool = False,
|
| 206 |
+
truncation: bool = False,
|
| 207 |
+
max_length: Optional[int] = None,
|
| 208 |
+
return_tensors: Optional[str] = None,
|
| 209 |
+
) -> List[int]:
|
| 210 |
+
encoded = self.encode_plus(
|
| 211 |
+
text=text,
|
| 212 |
+
text_pair=text_pair,
|
| 213 |
+
add_special_tokens=add_special_tokens,
|
| 214 |
+
padding=padding,
|
| 215 |
+
truncation=truncation,
|
| 216 |
+
max_length=max_length,
|
| 217 |
+
return_tensors=return_tensors,
|
| 218 |
+
)
|
| 219 |
+
input_ids = encoded["input_ids"]
|
| 220 |
+
if isinstance(input_ids, torch.Tensor):
|
| 221 |
+
if input_ids.dim() > 1:
|
| 222 |
+
input_ids = input_ids.squeeze(0)
|
| 223 |
+
input_ids = input_ids.tolist()
|
| 224 |
+
return input_ids
|
| 225 |
+
|
| 226 |
+
def __call__(
|
| 227 |
+
self,
|
| 228 |
+
text: Union[str, List[str]],
|
| 229 |
+
text_pair: Optional[Union[str, List[str]]] = None,
|
| 230 |
+
add_special_tokens: bool = True,
|
| 231 |
+
padding: Union[bool, str] = False,
|
| 232 |
+
truncation: Union[bool, str] = False,
|
| 233 |
+
max_length: Optional[int] = None,
|
| 234 |
+
stride: int = 0,
|
| 235 |
+
is_split_into_words: bool = False,
|
| 236 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 237 |
+
return_tensors: Optional[Union[str, Any]] = None,
|
| 238 |
+
return_token_type_ids: Optional[bool] = None,
|
| 239 |
+
return_attention_mask: Optional[bool] = None,
|
| 240 |
+
return_overflowing_tokens: bool = False,
|
| 241 |
+
return_special_tokens_mask: bool = False,
|
| 242 |
+
return_offsets_mapping: bool = False,
|
| 243 |
+
return_length: bool = False,
|
| 244 |
+
verbose: bool = True,
|
| 245 |
+
**kwargs
|
| 246 |
+
) -> BatchEncoding:
|
| 247 |
+
"""HuggingFace-compatible: one string → encode_plus, list → batch_encode_plus"""
|
| 248 |
+
if return_token_type_ids is None:
|
| 249 |
+
return_token_type_ids = True
|
| 250 |
+
if return_attention_mask is None:
|
| 251 |
+
return_attention_mask = True
|
| 252 |
+
|
| 253 |
+
if isinstance(text, list):
|
| 254 |
+
if text_pair is not None:
|
| 255 |
+
batch = [(t, p) for t, p in zip(text, text_pair)]
|
| 256 |
+
else:
|
| 257 |
+
batch = text
|
| 258 |
+
return self.batch_encode_plus(
|
| 259 |
+
batch,
|
| 260 |
+
add_special_tokens=add_special_tokens,
|
| 261 |
+
padding=padding,
|
| 262 |
+
truncation=truncation,
|
| 263 |
+
max_length=max_length,
|
| 264 |
+
stride=stride,
|
| 265 |
+
is_split_into_words=is_split_into_words,
|
| 266 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 267 |
+
return_tensors=return_tensors,
|
| 268 |
+
return_token_type_ids=return_token_type_ids,
|
| 269 |
+
return_attention_mask=return_attention_mask,
|
| 270 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 271 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 272 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 273 |
+
return_length=return_length,
|
| 274 |
+
verbose=verbose,
|
| 275 |
+
**kwargs
|
| 276 |
+
)
|
| 277 |
+
else:
|
| 278 |
+
return self.encode_plus(
|
| 279 |
+
text=text,
|
| 280 |
+
text_pair=text_pair,
|
| 281 |
+
add_special_tokens=add_special_tokens,
|
| 282 |
+
padding=padding,
|
| 283 |
+
truncation=truncation,
|
| 284 |
+
max_length=max_length,
|
| 285 |
+
stride=stride,
|
| 286 |
+
is_split_into_words=is_split_into_words,
|
| 287 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 288 |
+
return_tensors=return_tensors,
|
| 289 |
+
return_token_type_ids=return_token_type_ids,
|
| 290 |
+
return_attention_mask=return_attention_mask,
|
| 291 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 292 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 293 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 294 |
+
return_length=return_length,
|
| 295 |
+
verbose=verbose,
|
| 296 |
+
**kwargs
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
def encode_plus(
|
| 300 |
+
self,
|
| 301 |
+
text: str,
|
| 302 |
+
text_pair: Optional[str] = None,
|
| 303 |
+
add_special_tokens: bool = True,
|
| 304 |
+
padding: Union[bool, str] = False,
|
| 305 |
+
truncation: Union[bool, str] = False,
|
| 306 |
+
max_length: Optional[int] = None,
|
| 307 |
+
stride: int = 0,
|
| 308 |
+
is_split_into_words: bool = False,
|
| 309 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 310 |
+
return_tensors: Optional[Union[str, Any]] = None,
|
| 311 |
+
return_token_type_ids: Optional[bool] = True,
|
| 312 |
+
return_attention_mask: Optional[bool] = True,
|
| 313 |
+
return_overflowing_tokens: bool = False,
|
| 314 |
+
return_special_tokens_mask: bool = False,
|
| 315 |
+
return_offsets_mapping: bool = False,
|
| 316 |
+
return_length: bool = False,
|
| 317 |
+
verbose: bool = True,
|
| 318 |
+
**kwargs
|
| 319 |
+
) -> BatchEncoding:
|
| 320 |
+
if max_length is None: max_length = self.model_max_length
|
| 321 |
+
ids_a = list(self._cached_encode_str(text.strip()))
|
| 322 |
+
ids_b = list(self._cached_encode_str(text_pair.strip())) if text_pair else None
|
| 323 |
+
|
| 324 |
+
input_ids, token_type_ids = [], []
|
| 325 |
+
if add_special_tokens:
|
| 326 |
+
input_ids.append(self.bos_token_id); token_type_ids.append(0)
|
| 327 |
+
input_ids.extend(ids_a); token_type_ids.extend([0] * len(ids_a))
|
| 328 |
+
input_ids.append(self.eos_token_id); token_type_ids.append(0)
|
| 329 |
+
if ids_b is not None:
|
| 330 |
+
input_ids.extend(ids_b); token_type_ids.extend([1] * len(ids_b))
|
| 331 |
+
input_ids.append(self.eos_token_id); token_type_ids.append(1)
|
| 332 |
+
else:
|
| 333 |
+
input_ids = ids_a.copy(); token_type_ids = [0] * len(input_ids)
|
| 334 |
+
if ids_b is not None:
|
| 335 |
+
input_ids.extend(ids_b); token_type_ids.extend([1] * len(ids_b))
|
| 336 |
+
|
| 337 |
+
if truncation and len(input_ids) > max_length:
|
| 338 |
+
input_ids, token_type_ids = input_ids[:max_length], token_type_ids[:max_length]
|
| 339 |
+
|
| 340 |
+
encoded_dict = {"input_ids": input_ids}
|
| 341 |
+
if return_attention_mask:
|
| 342 |
+
if padding == True or padding == "max_length":
|
| 343 |
+
pad_len = max_length - len(input_ids)
|
| 344 |
+
if pad_len > 0:
|
| 345 |
+
if self.padding_side == "right":
|
| 346 |
+
input_ids.extend([self.pad_token_id] * pad_len)
|
| 347 |
+
token_type_ids.extend([0] * pad_len)
|
| 348 |
+
else:
|
| 349 |
+
input_ids = [self.pad_token_id] * pad_len + input_ids
|
| 350 |
+
token_type_ids = [0] * pad_len + token_type_ids
|
| 351 |
+
attention_mask = [0 if tid == self.pad_token_id else 1 for tid in input_ids]
|
| 352 |
+
encoded_dict["attention_mask"] = attention_mask
|
| 353 |
+
if return_token_type_ids: encoded_dict["token_type_ids"] = token_type_ids
|
| 354 |
+
if return_special_tokens_mask:
|
| 355 |
+
encoded_dict["special_tokens_mask"] = [
|
| 356 |
+
1 if tid in {self.bos_token_id, self.eos_token_id, self.pad_token_id, self.mask_token_id} else 0
|
| 357 |
+
for tid in input_ids
|
| 358 |
+
]
|
| 359 |
+
if return_length:
|
| 360 |
+
encoded_dict["length"] = len([tid for tid in input_ids if tid != self.pad_token_id])
|
| 361 |
+
|
| 362 |
+
if return_tensors in ["pt", "torch"]:
|
| 363 |
+
out = {}
|
| 364 |
+
for k, v in encoded_dict.items():
|
| 365 |
+
if isinstance(v, list):
|
| 366 |
+
tensor = torch.tensor(
|
| 367 |
+
[self.unk_token_id if x is None else int(x) for x in v], dtype=torch.long
|
| 368 |
+
).unsqueeze(0)
|
| 369 |
+
out[k] = tensor
|
| 370 |
+
else:
|
| 371 |
+
out[k] = v
|
| 372 |
+
return BatchEncoding(out, tensor_type=return_tensors)
|
| 373 |
+
return BatchEncoding(encoded_dict, tensor_type=None)
|
| 374 |
+
|
| 375 |
+
def batch_encode_plus(
|
| 376 |
+
self,
|
| 377 |
+
batch_text_or_text_pairs: List[Union[str, Tuple[str, str]]],
|
| 378 |
+
add_special_tokens: bool = True,
|
| 379 |
+
padding: Union[bool, str] = False,
|
| 380 |
+
truncation: Union[bool, str] = False,
|
| 381 |
+
max_length: Optional[int] = None,
|
| 382 |
+
stride: int = 0,
|
| 383 |
+
is_split_into_words: bool = False,
|
| 384 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 385 |
+
return_tensors: Optional[Union[str, Any]] = None,
|
| 386 |
+
return_token_type_ids: Optional[bool] = True,
|
| 387 |
+
return_attention_mask: Optional[bool] = True,
|
| 388 |
+
return_overflowing_tokens: bool = False,
|
| 389 |
+
return_special_tokens_mask: bool = False,
|
| 390 |
+
return_offsets_mapping: bool = False,
|
| 391 |
+
return_length: bool = False,
|
| 392 |
+
verbose: bool = True,
|
| 393 |
+
**kwargs
|
| 394 |
+
) -> BatchEncoding:
|
| 395 |
+
if padding is True: padding = "longest"
|
| 396 |
+
if padding == "max_length" and max_length is None: max_length = self.model_max_length
|
| 397 |
+
|
| 398 |
+
all_input_ids, all_token_type_ids, all_attention_masks = [], [], []
|
| 399 |
+
all_special_masks, all_lengths = [], []
|
| 400 |
+
for item in batch_text_or_text_pairs:
|
| 401 |
+
t, tp = item if isinstance(item, tuple) else (item, None)
|
| 402 |
+
enc = self.encode_plus(
|
| 403 |
+
text=t, text_pair=tp, add_special_tokens=add_special_tokens,
|
| 404 |
+
padding=False, truncation=truncation, max_length=max_length,
|
| 405 |
+
return_tensors=None, return_token_type_ids=return_token_type_ids,
|
| 406 |
+
return_attention_mask=return_attention_mask,
|
| 407 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 408 |
+
return_length=return_length, **kwargs
|
| 409 |
+
)
|
| 410 |
+
ids, tt, am = enc["input_ids"], enc.get("token_type_ids", [0]*len(enc["input_ids"])), enc.get("attention_mask",[1]*len(enc["input_ids"]))
|
| 411 |
+
sm, ln = enc.get("special_tokens_mask",[0]*len(ids)), enc.get("length", len([x for x in ids if x != self.pad_token_id]))
|
| 412 |
+
all_input_ids.append(ids); all_token_type_ids.append(tt); all_attention_masks.append(am)
|
| 413 |
+
all_special_masks.append(sm); all_lengths.append(ln)
|
| 414 |
+
|
| 415 |
+
pad_to = max(len(x) for x in all_input_ids) if padding == "longest" else (max_length if padding == "max_length" else None)
|
| 416 |
+
batched = {
|
| 417 |
+
"input_ids": all_input_ids,
|
| 418 |
+
"token_type_ids": all_token_type_ids if return_token_type_ids else None,
|
| 419 |
+
"attention_mask": all_attention_masks if return_attention_mask else None,
|
| 420 |
+
"special_tokens_mask": all_special_masks if return_special_tokens_mask else None,
|
| 421 |
+
"length": all_lengths if return_length else None,
|
| 422 |
+
}
|
| 423 |
+
if pad_to is not None:
|
| 424 |
+
for key in ["input_ids","token_type_ids","attention_mask","special_tokens_mask"]:
|
| 425 |
+
if batched.get(key) is None: continue
|
| 426 |
+
padded = []
|
| 427 |
+
for seq in batched[key]:
|
| 428 |
+
pad_len = pad_to - len(seq)
|
| 429 |
+
pad_val = self.pad_token_id if key=="input_ids" else 0
|
| 430 |
+
if pad_len > 0:
|
| 431 |
+
seq = seq+[pad_val]*pad_len if self.padding_side=="right" else [pad_val]*pad_len+seq
|
| 432 |
+
padded.append(seq)
|
| 433 |
+
batched[key] = padded
|
| 434 |
+
|
| 435 |
+
if return_tensors in ["pt", "torch"]:
|
| 436 |
+
def to_tensor(lst, pad_val=0):
|
| 437 |
+
return torch.tensor([[self.unk_token_id if x is None else int(x) for x in row] for row in lst], dtype=torch.long)
|
| 438 |
+
out = {}
|
| 439 |
+
if batched.get("input_ids") is not None: out["input_ids"] = to_tensor(batched["input_ids"], self.pad_token_id)
|
| 440 |
+
if batched.get("attention_mask") is not None: out["attention_mask"] = to_tensor(batched["attention_mask"],0)
|
| 441 |
+
if batched.get("token_type_ids") is not None: out["token_type_ids"] = to_tensor(batched["token_type_ids"],0)
|
| 442 |
+
if batched.get("special_tokens_mask") is not None: out["special_tokens_mask"] = to_tensor(batched["special_tokens_mask"],0)
|
| 443 |
+
if return_length and batched.get("length") is not None: out["length"] = torch.tensor([int(x) for x in batched["length"]], dtype=torch.long)
|
| 444 |
+
return BatchEncoding(out, tensor_type=return_tensors)
|
| 445 |
+
return BatchEncoding({k:v for k,v in batched.items() if v is not None}, tensor_type=None)
|
| 446 |
+
|
| 447 |
+
# ------------------------------
|
| 448 |
+
# Decoding
|
| 449 |
+
# ------------------------------
|
| 450 |
+
def decode(self, token_ids, skip_special_tokens=False, **kwargs):
|
| 451 |
+
if isinstance(token_ids, torch.Tensor): token_ids = token_ids.tolist()
|
| 452 |
+
special_ids = {self.bos_token_id,self.eos_token_id,self.pad_token_id,self.mask_token_id} if skip_special_tokens else set()
|
| 453 |
+
tokens = [self.id_to_token.get(tid,self.unk_token) for tid in token_ids if tid not in special_ids]
|
| 454 |
+
return "".join(tokens)
|
| 455 |
+
|
| 456 |
+
def batch_decode(self, sequences, skip_special_tokens=False, **kwargs):
|
| 457 |
+
if isinstance(sequences, torch.Tensor): sequences = sequences.tolist()
|
| 458 |
+
return [self.decode(seq, skip_special_tokens=skip_special_tokens, **kwargs) for seq in sequences]
|
| 459 |
+
|
| 460 |
+
def decode_with_trace(self, token_ids: List[int]):
|
| 461 |
+
print(f"\n🔍 Decoding {len(token_ids)} tokens:")
|
| 462 |
+
for i, tid in enumerate(token_ids):
|
| 463 |
+
token = self.id_to_token.get(tid, self.unk_token)
|
| 464 |
+
tid_str = "None" if tid is None else f"{tid:5d}"
|
| 465 |
+
print(f" [{i:03d}] ID={tid_str} → '{token}'")
|
| 466 |
+
|
| 467 |
+
# ------------------------------
|
| 468 |
+
# Save / Load
|
| 469 |
+
# ------------------------------
|
| 470 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 471 |
+
if not os.path.isdir(save_directory): os.makedirs(save_directory)
|
| 472 |
+
vocab_file = os.path.join(save_directory,(filename_prefix+"-" if filename_prefix else "")+"vocab.json")
|
| 473 |
+
with open(vocab_file,"w",encoding="utf-8") as f: json.dump(self.token_to_id,f,ensure_ascii=False,indent=2)
|
| 474 |
+
return (vocab_file,)
|
| 475 |
+
|
| 476 |
+
def save_pretrained(self, save_directory: Union[str, os.PathLike], filename_prefix: Optional[str]=None, **kwargs):
|
| 477 |
+
if not os.path.exists(save_directory): os.makedirs(save_directory)
|
| 478 |
+
self.save_vocabulary(save_directory, filename_prefix)
|
| 479 |
+
config_file = os.path.join(save_directory,"tokenizer_config.json")
|
| 480 |
+
with open(config_file,"w",encoding="utf-8") as f:
|
| 481 |
+
json.dump({
|
| 482 |
+
"tokenizer_class": self.__class__.__name__,
|
| 483 |
+
"model_max_length": self.model_max_length,
|
| 484 |
+
"padding_side": self.padding_side,
|
| 485 |
+
"truncation_side": self.truncation_side,
|
| 486 |
+
"special_tokens": {
|
| 487 |
+
"bos_token": self.bos_token,
|
| 488 |
+
"eos_token": self.eos_token,
|
| 489 |
+
"pad_token": self.pad_token,
|
| 490 |
+
"unk_token": self.unk_token,
|
| 491 |
+
"mask_token": self.mask_token,
|
| 492 |
+
}
|
| 493 |
+
},f,ensure_ascii=False,indent=2)
|
| 494 |
+
return (save_directory,)
|
| 495 |
+
|
| 496 |
+
@classmethod
|
| 497 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 498 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 499 |
+
vocab_file = os.path.join(pretrained_model_name_or_path,"vocab.json")
|
| 500 |
+
config_file = os.path.join(pretrained_model_name_or_path,"tokenizer_config.json")
|
| 501 |
+
config = {}
|
| 502 |
+
if os.path.exists(config_file):
|
| 503 |
+
with open(config_file,"r",encoding="utf-8") as f: config=json.load(f)
|
| 504 |
+
return cls(vocab_file=vocab_file, **{**config,**kwargs})
|
| 505 |
+
else:
|
| 506 |
+
raise NotImplementedError("Loading from Hub not implemented yet")
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# ------------------------------
|
| 510 |
+
# SELFIES variant
|
| 511 |
+
# ------------------------------
|
| 512 |
+
class FastChemTokenizerSelfies(FastChemTokenizer):
|
| 513 |
+
def __init__(self, *args, **kwargs):
|
| 514 |
+
super().__init__(*args, **kwargs) # ✅ ensures BOS/EOS etc. are set
|
| 515 |
+
|
| 516 |
+
"""SELFIES variant that handles whitespace-separated tokens."""
|
| 517 |
+
|
| 518 |
+
def _encode_core(self, text: str) -> List[int]:
|
| 519 |
+
result_ids, i, n = [], 0, len(text)
|
| 520 |
+
while i < n:
|
| 521 |
+
if text[i].isspace(): i += 1; continue
|
| 522 |
+
node, j = self.trie_root, i
|
| 523 |
+
last_match_id, last_match_end = None, i
|
| 524 |
+
while j < n and text[j] in node.children:
|
| 525 |
+
node = node.children[text[j]]; j += 1
|
| 526 |
+
if node.token_id is not None:
|
| 527 |
+
last_match_id, last_match_end = node.token_id, j
|
| 528 |
+
if last_match_id is not None:
|
| 529 |
+
result_ids.append(last_match_id); i = last_match_end
|
| 530 |
+
else:
|
| 531 |
+
result_ids.append(self.token_to_id.get(text[i], self.unk_token_id)); i += 1
|
| 532 |
+
return result_ids
|
| 533 |
+
|
| 534 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str: return " ".join(tokens)
|
| 535 |
+
def decode(self, token_ids, skip_special_tokens=False, **kwargs):
|
| 536 |
+
if isinstance(token_ids, torch.Tensor): token_ids = token_ids.tolist()
|
| 537 |
+
special_ids = {self.bos_token_id,self.eos_token_id,self.pad_token_id,self.mask_token_id} if skip_special_tokens else set()
|
| 538 |
+
tokens = [self.id_to_token.get(tid,self.unk_token) for tid in token_ids if tid not in special_ids]
|
| 539 |
+
return " ".join(tokens)
|