Transformers
Safetensors
t5
text2text-generation
protein-language-model
fastplms
custom_code
text-generation-inference
Instructions to use Synthyra/ANKH_base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Synthyra/ANKH_base with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained("Synthyra/ANKH_base", trust_remote_code=True) model = AutoModelForSeq2SeqLM.from_pretrained("Synthyra/ANKH_base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload modeling_ankh.py with huggingface_hub
Browse files- modeling_ankh.py +759 -0
modeling_ankh.py
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
from typing import Optional, Tuple, Dict, Any
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from transformers import PreTrainedModel, PretrainedConfig, AutoTokenizer
|
| 9 |
+
from transformers.modeling_outputs import ModelOutput
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from fastplms.attention import (
|
| 13 |
+
AttentionBackend, VALID_ATTENTION_BACKENDS,
|
| 14 |
+
resolve_attention_backend, get_attention_mask,
|
| 15 |
+
_get_flex_attention_fn,
|
| 16 |
+
create_block_mask, flex_attention, BlockMask,
|
| 17 |
+
)
|
| 18 |
+
from fastplms.embedding_mixin import Pooler, EmbeddingMixin, ProteinDataset, parse_fasta, build_collator
|
| 19 |
+
except ImportError:
|
| 20 |
+
pass # Running as HF Hub composite; shared definitions are above
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
# Output dataclasses
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class AnkhEncoderOutput(ModelOutput):
|
| 29 |
+
last_hidden_state: Optional[torch.Tensor] = None
|
| 30 |
+
hidden_states: Optional[Tuple[torch.Tensor, ...]] = None
|
| 31 |
+
attentions: Optional[Tuple[torch.Tensor, ...]] = None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class AnkhMaskedLMOutput(ModelOutput):
|
| 36 |
+
loss: Optional[torch.Tensor] = None
|
| 37 |
+
logits: Optional[torch.Tensor] = None
|
| 38 |
+
last_hidden_state: Optional[torch.Tensor] = None
|
| 39 |
+
hidden_states: Optional[Tuple[torch.Tensor, ...]] = None
|
| 40 |
+
attentions: Optional[Tuple[torch.Tensor, ...]] = None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ---------------------------------------------------------------------------
|
| 44 |
+
# Config
|
| 45 |
+
# ---------------------------------------------------------------------------
|
| 46 |
+
|
| 47 |
+
class FastAnkhConfig(PretrainedConfig):
|
| 48 |
+
model_type = "fast_ankh"
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
vocab_size: int = 144,
|
| 53 |
+
d_model: int = 768,
|
| 54 |
+
d_kv: int = 64,
|
| 55 |
+
d_ff: int = 3072,
|
| 56 |
+
num_heads: int = 12,
|
| 57 |
+
num_layers: int = 48,
|
| 58 |
+
relative_attention_num_buckets: int = 64,
|
| 59 |
+
relative_attention_max_distance: int = 128,
|
| 60 |
+
dense_act_fn: str = "gelu_new",
|
| 61 |
+
layer_norm_epsilon: float = 1e-6,
|
| 62 |
+
initializer_factor: float = 1.0,
|
| 63 |
+
pad_token_id: int = 0,
|
| 64 |
+
eos_token_id: int = 1,
|
| 65 |
+
attn_backend: str = "sdpa",
|
| 66 |
+
**kwargs,
|
| 67 |
+
):
|
| 68 |
+
super().__init__(
|
| 69 |
+
pad_token_id=pad_token_id,
|
| 70 |
+
eos_token_id=eos_token_id,
|
| 71 |
+
**kwargs,
|
| 72 |
+
)
|
| 73 |
+
self.vocab_size = vocab_size
|
| 74 |
+
self.d_model = d_model
|
| 75 |
+
self.d_kv = d_kv
|
| 76 |
+
self.d_ff = d_ff
|
| 77 |
+
self.num_heads = num_heads
|
| 78 |
+
self.num_layers = num_layers
|
| 79 |
+
self.relative_attention_num_buckets = relative_attention_num_buckets
|
| 80 |
+
self.relative_attention_max_distance = relative_attention_max_distance
|
| 81 |
+
self.dense_act_fn = dense_act_fn
|
| 82 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 83 |
+
self.initializer_factor = initializer_factor
|
| 84 |
+
self.tie_word_embeddings = False
|
| 85 |
+
self.attn_backend = attn_backend
|
| 86 |
+
|
| 87 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 88 |
+
output = super().to_dict()
|
| 89 |
+
return output
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ---------------------------------------------------------------------------
|
| 93 |
+
# Submodules
|
| 94 |
+
# ---------------------------------------------------------------------------
|
| 95 |
+
|
| 96 |
+
class AnkhRMSNorm(nn.Module):
|
| 97 |
+
"""T5-style RMS layer norm: scales without mean subtraction or bias."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, hidden_size: int, eps: float = 1e-6):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 102 |
+
self.variance_epsilon = eps
|
| 103 |
+
|
| 104 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 105 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
| 106 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 107 |
+
return self.weight * hidden_states.to(self.weight.dtype)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _gelu_new(x: torch.Tensor) -> torch.Tensor:
|
| 111 |
+
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class AnkhGatedFFN(nn.Module):
|
| 115 |
+
"""T5-style gated feed-forward: activation(wi_0(x)) * wi_1(x) -> wo."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, config: FastAnkhConfig):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 120 |
+
self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
|
| 121 |
+
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
|
| 122 |
+
self.act = F.silu if config.dense_act_fn == "silu" else _gelu_new
|
| 123 |
+
|
| 124 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 125 |
+
return self.wo(self.act(self.wi_0(hidden_states)) * self.wi_1(hidden_states))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ---------------------------------------------------------------------------
|
| 129 |
+
# Attention
|
| 130 |
+
# ---------------------------------------------------------------------------
|
| 131 |
+
|
| 132 |
+
class AnkhSelfAttention(nn.Module):
|
| 133 |
+
"""T5-style self-attention with relative position bias and multi-backend dispatch.
|
| 134 |
+
|
| 135 |
+
Only layer 0 has ``has_relative_attention_bias=True`` and owns the
|
| 136 |
+
``nn.Embedding`` that produces the position bias. All other layers
|
| 137 |
+
receive the precomputed bias through the forward call.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
def __init__(self, config: FastAnkhConfig, has_relative_attention_bias: bool = False):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.num_heads = config.num_heads
|
| 143 |
+
self.d_kv = config.d_kv
|
| 144 |
+
self.inner_dim = self.num_heads * self.d_kv
|
| 145 |
+
self.has_relative_attention_bias = has_relative_attention_bias
|
| 146 |
+
self.relative_attention_num_buckets = config.relative_attention_num_buckets
|
| 147 |
+
self.relative_attention_max_distance = config.relative_attention_max_distance
|
| 148 |
+
|
| 149 |
+
self.q = nn.Linear(config.d_model, self.inner_dim, bias=False)
|
| 150 |
+
self.k = nn.Linear(config.d_model, self.inner_dim, bias=False)
|
| 151 |
+
self.v = nn.Linear(config.d_model, self.inner_dim, bias=False)
|
| 152 |
+
self.o = nn.Linear(self.inner_dim, config.d_model, bias=False)
|
| 153 |
+
self.scale = self.d_kv ** -0.5
|
| 154 |
+
|
| 155 |
+
if self.has_relative_attention_bias:
|
| 156 |
+
self.relative_attention_bias = nn.Embedding(
|
| 157 |
+
config.relative_attention_num_buckets, config.num_heads
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
self.attn_backend: AttentionBackend = AttentionBackend.SDPA # set by encoder
|
| 161 |
+
|
| 162 |
+
# ---- T5 relative position bucketing ----
|
| 163 |
+
|
| 164 |
+
@staticmethod
|
| 165 |
+
def _relative_position_bucket(
|
| 166 |
+
relative_position: torch.Tensor,
|
| 167 |
+
num_buckets: int = 32,
|
| 168 |
+
max_distance: int = 128,
|
| 169 |
+
) -> torch.Tensor:
|
| 170 |
+
"""Bidirectional log-bucketed relative position mapping (T5 style)."""
|
| 171 |
+
# Bidirectional: half buckets for negative, half for positive
|
| 172 |
+
num_buckets //= 2
|
| 173 |
+
relative_buckets = (relative_position > 0).to(torch.long) * num_buckets
|
| 174 |
+
relative_position = torch.abs(relative_position)
|
| 175 |
+
|
| 176 |
+
max_exact = num_buckets // 2
|
| 177 |
+
is_small = relative_position < max_exact
|
| 178 |
+
|
| 179 |
+
relative_position_if_large = max_exact + (
|
| 180 |
+
torch.log(relative_position.float() / max_exact)
|
| 181 |
+
/ math.log(max_distance / max_exact)
|
| 182 |
+
* (num_buckets - max_exact)
|
| 183 |
+
).to(torch.long)
|
| 184 |
+
relative_position_if_large = torch.clamp(relative_position_if_large, max=num_buckets - 1)
|
| 185 |
+
|
| 186 |
+
relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
|
| 187 |
+
return relative_buckets
|
| 188 |
+
|
| 189 |
+
def compute_bias(self, query_length: int, key_length: int, device: torch.device) -> torch.Tensor:
|
| 190 |
+
"""Compute (1, H, Q, K) position bias tensor for SDPA / manual paths."""
|
| 191 |
+
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
|
| 192 |
+
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
|
| 193 |
+
relative_position = memory_position - context_position
|
| 194 |
+
buckets = self._relative_position_bucket(
|
| 195 |
+
relative_position,
|
| 196 |
+
num_buckets=self.relative_attention_num_buckets,
|
| 197 |
+
max_distance=self.relative_attention_max_distance,
|
| 198 |
+
)
|
| 199 |
+
values = self.relative_attention_bias(buckets) # (Q, K, H)
|
| 200 |
+
return values.permute(2, 0, 1).unsqueeze(0) # (1, H, Q, K)
|
| 201 |
+
|
| 202 |
+
# ---- Forward ----
|
| 203 |
+
|
| 204 |
+
def forward(
|
| 205 |
+
self,
|
| 206 |
+
hidden_states: torch.Tensor,
|
| 207 |
+
attention_mask_2d: torch.Tensor | None = None,
|
| 208 |
+
attention_mask_4d: torch.Tensor | None = None,
|
| 209 |
+
flex_block_mask: "BlockMask | None" = None,
|
| 210 |
+
position_bias: torch.Tensor | None = None,
|
| 211 |
+
flex_score_mod=None,
|
| 212 |
+
output_attentions: bool = False,
|
| 213 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
| 214 |
+
"""Returns (attn_output, attn_weights_or_none, position_bias)."""
|
| 215 |
+
batch_size, seq_length = hidden_states.shape[:2]
|
| 216 |
+
hidden_shape = (batch_size, seq_length, self.num_heads, self.d_kv)
|
| 217 |
+
|
| 218 |
+
query_BHLD = self.q(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 219 |
+
key_BHLD = self.k(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 220 |
+
value_BHLD = self.v(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 221 |
+
|
| 222 |
+
# Compute position bias on first layer (SDPA/manual only; flex uses score_mod)
|
| 223 |
+
if position_bias is None and self.has_relative_attention_bias and self.attn_backend != AttentionBackend.FLEX:
|
| 224 |
+
position_bias = self.compute_bias(seq_length, seq_length, hidden_states.device)
|
| 225 |
+
# Fold padding mask into position bias so layers don't need separate mask
|
| 226 |
+
if attention_mask_4d is not None:
|
| 227 |
+
position_bias = position_bias + attention_mask_4d.masked_fill(
|
| 228 |
+
attention_mask_4d.logical_not(), float("-inf")
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
if output_attentions:
|
| 232 |
+
attn_output, attn_weights = self._manual_attn(query_BHLD, key_BHLD, value_BHLD, position_bias)
|
| 233 |
+
return attn_output, attn_weights, position_bias
|
| 234 |
+
|
| 235 |
+
if self.attn_backend == AttentionBackend.FLEX:
|
| 236 |
+
attn_output = self._flex_attn(query_BHLD, key_BHLD, value_BHLD, flex_block_mask, flex_score_mod)
|
| 237 |
+
elif self.attn_backend == AttentionBackend.SDPA:
|
| 238 |
+
attn_output = self._sdpa_attn(query_BHLD, key_BHLD, value_BHLD, position_bias)
|
| 239 |
+
else:
|
| 240 |
+
raise AssertionError(f"Unsupported backend for ANKH: {self.attn_backend}")
|
| 241 |
+
|
| 242 |
+
return attn_output, None, position_bias
|
| 243 |
+
|
| 244 |
+
def _sdpa_attn(
|
| 245 |
+
self,
|
| 246 |
+
query_BHLD: torch.Tensor,
|
| 247 |
+
key_BHLD: torch.Tensor,
|
| 248 |
+
value_BHLD: torch.Tensor,
|
| 249 |
+
position_bias: torch.Tensor | None,
|
| 250 |
+
) -> torch.Tensor:
|
| 251 |
+
# SDPA: position_bias is (1, H, Q, K) additive bias (includes padding mask)
|
| 252 |
+
context_BHLD = F.scaled_dot_product_attention(
|
| 253 |
+
query_BHLD, key_BHLD, value_BHLD,
|
| 254 |
+
attn_mask=position_bias,
|
| 255 |
+
scale=self.scale,
|
| 256 |
+
)
|
| 257 |
+
return context_BHLD.transpose(1, 2).contiguous().view(
|
| 258 |
+
query_BHLD.shape[0], -1, self.inner_dim
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def _flex_attn(
|
| 262 |
+
self,
|
| 263 |
+
query_BHLD: torch.Tensor,
|
| 264 |
+
key_BHLD: torch.Tensor,
|
| 265 |
+
value_BHLD: torch.Tensor,
|
| 266 |
+
flex_block_mask: "BlockMask | None",
|
| 267 |
+
flex_score_mod,
|
| 268 |
+
) -> torch.Tensor:
|
| 269 |
+
assert flex_attention is not None, "Flex attention is not available."
|
| 270 |
+
fn = _get_flex_attention_fn()
|
| 271 |
+
context_BHLD = fn(
|
| 272 |
+
query_BHLD, key_BHLD, value_BHLD,
|
| 273 |
+
score_mod=flex_score_mod,
|
| 274 |
+
block_mask=flex_block_mask,
|
| 275 |
+
scale=self.scale,
|
| 276 |
+
)
|
| 277 |
+
return context_BHLD.transpose(1, 2).contiguous().view(
|
| 278 |
+
query_BHLD.shape[0], -1, self.inner_dim
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
def _manual_attn(
|
| 282 |
+
self,
|
| 283 |
+
query_BHLD: torch.Tensor,
|
| 284 |
+
key_BHLD: torch.Tensor,
|
| 285 |
+
value_BHLD: torch.Tensor,
|
| 286 |
+
position_bias: torch.Tensor | None,
|
| 287 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 288 |
+
attn_weights = torch.matmul(query_BHLD, key_BHLD.transpose(-1, -2)) * self.scale
|
| 289 |
+
if position_bias is not None:
|
| 290 |
+
attn_weights = attn_weights + position_bias
|
| 291 |
+
attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(attn_weights)
|
| 292 |
+
context_BHLD = torch.matmul(attn_weights, value_BHLD)
|
| 293 |
+
attn_output = context_BHLD.transpose(1, 2).contiguous().view(
|
| 294 |
+
query_BHLD.shape[0], -1, self.inner_dim
|
| 295 |
+
)
|
| 296 |
+
return attn_output, attn_weights
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# ---------------------------------------------------------------------------
|
| 300 |
+
# Encoder block & stack
|
| 301 |
+
# ---------------------------------------------------------------------------
|
| 302 |
+
|
| 303 |
+
class AnkhBlock(nn.Module):
|
| 304 |
+
def __init__(self, config: FastAnkhConfig, has_relative_attention_bias: bool = False):
|
| 305 |
+
super().__init__()
|
| 306 |
+
self.attention = AnkhSelfAttention(config, has_relative_attention_bias)
|
| 307 |
+
self.attention_norm = AnkhRMSNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 308 |
+
self.ffn = AnkhGatedFFN(config)
|
| 309 |
+
self.ffn_norm = AnkhRMSNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 310 |
+
|
| 311 |
+
def forward(
|
| 312 |
+
self,
|
| 313 |
+
hidden_states: torch.Tensor,
|
| 314 |
+
attention_mask_2d: torch.Tensor | None = None,
|
| 315 |
+
attention_mask_4d: torch.Tensor | None = None,
|
| 316 |
+
flex_block_mask: "BlockMask | None" = None,
|
| 317 |
+
position_bias: torch.Tensor | None = None,
|
| 318 |
+
flex_score_mod=None,
|
| 319 |
+
output_attentions: bool = False,
|
| 320 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
| 321 |
+
# Pre-norm self-attention
|
| 322 |
+
normed = self.attention_norm(hidden_states)
|
| 323 |
+
attn_output, attn_weights, position_bias = self.attention(
|
| 324 |
+
normed,
|
| 325 |
+
attention_mask_2d=attention_mask_2d,
|
| 326 |
+
attention_mask_4d=attention_mask_4d,
|
| 327 |
+
flex_block_mask=flex_block_mask,
|
| 328 |
+
position_bias=position_bias,
|
| 329 |
+
flex_score_mod=flex_score_mod,
|
| 330 |
+
output_attentions=output_attentions,
|
| 331 |
+
)
|
| 332 |
+
hidden_states = hidden_states + attn_output
|
| 333 |
+
|
| 334 |
+
# Pre-norm FFN
|
| 335 |
+
normed = self.ffn_norm(hidden_states)
|
| 336 |
+
hidden_states = hidden_states + self.ffn(normed)
|
| 337 |
+
|
| 338 |
+
return hidden_states, attn_weights, position_bias
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class AnkhEncoder(nn.Module):
|
| 342 |
+
def __init__(self, config: FastAnkhConfig):
|
| 343 |
+
super().__init__()
|
| 344 |
+
self.config = config
|
| 345 |
+
resolved = resolve_attention_backend(config.attn_backend)
|
| 346 |
+
# ANKH uses relative position bias; flash attention kernels don't support arbitrary biases.
|
| 347 |
+
if resolved == AttentionBackend.KERNELS_FLASH:
|
| 348 |
+
print("ANKH: kernels_flash not supported (relative position bias); falling back to flex/sdpa")
|
| 349 |
+
resolved = AttentionBackend.FLEX if flex_attention is not None else AttentionBackend.SDPA
|
| 350 |
+
self.attention_backend = resolved
|
| 351 |
+
|
| 352 |
+
self.layer = nn.ModuleList([
|
| 353 |
+
AnkhBlock(config, has_relative_attention_bias=(i == 0))
|
| 354 |
+
for i in range(config.num_layers)
|
| 355 |
+
])
|
| 356 |
+
# Propagate resolved backend to all attention modules
|
| 357 |
+
for block in self.layer:
|
| 358 |
+
block.attention.attn_backend = self.attention_backend
|
| 359 |
+
|
| 360 |
+
self.final_layer_norm = AnkhRMSNorm(config.d_model, eps=config.layer_norm_epsilon)
|
| 361 |
+
self.gradient_checkpointing = False
|
| 362 |
+
|
| 363 |
+
@torch.compiler.disable
|
| 364 |
+
def _compute_materialized_bias(self, seq_len: int, device: torch.device) -> torch.Tensor:
|
| 365 |
+
"""Precompute full (Q, K, H) bias tensor for flex score_mod lookup.
|
| 366 |
+
|
| 367 |
+
Materializing the bias and indexing in score_mod is ~2.4x faster than
|
| 368 |
+
computing buckets on-the-fly (PyTorch issue #138493).
|
| 369 |
+
"""
|
| 370 |
+
bias_embedding = self.layer[0].attention.relative_attention_bias
|
| 371 |
+
context_position = torch.arange(seq_len, dtype=torch.long, device=device)[:, None]
|
| 372 |
+
memory_position = torch.arange(seq_len, dtype=torch.long, device=device)[None, :]
|
| 373 |
+
relative_position = memory_position - context_position
|
| 374 |
+
buckets = AnkhSelfAttention._relative_position_bucket(
|
| 375 |
+
relative_position,
|
| 376 |
+
num_buckets=self.config.relative_attention_num_buckets,
|
| 377 |
+
max_distance=self.config.relative_attention_max_distance,
|
| 378 |
+
)
|
| 379 |
+
return bias_embedding(buckets) # (Q, K, H)
|
| 380 |
+
|
| 381 |
+
def _build_flex_score_mod(self, seq_len: int, device: torch.device):
|
| 382 |
+
"""Build score_mod closure that reads from materialized bias tensor."""
|
| 383 |
+
bias = self._compute_materialized_bias(seq_len, device)
|
| 384 |
+
|
| 385 |
+
def score_mod(score, b, h, q_idx, kv_idx):
|
| 386 |
+
return score + bias[q_idx, kv_idx, h]
|
| 387 |
+
|
| 388 |
+
return score_mod
|
| 389 |
+
|
| 390 |
+
def forward(
|
| 391 |
+
self,
|
| 392 |
+
hidden_states: torch.Tensor,
|
| 393 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 394 |
+
output_hidden_states: bool = False,
|
| 395 |
+
output_attentions: bool = False,
|
| 396 |
+
) -> AnkhEncoderOutput:
|
| 397 |
+
all_hidden_states = () if output_hidden_states else None
|
| 398 |
+
all_attentions = () if output_attentions else None
|
| 399 |
+
|
| 400 |
+
batch_size, seq_len = hidden_states.shape[:2]
|
| 401 |
+
attention_mask_2d, attention_mask_4d, flex_block_mask = get_attention_mask(
|
| 402 |
+
effective_backend=self.attention_backend,
|
| 403 |
+
batch_size=batch_size,
|
| 404 |
+
seq_len=seq_len,
|
| 405 |
+
device=hidden_states.device,
|
| 406 |
+
attention_mask=attention_mask,
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
# Build flex score_mod or let SDPA compute position_bias in layer 0
|
| 410 |
+
flex_score_mod = None
|
| 411 |
+
position_bias = None
|
| 412 |
+
if self.attention_backend == AttentionBackend.FLEX:
|
| 413 |
+
flex_score_mod = self._build_flex_score_mod(seq_len, hidden_states.device)
|
| 414 |
+
|
| 415 |
+
for layer_module in self.layer:
|
| 416 |
+
if output_hidden_states:
|
| 417 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 418 |
+
|
| 419 |
+
if self.gradient_checkpointing and self.training:
|
| 420 |
+
hidden_states, attn_weights, position_bias = self._gradient_checkpointing_func(
|
| 421 |
+
layer_module.__call__,
|
| 422 |
+
hidden_states,
|
| 423 |
+
attention_mask_2d,
|
| 424 |
+
attention_mask_4d,
|
| 425 |
+
flex_block_mask,
|
| 426 |
+
position_bias,
|
| 427 |
+
flex_score_mod,
|
| 428 |
+
output_attentions,
|
| 429 |
+
)
|
| 430 |
+
else:
|
| 431 |
+
hidden_states, attn_weights, position_bias = layer_module(
|
| 432 |
+
hidden_states,
|
| 433 |
+
attention_mask_2d=attention_mask_2d,
|
| 434 |
+
attention_mask_4d=attention_mask_4d,
|
| 435 |
+
flex_block_mask=flex_block_mask,
|
| 436 |
+
position_bias=position_bias,
|
| 437 |
+
flex_score_mod=flex_score_mod,
|
| 438 |
+
output_attentions=output_attentions,
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
if all_attentions is not None:
|
| 442 |
+
all_attentions = all_attentions + (attn_weights,)
|
| 443 |
+
|
| 444 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 445 |
+
|
| 446 |
+
if output_hidden_states:
|
| 447 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 448 |
+
|
| 449 |
+
return AnkhEncoderOutput(
|
| 450 |
+
last_hidden_state=hidden_states,
|
| 451 |
+
hidden_states=all_hidden_states,
|
| 452 |
+
attentions=all_attentions,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
# ---------------------------------------------------------------------------
|
| 457 |
+
# PreTrainedModel base
|
| 458 |
+
# ---------------------------------------------------------------------------
|
| 459 |
+
|
| 460 |
+
class AnkhPreTrainedModel(PreTrainedModel):
|
| 461 |
+
config_class = FastAnkhConfig
|
| 462 |
+
base_model_prefix = "ankh"
|
| 463 |
+
supports_gradient_checkpointing = True
|
| 464 |
+
_no_split_modules = ["AnkhBlock"]
|
| 465 |
+
|
| 466 |
+
@classmethod
|
| 467 |
+
def is_remote_code(cls) -> bool:
|
| 468 |
+
return True
|
| 469 |
+
|
| 470 |
+
@torch.no_grad()
|
| 471 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 472 |
+
factor = self.config.initializer_factor
|
| 473 |
+
if isinstance(module, nn.Linear):
|
| 474 |
+
module.weight.data.normal_(mean=0.0, std=factor * (self.config.d_model ** -0.5))
|
| 475 |
+
elif isinstance(module, nn.Embedding):
|
| 476 |
+
module.weight.data.normal_(mean=0.0, std=factor * 1.0)
|
| 477 |
+
elif isinstance(module, AnkhRMSNorm):
|
| 478 |
+
module.weight.data.fill_(1.0)
|
| 479 |
+
|
| 480 |
+
def post_init(self) -> None:
|
| 481 |
+
super().post_init()
|
| 482 |
+
|
| 483 |
+
def get_output_embeddings(self):
|
| 484 |
+
return None
|
| 485 |
+
|
| 486 |
+
@property
|
| 487 |
+
def attn_backend(self) -> str:
|
| 488 |
+
return self.config.attn_backend
|
| 489 |
+
|
| 490 |
+
@attn_backend.setter
|
| 491 |
+
def attn_backend(self, backend: str) -> None:
|
| 492 |
+
assert backend in VALID_ATTENTION_BACKENDS, (
|
| 493 |
+
f"Unsupported attn_backend: {backend}. Expected one of {VALID_ATTENTION_BACKENDS}."
|
| 494 |
+
)
|
| 495 |
+
self.config.attn_backend = backend
|
| 496 |
+
resolved = resolve_attention_backend(backend)
|
| 497 |
+
if resolved == AttentionBackend.KERNELS_FLASH:
|
| 498 |
+
print("ANKH: kernels_flash -> flex/sdpa fallback")
|
| 499 |
+
resolved = AttentionBackend.FLEX if flex_attention is not None else AttentionBackend.SDPA
|
| 500 |
+
for module in self.modules():
|
| 501 |
+
if isinstance(module, AnkhEncoder):
|
| 502 |
+
module.attention_backend = resolved
|
| 503 |
+
for block in module.layer:
|
| 504 |
+
block.attention.attn_backend = resolved
|
| 505 |
+
elif isinstance(module, AnkhSelfAttention):
|
| 506 |
+
module.attn_backend = resolved
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# ---------------------------------------------------------------------------
|
| 510 |
+
# Model classes
|
| 511 |
+
# ---------------------------------------------------------------------------
|
| 512 |
+
|
| 513 |
+
class FastAnkhModel(AnkhPreTrainedModel, EmbeddingMixin):
|
| 514 |
+
"""ANKH encoder model for embedding extraction."""
|
| 515 |
+
|
| 516 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 517 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 518 |
+
self.config = config
|
| 519 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
|
| 520 |
+
self.encoder = AnkhEncoder(config)
|
| 521 |
+
self.tokenizer = AutoTokenizer.from_pretrained("ElnaggarLab/ankh-base")
|
| 522 |
+
self.post_init()
|
| 523 |
+
|
| 524 |
+
def get_input_embeddings(self):
|
| 525 |
+
return self.embed_tokens
|
| 526 |
+
|
| 527 |
+
def set_input_embeddings(self, value):
|
| 528 |
+
self.embed_tokens = value
|
| 529 |
+
|
| 530 |
+
def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 531 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 532 |
+
encoder_output = self.encoder(hidden_states, attention_mask=attention_mask)
|
| 533 |
+
return encoder_output.last_hidden_state
|
| 534 |
+
|
| 535 |
+
def forward(
|
| 536 |
+
self,
|
| 537 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 538 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 539 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 540 |
+
output_hidden_states: Optional[bool] = None,
|
| 541 |
+
output_attentions: Optional[bool] = None,
|
| 542 |
+
**kwargs,
|
| 543 |
+
) -> AnkhEncoderOutput:
|
| 544 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 545 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 546 |
+
|
| 547 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 548 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 549 |
+
elif input_ids is not None:
|
| 550 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 551 |
+
elif inputs_embeds is not None:
|
| 552 |
+
hidden_states = inputs_embeds
|
| 553 |
+
else:
|
| 554 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 555 |
+
|
| 556 |
+
return self.encoder(
|
| 557 |
+
hidden_states,
|
| 558 |
+
attention_mask=attention_mask,
|
| 559 |
+
output_hidden_states=output_hidden_states or False,
|
| 560 |
+
output_attentions=output_attentions or False,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class FastAnkhForMaskedLM(AnkhPreTrainedModel, EmbeddingMixin):
|
| 565 |
+
"""ANKH encoder with LM head for masked language modeling.
|
| 566 |
+
|
| 567 |
+
NOTE: The LM head is initialized from the shared embedding weights but is NOT
|
| 568 |
+
tied. The original ANKH models were trained with T5's span corruption objective
|
| 569 |
+
using an encoder-decoder architecture. This encoder-only MaskedLM variant is
|
| 570 |
+
not pre-trained for standard MLM and requires additional fine-tuning.
|
| 571 |
+
"""
|
| 572 |
+
|
| 573 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 574 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 575 |
+
self.config = config
|
| 576 |
+
self.ankh = FastAnkhModel(config)
|
| 577 |
+
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 578 |
+
self.loss_fct = nn.CrossEntropyLoss()
|
| 579 |
+
self.post_init()
|
| 580 |
+
|
| 581 |
+
@property
|
| 582 |
+
def tokenizer(self):
|
| 583 |
+
return self.ankh.tokenizer
|
| 584 |
+
|
| 585 |
+
def get_input_embeddings(self):
|
| 586 |
+
return self.ankh.embed_tokens
|
| 587 |
+
|
| 588 |
+
def set_input_embeddings(self, value):
|
| 589 |
+
self.ankh.embed_tokens = value
|
| 590 |
+
|
| 591 |
+
def get_output_embeddings(self):
|
| 592 |
+
return self.lm_head
|
| 593 |
+
|
| 594 |
+
def set_output_embeddings(self, new_embeddings):
|
| 595 |
+
self.lm_head = new_embeddings
|
| 596 |
+
|
| 597 |
+
def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 598 |
+
return self.ankh._embed(input_ids, attention_mask)
|
| 599 |
+
|
| 600 |
+
def forward(
|
| 601 |
+
self,
|
| 602 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 603 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 604 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 605 |
+
labels: Optional[torch.Tensor] = None,
|
| 606 |
+
output_hidden_states: Optional[bool] = None,
|
| 607 |
+
output_attentions: Optional[bool] = None,
|
| 608 |
+
**kwargs,
|
| 609 |
+
) -> AnkhMaskedLMOutput:
|
| 610 |
+
outputs = self.ankh(
|
| 611 |
+
input_ids,
|
| 612 |
+
attention_mask=attention_mask,
|
| 613 |
+
inputs_embeds=inputs_embeds,
|
| 614 |
+
output_hidden_states=output_hidden_states,
|
| 615 |
+
output_attentions=output_attentions,
|
| 616 |
+
)
|
| 617 |
+
sequence_output = outputs.last_hidden_state
|
| 618 |
+
logits = self.lm_head(sequence_output)
|
| 619 |
+
|
| 620 |
+
loss = None
|
| 621 |
+
if labels is not None:
|
| 622 |
+
labels = labels.to(logits.device)
|
| 623 |
+
loss = self.loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 624 |
+
|
| 625 |
+
return AnkhMaskedLMOutput(
|
| 626 |
+
loss=loss,
|
| 627 |
+
logits=logits,
|
| 628 |
+
last_hidden_state=sequence_output,
|
| 629 |
+
hidden_states=outputs.hidden_states,
|
| 630 |
+
attentions=outputs.attentions,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class FastAnkhForSequenceClassification(AnkhPreTrainedModel, EmbeddingMixin):
|
| 635 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 636 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 637 |
+
self.num_labels = config.num_labels
|
| 638 |
+
self.config = config
|
| 639 |
+
self.ankh = FastAnkhModel(config)
|
| 640 |
+
self.classifier = nn.Linear(config.d_model, config.num_labels)
|
| 641 |
+
self.mse = nn.MSELoss()
|
| 642 |
+
self.ce = nn.CrossEntropyLoss()
|
| 643 |
+
self.bce = nn.BCEWithLogitsLoss()
|
| 644 |
+
self.post_init()
|
| 645 |
+
|
| 646 |
+
@property
|
| 647 |
+
def tokenizer(self):
|
| 648 |
+
return self.ankh.tokenizer
|
| 649 |
+
|
| 650 |
+
def get_input_embeddings(self):
|
| 651 |
+
return self.ankh.embed_tokens
|
| 652 |
+
|
| 653 |
+
def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 654 |
+
return self.ankh._embed(input_ids, attention_mask)
|
| 655 |
+
|
| 656 |
+
def forward(
|
| 657 |
+
self,
|
| 658 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 659 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 660 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 661 |
+
labels: Optional[torch.Tensor] = None,
|
| 662 |
+
output_hidden_states: Optional[bool] = None,
|
| 663 |
+
output_attentions: Optional[bool] = None,
|
| 664 |
+
**kwargs,
|
| 665 |
+
) -> AnkhMaskedLMOutput:
|
| 666 |
+
outputs = self.ankh(
|
| 667 |
+
input_ids,
|
| 668 |
+
attention_mask=attention_mask,
|
| 669 |
+
inputs_embeds=inputs_embeds,
|
| 670 |
+
output_hidden_states=output_hidden_states,
|
| 671 |
+
output_attentions=output_attentions,
|
| 672 |
+
)
|
| 673 |
+
# Pool: mean over non-padding tokens
|
| 674 |
+
sequence_output = outputs.last_hidden_state
|
| 675 |
+
if attention_mask is not None:
|
| 676 |
+
mask = attention_mask.unsqueeze(-1).to(sequence_output.dtype)
|
| 677 |
+
pooled = (sequence_output * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1)
|
| 678 |
+
else:
|
| 679 |
+
pooled = sequence_output.mean(dim=1)
|
| 680 |
+
logits = self.classifier(pooled)
|
| 681 |
+
|
| 682 |
+
loss = None
|
| 683 |
+
if labels is not None:
|
| 684 |
+
labels = labels.to(logits.device)
|
| 685 |
+
if self.config.problem_type is None:
|
| 686 |
+
if self.num_labels == 1:
|
| 687 |
+
self.config.problem_type = "regression"
|
| 688 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 689 |
+
self.config.problem_type = "single_label_classification"
|
| 690 |
+
else:
|
| 691 |
+
self.config.problem_type = "multi_label_classification"
|
| 692 |
+
|
| 693 |
+
if self.config.problem_type == "regression":
|
| 694 |
+
loss = self.mse(logits.squeeze(), labels.squeeze()) if self.num_labels == 1 else self.mse(logits, labels)
|
| 695 |
+
elif self.config.problem_type == "single_label_classification":
|
| 696 |
+
loss = self.ce(logits.view(-1, self.num_labels), labels.view(-1))
|
| 697 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 698 |
+
loss = self.bce(logits, labels)
|
| 699 |
+
|
| 700 |
+
return AnkhMaskedLMOutput(
|
| 701 |
+
loss=loss,
|
| 702 |
+
logits=logits,
|
| 703 |
+
last_hidden_state=sequence_output,
|
| 704 |
+
hidden_states=outputs.hidden_states,
|
| 705 |
+
attentions=outputs.attentions,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class FastAnkhForTokenClassification(AnkhPreTrainedModel, EmbeddingMixin):
|
| 710 |
+
def __init__(self, config: FastAnkhConfig, **kwargs):
|
| 711 |
+
AnkhPreTrainedModel.__init__(self, config, **kwargs)
|
| 712 |
+
self.num_labels = config.num_labels
|
| 713 |
+
self.ankh = FastAnkhModel(config)
|
| 714 |
+
self.classifier = nn.Linear(config.d_model, config.num_labels)
|
| 715 |
+
self.loss_fct = nn.CrossEntropyLoss()
|
| 716 |
+
self.post_init()
|
| 717 |
+
|
| 718 |
+
@property
|
| 719 |
+
def tokenizer(self):
|
| 720 |
+
return self.ankh.tokenizer
|
| 721 |
+
|
| 722 |
+
def get_input_embeddings(self):
|
| 723 |
+
return self.ankh.embed_tokens
|
| 724 |
+
|
| 725 |
+
def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 726 |
+
return self.ankh._embed(input_ids, attention_mask)
|
| 727 |
+
|
| 728 |
+
def forward(
|
| 729 |
+
self,
|
| 730 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 731 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 732 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 733 |
+
labels: Optional[torch.Tensor] = None,
|
| 734 |
+
output_hidden_states: Optional[bool] = None,
|
| 735 |
+
output_attentions: Optional[bool] = None,
|
| 736 |
+
**kwargs,
|
| 737 |
+
) -> AnkhMaskedLMOutput:
|
| 738 |
+
outputs = self.ankh(
|
| 739 |
+
input_ids,
|
| 740 |
+
attention_mask=attention_mask,
|
| 741 |
+
inputs_embeds=inputs_embeds,
|
| 742 |
+
output_hidden_states=output_hidden_states,
|
| 743 |
+
output_attentions=output_attentions,
|
| 744 |
+
)
|
| 745 |
+
sequence_output = outputs.last_hidden_state
|
| 746 |
+
logits = self.classifier(sequence_output)
|
| 747 |
+
|
| 748 |
+
loss = None
|
| 749 |
+
if labels is not None:
|
| 750 |
+
labels = labels.to(logits.device)
|
| 751 |
+
loss = self.loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 752 |
+
|
| 753 |
+
return AnkhMaskedLMOutput(
|
| 754 |
+
loss=loss,
|
| 755 |
+
logits=logits,
|
| 756 |
+
last_hidden_state=sequence_output,
|
| 757 |
+
hidden_states=outputs.hidden_states,
|
| 758 |
+
attentions=outputs.attentions,
|
| 759 |
+
)
|