Fix Transformers 5 compatibility and make xFormers optional

#3
Files changed (3) hide show
  1. README.md +1 -1
  2. model.py +13 -18
  3. swiglu.py +49 -0
README.md CHANGED
@@ -55,7 +55,7 @@ For detailed benchmarking, see https://acr.ps/neoarabert.
55
  ### How to Use
56
  Install these libraries:
57
  ```
58
- pip install fast-disambig hf_transfer==0.1.9 torch==2.5.1 transformers==4.49.0 xformers==0.0.28.post3 torchvision torchaudio
59
  ```
60
  Load the model and use it to generate embeddings:
61
  ```python
 
55
  ### How to Use
56
  Install these libraries:
57
  ```
58
+ pip install fast-disambig hf_transfer==0.1.9 torch==2.14.1 transformers==5.20.2 xformers==0.0.35 torchvision torchaudio
59
  ```
60
  Load the model and use it to generate embeddings:
61
  ```python
model.py CHANGED
@@ -1,15 +1,3 @@
1
- import warnings
2
-
3
- # xformers 0.0.27 still calls `torch.library.impl_abstract`, which torch
4
- # deprecated in favor of `register_fake`. Suppress the FutureWarning before
5
- # importing xformers so anyone doing `AutoModel.from_pretrained(...)` gets
6
- # clean output. xformers 0.0.28+ fixed it; this filter is a no-op there.
7
- warnings.filterwarnings(
8
- "ignore",
9
- message=r"`torch\.library\.impl_abstract` was renamed.*",
10
- category=FutureWarning,
11
- )
12
-
13
  import torch
14
  from torch import nn
15
 
@@ -19,8 +7,6 @@ from torch.nn.functional import scaled_dot_product_attention
19
  from typing import Optional, Tuple
20
  import numpy as np
21
 
22
- from xformers.ops import SwiGLU
23
-
24
  try:
25
  from flash_attn.flash_attn_interface import flash_attn_varlen_func
26
 
@@ -38,6 +24,7 @@ from transformers.modeling_outputs import (
38
  MaskedLMOutput,
39
  SequenceClassifierOutput,
40
  )
 
41
 
42
  try:
43
  import logging as _std_logging
@@ -52,6 +39,7 @@ except Exception:
52
  pass
53
 
54
  from .rotary import precompute_freqs_cis, apply_rotary_emb
 
55
 
56
 
57
  class DataCollatorWithPacking(DataCollatorForLanguageModeling):
@@ -226,9 +214,9 @@ class NeoBERTPreTrainedModel(PreTrainedModel):
226
 
227
  def _init_weights(self, module):
228
  if isinstance(module, nn.Linear):
229
- module.weight.data.uniform_(-self.config.decoder_init_range, self.config.decoder_init_range)
230
  elif isinstance(module, nn.Embedding):
231
- module.weight.data.uniform_(-self.config.embedding_init_range, self.config.embedding_init_range)
232
 
233
 
234
  class NeoBERT(NeoBERTPreTrainedModel):
@@ -318,6 +306,13 @@ class NeoBERT(NeoBERTPreTrainedModel):
318
  attentions=attentions if output_attentions else None,
319
  )
320
 
 
 
 
 
 
 
 
321
 
322
  class NeoBERTLMHead(NeoBERTPreTrainedModel):
323
  config_class = NeoBERTConfig
@@ -384,9 +379,9 @@ class NeoBERTForSequenceClassification(NeoBERTPreTrainedModel):
384
 
385
  def _init_weights(self, module):
386
  if isinstance(module, nn.Linear):
387
- module.weight.data.normal_(mean=0.0, std=self.classifier_init_range)
388
  if module.bias is not None:
389
- module.bias.data.zero_()
390
 
391
  def forward(
392
  self,
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
  from torch import nn
3
 
 
7
  from typing import Optional, Tuple
8
  import numpy as np
9
 
 
 
10
  try:
11
  from flash_attn.flash_attn_interface import flash_attn_varlen_func
12
 
 
24
  MaskedLMOutput,
25
  SequenceClassifierOutput,
26
  )
27
+ from transformers import initialization as init
28
 
29
  try:
30
  import logging as _std_logging
 
39
  pass
40
 
41
  from .rotary import precompute_freqs_cis, apply_rotary_emb
42
+ from .swiglu import SwiGLU
43
 
44
 
45
  class DataCollatorWithPacking(DataCollatorForLanguageModeling):
 
214
 
215
  def _init_weights(self, module):
216
  if isinstance(module, nn.Linear):
217
+ init.uniform_(module.weight, -self.config.decoder_init_range, self.config.decoder_init_range)
218
  elif isinstance(module, nn.Embedding):
219
+ init.uniform_(module.weight, -self.config.embedding_init_range, self.config.embedding_init_range)
220
 
221
 
222
  class NeoBERT(NeoBERTPreTrainedModel):
 
306
  attentions=attentions if output_attentions else None,
307
  )
308
 
309
+ def _init_weights(self, module):
310
+ super()._init_weights(module)
311
+ if isinstance(module, NeoBERT):
312
+ config = module.config
313
+ freqs_cis = precompute_freqs_cis(config.hidden_size // config.num_attention_heads, config.max_length)
314
+ init.copy_(module.freqs_cis, freqs_cis)
315
+
316
 
317
  class NeoBERTLMHead(NeoBERTPreTrainedModel):
318
  config_class = NeoBERTConfig
 
379
 
380
  def _init_weights(self, module):
381
  if isinstance(module, nn.Linear):
382
+ init.normal_(module.weight, mean=0.0, std=self.classifier_init_range)
383
  if module.bias is not None:
384
+ init.zeros_(module.bias)
385
 
386
  def forward(
387
  self,
swiglu.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ class _SwiGLU(nn.Module):
9
+ def __init__(
10
+ self,
11
+ in_features: int,
12
+ hidden_features: int,
13
+ out_features: int | None = None,
14
+ bias: bool = True,
15
+ ):
16
+ super().__init__()
17
+
18
+ out_features = out_features or in_features
19
+
20
+ self.in_features = in_features
21
+ self.hidden_features = hidden_features
22
+ self.out_features = out_features or in_features
23
+
24
+ self.w12 = nn.Linear(
25
+ in_features, 2 * hidden_features, bias=bias
26
+ )
27
+ self.w3 = nn.Linear(
28
+ hidden_features, out_features, bias=bias
29
+ )
30
+
31
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
32
+ x1, x2 = self.w12(x).chunk(2, dim=-1)
33
+ return self.w3(F.silu(x1) * x2)
34
+
35
+
36
+ # xformers 0.0.27 still calls `torch.library.impl_abstract`, which torch
37
+ # deprecated in favor of `register_fake`. Suppress the FutureWarning before
38
+ # importing xformers so anyone doing `AutoModel.from_pretrained(...)` gets
39
+ # clean output. xformers 0.0.28+ fixed it; this filter is a no-op there.
40
+ warnings.filterwarnings(
41
+ "ignore",
42
+ message=r"`torch\.library\.impl_abstract` was renamed.*",
43
+ category=FutureWarning,
44
+ )
45
+
46
+ try:
47
+ from xformers.ops import SwiGLU
48
+ except ImportError:
49
+ SwiGLU = _SwiGLU