diff --git a/deepmd/dpmodel/common.py b/deepmd/dpmodel/common.py index 423c5c425e..6e6113b494 100644 --- a/deepmd/dpmodel/common.py +++ b/deepmd/dpmodel/common.py @@ -8,6 +8,7 @@ Optional, ) +import array_api_compat import ml_dtypes import numpy as np @@ -109,7 +110,10 @@ def to_numpy_array(x: Any) -> Optional[np.ndarray]: # asarray is not within Array API standard, so may fail return np.asarray(x) except (ValueError, AttributeError): - return np.from_dlpack(x, copy=True) + xp = array_api_compat.array_namespace(x) + # to fix BufferError: Cannot export readonly array since signalling readonly is unsupported by DLPack. + x = xp.asarray(x, copy=True) + return np.from_dlpack(x) __all__ = [ diff --git a/deepmd/dpmodel/descriptor/dpa1.py b/deepmd/dpmodel/descriptor/dpa1.py index a84cc18882..259593e731 100644 --- a/deepmd/dpmodel/descriptor/dpa1.py +++ b/deepmd/dpmodel/descriptor/dpa1.py @@ -18,6 +18,9 @@ from deepmd.dpmodel.array_api import ( xp_take_along_axis, ) +from deepmd.dpmodel.common import ( + to_numpy_array, +) from deepmd.dpmodel.utils import ( EmbeddingNet, EnvMat, @@ -548,8 +551,8 @@ def serialize(self) -> dict: "exclude_types": obj.exclude_types, "env_protection": obj.env_protection, "@variables": { - "davg": np.array(obj["davg"]), - "dstd": np.array(obj["dstd"]), + "davg": to_numpy_array(obj["davg"]), + "dstd": to_numpy_array(obj["dstd"]), }, ## to be updated when the options are supported. "trainable": self.trainable, @@ -1022,8 +1025,8 @@ def serialize(self) -> dict: "exclude_types": obj.exclude_types, "env_protection": obj.env_protection, "@variables": { - "davg": np.array(obj["davg"]), - "dstd": np.array(obj["dstd"]), + "davg": to_numpy_array(obj["davg"]), + "dstd": to_numpy_array(obj["dstd"]), }, } if obj.tebd_input_mode in ["strip"]: