Instructions to use Synthyra/ESMplusplus_large with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Synthyra/ESMplusplus_large with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="Synthyra/ESMplusplus_large", trust_remote_code=True)# Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("Synthyra/ESMplusplus_large", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
Upload modeling_esm_plusplus.py with huggingface_hub
Browse files- modeling_esm_plusplus.py +640 -10
modeling_esm_plusplus.py
CHANGED
|
@@ -1150,6 +1150,544 @@ def bool_to_additive_mask(
|
|
| 1150 |
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 1151 |
return additive
|
| 1152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1153 |
"""
|
| 1154 |
ESM++ model implementation.
|
| 1155 |
|
|
@@ -1728,23 +2266,37 @@ class TransformerStack(nn.Module):
|
|
| 1728 |
self,
|
| 1729 |
x: torch.Tensor,
|
| 1730 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 1731 |
output_hidden_states: Optional[bool] = False,
|
| 1732 |
output_attentions: Optional[bool] = False,
|
| 1733 |
output_s_max: Optional[bool] = False,
|
|
|
|
| 1734 |
) -> TransformerOutput:
|
| 1735 |
hidden_states = () if output_hidden_states else None
|
| 1736 |
attentions = () if output_attentions else None
|
| 1737 |
full_s_max = () if output_s_max else None
|
| 1738 |
|
| 1739 |
-
|
| 1740 |
-
|
| 1741 |
-
|
| 1742 |
-
|
| 1743 |
-
|
| 1744 |
-
|
| 1745 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1746 |
|
| 1747 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1748 |
if self.gradient_checkpointing and self.training:
|
| 1749 |
x, attn_weights, s_max = self._gradient_checkpointing_func(
|
| 1750 |
block.__call__,
|
|
@@ -1769,7 +2321,8 @@ class TransformerStack(nn.Module):
|
|
| 1769 |
attentions += (attn_weights,)
|
| 1770 |
if output_hidden_states:
|
| 1771 |
assert hidden_states is not None
|
| 1772 |
-
|
|
|
|
| 1773 |
if full_s_max is not None:
|
| 1774 |
full_s_max += (s_max,)
|
| 1775 |
|
|
@@ -1784,6 +2337,69 @@ class TransformerStack(nn.Module):
|
|
| 1784 |
s_max=full_s_max,
|
| 1785 |
)
|
| 1786 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1787 |
|
| 1788 |
class PreTrainedESMplusplusModel(PreTrainedModel):
|
| 1789 |
"""
|
|
@@ -1920,10 +2536,12 @@ class ESMplusplusModel(PreTrainedESMplusplusModel, EmbeddingMixin):
|
|
| 1920 |
self,
|
| 1921 |
input_ids: Optional[torch.Tensor] = None,
|
| 1922 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 1923 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1924 |
output_attentions: Optional[bool] = None,
|
| 1925 |
output_hidden_states: Optional[bool] = None,
|
| 1926 |
output_s_max: Optional[bool] = False,
|
|
|
|
| 1927 |
return_dict: Optional[bool] = None,
|
| 1928 |
**kwargs,
|
| 1929 |
) -> ESMplusplusOutput:
|
|
@@ -1938,9 +2556,11 @@ class ESMplusplusModel(PreTrainedESMplusplusModel, EmbeddingMixin):
|
|
| 1938 |
transformer_output = self.transformer(
|
| 1939 |
x=x,
|
| 1940 |
attention_mask=attention_mask,
|
|
|
|
| 1941 |
output_hidden_states=output_hidden_states,
|
| 1942 |
output_attentions=output_attentions,
|
| 1943 |
output_s_max=output_s_max,
|
|
|
|
| 1944 |
)
|
| 1945 |
return ESMplusplusOutput(
|
| 1946 |
last_hidden_state=transformer_output.last_hidden_state,
|
|
@@ -2014,12 +2634,15 @@ class ESMplusplusForMaskedLM(FastPLMTestTimeTrainingMixin, PreTrainedESMplusplus
|
|
| 2014 |
self,
|
| 2015 |
input_ids: Optional[torch.Tensor] = None,
|
| 2016 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 2017 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2018 |
labels: Optional[torch.Tensor] = None,
|
| 2019 |
output_attentions: Optional[bool] = None,
|
| 2020 |
output_hidden_states: Optional[bool] = None,
|
| 2021 |
output_s_max: Optional[bool] = False,
|
|
|
|
| 2022 |
return_dict: Optional[bool] = None,
|
|
|
|
| 2023 |
**kwargs,
|
| 2024 |
) -> ESMplusplusOutput:
|
| 2025 |
if inputs_embeds is None:
|
|
@@ -2030,15 +2653,18 @@ class ESMplusplusForMaskedLM(FastPLMTestTimeTrainingMixin, PreTrainedESMplusplus
|
|
| 2030 |
output = self.transformer(
|
| 2031 |
x=x,
|
| 2032 |
attention_mask=attention_mask,
|
|
|
|
| 2033 |
output_hidden_states=output_hidden_states,
|
| 2034 |
output_attentions=output_attentions,
|
| 2035 |
output_s_max=output_s_max,
|
|
|
|
| 2036 |
)
|
| 2037 |
|
| 2038 |
last_hidden_state = output.last_hidden_state
|
| 2039 |
-
logits = self.sequence_head(last_hidden_state)
|
| 2040 |
loss = None
|
| 2041 |
if labels is not None:
|
|
|
|
| 2042 |
loss = self.ce_loss(logits.view(-1, self.vocab_size), labels.view(-1))
|
| 2043 |
|
| 2044 |
return ESMplusplusOutput(
|
|
@@ -2099,6 +2725,7 @@ class ESMplusplusForSequenceClassification(ESMplusplusForMaskedLM, EmbeddingMixi
|
|
| 2099 |
self,
|
| 2100 |
input_ids: Optional[torch.Tensor] = None,
|
| 2101 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 2102 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2103 |
labels: Optional[torch.Tensor] = None,
|
| 2104 |
output_attentions: Optional[bool] = None,
|
|
@@ -2110,6 +2737,7 @@ class ESMplusplusForSequenceClassification(ESMplusplusForMaskedLM, EmbeddingMixi
|
|
| 2110 |
output = super().forward(
|
| 2111 |
input_ids=input_ids,
|
| 2112 |
attention_mask=attention_mask,
|
|
|
|
| 2113 |
inputs_embeds=inputs_embeds,
|
| 2114 |
labels=None,
|
| 2115 |
output_attentions=output_attentions,
|
|
@@ -2192,6 +2820,7 @@ class ESMplusplusForTokenClassification(ESMplusplusForMaskedLM, EmbeddingMixin):
|
|
| 2192 |
self,
|
| 2193 |
input_ids: Optional[torch.Tensor] = None,
|
| 2194 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 2195 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2196 |
labels: Optional[torch.Tensor] = None,
|
| 2197 |
output_attentions: Optional[bool] = None,
|
|
@@ -2203,6 +2832,7 @@ class ESMplusplusForTokenClassification(ESMplusplusForMaskedLM, EmbeddingMixin):
|
|
| 2203 |
output = super().forward(
|
| 2204 |
input_ids=input_ids,
|
| 2205 |
attention_mask=attention_mask,
|
|
|
|
| 2206 |
inputs_embeds=inputs_embeds,
|
| 2207 |
labels=None,
|
| 2208 |
output_attentions=output_attentions,
|
|
|
|
| 1150 |
additive.masked_fill_(bool_mask.logical_not(), float("-inf"))
|
| 1151 |
return additive
|
| 1152 |
|
| 1153 |
+
import typing as T
|
| 1154 |
+
from dataclasses import dataclass, fields
|
| 1155 |
+
|
| 1156 |
+
import torch
|
| 1157 |
+
import torch.nn as nn
|
| 1158 |
+
import torch.nn.functional as F
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
@dataclass
|
| 1162 |
+
class TTTConfig:
|
| 1163 |
+
lr: float = 4e-4
|
| 1164 |
+
steps: int = 30
|
| 1165 |
+
ags: int = 16
|
| 1166 |
+
batch_size: int = 2
|
| 1167 |
+
mask_ratio: float = 0.15
|
| 1168 |
+
crop_size: int = 1024
|
| 1169 |
+
bert_leave_prob: float = 0.1
|
| 1170 |
+
bert_replace_prob: float = 0.1
|
| 1171 |
+
optimizer: str = "sgd"
|
| 1172 |
+
momentum: float = 0.0
|
| 1173 |
+
weight_decay: float = 0.0
|
| 1174 |
+
seed: int | None = 0
|
| 1175 |
+
lora_rank: int = 8
|
| 1176 |
+
lora_alpha: float = 32.0
|
| 1177 |
+
lora_target_replace_module: str | None = None
|
| 1178 |
+
lora_target_modules: tuple[str, ...] | None = None
|
| 1179 |
+
initial_state_reset: bool = True
|
| 1180 |
+
automatic_best_state_reset: bool = False
|
| 1181 |
+
eval_each_step: bool = False
|
| 1182 |
+
gradient_clip: bool = False
|
| 1183 |
+
gradient_clip_max_norm: float = 1.0
|
| 1184 |
+
|
| 1185 |
+
@classmethod
|
| 1186 |
+
def from_kwargs(cls, **kwargs: T.Any) -> "TTTConfig":
|
| 1187 |
+
valid_names = {field.name for field in fields(cls)}
|
| 1188 |
+
unknown_names = set(kwargs) - valid_names
|
| 1189 |
+
assert len(unknown_names) == 0, f"Unknown TTTConfig fields: {sorted(unknown_names)}"
|
| 1190 |
+
return cls(**kwargs)
|
| 1191 |
+
|
| 1192 |
+
def merged(self, overrides: T.Mapping[str, T.Any] | "TTTConfig" | None) -> "TTTConfig":
|
| 1193 |
+
if overrides is None:
|
| 1194 |
+
return self
|
| 1195 |
+
if isinstance(overrides, TTTConfig):
|
| 1196 |
+
return overrides
|
| 1197 |
+
values = {field.name: self.__dict__[field.name] for field in fields(self)}
|
| 1198 |
+
for name, value in overrides.items():
|
| 1199 |
+
assert name in values, f"Unknown TTTConfig field: {name}"
|
| 1200 |
+
values[name] = value
|
| 1201 |
+
return TTTConfig(**values)
|
| 1202 |
+
|
| 1203 |
+
def verify(self) -> None:
|
| 1204 |
+
assert self.lr > 0.0, "TTT learning rate must be positive."
|
| 1205 |
+
assert self.steps >= 1, "TTT steps must be >= 1."
|
| 1206 |
+
assert self.ags >= 1, "TTT gradient accumulation steps must be >= 1."
|
| 1207 |
+
assert self.batch_size >= 1, "TTT batch_size must be >= 1."
|
| 1208 |
+
assert 0.0 < self.mask_ratio <= 1.0, "TTT mask_ratio must be in (0, 1]."
|
| 1209 |
+
assert self.crop_size >= 1, "TTT crop_size must be >= 1."
|
| 1210 |
+
assert self.lora_rank >= 1, "TTT v1 is LoRA-only, so lora_rank must be >= 1."
|
| 1211 |
+
assert self.lora_alpha > 0.0, "TTT lora_alpha must be positive."
|
| 1212 |
+
assert self.optimizer in {"adamw", "sgd"}, "TTT optimizer must be 'adamw' or 'sgd'."
|
| 1213 |
+
assert 0.0 <= self.bert_leave_prob <= 1.0, "bert_leave_prob must be in [0, 1]."
|
| 1214 |
+
assert 0.0 <= self.bert_replace_prob <= 1.0, "bert_replace_prob must be in [0, 1]."
|
| 1215 |
+
assert self.bert_leave_prob + self.bert_replace_prob <= 1.0, (
|
| 1216 |
+
"bert_leave_prob + bert_replace_prob must be <= 1."
|
| 1217 |
+
)
|
| 1218 |
+
if self.gradient_clip:
|
| 1219 |
+
assert self.gradient_clip_max_norm > 0.0, "gradient_clip_max_norm must be positive."
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
class LoraInjectedLinear(nn.Module):
|
| 1223 |
+
def __init__(self, linear: nn.Module, rank: int, alpha: float) -> None:
|
| 1224 |
+
super().__init__()
|
| 1225 |
+
weight = linear._parameters["weight"]
|
| 1226 |
+
assert weight.ndim == 2, "LoRA can only wrap 2D linear weights."
|
| 1227 |
+
self.linear = linear
|
| 1228 |
+
self.linear.requires_grad_(False)
|
| 1229 |
+
self.rank = rank
|
| 1230 |
+
self.scale = alpha
|
| 1231 |
+
in_features = weight.shape[1]
|
| 1232 |
+
out_features = weight.shape[0]
|
| 1233 |
+
self.lora_down = nn.Linear(in_features, rank, bias=False, dtype=torch.float32)
|
| 1234 |
+
self.lora_up = nn.Linear(rank, out_features, bias=False, dtype=torch.float32)
|
| 1235 |
+
self.lora_down.to(device=weight.device)
|
| 1236 |
+
self.lora_up.to(device=weight.device)
|
| 1237 |
+
nn.init.normal_(self.lora_down.weight, std=1.0 / rank)
|
| 1238 |
+
nn.init.zeros_(self.lora_up.weight)
|
| 1239 |
+
|
| 1240 |
+
@property
|
| 1241 |
+
def weight(self) -> torch.Tensor:
|
| 1242 |
+
return self.linear._parameters["weight"]
|
| 1243 |
+
|
| 1244 |
+
@property
|
| 1245 |
+
def bias(self) -> torch.Tensor | None:
|
| 1246 |
+
return self.linear._parameters["bias"]
|
| 1247 |
+
|
| 1248 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 1249 |
+
base = self.linear(x)
|
| 1250 |
+
delta = self.lora_up(self.lora_down(x.to(dtype=torch.float32))) * self.scale
|
| 1251 |
+
return base + delta.to(dtype=base.dtype)
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
class FastPLMTestTimeTrainingMixin:
|
| 1255 |
+
def init_ttt(self, ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None) -> None:
|
| 1256 |
+
base_config = TTTConfig()
|
| 1257 |
+
self._ttt_cfg = base_config.merged(ttt_config)
|
| 1258 |
+
self._ttt_cfg.verify()
|
| 1259 |
+
self._ttt_initialized = False
|
| 1260 |
+
self._ttt_initial_state: list[dict[str, torch.Tensor]] | None = None
|
| 1261 |
+
|
| 1262 |
+
@property
|
| 1263 |
+
def ttt_config(self) -> TTTConfig:
|
| 1264 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 1265 |
+
self.init_ttt()
|
| 1266 |
+
return self._ttt_cfg
|
| 1267 |
+
|
| 1268 |
+
def _ttt_get_trainable_modules(self) -> list[nn.Module]:
|
| 1269 |
+
return [self]
|
| 1270 |
+
|
| 1271 |
+
def _ttt_get_frozen_modules(self) -> list[nn.Module]:
|
| 1272 |
+
return []
|
| 1273 |
+
|
| 1274 |
+
def _ttt_tokenize(
|
| 1275 |
+
self,
|
| 1276 |
+
seq: str | list[str] | None = None,
|
| 1277 |
+
input_ids: torch.Tensor | None = None,
|
| 1278 |
+
**kwargs: T.Any,
|
| 1279 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1280 |
+
del kwargs
|
| 1281 |
+
if input_ids is not None:
|
| 1282 |
+
return input_ids
|
| 1283 |
+
assert seq is not None, "Pass either seq or input_ids for TTT."
|
| 1284 |
+
tokenized = self.tokenizer(seq, return_tensors="pt", padding=True)
|
| 1285 |
+
return tokenized["input_ids"]
|
| 1286 |
+
|
| 1287 |
+
def _ttt_mask_token(self) -> int:
|
| 1288 |
+
return int(self.tokenizer.mask_token_id)
|
| 1289 |
+
|
| 1290 |
+
def _ttt_padding_token(self) -> int:
|
| 1291 |
+
return int(self.tokenizer.pad_token_id)
|
| 1292 |
+
|
| 1293 |
+
def _ttt_replacement_tokens(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 1294 |
+
tokenizer = self.tokenizer
|
| 1295 |
+
special_ids = set(tokenizer.all_special_ids)
|
| 1296 |
+
vocab_size = int(self.config.vocab_size)
|
| 1297 |
+
ids = [idx for idx in range(vocab_size) if idx not in special_ids]
|
| 1298 |
+
assert len(ids) > 0, "TTT replacement token set is empty."
|
| 1299 |
+
return torch.tensor(ids, device=input_ids.device, dtype=input_ids.dtype)
|
| 1300 |
+
|
| 1301 |
+
def _ttt_predict_logits(
|
| 1302 |
+
self,
|
| 1303 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1304 |
+
**kwargs: T.Any,
|
| 1305 |
+
) -> torch.Tensor:
|
| 1306 |
+
del kwargs
|
| 1307 |
+
if isinstance(batch, dict):
|
| 1308 |
+
output = self(**batch)
|
| 1309 |
+
return output.logits
|
| 1310 |
+
attention_mask = batch.ne(self._ttt_padding_token())
|
| 1311 |
+
output = self(input_ids=batch, attention_mask=attention_mask)
|
| 1312 |
+
return output.logits
|
| 1313 |
+
|
| 1314 |
+
def _ttt_eval_step(
|
| 1315 |
+
self,
|
| 1316 |
+
step: int,
|
| 1317 |
+
loss: float,
|
| 1318 |
+
seq: str | list[str] | None = None,
|
| 1319 |
+
input_ids: torch.Tensor | None = None,
|
| 1320 |
+
**kwargs: T.Any,
|
| 1321 |
+
) -> tuple[dict[str, T.Any], float | None]:
|
| 1322 |
+
del step, loss, seq, input_ids, kwargs
|
| 1323 |
+
return {}, None
|
| 1324 |
+
|
| 1325 |
+
def _ttt_is_lora_target(
|
| 1326 |
+
self,
|
| 1327 |
+
name: str,
|
| 1328 |
+
full_name: str,
|
| 1329 |
+
module: nn.Module,
|
| 1330 |
+
active: bool,
|
| 1331 |
+
target_modules: tuple[str, ...] | None,
|
| 1332 |
+
) -> bool:
|
| 1333 |
+
if not active:
|
| 1334 |
+
return False
|
| 1335 |
+
if isinstance(module, LoraInjectedLinear):
|
| 1336 |
+
return False
|
| 1337 |
+
if (
|
| 1338 |
+
target_modules is not None
|
| 1339 |
+
and name not in target_modules
|
| 1340 |
+
and full_name not in target_modules
|
| 1341 |
+
):
|
| 1342 |
+
return False
|
| 1343 |
+
if isinstance(module, nn.Linear):
|
| 1344 |
+
return True
|
| 1345 |
+
if "weight" not in module._parameters:
|
| 1346 |
+
return False
|
| 1347 |
+
weight = module._parameters["weight"]
|
| 1348 |
+
if weight is None or weight.ndim != 2:
|
| 1349 |
+
return False
|
| 1350 |
+
return "Linear" in module.__class__.__name__
|
| 1351 |
+
|
| 1352 |
+
def _ttt_inject_lora(self) -> int:
|
| 1353 |
+
cfg = self.ttt_config
|
| 1354 |
+
cfg.verify()
|
| 1355 |
+
target_class = cfg.lora_target_replace_module
|
| 1356 |
+
target_modules = cfg.lora_target_modules
|
| 1357 |
+
wrapped = 0
|
| 1358 |
+
|
| 1359 |
+
def inject(module: nn.Module, prefix: str, active: bool) -> None:
|
| 1360 |
+
nonlocal wrapped
|
| 1361 |
+
for name, child in list(module.named_children()):
|
| 1362 |
+
full_name = f"{prefix}.{name}" if prefix else name
|
| 1363 |
+
child_active = active
|
| 1364 |
+
if target_class is not None:
|
| 1365 |
+
child_active = active or child.__class__.__name__ == target_class
|
| 1366 |
+
if self._ttt_is_lora_target(name, full_name, child, child_active, target_modules):
|
| 1367 |
+
setattr(
|
| 1368 |
+
module,
|
| 1369 |
+
name,
|
| 1370 |
+
LoraInjectedLinear(child, rank=cfg.lora_rank, alpha=cfg.lora_alpha),
|
| 1371 |
+
)
|
| 1372 |
+
wrapped += 1
|
| 1373 |
+
continue
|
| 1374 |
+
inject(child, full_name, child_active)
|
| 1375 |
+
|
| 1376 |
+
for trainable_module in self._ttt_get_trainable_modules():
|
| 1377 |
+
inject(trainable_module, "", target_class is None)
|
| 1378 |
+
assert wrapped > 0, "TTT LoRA injection did not find any target modules."
|
| 1379 |
+
return wrapped
|
| 1380 |
+
|
| 1381 |
+
def _ttt_lora_modules(self) -> list[LoraInjectedLinear]:
|
| 1382 |
+
return [module for module in self.modules() if isinstance(module, LoraInjectedLinear)]
|
| 1383 |
+
|
| 1384 |
+
def _ttt_lora_parameters(self) -> list[nn.Parameter]:
|
| 1385 |
+
params: list[nn.Parameter] = []
|
| 1386 |
+
for module in self._ttt_lora_modules():
|
| 1387 |
+
params.extend(module.lora_down.parameters())
|
| 1388 |
+
params.extend(module.lora_up.parameters())
|
| 1389 |
+
assert len(params) > 0, "TTT has no LoRA parameters."
|
| 1390 |
+
return params
|
| 1391 |
+
|
| 1392 |
+
def _ttt_snapshot_lora_state(self) -> list[dict[str, torch.Tensor]]:
|
| 1393 |
+
snapshot = []
|
| 1394 |
+
for module in self._ttt_lora_modules():
|
| 1395 |
+
snapshot.append(
|
| 1396 |
+
{
|
| 1397 |
+
"lora_down.weight": module.lora_down.weight.detach().clone(),
|
| 1398 |
+
"lora_up.weight": module.lora_up.weight.detach().clone(),
|
| 1399 |
+
}
|
| 1400 |
+
)
|
| 1401 |
+
assert len(snapshot) > 0, "TTT has no LoRA state to snapshot."
|
| 1402 |
+
return snapshot
|
| 1403 |
+
|
| 1404 |
+
def _ttt_restore_lora_state(self, state: list[dict[str, torch.Tensor]]) -> None:
|
| 1405 |
+
modules = self._ttt_lora_modules()
|
| 1406 |
+
assert len(modules) == len(state), "TTT LoRA state/module count mismatch."
|
| 1407 |
+
with torch.no_grad():
|
| 1408 |
+
for module, module_state in zip(modules, state):
|
| 1409 |
+
module.lora_down.weight.copy_(module_state["lora_down.weight"])
|
| 1410 |
+
module.lora_up.weight.copy_(module_state["lora_up.weight"])
|
| 1411 |
+
|
| 1412 |
+
def _ttt_ensure_initialized(self) -> None:
|
| 1413 |
+
if "_ttt_cfg" not in self.__dict__:
|
| 1414 |
+
self.init_ttt()
|
| 1415 |
+
if self._ttt_initialized:
|
| 1416 |
+
return
|
| 1417 |
+
self._ttt_inject_lora()
|
| 1418 |
+
self._ttt_initial_state = self._ttt_snapshot_lora_state()
|
| 1419 |
+
self._ttt_initialized = True
|
| 1420 |
+
|
| 1421 |
+
def ttt_reset(self) -> None:
|
| 1422 |
+
self._ttt_ensure_initialized()
|
| 1423 |
+
assert self._ttt_initial_state is not None, "TTT initial state is not available."
|
| 1424 |
+
self._ttt_restore_lora_state(self._ttt_initial_state)
|
| 1425 |
+
|
| 1426 |
+
def _ttt_make_optimizer(self) -> torch.optim.Optimizer:
|
| 1427 |
+
cfg = self.ttt_config
|
| 1428 |
+
params = self._ttt_lora_parameters()
|
| 1429 |
+
if cfg.optimizer == "sgd":
|
| 1430 |
+
return torch.optim.SGD(
|
| 1431 |
+
params,
|
| 1432 |
+
lr=cfg.lr,
|
| 1433 |
+
momentum=cfg.momentum,
|
| 1434 |
+
weight_decay=cfg.weight_decay,
|
| 1435 |
+
)
|
| 1436 |
+
return torch.optim.AdamW(params, lr=cfg.lr, weight_decay=cfg.weight_decay)
|
| 1437 |
+
|
| 1438 |
+
def _ttt_to_device(
|
| 1439 |
+
self,
|
| 1440 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1441 |
+
device: torch.device,
|
| 1442 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1443 |
+
if isinstance(batch, dict):
|
| 1444 |
+
return {name: tensor.to(device) for name, tensor in batch.items()}
|
| 1445 |
+
return batch.to(device)
|
| 1446 |
+
|
| 1447 |
+
def _ttt_input_ids_from_batch(
|
| 1448 |
+
self,
|
| 1449 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1450 |
+
) -> torch.Tensor:
|
| 1451 |
+
if isinstance(batch, dict):
|
| 1452 |
+
return batch["input_ids"]
|
| 1453 |
+
return batch
|
| 1454 |
+
|
| 1455 |
+
def _ttt_set_input_ids(
|
| 1456 |
+
self,
|
| 1457 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1458 |
+
input_ids: torch.Tensor,
|
| 1459 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1460 |
+
if isinstance(batch, dict):
|
| 1461 |
+
updated = dict(batch)
|
| 1462 |
+
updated["input_ids"] = input_ids
|
| 1463 |
+
return updated
|
| 1464 |
+
return input_ids
|
| 1465 |
+
|
| 1466 |
+
def _ttt_non_special_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
|
| 1467 |
+
pad_token = self._ttt_padding_token()
|
| 1468 |
+
mask = input_ids.ne(pad_token)
|
| 1469 |
+
special_ids = set(self.tokenizer.all_special_ids)
|
| 1470 |
+
for special_id in special_ids:
|
| 1471 |
+
mask = mask & input_ids.ne(int(special_id))
|
| 1472 |
+
return mask
|
| 1473 |
+
|
| 1474 |
+
def _ttt_sample_crop(
|
| 1475 |
+
self,
|
| 1476 |
+
batch: torch.Tensor | dict[str, torch.Tensor],
|
| 1477 |
+
generator: torch.Generator,
|
| 1478 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 1479 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 1480 |
+
cfg = self.ttt_config
|
| 1481 |
+
if input_ids.shape[1] <= cfg.crop_size:
|
| 1482 |
+
return batch
|
| 1483 |
+
high = input_ids.shape[1] - cfg.crop_size + 1
|
| 1484 |
+
start = int(
|
| 1485 |
+
torch.randint(
|
| 1486 |
+
high,
|
| 1487 |
+
(1,),
|
| 1488 |
+
generator=generator,
|
| 1489 |
+
device=input_ids.device,
|
| 1490 |
+
).item()
|
| 1491 |
+
)
|
| 1492 |
+
end = start + cfg.crop_size
|
| 1493 |
+
if isinstance(batch, dict):
|
| 1494 |
+
cropped = {}
|
| 1495 |
+
for name, tensor in batch.items():
|
| 1496 |
+
if tensor.ndim >= 2 and tensor.shape[1] == input_ids.shape[1]:
|
| 1497 |
+
cropped[name] = tensor[:, start:end]
|
| 1498 |
+
else:
|
| 1499 |
+
cropped[name] = tensor
|
| 1500 |
+
return cropped
|
| 1501 |
+
return input_ids[:, start:end]
|
| 1502 |
+
|
| 1503 |
+
def _ttt_sample_batch(
|
| 1504 |
+
self,
|
| 1505 |
+
tokenized: torch.Tensor | dict[str, torch.Tensor],
|
| 1506 |
+
generator: torch.Generator,
|
| 1507 |
+
) -> tuple[torch.Tensor | dict[str, torch.Tensor], torch.Tensor]:
|
| 1508 |
+
cfg = self.ttt_config
|
| 1509 |
+
batch = self._ttt_sample_crop(tokenized, generator)
|
| 1510 |
+
input_ids = self._ttt_input_ids_from_batch(batch)
|
| 1511 |
+
rows = torch.randint(
|
| 1512 |
+
input_ids.shape[0],
|
| 1513 |
+
(cfg.batch_size,),
|
| 1514 |
+
generator=generator,
|
| 1515 |
+
device=input_ids.device,
|
| 1516 |
+
)
|
| 1517 |
+
if isinstance(batch, dict):
|
| 1518 |
+
sampled: torch.Tensor | dict[str, torch.Tensor] = {}
|
| 1519 |
+
for name, tensor in batch.items():
|
| 1520 |
+
if tensor.ndim >= 1 and tensor.shape[0] == input_ids.shape[0]:
|
| 1521 |
+
sampled[name] = tensor.index_select(0, rows)
|
| 1522 |
+
else:
|
| 1523 |
+
sampled[name] = tensor
|
| 1524 |
+
else:
|
| 1525 |
+
sampled = input_ids.index_select(0, rows)
|
| 1526 |
+
|
| 1527 |
+
sampled_ids = self._ttt_input_ids_from_batch(sampled)
|
| 1528 |
+
labels = sampled_ids.clone()
|
| 1529 |
+
non_special = self._ttt_non_special_mask(sampled_ids)
|
| 1530 |
+
label_mask = torch.zeros_like(non_special)
|
| 1531 |
+
for row_idx in range(sampled_ids.shape[0]):
|
| 1532 |
+
candidate_positions = torch.where(non_special[row_idx])[0]
|
| 1533 |
+
if candidate_positions.numel() == 0:
|
| 1534 |
+
continue
|
| 1535 |
+
num_mask = max(1, int(round(candidate_positions.numel() * cfg.mask_ratio)))
|
| 1536 |
+
order = torch.randperm(
|
| 1537 |
+
candidate_positions.numel(),
|
| 1538 |
+
generator=generator,
|
| 1539 |
+
device=sampled_ids.device,
|
| 1540 |
+
)
|
| 1541 |
+
chosen = candidate_positions[order[:num_mask]]
|
| 1542 |
+
label_mask[row_idx, chosen] = True
|
| 1543 |
+
labels = labels.masked_fill(~label_mask, -100)
|
| 1544 |
+
|
| 1545 |
+
masked_ids = sampled_ids.clone()
|
| 1546 |
+
chosen_positions = torch.where(label_mask)
|
| 1547 |
+
if chosen_positions[0].numel() > 0:
|
| 1548 |
+
random_values = torch.rand(
|
| 1549 |
+
chosen_positions[0].shape,
|
| 1550 |
+
generator=generator,
|
| 1551 |
+
device=sampled_ids.device,
|
| 1552 |
+
)
|
| 1553 |
+
leave = random_values < cfg.bert_leave_prob
|
| 1554 |
+
replace = (random_values >= cfg.bert_leave_prob) & (
|
| 1555 |
+
random_values < cfg.bert_leave_prob + cfg.bert_replace_prob
|
| 1556 |
+
)
|
| 1557 |
+
mask = ~(leave | replace)
|
| 1558 |
+
if mask.any():
|
| 1559 |
+
masked_ids[
|
| 1560 |
+
chosen_positions[0][mask],
|
| 1561 |
+
chosen_positions[1][mask],
|
| 1562 |
+
] = self._ttt_mask_token()
|
| 1563 |
+
if replace.any():
|
| 1564 |
+
replacement_tokens = self._ttt_replacement_tokens(sampled_ids)
|
| 1565 |
+
replacement_idx = torch.randint(
|
| 1566 |
+
replacement_tokens.shape[0],
|
| 1567 |
+
(int(replace.sum().item()),),
|
| 1568 |
+
generator=generator,
|
| 1569 |
+
device=sampled_ids.device,
|
| 1570 |
+
)
|
| 1571 |
+
masked_ids[
|
| 1572 |
+
chosen_positions[0][replace],
|
| 1573 |
+
chosen_positions[1][replace],
|
| 1574 |
+
] = replacement_tokens[replacement_idx]
|
| 1575 |
+
|
| 1576 |
+
return self._ttt_set_input_ids(sampled, masked_ids), labels
|
| 1577 |
+
|
| 1578 |
+
def ttt(
|
| 1579 |
+
self,
|
| 1580 |
+
seq: str | list[str] | None = None,
|
| 1581 |
+
input_ids: torch.Tensor | None = None,
|
| 1582 |
+
ttt_config: TTTConfig | T.Mapping[str, T.Any] | None = None,
|
| 1583 |
+
**kwargs: T.Any,
|
| 1584 |
+
) -> dict[str, T.Any]:
|
| 1585 |
+
if ttt_config is not None:
|
| 1586 |
+
if "_ttt_initialized" in self.__dict__ and self._ttt_initialized:
|
| 1587 |
+
next_cfg = self.ttt_config.merged(ttt_config)
|
| 1588 |
+
assert next_cfg.lora_rank == self.ttt_config.lora_rank, (
|
| 1589 |
+
"Changing lora_rank after TTT initialization is not supported."
|
| 1590 |
+
)
|
| 1591 |
+
assert next_cfg.lora_alpha == self.ttt_config.lora_alpha, (
|
| 1592 |
+
"Changing lora_alpha after TTT initialization is not supported."
|
| 1593 |
+
)
|
| 1594 |
+
assert (
|
| 1595 |
+
next_cfg.lora_target_replace_module
|
| 1596 |
+
== self.ttt_config.lora_target_replace_module
|
| 1597 |
+
), "Changing LoRA target class after TTT initialization is not supported."
|
| 1598 |
+
assert next_cfg.lora_target_modules == self.ttt_config.lora_target_modules, (
|
| 1599 |
+
"Changing LoRA target modules after TTT initialization is not supported."
|
| 1600 |
+
)
|
| 1601 |
+
self._ttt_cfg = next_cfg
|
| 1602 |
+
else:
|
| 1603 |
+
self.init_ttt(ttt_config)
|
| 1604 |
+
|
| 1605 |
+
self._ttt_ensure_initialized()
|
| 1606 |
+
cfg = self.ttt_config
|
| 1607 |
+
if cfg.initial_state_reset:
|
| 1608 |
+
self.ttt_reset()
|
| 1609 |
+
|
| 1610 |
+
device = next(self.parameters()).device
|
| 1611 |
+
tokenized = self._ttt_tokenize(seq=seq, input_ids=input_ids, **kwargs)
|
| 1612 |
+
tokenized = self._ttt_to_device(tokenized, device)
|
| 1613 |
+
generator_device = device if device.type == "cuda" else torch.device("cpu")
|
| 1614 |
+
generator = torch.Generator(device=generator_device)
|
| 1615 |
+
if cfg.seed is not None:
|
| 1616 |
+
generator.manual_seed(cfg.seed)
|
| 1617 |
+
|
| 1618 |
+
module_modes = {module: module.training for module in self.modules()}
|
| 1619 |
+
requires_grad = {param: param.requires_grad for param in self.parameters()}
|
| 1620 |
+
losses: list[float] = []
|
| 1621 |
+
step_metrics: list[dict[str, T.Any]] = []
|
| 1622 |
+
best_state: list[dict[str, torch.Tensor]] | None = None
|
| 1623 |
+
best_metric: float | None = None
|
| 1624 |
+
best_step = 0
|
| 1625 |
+
|
| 1626 |
+
try:
|
| 1627 |
+
self.train()
|
| 1628 |
+
for param in self.parameters():
|
| 1629 |
+
param.requires_grad_(False)
|
| 1630 |
+
for param in self._ttt_lora_parameters():
|
| 1631 |
+
param.requires_grad_(True)
|
| 1632 |
+
|
| 1633 |
+
optimizer = self._ttt_make_optimizer()
|
| 1634 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1635 |
+
total_micro_steps = cfg.steps * cfg.ags
|
| 1636 |
+
for micro_step in range(total_micro_steps):
|
| 1637 |
+
batch, labels = self._ttt_sample_batch(tokenized, generator)
|
| 1638 |
+
logits = self._ttt_predict_logits(batch, **kwargs)
|
| 1639 |
+
labels = labels.to(device=logits.device)
|
| 1640 |
+
loss = F.cross_entropy(
|
| 1641 |
+
logits.reshape(-1, logits.shape[-1]),
|
| 1642 |
+
labels.reshape(-1),
|
| 1643 |
+
ignore_index=-100,
|
| 1644 |
+
)
|
| 1645 |
+
(loss / cfg.ags).backward()
|
| 1646 |
+
if (micro_step + 1) % cfg.ags != 0:
|
| 1647 |
+
continue
|
| 1648 |
+
|
| 1649 |
+
if cfg.gradient_clip:
|
| 1650 |
+
torch.nn.utils.clip_grad_norm_(
|
| 1651 |
+
self._ttt_lora_parameters(),
|
| 1652 |
+
cfg.gradient_clip_max_norm,
|
| 1653 |
+
)
|
| 1654 |
+
optimizer.step()
|
| 1655 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1656 |
+
step = (micro_step + 1) // cfg.ags
|
| 1657 |
+
loss_value = float(loss.detach().item())
|
| 1658 |
+
losses.append(loss_value)
|
| 1659 |
+
if cfg.eval_each_step:
|
| 1660 |
+
metrics, metric = self._ttt_eval_step(
|
| 1661 |
+
step=step,
|
| 1662 |
+
loss=loss_value,
|
| 1663 |
+
seq=seq,
|
| 1664 |
+
input_ids=input_ids,
|
| 1665 |
+
**kwargs,
|
| 1666 |
+
)
|
| 1667 |
+
if len(metrics) > 0:
|
| 1668 |
+
step_metrics.append(metrics)
|
| 1669 |
+
if metric is not None and (
|
| 1670 |
+
best_metric is None or metric > best_metric
|
| 1671 |
+
):
|
| 1672 |
+
best_metric = metric
|
| 1673 |
+
best_step = step
|
| 1674 |
+
best_state = self._ttt_snapshot_lora_state()
|
| 1675 |
+
|
| 1676 |
+
if cfg.automatic_best_state_reset and best_state is not None:
|
| 1677 |
+
self._ttt_restore_lora_state(best_state)
|
| 1678 |
+
finally:
|
| 1679 |
+
for param, value in requires_grad.items():
|
| 1680 |
+
param.requires_grad_(value)
|
| 1681 |
+
for module, training in module_modes.items():
|
| 1682 |
+
module.train(training)
|
| 1683 |
+
|
| 1684 |
+
return {
|
| 1685 |
+
"losses": losses,
|
| 1686 |
+
"step_metrics": step_metrics,
|
| 1687 |
+
"best_step": best_step,
|
| 1688 |
+
"best_metric": best_metric,
|
| 1689 |
+
}
|
| 1690 |
+
|
| 1691 |
"""
|
| 1692 |
ESM++ model implementation.
|
| 1693 |
|
|
|
|
| 2266 |
self,
|
| 2267 |
x: torch.Tensor,
|
| 2268 |
attention_mask: Optional[torch.Tensor] = None,
|
| 2269 |
+
sequence_id: Optional[torch.Tensor] = None,
|
| 2270 |
output_hidden_states: Optional[bool] = False,
|
| 2271 |
output_attentions: Optional[bool] = False,
|
| 2272 |
output_s_max: Optional[bool] = False,
|
| 2273 |
+
esmfold2_hidden_states: bool = False,
|
| 2274 |
) -> TransformerOutput:
|
| 2275 |
hidden_states = () if output_hidden_states else None
|
| 2276 |
attentions = () if output_attentions else None
|
| 2277 |
full_s_max = () if output_s_max else None
|
| 2278 |
|
| 2279 |
+
if sequence_id is None:
|
| 2280 |
+
attention_mask_2d, attention_mask_4d, flex_block_mask = get_attention_mask(
|
| 2281 |
+
effective_backend=self.attention_backend,
|
| 2282 |
+
batch_size=x.shape[0],
|
| 2283 |
+
seq_len=x.shape[1],
|
| 2284 |
+
device=x.device,
|
| 2285 |
+
attention_mask=attention_mask,
|
| 2286 |
+
)
|
| 2287 |
+
else:
|
| 2288 |
+
attention_mask_2d, attention_mask_4d, flex_block_mask = self._sequence_id_attention_masks(
|
| 2289 |
+
sequence_id=sequence_id,
|
| 2290 |
+
batch_size=x.shape[0],
|
| 2291 |
+
seq_len=x.shape[1],
|
| 2292 |
+
device=x.device,
|
| 2293 |
+
)
|
| 2294 |
|
| 2295 |
+
if output_hidden_states and esmfold2_hidden_states:
|
| 2296 |
+
assert hidden_states is not None
|
| 2297 |
+
hidden_states += (x,)
|
| 2298 |
+
|
| 2299 |
+
for block_index, block in enumerate(self.blocks):
|
| 2300 |
if self.gradient_checkpointing and self.training:
|
| 2301 |
x, attn_weights, s_max = self._gradient_checkpointing_func(
|
| 2302 |
block.__call__,
|
|
|
|
| 2321 |
attentions += (attn_weights,)
|
| 2322 |
if output_hidden_states:
|
| 2323 |
assert hidden_states is not None
|
| 2324 |
+
if not esmfold2_hidden_states or block_index < len(self.blocks) - 1:
|
| 2325 |
+
hidden_states += (x,)
|
| 2326 |
if full_s_max is not None:
|
| 2327 |
full_s_max += (s_max,)
|
| 2328 |
|
|
|
|
| 2337 |
s_max=full_s_max,
|
| 2338 |
)
|
| 2339 |
|
| 2340 |
+
def _sequence_id_attention_masks(
|
| 2341 |
+
self,
|
| 2342 |
+
sequence_id: torch.Tensor,
|
| 2343 |
+
batch_size: int,
|
| 2344 |
+
seq_len: int,
|
| 2345 |
+
device: torch.device,
|
| 2346 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[BlockMask]]:
|
| 2347 |
+
assert sequence_id.shape == (batch_size, seq_len), (
|
| 2348 |
+
f"sequence_id shape must be {(batch_size, seq_len)}, got {tuple(sequence_id.shape)}"
|
| 2349 |
+
)
|
| 2350 |
+
if sequence_id.dtype == torch.bool:
|
| 2351 |
+
attention_mask_2d = sequence_id
|
| 2352 |
+
attention_mask_4d = (
|
| 2353 |
+
attention_mask_2d[:, None, :, None]
|
| 2354 |
+
& attention_mask_2d[:, None, None, :]
|
| 2355 |
+
)
|
| 2356 |
+
else:
|
| 2357 |
+
attention_mask_2d = sequence_id != -1
|
| 2358 |
+
attention_mask_4d = (
|
| 2359 |
+
attention_mask_2d[:, None, :, None]
|
| 2360 |
+
& attention_mask_2d[:, None, None, :]
|
| 2361 |
+
& (sequence_id.unsqueeze(-1) == sequence_id.unsqueeze(-2)).unsqueeze(1)
|
| 2362 |
+
)
|
| 2363 |
+
|
| 2364 |
+
if self.attention_backend == AttentionBackend.KERNELS_FLASH:
|
| 2365 |
+
assert sequence_id.dtype == torch.bool, (
|
| 2366 |
+
"ESM++ kernels_flash only supports boolean sequence_id padding masks. "
|
| 2367 |
+
"Use sdpa or flex for chain-aware integer sequence_id masks."
|
| 2368 |
+
)
|
| 2369 |
+
return attention_mask_2d, attention_mask_4d, None
|
| 2370 |
+
|
| 2371 |
+
if self.attention_backend == AttentionBackend.FLEX:
|
| 2372 |
+
assert create_block_mask is not None, (
|
| 2373 |
+
"Flex attention backend requested but torch.create_block_mask is unavailable."
|
| 2374 |
+
)
|
| 2375 |
+
|
| 2376 |
+
if sequence_id.dtype == torch.bool:
|
| 2377 |
+
|
| 2378 |
+
def mask_mod(batch_idx, head_idx, q_idx, kv_idx):
|
| 2379 |
+
return (
|
| 2380 |
+
sequence_id[batch_idx, q_idx]
|
| 2381 |
+
& sequence_id[batch_idx, kv_idx]
|
| 2382 |
+
)
|
| 2383 |
+
|
| 2384 |
+
else:
|
| 2385 |
+
|
| 2386 |
+
def mask_mod(batch_idx, head_idx, q_idx, kv_idx):
|
| 2387 |
+
q_id = sequence_id[batch_idx, q_idx]
|
| 2388 |
+
kv_id = sequence_id[batch_idx, kv_idx]
|
| 2389 |
+
return (q_id != -1) & (q_id == kv_id)
|
| 2390 |
+
|
| 2391 |
+
flex_block_mask = create_block_mask(
|
| 2392 |
+
mask_mod,
|
| 2393 |
+
batch_size,
|
| 2394 |
+
1,
|
| 2395 |
+
seq_len,
|
| 2396 |
+
seq_len,
|
| 2397 |
+
device=device,
|
| 2398 |
+
)
|
| 2399 |
+
return attention_mask_2d, attention_mask_4d, flex_block_mask
|
| 2400 |
+
|
| 2401 |
+
return attention_mask_2d, attention_mask_4d, None
|
| 2402 |
+
|
| 2403 |
|
| 2404 |
class PreTrainedESMplusplusModel(PreTrainedModel):
|
| 2405 |
"""
|
|
|
|
| 2536 |
self,
|
| 2537 |
input_ids: Optional[torch.Tensor] = None,
|
| 2538 |
attention_mask: Optional[torch.Tensor] = None,
|
| 2539 |
+
sequence_id: Optional[torch.Tensor] = None,
|
| 2540 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2541 |
output_attentions: Optional[bool] = None,
|
| 2542 |
output_hidden_states: Optional[bool] = None,
|
| 2543 |
output_s_max: Optional[bool] = False,
|
| 2544 |
+
esmfold2_hidden_states: bool = False,
|
| 2545 |
return_dict: Optional[bool] = None,
|
| 2546 |
**kwargs,
|
| 2547 |
) -> ESMplusplusOutput:
|
|
|
|
| 2556 |
transformer_output = self.transformer(
|
| 2557 |
x=x,
|
| 2558 |
attention_mask=attention_mask,
|
| 2559 |
+
sequence_id=sequence_id,
|
| 2560 |
output_hidden_states=output_hidden_states,
|
| 2561 |
output_attentions=output_attentions,
|
| 2562 |
output_s_max=output_s_max,
|
| 2563 |
+
esmfold2_hidden_states=esmfold2_hidden_states,
|
| 2564 |
)
|
| 2565 |
return ESMplusplusOutput(
|
| 2566 |
last_hidden_state=transformer_output.last_hidden_state,
|
|
|
|
| 2634 |
self,
|
| 2635 |
input_ids: Optional[torch.Tensor] = None,
|
| 2636 |
attention_mask: Optional[torch.Tensor] = None,
|
| 2637 |
+
sequence_id: Optional[torch.Tensor] = None,
|
| 2638 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2639 |
labels: Optional[torch.Tensor] = None,
|
| 2640 |
output_attentions: Optional[bool] = None,
|
| 2641 |
output_hidden_states: Optional[bool] = None,
|
| 2642 |
output_s_max: Optional[bool] = False,
|
| 2643 |
+
esmfold2_hidden_states: bool = False,
|
| 2644 |
return_dict: Optional[bool] = None,
|
| 2645 |
+
compute_logits: bool = True,
|
| 2646 |
**kwargs,
|
| 2647 |
) -> ESMplusplusOutput:
|
| 2648 |
if inputs_embeds is None:
|
|
|
|
| 2653 |
output = self.transformer(
|
| 2654 |
x=x,
|
| 2655 |
attention_mask=attention_mask,
|
| 2656 |
+
sequence_id=sequence_id,
|
| 2657 |
output_hidden_states=output_hidden_states,
|
| 2658 |
output_attentions=output_attentions,
|
| 2659 |
output_s_max=output_s_max,
|
| 2660 |
+
esmfold2_hidden_states=esmfold2_hidden_states,
|
| 2661 |
)
|
| 2662 |
|
| 2663 |
last_hidden_state = output.last_hidden_state
|
| 2664 |
+
logits = self.sequence_head(last_hidden_state) if compute_logits else None
|
| 2665 |
loss = None
|
| 2666 |
if labels is not None:
|
| 2667 |
+
assert logits is not None, "labels require compute_logits=True."
|
| 2668 |
loss = self.ce_loss(logits.view(-1, self.vocab_size), labels.view(-1))
|
| 2669 |
|
| 2670 |
return ESMplusplusOutput(
|
|
|
|
| 2725 |
self,
|
| 2726 |
input_ids: Optional[torch.Tensor] = None,
|
| 2727 |
attention_mask: Optional[torch.Tensor] = None,
|
| 2728 |
+
sequence_id: Optional[torch.Tensor] = None,
|
| 2729 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2730 |
labels: Optional[torch.Tensor] = None,
|
| 2731 |
output_attentions: Optional[bool] = None,
|
|
|
|
| 2737 |
output = super().forward(
|
| 2738 |
input_ids=input_ids,
|
| 2739 |
attention_mask=attention_mask,
|
| 2740 |
+
sequence_id=sequence_id,
|
| 2741 |
inputs_embeds=inputs_embeds,
|
| 2742 |
labels=None,
|
| 2743 |
output_attentions=output_attentions,
|
|
|
|
| 2820 |
self,
|
| 2821 |
input_ids: Optional[torch.Tensor] = None,
|
| 2822 |
attention_mask: Optional[torch.Tensor] = None,
|
| 2823 |
+
sequence_id: Optional[torch.Tensor] = None,
|
| 2824 |
inputs_embeds: Optional[torch.Tensor] = None,
|
| 2825 |
labels: Optional[torch.Tensor] = None,
|
| 2826 |
output_attentions: Optional[bool] = None,
|
|
|
|
| 2832 |
output = super().forward(
|
| 2833 |
input_ids=input_ids,
|
| 2834 |
attention_mask=attention_mask,
|
| 2835 |
+
sequence_id=sequence_id,
|
| 2836 |
inputs_embeds=inputs_embeds,
|
| 2837 |
labels=None,
|
| 2838 |
output_attentions=output_attentions,
|