HimalayaGPT commited on
Commit
04f9bde
·
verified ·
1 Parent(s): f2fd1df

Default to manual safetensors load to avoid Colab meta-tensor failures

Browse files
Files changed (1) hide show
  1. run_standalone_inference.py +72 -25
run_standalone_inference.py CHANGED
@@ -57,6 +57,12 @@ def parse_args() -> argparse.Namespace:
57
  help="Use transformers/accelerate device_map='auto'. Disabled by default for maximum Colab compatibility.",
58
  )
59
  p.add_argument("--prompts-file", default=None, help="Optional .txt file with one prompt per line")
 
 
 
 
 
 
60
  return p.parse_args()
61
 
62
 
@@ -166,6 +172,58 @@ def _has_meta_tensors(model) -> bool:
166
  return False
167
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def generate_compat(model, input_ids, max_new_tokens: int, temperature: float, top_k: int, seed: int):
170
  import torch
171
  import torch.nn.functional as F
@@ -195,7 +253,7 @@ def main() -> None:
195
  import torch
196
  import transformers
197
  from huggingface_hub import snapshot_download
198
- from transformers import AutoModelForCausalLM, AutoTokenizer
199
 
200
  if transformers.__version__ == "4.57.0":
201
  print(
@@ -216,29 +274,15 @@ def main() -> None:
216
  sha = Path(local).name
217
 
218
  tok = AutoTokenizer.from_pretrained(local, trust_remote_code=True)
219
- model = AutoModelForCausalLM.from_pretrained(
220
- local,
221
- trust_remote_code=True,
222
- torch_dtype=torch_dtype,
223
- device_map="auto" if (device.type == "cuda" and args.use_device_map) else None,
224
- low_cpu_mem_usage=bool(device.type == "cuda" and args.use_device_map),
225
- )
226
- if device.type == "cpu" or (device.type == "cuda" and not args.use_device_map):
227
- if _has_meta_tensors(model):
228
- print("[warn] Detected meta tensors after load; retrying with device_map='auto' fallback.")
229
- del model
230
- if torch.cuda.is_available():
231
- torch.cuda.empty_cache()
232
- model = AutoModelForCausalLM.from_pretrained(
233
- local,
234
- trust_remote_code=True,
235
- torch_dtype=torch_dtype,
236
- device_map="auto" if device.type == "cuda" else None,
237
- low_cpu_mem_usage=bool(device.type == "cuda"),
238
- )
239
- else:
240
- model = model.to(device)
241
- model.eval()
242
 
243
  cfg = model.config
244
  vocab_size = int(getattr(cfg, "padded_vocab_size", getattr(cfg, "vocab_size", len(tok))))
@@ -258,7 +302,10 @@ def main() -> None:
258
  max_prompt_tokens = max(1, context_window - args.max_new_tokens)
259
 
260
  print(f"repo={args.repo_id} revision={args.revision} snapshot_sha={sha}")
261
- print(f"device={device} dtype={torch_dtype} prompt_style={prompt_style} use_device_map={args.use_device_map}")
 
 
 
262
  print(f"context_window={context_window} max_prompt_tokens={max_prompt_tokens}")
263
 
264
  torch.manual_seed(args.seed)
 
57
  help="Use transformers/accelerate device_map='auto'. Disabled by default for maximum Colab compatibility.",
58
  )
59
  p.add_argument("--prompts-file", default=None, help="Optional .txt file with one prompt per line")
60
+ p.add_argument(
61
+ "--load-mode",
62
+ choices=["manual", "from_pretrained"],
63
+ default="manual",
64
+ help="Model loading strategy. `manual` avoids meta-tensor edge cases on Colab.",
65
+ )
66
  return p.parse_args()
67
 
68
 
 
172
  return False
173
 
174
 
175
+ def _load_model_manual(local_dir: str, torch_dtype, device):
176
+ from pathlib import Path
177
+
178
+ import torch
179
+ from safetensors.torch import load_file
180
+ from transformers import AutoConfig, AutoModelForCausalLM
181
+
182
+ config = AutoConfig.from_pretrained(local_dir, trust_remote_code=True)
183
+ model = AutoModelForCausalLM.from_config(config, trust_remote_code=True)
184
+ weights_path = Path(local_dir) / "model.safetensors"
185
+ state_dict = load_file(str(weights_path), device="cpu")
186
+ incompatible = model.load_state_dict(state_dict, strict=False)
187
+ if incompatible.missing_keys or incompatible.unexpected_keys:
188
+ raise RuntimeError(
189
+ "State dict mismatch while manual-loading model.safetensors. "
190
+ f"missing={len(incompatible.missing_keys)} unexpected={len(incompatible.unexpected_keys)}"
191
+ )
192
+ model = model.to(device=device, dtype=torch_dtype)
193
+ model.eval()
194
+ return model
195
+
196
+
197
+ def _load_model_from_pretrained(local_dir: str, torch_dtype, device, use_device_map: bool):
198
+ import torch
199
+ from transformers import AutoModelForCausalLM
200
+
201
+ model = AutoModelForCausalLM.from_pretrained(
202
+ local_dir,
203
+ trust_remote_code=True,
204
+ torch_dtype=torch_dtype,
205
+ device_map="auto" if (device.type == "cuda" and use_device_map) else None,
206
+ low_cpu_mem_usage=bool(device.type == "cuda" and use_device_map),
207
+ )
208
+ if device.type == "cpu" or (device.type == "cuda" and not use_device_map):
209
+ if _has_meta_tensors(model):
210
+ print("[warn] Detected meta tensors after load; retrying with device_map='auto' fallback.")
211
+ del model
212
+ if torch.cuda.is_available():
213
+ torch.cuda.empty_cache()
214
+ model = AutoModelForCausalLM.from_pretrained(
215
+ local_dir,
216
+ trust_remote_code=True,
217
+ torch_dtype=torch_dtype,
218
+ device_map="auto" if device.type == "cuda" else None,
219
+ low_cpu_mem_usage=bool(device.type == "cuda"),
220
+ )
221
+ else:
222
+ model = model.to(device)
223
+ model.eval()
224
+ return model
225
+
226
+
227
  def generate_compat(model, input_ids, max_new_tokens: int, temperature: float, top_k: int, seed: int):
228
  import torch
229
  import torch.nn.functional as F
 
253
  import torch
254
  import transformers
255
  from huggingface_hub import snapshot_download
256
+ from transformers import AutoTokenizer
257
 
258
  if transformers.__version__ == "4.57.0":
259
  print(
 
274
  sha = Path(local).name
275
 
276
  tok = AutoTokenizer.from_pretrained(local, trust_remote_code=True)
277
+ if args.load_mode == "manual":
278
+ model = _load_model_manual(local, torch_dtype=torch_dtype, device=device)
279
+ else:
280
+ model = _load_model_from_pretrained(
281
+ local,
282
+ torch_dtype=torch_dtype,
283
+ device=device,
284
+ use_device_map=args.use_device_map,
285
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
  cfg = model.config
288
  vocab_size = int(getattr(cfg, "padded_vocab_size", getattr(cfg, "vocab_size", len(tok))))
 
302
  max_prompt_tokens = max(1, context_window - args.max_new_tokens)
303
 
304
  print(f"repo={args.repo_id} revision={args.revision} snapshot_sha={sha}")
305
+ print(
306
+ f"device={device} dtype={torch_dtype} prompt_style={prompt_style} "
307
+ f"use_device_map={args.use_device_map} load_mode={args.load_mode}"
308
+ )
309
  print(f"context_window={context_window} max_prompt_tokens={max_prompt_tokens}")
310
 
311
  torch.manual_seed(args.seed)