Merged
[feat] support NPU pinned memory for DCP StateDictStager #46095
AWWOLFAdd on Sep 9
[feat] support NPU pinned memory for DCP StateDictStager #46095
Merged
Total: 2 files changed+34-1
| @@ -16,6 +16,7 @@ from torch.utils import cpp_extension | |||
| 16 | from torch.autograd.profiler_util import Kernel | 16 | from torch.autograd.profiler_util import Kernel |
| 17 | from torch_npu.utils import _dynamo | 17 | from torch_npu.utils import _dynamo |
| 18 | import torch_npu | 18 | import torch_npu |
| 19 | +from torch_npu.npu import _pin_memory_utils as npu_pin_memory_utils | ||
| 19 | 20 | ||
| 20 | try: | 21 | try: |
| 21 | from packaging.version import Version as Version | 22 | from packaging.version import Version as Version |
| @@ -383,7 +384,8 @@ def _patch_cuda(): | |||
| 383 | ['cuda.random', torch_npu.npu.random], | 384 | ['cuda.random', torch_npu.npu.random], |
| 384 | ['cuda.amp.autocast_mode', torch_npu.npu.amp.autocast_mode], | 385 | ['cuda.amp.autocast_mode', torch_npu.npu.amp.autocast_mode], |
| 385 | ['cuda.amp.common', torch_npu.npu.amp.common], | 386 | ['cuda.amp.common', torch_npu.npu.amp.common], |
| 386 | - ['cuda.amp.grad_scaler', torch_npu.npu.amp.grad_scaler] | 387 | + ['cuda.amp.grad_scaler', torch_npu.npu.amp.grad_scaler], |
| 388 | + ['cuda._pin_memory_utils', npu_pin_memory_utils] | ||
| 387 | ] | 389 | ] |
| 388 | 390 | ||
| 389 | from torch_npu._init.patches.monkey_patches import _apply_patches | 391 | from torch_npu._init.patches.monkey_patches import _apply_patches |
| @@ -0,0 +1,31 @@ | |||
| 1 | +import torch_npu | ||
| 2 | + | ||
| 3 | +from torch_npu.utils._error_code import ErrCode, pta_error | ||
| 4 | + | ||
| 5 | +__all__ = ["pin_memory", "unpin_memory"] | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +# CANN flag for registering existing host memory as page-locked memory. | ||
| 9 | +_ACL_HOST_REG_PINNED = 0x10000000 | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def pin_memory(data_ptr: int, size: int) -> None: | ||
| 13 | + result = torch_npu.npu.npurt().npuHostRegister( | ||
| 14 | + data_ptr, | ||
| 15 | + size, | ||
| 16 | + _ACL_HOST_REG_PINNED, | ||
| 17 | + ) | ||
| 18 | + if result != 0: | ||
| 19 | + raise RuntimeError( | ||
| 20 | + f"npuHostRegister failed with error code {result}." | ||
| 21 | + + pta_error(ErrCode.ACL) | ||
| 22 | + ) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def unpin_memory(data_ptr: int) -> None: | ||
| 26 | + result = torch_npu.npu.npurt().npuHostUnregister(data_ptr) | ||
| 27 | + if result != 0: | ||
| 28 | + raise RuntimeError( | ||
| 29 | + f"npuHostUnregister failed with error code {result}." | ||
| 30 | + + pta_error(ErrCode.ACL) | ||
| 31 | + ) | ||