kd13 commited on
Commit
4490265
·
verified ·
1 Parent(s): 6d646da

Update modeling_mybert.py

Browse files
Files changed (1) hide show
  1. modeling_mybert.py +2 -16
modeling_mybert.py CHANGED
@@ -58,8 +58,7 @@ class MyBertSelfAttention(nn.Module):
58
  k = k.view(*shp).transpose(1, 2)
59
  v = v.view(*shp).transpose(1, 2)
60
  if cos is not None:
61
- q, k = _apply_rope(q, k, cos, sin) # RoPE on Q,K only
62
- # attn_mask=None + dropout 0 -> SDPA selects the FlashAttention kernel on sm_89
63
  ctx = F.scaled_dot_product_attention(
64
  q, k, v, attn_mask=attention_mask,
65
  dropout_p=self.dropout_prob if self.training else 0.0, is_causal=False,
@@ -89,8 +88,6 @@ class MyBertAttention(nn.Module):
89
 
90
 
91
  class MyBertSwiGLU(nn.Module):
92
- """SwiGLU FFN: down( silu(gate(x)) * up(x) ). Encoder only -- NOT the MLM head."""
93
-
94
  def __init__(self, config):
95
  super().__init__()
96
  b = config.use_bias
@@ -131,8 +128,6 @@ class MyBertEncoder(nn.Module):
131
 
132
 
133
  class MyBertPredictionHeadTransform(nn.Module):
134
- """MLM head keeps GELU -- SwiGLU deliberately NOT used here."""
135
-
136
  def __init__(self, config):
137
  super().__init__()
138
  self.dense = nn.Linear(config.hidden_size, config.hidden_size)
@@ -181,10 +176,6 @@ class MyBertPreTrainedModel(PreTrainedModel):
181
  elif isinstance(module, nn.LayerNorm):
182
  module.bias.data.zero_()
183
  module.weight.data.fill_(1.0)
184
- # transformers v5 loads the model on the meta device, then materialises
185
- # non-persistent buffers with torch.empty (uninitialised memory) and calls
186
- # _init_weights to refill them. Without this branch rope_cos/rope_sin are
187
- # garbage after from_pretrained() -> NaN logits in the fill-mask pipeline.
188
  if isinstance(module, MyBertModel):
189
  head_dim = self.config.hidden_size // self.config.num_attention_heads
190
  cos, sin = _build_rope_cache(head_dim, self.config.max_position_embeddings,
@@ -205,7 +196,6 @@ class MyBertModel(MyBertPreTrainedModel):
205
  self.register_buffer("rope_sin", sin, persistent=False)
206
  self.post_init()
207
 
208
- # scaled init on residual-output projections (pre-LN depth stability)
209
  n = config.num_hidden_layers
210
  for lyr in self.encoder.layer:
211
  lyr.attention.output.dense.weight.data.normal_(
@@ -232,7 +222,6 @@ class MyBertModel(MyBertPreTrainedModel):
232
 
233
 
234
  class MyBertForMaskedLM(MyBertPreTrainedModel):
235
- # modern transformers wants a DICT here (a list raises AttributeError in post_init)
236
  _tied_weights_keys = {
237
  "cls.predictions.decoder.weight": "mybert.embeddings.word_embeddings.weight",
238
  }
@@ -255,9 +244,6 @@ class MyBertForMaskedLM(MyBertPreTrainedModel):
255
  return_dict=True).last_hidden_state
256
 
257
  if labels is not None and self.config.sparse_prediction:
258
- # LM head ONLY on masked positions -- identical loss to dense (diff 0.0),
259
- # no B x T x 28996 logit tensor. Fixed-count masking keeps this shape STATIC,
260
- # so torch.compile never recompiles.
261
  flat_h = seq.view(-1, seq.size(-1))
262
  flat_y = labels.view(-1)
263
  idx = (flat_y != -100).nonzero(as_tuple=True)[0]
@@ -266,7 +252,7 @@ class MyBertForMaskedLM(MyBertPreTrainedModel):
266
  label_smoothing=label_smoothing)
267
  return MaskedLMOutput(loss=loss, logits=None)
268
 
269
- logits = self.cls(seq) # dense path -> fill-mask pipeline
270
  loss = None
271
  if labels is not None:
272
  loss = F.cross_entropy(logits.float().view(-1, self.config.vocab_size),
 
58
  k = k.view(*shp).transpose(1, 2)
59
  v = v.view(*shp).transpose(1, 2)
60
  if cos is not None:
61
+ q, k = _apply_rope(q, k, cos, sin)
 
62
  ctx = F.scaled_dot_product_attention(
63
  q, k, v, attn_mask=attention_mask,
64
  dropout_p=self.dropout_prob if self.training else 0.0, is_causal=False,
 
88
 
89
 
90
  class MyBertSwiGLU(nn.Module):
 
 
91
  def __init__(self, config):
92
  super().__init__()
93
  b = config.use_bias
 
128
 
129
 
130
  class MyBertPredictionHeadTransform(nn.Module):
 
 
131
  def __init__(self, config):
132
  super().__init__()
133
  self.dense = nn.Linear(config.hidden_size, config.hidden_size)
 
176
  elif isinstance(module, nn.LayerNorm):
177
  module.bias.data.zero_()
178
  module.weight.data.fill_(1.0)
 
 
 
 
179
  if isinstance(module, MyBertModel):
180
  head_dim = self.config.hidden_size // self.config.num_attention_heads
181
  cos, sin = _build_rope_cache(head_dim, self.config.max_position_embeddings,
 
196
  self.register_buffer("rope_sin", sin, persistent=False)
197
  self.post_init()
198
 
 
199
  n = config.num_hidden_layers
200
  for lyr in self.encoder.layer:
201
  lyr.attention.output.dense.weight.data.normal_(
 
222
 
223
 
224
  class MyBertForMaskedLM(MyBertPreTrainedModel):
 
225
  _tied_weights_keys = {
226
  "cls.predictions.decoder.weight": "mybert.embeddings.word_embeddings.weight",
227
  }
 
244
  return_dict=True).last_hidden_state
245
 
246
  if labels is not None and self.config.sparse_prediction:
 
 
 
247
  flat_h = seq.view(-1, seq.size(-1))
248
  flat_y = labels.view(-1)
249
  idx = (flat_y != -100).nonzero(as_tuple=True)[0]
 
252
  label_smoothing=label_smoothing)
253
  return MaskedLMOutput(loss=loss, logits=None)
254
 
255
+ logits = self.cls(seq)
256
  loss = None
257
  if labels is not None:
258
  loss = F.cross_entropy(logits.float().view(-1, self.config.vocab_size),