failed09 commited on
Commit
62a610e
·
verified ·
1 Parent(s): e154be9

Fix dynamic import of configuration_bashkir_roberta

Browse files
Files changed (1) hide show
  1. modeling_bashkir_roberta.py +117 -114
modeling_bashkir_roberta.py CHANGED
@@ -1,114 +1,117 @@
1
- """Exact Hugging Face-compatible implementation of BashkirRoBERTa Pre-LN."""
2
-
3
- import torch
4
- from torch import nn
5
- from transformers import PreTrainedModel
6
- from transformers.modeling_outputs import MaskedLMOutput
7
-
8
- from configuration_bashkir_roberta import BashkirRobertaConfig
9
-
10
-
11
- class BashkirRobertaEmbeddings(nn.Module):
12
- def __init__(self, config):
13
- super().__init__()
14
- self.word_embeddings = nn.Embedding(
15
- config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
16
- )
17
- self.position_embeddings = nn.Embedding(
18
- config.max_position_embeddings, config.hidden_size
19
- )
20
- self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12)
21
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
22
-
23
- def forward(self, input_ids):
24
- sequence_length = input_ids.shape[1]
25
- positions = torch.arange(
26
- sequence_length, dtype=torch.long, device=input_ids.device
27
- ).unsqueeze(0)
28
- hidden_states = self.word_embeddings(input_ids) + self.position_embeddings(positions)
29
- return self.dropout(self.LayerNorm(hidden_states))
30
-
31
-
32
- class BashkirRobertaLayer(nn.Module):
33
- """Pre-LayerNorm transformer block, matching ``train_flagship.py`` exactly."""
34
-
35
- def __init__(self, config):
36
- super().__init__()
37
- self.self_attn = nn.MultiheadAttention(
38
- config.hidden_size,
39
- config.num_attention_heads,
40
- dropout=config.hidden_dropout_prob,
41
- batch_first=True,
42
- )
43
- self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-12)
44
- self.ffn = nn.Sequential(
45
- nn.Linear(config.hidden_size, config.intermediate_size),
46
- nn.GELU(),
47
- nn.Dropout(config.hidden_dropout_prob),
48
- nn.Linear(config.intermediate_size, config.hidden_size),
49
- nn.Dropout(config.hidden_dropout_prob),
50
- )
51
- self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-12)
52
-
53
- def forward(self, hidden_states, padding_mask=None):
54
- normalized = self.norm1(hidden_states)
55
- attention, _ = self.self_attn(
56
- normalized, normalized, normalized, key_padding_mask=padding_mask
57
- )
58
- hidden_states = hidden_states + attention
59
- return hidden_states + self.ffn(self.norm2(hidden_states))
60
-
61
-
62
- class BashkirRobertaForMaskedLM(PreTrainedModel):
63
- config_class = BashkirRobertaConfig
64
- base_model_prefix = "bashkir_roberta"
65
- main_input_name = "input_ids"
66
- _tied_weights_keys = {"lm_head.weight": "embeddings.word_embeddings.weight"}
67
-
68
- def __init__(self, config):
69
- super().__init__(config)
70
- self.embeddings = BashkirRobertaEmbeddings(config)
71
- self.layers = nn.ModuleList(
72
- [BashkirRobertaLayer(config) for _ in range(config.num_hidden_layers)]
73
- )
74
- self.norm_final = nn.LayerNorm(config.hidden_size, eps=1e-12)
75
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
76
- self.post_init()
77
-
78
- def get_input_embeddings(self):
79
- return self.embeddings.word_embeddings
80
-
81
- def set_input_embeddings(self, value):
82
- self.embeddings.word_embeddings = value
83
-
84
- def get_output_embeddings(self):
85
- return self.lm_head
86
-
87
- def set_output_embeddings(self, new_embeddings):
88
- self.lm_head = new_embeddings
89
-
90
- def tie_weights(self, **kwargs):
91
- if self.config.tie_word_embeddings:
92
- self.lm_head.weight = self.embeddings.word_embeddings.weight
93
-
94
- def forward(self, input_ids, attention_mask=None, labels=None, return_dict=True, **kwargs):
95
- if input_ids.shape[1] > self.config.max_position_embeddings:
96
- raise ValueError(
97
- f"Sequence length {input_ids.shape[1]} exceeds "
98
- f"max_position_embeddings={self.config.max_position_embeddings}."
99
- )
100
- padding_mask = input_ids.eq(self.config.pad_token_id) if attention_mask is None else attention_mask.eq(0)
101
- hidden_states = self.embeddings(input_ids)
102
- for layer in self.layers:
103
- hidden_states = layer(hidden_states, padding_mask=padding_mask)
104
- hidden_states = self.norm_final(hidden_states)
105
- logits = self.lm_head(hidden_states)
106
-
107
- loss = None
108
- if labels is not None:
109
- loss = nn.functional.cross_entropy(
110
- logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100
111
- )
112
- if not return_dict:
113
- return (loss, logits) if loss is not None else (logits,)
114
- return MaskedLMOutput(loss=loss, logits=logits)
 
 
 
 
1
+ """Exact Hugging Face-compatible implementation of BashkirRoBERTa Pre-LN."""
2
+
3
+ import torch
4
+ from torch import nn
5
+ from transformers import PreTrainedModel
6
+ from transformers.modeling_outputs import MaskedLMOutput
7
+
8
+ try:
9
+ from .configuration_bashkir_roberta import BashkirRobertaConfig
10
+ except (ImportError, ValueError):
11
+ from configuration_bashkir_roberta import BashkirRobertaConfig
12
+
13
+
14
+ class BashkirRobertaEmbeddings(nn.Module):
15
+ def __init__(self, config):
16
+ super().__init__()
17
+ self.word_embeddings = nn.Embedding(
18
+ config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
19
+ )
20
+ self.position_embeddings = nn.Embedding(
21
+ config.max_position_embeddings, config.hidden_size
22
+ )
23
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12)
24
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
25
+
26
+ def forward(self, input_ids):
27
+ sequence_length = input_ids.shape[1]
28
+ positions = torch.arange(
29
+ sequence_length, dtype=torch.long, device=input_ids.device
30
+ ).unsqueeze(0)
31
+ hidden_states = self.word_embeddings(input_ids) + self.position_embeddings(positions)
32
+ return self.dropout(self.LayerNorm(hidden_states))
33
+
34
+
35
+ class BashkirRobertaLayer(nn.Module):
36
+ """Pre-LayerNorm transformer block, matching ``train_flagship.py`` exactly."""
37
+
38
+ def __init__(self, config):
39
+ super().__init__()
40
+ self.self_attn = nn.MultiheadAttention(
41
+ config.hidden_size,
42
+ config.num_attention_heads,
43
+ dropout=config.hidden_dropout_prob,
44
+ batch_first=True,
45
+ )
46
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-12)
47
+ self.ffn = nn.Sequential(
48
+ nn.Linear(config.hidden_size, config.intermediate_size),
49
+ nn.GELU(),
50
+ nn.Dropout(config.hidden_dropout_prob),
51
+ nn.Linear(config.intermediate_size, config.hidden_size),
52
+ nn.Dropout(config.hidden_dropout_prob),
53
+ )
54
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-12)
55
+
56
+ def forward(self, hidden_states, padding_mask=None):
57
+ normalized = self.norm1(hidden_states)
58
+ attention, _ = self.self_attn(
59
+ normalized, normalized, normalized, key_padding_mask=padding_mask
60
+ )
61
+ hidden_states = hidden_states + attention
62
+ return hidden_states + self.ffn(self.norm2(hidden_states))
63
+
64
+
65
+ class BashkirRobertaForMaskedLM(PreTrainedModel):
66
+ config_class = BashkirRobertaConfig
67
+ base_model_prefix = "bashkir_roberta"
68
+ main_input_name = "input_ids"
69
+ _tied_weights_keys = {"lm_head.weight": "embeddings.word_embeddings.weight"}
70
+
71
+ def __init__(self, config):
72
+ super().__init__(config)
73
+ self.embeddings = BashkirRobertaEmbeddings(config)
74
+ self.layers = nn.ModuleList(
75
+ [BashkirRobertaLayer(config) for _ in range(config.num_hidden_layers)]
76
+ )
77
+ self.norm_final = nn.LayerNorm(config.hidden_size, eps=1e-12)
78
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
79
+ self.post_init()
80
+
81
+ def get_input_embeddings(self):
82
+ return self.embeddings.word_embeddings
83
+
84
+ def set_input_embeddings(self, value):
85
+ self.embeddings.word_embeddings = value
86
+
87
+ def get_output_embeddings(self):
88
+ return self.lm_head
89
+
90
+ def set_output_embeddings(self, new_embeddings):
91
+ self.lm_head = new_embeddings
92
+
93
+ def tie_weights(self, **kwargs):
94
+ if self.config.tie_word_embeddings:
95
+ self.lm_head.weight = self.embeddings.word_embeddings.weight
96
+
97
+ def forward(self, input_ids, attention_mask=None, labels=None, return_dict=True, **kwargs):
98
+ if input_ids.shape[1] > self.config.max_position_embeddings:
99
+ raise ValueError(
100
+ f"Sequence length {input_ids.shape[1]} exceeds "
101
+ f"max_position_embeddings={self.config.max_position_embeddings}."
102
+ )
103
+ padding_mask = input_ids.eq(self.config.pad_token_id) if attention_mask is None else attention_mask.eq(0)
104
+ hidden_states = self.embeddings(input_ids)
105
+ for layer in self.layers:
106
+ hidden_states = layer(hidden_states, padding_mask=padding_mask)
107
+ hidden_states = self.norm_final(hidden_states)
108
+ logits = self.lm_head(hidden_states)
109
+
110
+ loss = None
111
+ if labels is not None:
112
+ loss = nn.functional.cross_entropy(
113
+ logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100
114
+ )
115
+ if not return_dict:
116
+ return (loss, logits) if loss is not None else (logits,)
117
+ return MaskedLMOutput(loss=loss, logits=logits)