os: [ubuntu-latest, macos-latest, windows-latest]
# Lowest and highest, no version specified so that
# new releases get automatically tested against
- torch_version: [torch==1.10, torch]
+ version: [{torch: torch==1.10, python: "3.7"}, {torch: torch, python: "3.10"}]
defaults:
run:
working-directory: ./bindings/python
- name: Install Python
uses: actions/setup-python@v2
with:
- python-version: 3.7
+ python-version: ${{ matrix.version.python }}
architecture: "x64"
- name: Lint with RustFmt
run: |
pip install -U pip
pip install .[numpy,tensorflow,paddlepaddle]
- pip install ${{ matrix.torch_version }}
+ pip install ${{ matrix.version.torch }}
- name: Install (jax, flax)
if: matrix.os != 'windows-latest'
for k, v in state_dict.items():
if v.device != torch.device("meta"):
# Need to add device as key because of multiple GPU.
- tensors[(storage_ptr(v), v.device)].add(k)
+ tensors[(v.device, storage_ptr(v), storage_size(v))].add(k)
tensors = list(sorted(tensors.values()))
return tensors
raise ValueError("Big endian is not supported, serialization need to be in little endian")
if not isinstance(tensors, dict):
raise ValueError(f"Expected a dict of [str, torch.Tensor] but received {type(tensors)}")
- ptrs = defaultdict(set)
+
+ invalid_tensors = []
for k, v in tensors.items():
if not isinstance(v, torch.Tensor):
raise ValueError(f"Key `{k}` is invalid, expected torch.Tensor but received {type(v)}")
- if v.layout == torch.strided:
- ptrs[storage_ptr(v)].add(k)
+ if v.layout != torch.strided:
+ invalid_tensors.append(k)
+ if invalid_tensors:
+ raise ValueError(
+ f"You are trying to save a sparse tensors: `{invalid_tensors}` which this library does not support."
+ " You can make it a dense tensor before saving with `.to_dense()` but be aware this might"
+ " make a much larger file than needed."
+ )
+ shared_pointers = _find_shared_tensors(tensors)
failing = []
- for ptr, names in ptrs.items():
+ for names in shared_pointers:
if len(names) > 1:
failing.append(names)
save_file(data, local)
self.assertEqual(
str(ctx.exception),
- "You are trying to save a sparse tensor: `test` which this library does not support. You can make it a"
+ "You are trying to save a sparse tensors: `['test']` which this library does not support. You can make it a"
" dense tensor before saving with `.to_dense()` but be aware this might make a much larger file than"
" needed.",
)
from safetensors import SafetensorError, safe_open, serialize
from safetensors.numpy import load, load_file, save, save_file
+from safetensors.torch import _find_shared_tensors
from safetensors.torch import load_file as load_file_pt
from safetensors.torch import save_file as save_file_pt
+from safetensors.torch import storage_ptr, storage_size
class TestCase(unittest.TestCase):
load_file_pt(Path("./out.safetensors"))
os.remove(Path("./out.safetensors"))
+ def test_pt_sf_save_model_overlapping_storage(self):
+ m = torch.randn(10)
+ n = torch.empty([], dtype=m.dtype, device=m.device)
+ element_size = torch.finfo(m.dtype).bits // 8
+ try:
+ smaller_storage = m.untyped_storage()[: 4 * element_size]
+ except Exception:
+ try:
+ # Fallback for torch>=1.13
+ smaller_storage = m.storage().untyped()[: 4 * element_size]
+ except Exception:
+ try:
+ # Fallback for torch>=1.11
+ smaller_storage = m.storage()._untyped()[: 4 * element_size]
+ except Exception:
+ # Fallback for torch==1.10
+ smaller_storage = m.storage()[:4]
+
+ n.set_(source=smaller_storage)
+
+ # Check that we can have tensors with storage that have the same `data_ptr` but not the same storage size
+ self.assertEqual(storage_ptr(n), storage_ptr(m))
+ self.assertNotEqual(storage_size(n), storage_size(m))
+ self.assertEqual(storage_size(n), 4 * element_size)
+ self.assertEqual(storage_size(m), 10 * element_size)
+
+ shared_tensors = _find_shared_tensors({"m": m, "n": n})
+ self.assertEqual(shared_tensors, [{"m"}, {"n"}])
+
class WindowsTestCase(unittest.TestCase):
def test_get_correctly_dropped(self):