Transformers
xlm-roberta
🇪🇺 Region: EU

Fix uninitialised rotary inv_freq on transformers v5

#63
by tomaarsen HF Staff - opened
Files changed (1) hide show
  1. rotary.py +4 -2
rotary.py CHANGED
@@ -534,8 +534,10 @@ class RotaryEmbedding(torch.nn.Module):
534
  # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
535
  # And the output of arange can be quite large, so bf16 would lose a lot of precision.
536
  # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
537
- if rotary_base_changed:
538
- self.inv_freq = self._compute_inv_freq(device=device)
 
 
539
  if self.pos_idx_in_fp32:
540
  t = torch.arange(seqlen, device=device, dtype=torch.float32)
541
  # We want fp32 here as well since inv_freq will be multiplied with t, and the output
 
534
  # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
535
  # And the output of arange can be quite large, so bf16 would lose a lot of precision.
536
  # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
537
+ # NOTE: transformers>=5 builds the model on the meta device and materialises
538
+ # non-persistent buffers without re-running __init__, so the inv_freq computed
539
+ # there can be uninitialised memory. Recompute whenever the cache is (re)built.
540
+ self.inv_freq = self._compute_inv_freq(device=device)
541
  if self.pos_idx_in_fp32:
542
  t = torch.arange(seqlen, device=device, dtype=torch.float32)
543
  # We want fp32 here as well since inv_freq will be multiplied with t, and the output