|
1 | 1 | from typing import Any, Dict, cast |
2 | | -from io import BytesIO |
3 | 2 | from pathlib import Path |
4 | 3 | import srsly |
5 | | -import torch |
6 | | -import warnings |
| 4 | +from safetensors.torch import save, load as safetensors_load |
7 | 5 | from thinc.api import get_torch_default_device |
8 | 6 | from spacy.util import SimpleFrozenDict |
9 | 7 |
|
@@ -70,10 +68,7 @@ def to_bytes(self): |
70 | 68 | for x in temp_dir.glob("**/*"): |
71 | 69 | if x.is_file(): |
72 | 70 | 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()) |
77 | 72 | else: |
78 | 73 | tok_cfg = hf_model._init_tokenizer_config |
79 | 74 | trf_cfg = hf_model._init_transformer_config |
@@ -117,27 +112,9 @@ def from_bytes(self, bytes_data): |
117 | 112 | SimpleFrozenDict(), |
118 | 113 | ) |
119 | 114 | self._model = transformer |
120 | | - filelike = BytesIO(msg["state"]) |
121 | | - filelike.seek(0) |
122 | 115 | 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) |
141 | 118 | self._model.to(device) |
142 | 119 | else: |
143 | 120 | self._hfmodel = HFObjects( |
|
0 commit comments