Skip to content

Commit d16fbbb

Browse files
committed
Fixes
1 parent 93a7ebd commit d16fbbb

2 files changed

Lines changed: 7 additions & 28 deletions

File tree

spacy_transformers/layers/hf_shim.py

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
from typing import Any, Dict, cast
2-
from io import BytesIO
32
from pathlib import Path
43
import srsly
5-
import torch
6-
import warnings
4+
from safetensors.torch import save, load as safetensors_load
75
from thinc.api import get_torch_default_device
86
from spacy.util import SimpleFrozenDict
97

@@ -70,10 +68,7 @@ def to_bytes(self):
7068
for x in temp_dir.glob("**/*"):
7169
if x.is_file():
7270
tok_dict[x.name] = x.read_bytes()
73-
filelike = BytesIO()
74-
torch.save(self._model.state_dict(), filelike)
75-
filelike.seek(0)
76-
weights_bytes = filelike.getvalue()
71+
weights_bytes = save(self._model.state_dict())
7772
else:
7873
tok_cfg = hf_model._init_tokenizer_config
7974
trf_cfg = hf_model._init_transformer_config
@@ -117,27 +112,9 @@ def from_bytes(self, bytes_data):
117112
SimpleFrozenDict(),
118113
)
119114
self._model = transformer
120-
filelike = BytesIO(msg["state"])
121-
filelike.seek(0)
122115
device = get_torch_default_device()
123-
try:
124-
self._model.load_state_dict(torch.load(filelike, map_location=device))
125-
except RuntimeError:
126-
warn_msg = (
127-
"Error loading saved torch state_dict with strict=True, "
128-
"likely due to differences between 'transformers' "
129-
"versions. Attempting to load with strict=False as a "
130-
"fallback...\n\n"
131-
"If you see errors or degraded performance, download a "
132-
"newer compatible model or retrain your custom model with "
133-
"the current 'transformers' and 'spacy-transformers' "
134-
"versions. For more details and available updates, run: "
135-
"python -m spacy validate"
136-
)
137-
warnings.warn(warn_msg)
138-
filelike.seek(0)
139-
b = torch.load(filelike, map_location=device)
140-
self._model.load_state_dict(b, strict=False)
116+
state_dict = safetensors_load(msg["state"])
117+
self._model.load_state_dict(state_dict)
141118
self._model.to(device)
142119
else:
143120
self._hfmodel = HFObjects(

spacy_transformers/layers/transformer_model.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,9 @@ def huggingface_from_pretrained(
277277
vocab_file_contents = fileh.read()
278278
trf_config["return_dict"] = True
279279
config = config_cls.from_pretrained(str_path, **trf_config)
280-
transformer = model_cls.from_pretrained(str_path, config=config)
280+
transformer = model_cls.from_pretrained(
281+
str_path, config=config, weights_only=False
282+
)
281283
torch_device = get_torch_default_device()
282284
transformer.to(torch_device)
283285
return HFObjects(tokenizer, transformer, vocab_file_contents)

0 commit comments

Comments
 (0)