kashif HF Staff commited on
Commit
40f6a13
·
verified ·
1 Parent(s): ad90094

Fix inv_freq zero-init on v5: register original_inv_freq as buffer, add compute_default_rope_parameters, delegate rotary _init_weights to super

Browse files
Files changed (1) hide show
  1. modeling_sdar.py +41 -21
modeling_sdar.py CHANGED
@@ -277,17 +277,27 @@ class SDARAttention(nn.Module):
277
  value_states = torch.cat([past_value_states, value_states], dim=-2)
278
 
279
  attention_mask = attention_mask.bool() if attention_mask is not None else None
280
- # Always use SDPA (flash_attn path had a v5 compatibility issue that produced
281
- # identical outputs across query positions when Q and K seq lengths differed).
282
- attn_output = F.scaled_dot_product_attention(
283
- query=query_states,
284
- key=key_states,
285
- value=value_states,
286
- attn_mask=attention_mask,
287
- is_causal=False,
288
- scale=self.scaling,
289
- enable_gqa=True)
290
- attn_output = attn_output.transpose(1, 2).contiguous()
 
 
 
 
 
 
 
 
 
 
291
 
292
  attn_output = attn_output.reshape(*input_shape, -1).contiguous()
293
  attn_output = self.o_proj(attn_output)
@@ -385,17 +395,25 @@ class SDARPreTrainedModel(PreTrainedModel):
385
  module.weight.data[module.padding_idx].zero_()
386
  elif isinstance(module, SDARRMSNorm):
387
  module.weight.data.fill_(1.0)
 
 
 
 
388
 
389
 
390
  class SDARRotaryEmbedding(nn.Module):
 
 
391
  @staticmethod
392
- def _compute_default_rope(config, device=None):
393
- base = getattr(config, "rope_theta", 10000.0)
394
- if getattr(config, "head_dim", None):
395
- dim = config.head_dim
396
- else:
397
- dim = config.hidden_size // config.num_attention_heads
398
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
 
 
399
  return inv_freq, 1.0
400
 
401
  def __init__(self, config: SDARConfig, device=None):
@@ -411,15 +429,17 @@ class SDARRotaryEmbedding(nn.Module):
411
 
412
  self.config = config
413
 
414
- # transformers v5 removed "default" from ROPE_INIT_FUNCTIONS; compute inline.
415
  if self.rope_type == "default":
416
- inv_freq, self.attention_scaling = self._compute_default_rope(config, device)
417
  else:
418
  self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
419
  inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
420
 
 
 
 
421
  self.register_buffer("inv_freq", inv_freq, persistent=False)
422
- self.original_inv_freq = self.inv_freq
423
 
424
  @torch.no_grad()
425
  # power user: used with advanced RoPE types (e.g. dynamic rope)
 
277
  value_states = torch.cat([past_value_states, value_states], dim=-2)
278
 
279
  attention_mask = attention_mask.bool() if attention_mask is not None else None
280
+ if attention_mask is not None and torch.all(attention_mask): # decoding
281
+ query_states = query_states.transpose(1, 2)
282
+ key_states = key_states.transpose(1, 2)
283
+ value_states = value_states.transpose(1, 2)
284
+ attn_output = flash_attn_func(
285
+ query_states,
286
+ key_states,
287
+ value_states,
288
+ causal=False,
289
+ softmax_scale=self.scaling)
290
+
291
+ else: # prefilling
292
+ attn_output = F.scaled_dot_product_attention(
293
+ query=query_states,
294
+ key=key_states,
295
+ value=value_states,
296
+ attn_mask=attention_mask,
297
+ is_causal=False,
298
+ scale=self.scaling,
299
+ enable_gqa=True)
300
+ attn_output = attn_output.transpose(1, 2).contiguous()
301
 
302
  attn_output = attn_output.reshape(*input_shape, -1).contiguous()
303
  attn_output = self.o_proj(attn_output)
 
395
  module.weight.data[module.padding_idx].zero_()
396
  elif isinstance(module, SDARRMSNorm):
397
  module.weight.data.fill_(1.0)
398
+ # Delegate rotary-embedding buffer re-init to the base PreTrainedModel, which handles
399
+ # transformers v5's meta-device load by recomputing inv_freq via compute_default_rope_parameters.
400
+ else:
401
+ super()._init_weights(module)
402
 
403
 
404
  class SDARRotaryEmbedding(nn.Module):
405
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
406
+
407
  @staticmethod
408
+ def compute_default_rope_parameters(config, device=None, seq_len=None):
409
+ # transformers v5 removed "default" from ROPE_INIT_FUNCTIONS; match the Qwen3 implementation.
410
+ base = getattr(config, "rope_theta", None)
411
+ if base is None:
412
+ base = config.rope_parameters["rope_theta"]
413
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
414
+ inv_freq = 1.0 / (
415
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
416
+ )
417
  return inv_freq, 1.0
418
 
419
  def __init__(self, config: SDARConfig, device=None):
 
429
 
430
  self.config = config
431
 
 
432
  if self.rope_type == "default":
433
+ inv_freq, self.attention_scaling = self.compute_default_rope_parameters(config, device)
434
  else:
435
  self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
436
  inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
437
 
438
+ # Register both as buffers — transformers v5's `_move_missing_keys_from_meta_to_device`
439
+ # replaces non-persistent buffers with `torch.empty_like` (uninitialized / zeros); the base
440
+ # `_init_weights` then re-copies into them IF they're buffers with `original_inv_freq` present.
441
  self.register_buffer("inv_freq", inv_freq, persistent=False)
442
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
443
 
444
  @torch.no_grad()
445
  # power user: used with advanced RoPE types (e.g. dynamic rope)