Codex commited on
Commit
cafd1cc
·
1 Parent(s): 891cf48

Fix transformers compatibility issues for local execution

Browse files
Files changed (1) hide show
  1. core.py +56 -9
core.py CHANGED
@@ -13,6 +13,41 @@ from pypdf import PdfReader
13
  # Load environment variables on import
14
  import runtime # noqa: F401
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  from config import ( # noqa: E402
17
  MODEL_ID,
18
  PARAMETER_COUNT,
@@ -56,16 +91,9 @@ except ImportError:
56
 
57
 
58
  def get_model_and_tokenizer() -> tuple[Any, Any]:
59
- """Loads and returns the tokenizer and model from HF, using a compatibility patch for newer transformers v5+."""
60
  global _model, _tokenizer
61
  if _model is None:
62
- import transformers.utils
63
- import transformers.utils.import_utils
64
-
65
- # Monkey-patch to fix dynamic import compatibility of older OpenBMB model code in transformers v5+
66
- transformers.utils.is_torch_fx_available = lambda: True # type: ignore
67
- transformers.utils.import_utils.is_torch_fx_available = lambda: True # type: ignore
68
-
69
  import logging
70
  import warnings
71
 
@@ -81,7 +109,7 @@ def get_model_and_tokenizer() -> tuple[Any, Any]:
81
 
82
  logging.getLogger("transformers").addFilter(GenerationMixinFilter())
83
 
84
- from transformers import AutoModelForCausalLM, AutoTokenizer
85
 
86
  print(f"Loading tokenizer for {MODEL_ID}...")
87
  _tokenizer = AutoTokenizer.from_pretrained(
@@ -89,9 +117,28 @@ def get_model_and_tokenizer() -> tuple[Any, Any]:
89
  trust_remote_code=True,
90
  token=os.environ.get("HF_TOKEN"),
91
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  print(f"Loading model {MODEL_ID}...")
93
  _model = AutoModelForCausalLM.from_pretrained(
94
  MODEL_ID,
 
95
  dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
96
  low_cpu_mem_usage=True,
97
  trust_remote_code=True,
 
13
  # Load environment variables on import
14
  import runtime # noqa: F401
15
 
16
+ # Monkey-patch to fix compatibility issues of older OpenBMB model code in newer transformers
17
+ try:
18
+ import transformers.utils
19
+ import transformers.utils.import_utils
20
+
21
+ transformers.utils.is_torch_fx_available = lambda: True # type: ignore
22
+ transformers.utils.import_utils.is_torch_fx_available = lambda: True # type: ignore
23
+
24
+ # Patch PreTrainedModel.get_expanded_tied_weights_keys to handle list-based _tied_weights_keys in older models
25
+ from transformers import PreTrainedModel
26
+
27
+ original_get_expanded_tied_weights_keys = (
28
+ PreTrainedModel.get_expanded_tied_weights_keys
29
+ )
30
+
31
+ def patched_get_expanded_tied_weights_keys(
32
+ self, all_submodels: bool = False
33
+ ) -> dict:
34
+ if hasattr(self, "_tied_weights_keys") and isinstance(
35
+ self._tied_weights_keys, list
36
+ ):
37
+ new_tied_weights = {}
38
+ for key in self._tied_weights_keys:
39
+ new_tied_weights[key] = "model.embed_tokens.weight"
40
+ self._tied_weights_keys = new_tied_weights
41
+ return original_get_expanded_tied_weights_keys(
42
+ self, all_submodels=all_submodels
43
+ )
44
+
45
+ PreTrainedModel.get_expanded_tied_weights_keys = (
46
+ patched_get_expanded_tied_weights_keys # type: ignore
47
+ )
48
+ except ImportError:
49
+ pass
50
+
51
  from config import ( # noqa: E402
52
  MODEL_ID,
53
  PARAMETER_COUNT,
 
91
 
92
 
93
  def get_model_and_tokenizer() -> tuple[Any, Any]:
94
+ """Loads and returns the tokenizer and model from HF, using compatibility patches for newer transformers versions."""
95
  global _model, _tokenizer
96
  if _model is None:
 
 
 
 
 
 
 
97
  import logging
98
  import warnings
99
 
 
109
 
110
  logging.getLogger("transformers").addFilter(GenerationMixinFilter())
111
 
112
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
113
 
114
  print(f"Loading tokenizer for {MODEL_ID}...")
115
  _tokenizer = AutoTokenizer.from_pretrained(
 
117
  trust_remote_code=True,
118
  token=os.environ.get("HF_TOKEN"),
119
  )
120
+
121
+ print(f"Loading configuration for {MODEL_ID}...")
122
+ config = AutoConfig.from_pretrained(
123
+ MODEL_ID,
124
+ trust_remote_code=True,
125
+ token=os.environ.get("HF_TOKEN"),
126
+ )
127
+ # Fix transformers v4.45+ configuration incompatibility with OpenBMB's custom modeling_minicpm.py
128
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
129
+ rope_type = config.rope_scaling.get(
130
+ "type", config.rope_scaling.get("rope_type")
131
+ )
132
+ if rope_type in (None, "default"):
133
+ config.rope_scaling = None
134
+ else:
135
+ config.rope_scaling.setdefault("type", rope_type)
136
+ config.rope_scaling.setdefault("factor", 1.0)
137
+
138
  print(f"Loading model {MODEL_ID}...")
139
  _model = AutoModelForCausalLM.from_pretrained(
140
  MODEL_ID,
141
+ config=config,
142
  dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
143
  low_cpu_mem_usage=True,
144
  trust_remote_code=True,