From 62155a5f6c8b0400afb74964e3a244f6ed017bc4 Mon Sep 17 00:00:00 2001 From: Mick van Gelderen Date: Mon, 17 Mar 2025 02:14:17 -0700 Subject: [PATCH] Pass device to torch.asarray in get_tensor (#588) * Pass device to torch.asarray in get_tensor * Fixing default device. --------- Co-authored-by: Nicolas Patry --- bindings/python/src/lib.rs | 13 ++++++------- bindings/python/tests/test_pt_comparison.py | 12 +++++++++++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 4d1d5f8..b6a0f49 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -500,7 +500,12 @@ impl Open { let torch = get_module(py, &TORCH_MODULE)?; let dtype: PyObject = get_pydtype(torch, info.dtype, false)?; let torch_uint8: PyObject = get_pydtype(torch, Dtype::U8, false)?; - let kwargs = [(intern!(py, "dtype"), torch_uint8)].into_py_dict(py)?; + let device: PyObject = self.device.clone().into_pyobject(py)?.into(); + let kwargs = [ + (intern!(py, "dtype"), torch_uint8), + (intern!(py, "device"), device), + ] + .into_py_dict(py)?; let view_kwargs = [(intern!(py, "dtype"), dtype)].into_py_dict(py)?; let shape = info.shape.to_vec(); let shape: PyObject = shape.into_pyobject(py)?.into(); @@ -560,13 +565,7 @@ impl Open { } tensor = tensor.getattr(intern!(py, "reshape"))?.call1((shape,))?; - if self.device != Device::Cpu { - let device: PyObject = self.device.clone().into_pyobject(py)?.into(); - let kwargs = PyDict::new(py); - tensor = tensor.call_method("to", (device,), Some(&kwargs))?; - } Ok(tensor.into_pyobject(py)?.into()) - // torch.asarray(storage[start + n : stop + n], dtype=torch.uint8).view(dtype=dtype).reshape(shape) }) } } diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index fc61644..10e8cc0 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -173,7 +173,7 @@ class TorchTestCase(unittest.TestCase): def test_hpu(self): # must be run to load torch with Intel Gaudi bindings try: - import habana_frameworks.torch.core as htcore + import habana_frameworks.torch.core as htcore # noqa: F401 except ImportError: self.skipTest("HPU is not available") @@ -255,6 +255,16 @@ class LoadTestCase(unittest.TestCase): self.assertTrue(torch.allclose(v, tv)) self.assertEqual(v.device, torch.device("cpu")) + @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available") + def test_deserialization_device(self): + with torch.device("cuda:0"): + weights = load_file(self.sf_filename) + self.assertEqual(weights["test"].device, torch.device("cpu")) + + torch.set_default_device(torch.device("cuda:0")) + weights = load_file(self.sf_filename) + self.assertEqual(weights["test"].device, torch.device("cpu")) + @unittest.skipIf(not torch.cuda.is_available(), "Cuda is not available") def test_deserialization_safe_gpu(self): # First time to hit disk -- 2.43.0