Update modeling_opensci.py
Browse files- modeling_opensci.py +75 -29
modeling_opensci.py
CHANGED
|
@@ -27,18 +27,19 @@ from transformers.activations import ACT2FN
|
|
| 27 |
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
| 28 |
from transformers.generation import GenerationMixin
|
| 29 |
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 30 |
-
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 31 |
from transformers.modeling_outputs import (
|
| 32 |
BaseModelOutputWithPast,
|
| 33 |
CausalLMOutputWithPast,
|
|
|
|
| 34 |
SequenceClassifierOutputWithPast,
|
|
|
|
| 35 |
)
|
| 36 |
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 37 |
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 38 |
-
from transformers.processing_utils import Unpack
|
| 39 |
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 40 |
from transformers.utils import (
|
| 41 |
-
|
| 42 |
add_start_docstrings,
|
| 43 |
add_start_docstrings_to_model_forward,
|
| 44 |
logging,
|
|
@@ -47,6 +48,20 @@ from transformers.utils import (
|
|
| 47 |
from transformers.utils.deprecation import deprecate_kwarg
|
| 48 |
from .configuration_opensci import OpensciConfig
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
logger = logging.get_logger(__name__)
|
| 52 |
|
|
@@ -88,7 +103,20 @@ class OpensciRotaryEmbedding(nn.Module):
|
|
| 88 |
self.original_max_seq_len = config.max_position_embeddings
|
| 89 |
|
| 90 |
self.config = config
|
| 91 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 94 |
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
@@ -118,6 +146,14 @@ class OpensciRotaryEmbedding(nn.Module):
|
|
| 118 |
if "dynamic" in self.rope_type:
|
| 119 |
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
# Core RoPE block
|
| 122 |
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 123 |
position_ids_expanded = position_ids[:, None, :].float()
|
|
@@ -262,7 +298,7 @@ class OpensciAttention(nn.Module):
|
|
| 262 |
attention_mask: Optional[torch.Tensor],
|
| 263 |
past_key_value: Optional[Cache] = None,
|
| 264 |
cache_position: Optional[torch.LongTensor] = None,
|
| 265 |
-
**kwargs: Unpack[FlashAttentionKwargs],
|
| 266 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 267 |
input_shape = hidden_states.shape[:-1]
|
| 268 |
hidden_shape = (*input_shape, -1, self.head_dim)
|
|
@@ -283,14 +319,24 @@ class OpensciAttention(nn.Module):
|
|
| 283 |
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 284 |
|
| 285 |
attention_interface: Callable = eager_attention_forward
|
| 286 |
-
if self.config._attn_implementation
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
)
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
| 294 |
|
| 295 |
attn_output, attn_weights = attention_interface(
|
| 296 |
self,
|
|
@@ -300,7 +346,7 @@ class OpensciAttention(nn.Module):
|
|
| 300 |
attention_mask,
|
| 301 |
dropout=0.0 if not self.training else self.attention_dropout,
|
| 302 |
scaling=self.scaling,
|
| 303 |
-
**kwargs,
|
| 304 |
)
|
| 305 |
|
| 306 |
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
|
@@ -329,7 +375,7 @@ class OpensciDecoderLayer(nn.Module):
|
|
| 329 |
use_cache: Optional[bool] = False,
|
| 330 |
cache_position: Optional[torch.LongTensor] = None,
|
| 331 |
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 332 |
-
**kwargs: Unpack[FlashAttentionKwargs],
|
| 333 |
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 334 |
residual = hidden_states
|
| 335 |
|
|
@@ -339,13 +385,13 @@ class OpensciDecoderLayer(nn.Module):
|
|
| 339 |
hidden_states, self_attn_weights = self.self_attn(
|
| 340 |
hidden_states=hidden_states,
|
| 341 |
attention_mask=attention_mask,
|
| 342 |
-
position_ids=position_ids,
|
| 343 |
past_key_value=past_key_value,
|
| 344 |
-
output_attentions=output_attentions,
|
| 345 |
-
use_cache=use_cache,
|
| 346 |
cache_position=cache_position,
|
| 347 |
position_embeddings=position_embeddings,
|
| 348 |
-
**kwargs,
|
| 349 |
)
|
| 350 |
hidden_states = residual + hidden_states
|
| 351 |
|
|
@@ -496,8 +542,8 @@ class OpensciModel(OpensciPreTrainedModel):
|
|
| 496 |
config: OpensciConfig
|
| 497 |
"""
|
| 498 |
|
| 499 |
-
def __init__(self, config: OpensciConfig):
|
| 500 |
-
super().__init__(config)
|
| 501 |
self.padding_idx = config.pad_token_id
|
| 502 |
self.vocab_size = config.vocab_size
|
| 503 |
|
|
@@ -531,7 +577,7 @@ class OpensciModel(OpensciPreTrainedModel):
|
|
| 531 |
output_hidden_states: Optional[bool] = None,
|
| 532 |
return_dict: Optional[bool] = None,
|
| 533 |
cache_position: Optional[torch.LongTensor] = None,
|
| 534 |
-
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 535 |
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 536 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 537 |
output_hidden_states = (
|
|
@@ -603,7 +649,7 @@ class OpensciModel(OpensciPreTrainedModel):
|
|
| 603 |
use_cache=use_cache,
|
| 604 |
cache_position=cache_position,
|
| 605 |
position_embeddings=position_embeddings,
|
| 606 |
-
**flash_attn_kwargs,
|
| 607 |
)
|
| 608 |
|
| 609 |
hidden_states = layer_outputs[0]
|
|
@@ -747,15 +793,15 @@ class OpensciModel(OpensciPreTrainedModel):
|
|
| 747 |
return causal_mask
|
| 748 |
|
| 749 |
|
| 750 |
-
class KwargsForCausalLM(
|
| 751 |
|
| 752 |
|
| 753 |
class OpensciForCausalLM(OpensciPreTrainedModel, GenerationMixin):
|
| 754 |
-
_tied_weights_keys =
|
| 755 |
_tp_plan = {"lm_head": "colwise_rep"}
|
| 756 |
|
| 757 |
-
def __init__(self, config):
|
| 758 |
-
super().__init__(config)
|
| 759 |
self.model = OpensciModel(config)
|
| 760 |
self.vocab_size = config.vocab_size
|
| 761 |
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
|
@@ -891,8 +937,8 @@ class OpensciForCausalLM(OpensciPreTrainedModel, GenerationMixin):
|
|
| 891 |
Opensci_START_DOCSTRING,
|
| 892 |
)
|
| 893 |
class OpensciForSequenceClassification(OpensciPreTrainedModel):
|
| 894 |
-
def __init__(self, config):
|
| 895 |
-
super().__init__(config)
|
| 896 |
self.num_labels = config.num_labels
|
| 897 |
self.model = OpensciModel(config)
|
| 898 |
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
|
@@ -979,4 +1025,4 @@ class OpensciForSequenceClassification(OpensciPreTrainedModel):
|
|
| 979 |
past_key_values=transformer_outputs.past_key_values,
|
| 980 |
hidden_states=transformer_outputs.hidden_states,
|
| 981 |
attentions=transformer_outputs.attentions,
|
| 982 |
-
)
|
|
|
|
| 27 |
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
| 28 |
from transformers.generation import GenerationMixin
|
| 29 |
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 30 |
+
# from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 31 |
from transformers.modeling_outputs import (
|
| 32 |
BaseModelOutputWithPast,
|
| 33 |
CausalLMOutputWithPast,
|
| 34 |
+
QuestionAnsweringModelOutput,
|
| 35 |
SequenceClassifierOutputWithPast,
|
| 36 |
+
TokenClassifierOutput,
|
| 37 |
)
|
| 38 |
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 39 |
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
|
|
|
| 40 |
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 41 |
from transformers.utils import (
|
| 42 |
+
add_code_sample_docstrings,
|
| 43 |
add_start_docstrings,
|
| 44 |
add_start_docstrings_to_model_forward,
|
| 45 |
logging,
|
|
|
|
| 48 |
from transformers.utils.deprecation import deprecate_kwarg
|
| 49 |
from .configuration_opensci import OpensciConfig
|
| 50 |
|
| 51 |
+
# OELLM_PATCHED_v2
|
| 52 |
+
import transformers.utils as _tu_oellm
|
| 53 |
+
if hasattr(_tu_oellm, 'TransformersKwargs'):
|
| 54 |
+
TransformersKwargs = _tu_oellm.TransformersKwargs
|
| 55 |
+
else:
|
| 56 |
+
from typing import TypedDict as _TypedDict_oellm
|
| 57 |
+
class TransformersKwargs(_TypedDict_oellm, total=False): pass
|
| 58 |
+
import transformers.processing_utils as _tp_oellm
|
| 59 |
+
if hasattr(_tp_oellm, 'Unpack'):
|
| 60 |
+
Unpack = _tp_oellm.Unpack
|
| 61 |
+
else:
|
| 62 |
+
from typing_extensions import Unpack
|
| 63 |
+
|
| 64 |
+
|
| 65 |
|
| 66 |
logger = logging.get_logger(__name__)
|
| 67 |
|
|
|
|
| 103 |
self.original_max_seq_len = config.max_position_embeddings
|
| 104 |
|
| 105 |
self.config = config
|
| 106 |
+
if self.rope_type in ROPE_INIT_FUNCTIONS:
|
| 107 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 108 |
+
else:
|
| 109 |
+
# 'default' rope type was removed from ROPE_INIT_FUNCTIONS in transformers 5.0;
|
| 110 |
+
# inline the standard computation as a fallback.
|
| 111 |
+
def _default_rope_init(config, device=None, **kwargs):
|
| 112 |
+
base = config.rope_theta
|
| 113 |
+
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 114 |
+
dim = int(head_dim * getattr(config, "partial_rotary_factor", 1.0))
|
| 115 |
+
return (
|
| 116 |
+
1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim)),
|
| 117 |
+
1.0,
|
| 118 |
+
)
|
| 119 |
+
self.rope_init_fn = _default_rope_init
|
| 120 |
|
| 121 |
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 122 |
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
|
|
| 146 |
if "dynamic" in self.rope_type:
|
| 147 |
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 148 |
|
| 149 |
+
# Re-initialize inv_freq if it was not properly materialized (transformers 5.x meta-device loading).
|
| 150 |
+
# Non-persistent buffers are not stored in the checkpoint; 5.x leaves them as uninitialized
|
| 151 |
+
# memory after materialization (can be zeros, denormals, or large garbage values).
|
| 152 |
+
if not getattr(self, "_inv_freq_ready", False):
|
| 153 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device=x.device)
|
| 154 |
+
self.register_buffer("inv_freq", inv_freq.to(x.device), persistent=False)
|
| 155 |
+
self._inv_freq_ready = True
|
| 156 |
+
|
| 157 |
# Core RoPE block
|
| 158 |
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 159 |
position_ids_expanded = position_ids[:, None, :].float()
|
|
|
|
| 298 |
attention_mask: Optional[torch.Tensor],
|
| 299 |
past_key_value: Optional[Cache] = None,
|
| 300 |
cache_position: Optional[torch.LongTensor] = None,
|
| 301 |
+
# **kwargs: Unpack[FlashAttentionKwargs],
|
| 302 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 303 |
input_shape = hidden_states.shape[:-1]
|
| 304 |
hidden_shape = (*input_shape, -1, self.head_dim)
|
|
|
|
| 319 |
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 320 |
|
| 321 |
attention_interface: Callable = eager_attention_forward
|
| 322 |
+
if self.config._attn_implementation == "sdpa":
|
| 323 |
+
# Inline the 4.x-compatible SDPA wrapper: never passes enable_gqa so the
|
| 324 |
+
# same PyTorch kernel is selected regardless of transformers version.
|
| 325 |
+
def attention_interface(module, query, key, value, attention_mask, scaling, dropout=0.0, is_causal=None, **kw):
|
| 326 |
+
if hasattr(module, "num_key_value_groups"):
|
| 327 |
+
key = repeat_kv(key, module.num_key_value_groups)
|
| 328 |
+
value = repeat_kv(value, module.num_key_value_groups)
|
| 329 |
+
query, key, value = query.contiguous(), key.contiguous(), value.contiguous()
|
| 330 |
+
if is_causal is None:
|
| 331 |
+
is_causal = attention_mask is None and query.shape[2] > 1
|
| 332 |
+
out = torch.nn.functional.scaled_dot_product_attention(
|
| 333 |
+
query, key, value, attn_mask=attention_mask,
|
| 334 |
+
dropout_p=dropout, scale=scaling, is_causal=is_causal,
|
| 335 |
)
|
| 336 |
+
return out.transpose(1, 2).contiguous(), None
|
| 337 |
+
elif self.config._attn_implementation not in ("eager", "sdpa"):
|
| 338 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 339 |
+
|
| 340 |
|
| 341 |
attn_output, attn_weights = attention_interface(
|
| 342 |
self,
|
|
|
|
| 346 |
attention_mask,
|
| 347 |
dropout=0.0 if not self.training else self.attention_dropout,
|
| 348 |
scaling=self.scaling,
|
| 349 |
+
# **kwargs,
|
| 350 |
)
|
| 351 |
|
| 352 |
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
|
|
|
| 375 |
use_cache: Optional[bool] = False,
|
| 376 |
cache_position: Optional[torch.LongTensor] = None,
|
| 377 |
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 378 |
+
# **kwargs: Unpack[FlashAttentionKwargs],
|
| 379 |
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 380 |
residual = hidden_states
|
| 381 |
|
|
|
|
| 385 |
hidden_states, self_attn_weights = self.self_attn(
|
| 386 |
hidden_states=hidden_states,
|
| 387 |
attention_mask=attention_mask,
|
| 388 |
+
# position_ids=position_ids,
|
| 389 |
past_key_value=past_key_value,
|
| 390 |
+
# output_attentions=output_attentions,
|
| 391 |
+
# use_cache=use_cache,
|
| 392 |
cache_position=cache_position,
|
| 393 |
position_embeddings=position_embeddings,
|
| 394 |
+
# **kwargs,
|
| 395 |
)
|
| 396 |
hidden_states = residual + hidden_states
|
| 397 |
|
|
|
|
| 542 |
config: OpensciConfig
|
| 543 |
"""
|
| 544 |
|
| 545 |
+
def __init__(self, config: OpensciConfig, **kwargs):
|
| 546 |
+
super().__init__(config, **kwargs)
|
| 547 |
self.padding_idx = config.pad_token_id
|
| 548 |
self.vocab_size = config.vocab_size
|
| 549 |
|
|
|
|
| 577 |
output_hidden_states: Optional[bool] = None,
|
| 578 |
return_dict: Optional[bool] = None,
|
| 579 |
cache_position: Optional[torch.LongTensor] = None,
|
| 580 |
+
# **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
| 581 |
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 582 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 583 |
output_hidden_states = (
|
|
|
|
| 649 |
use_cache=use_cache,
|
| 650 |
cache_position=cache_position,
|
| 651 |
position_embeddings=position_embeddings,
|
| 652 |
+
# **flash_attn_kwargs,
|
| 653 |
)
|
| 654 |
|
| 655 |
hidden_states = layer_outputs[0]
|
|
|
|
| 793 |
return causal_mask
|
| 794 |
|
| 795 |
|
| 796 |
+
class KwargsForCausalLM(TransformersKwargs): ...
|
| 797 |
|
| 798 |
|
| 799 |
class OpensciForCausalLM(OpensciPreTrainedModel, GenerationMixin):
|
| 800 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 801 |
_tp_plan = {"lm_head": "colwise_rep"}
|
| 802 |
|
| 803 |
+
def __init__(self, config, **kwargs):
|
| 804 |
+
super().__init__(config, **kwargs)
|
| 805 |
self.model = OpensciModel(config)
|
| 806 |
self.vocab_size = config.vocab_size
|
| 807 |
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
|
|
|
| 937 |
Opensci_START_DOCSTRING,
|
| 938 |
)
|
| 939 |
class OpensciForSequenceClassification(OpensciPreTrainedModel):
|
| 940 |
+
def __init__(self, config, **kwargs):
|
| 941 |
+
super().__init__(config, **kwargs)
|
| 942 |
self.num_labels = config.num_labels
|
| 943 |
self.model = OpensciModel(config)
|
| 944 |
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
|
|
|
| 1025 |
past_key_values=transformer_outputs.past_key_values,
|
| 1026 |
hidden_states=transformer_outputs.hidden_states,
|
| 1027 |
attentions=transformer_outputs.attentions,
|
| 1028 |
+
)
|