feat: route hasPrimaryContext through ACL API when TORCH_NPU_USE_COMPATIBLE_IMPL=1

Co-authored-by: wuyouqi1<wuyouqi1@h-partners.com>



# message auto-generated for no-merge-commit merge:
!36456 merge feat/hasPrimaryContext-api-consistency into v2.7.1

feat: route hasPrimaryContext through ACL API when TORCH_NPU_USE_COMPATIBLE_IMPL=1

Created-by: wuyouqi1
Commit-by: wuyouqi1
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->
  # 【合入来源】
  - [x] 需求
  - [ ] 问题单
  - [x] issue/工单 https://gitcode.com/Ascend/pytorch/issues/2073
  - [ ] 重构优化
  - [ ] 资料更新

  # 【修改方案】
  1. isDeviceCtxActive() 增加 CheckCompatibleImpl() 门控:TORCH_NPU_USE_COMPATIBLE_IMPL=1 时走 hasPrimaryContext (ACL API), 否则走 used_devices 本地缓存。MaybeSetDevice / MaybeExchangeDevice 均调用 isDeviceCtxActive,连锁受益。

  2. 新增 c10_npu::getDeviceIndexWithPrimaryContext(): 对齐 c10::cuda::getDeviceIndexWithPrimaryContext,遍历 device,找到已有 primary context 的设备。

  3. CachingHostAllocator (allocate_host_memory / isPinned) 对齐 CUDA: 用 getDeviceIndexWithPrimaryContext() + OptionalDeviceGuard

  4. currentStreamCaptureStatus() 对齐 CUDA (CUDAGraphsUtils.cuh): 用 isDeviceCtxActive(current_device()) 替代 IsContextInitialized()。

  5. NPUHooksInterface::hasPrimaryContext / Python 绑定 _npu_hasPrimaryContext
     简化为直接调用 isDeviceCtxActive (门控已统一在此)。


  修改文件:
  - torch_npu/csrc/core/npu/NPUHooksInterface.cpp
  - torch_npu/csrc/core/npu/NPUFunctions.cpp
  - torch_npu/csrc/core/npu/NPUFunctions.h
  - torch_npu/csrc/core/npu/NPUGraphsUtils.h
  - torch_npu/csrc/core/npu/CachingHostAllocator.cpp
  - torch_npu/csrc/core/npu/CachingHostAllocator.h

  # 【资料变更】
  不涉及

  # 【接口变更】
  不涉及

  # 【功能验证】
- 单卡环境 + env unset(自动跳过,无需多卡)
- 多卡环境 + env unset(三个用例PASS)

```
(/root/my_envs/tmp_ffmh) [root@A5-PoD-A04-CPU3 0128]# export ASCEND_RT_VISIBLE_DEVICES=3
(/root/my_envs/tmp_ffmh) [root@A5-PoD-A04-CPU3 0128]# python test_npu_primary_ctx.py 
sss
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK (skipped=3)
(/root/my_envs/tmp_ffmh) [root@A5-PoD-A04-CPU3 0128]# unset ASCEND_RT_VISIBLE_DEVICES
(/root/my_envs/tmp_ffmh) [root@A5-PoD-A04-CPU3 0128]# python test_npu_primary_ctx.py 
...
----------------------------------------------------------------------
Ran 3 tests in 30.733s

OK
```

  # 【CheckList】
  - [x] 代码注释完备,正确记录错误日志
  - [x] 代码实现进行了返回值、空指针等校验
  - [x] PR标题正确使用类型标签
  - [x] PR持续集成流水线(CI)执行通过,代码检查无异常

See merge request: Ascend/pytorch!36456
This commit is contained in:
wuyouqi1
2026-05-28 11:53:00 +08:00
committed by ascend-robot
parent be60e12fbe
commit 3bf50b1b79
5 changed files with 41 additions and 8 deletions
@@ -189,9 +189,12 @@ public:
private:
void allocate_host_memory(size_t size, void** ptr) override
{
// alloc needs set device first when using dataloader with pin_memory=True
if (c10_npu::GetLocalDevice() < 0) {
c10_npu::SetCurrentDevice();
// Pinned memory allocated by any device can be used by any other device.
// Device guard must outlive the allocation calls below.
at::OptionalDeviceGuard device_guard;
auto primary_ctx_device_index = c10_npu::getDeviceIndexWithPrimaryContext();
if (primary_ctx_device_index.has_value()) {
device_guard.reset_device(at::Device(at::DeviceType::PrivateUse1, *primary_ctx_device_index));
}
bool host_registered = false;
@@ -18,6 +18,7 @@
#include "torch_npu/csrc/core/npu/NPUFunctions.h"
#include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
namespace at_npu::native {
@@ -47,8 +48,10 @@ inline TORCH_NPU_API bool CachingHostAllocator_isPinned(void* ptr) {
if (!c10_npu::NpuSysCtrl::GetInstance().GetInitFlag()) {
return false;
}
if (c10_npu::GetLocalDevice() < 0) {
c10_npu::SetCurrentDevice();
at::OptionalDeviceGuard device_guard;
auto primary_ctx_device_index = c10_npu::getDeviceIndexWithPrimaryContext();
if (primary_ctx_device_index.has_value()) {
device_guard.reset_device(at::Device(at::DeviceType::PrivateUse1, *primary_ctx_device_index));
}
aclrtPtrAttributes attributes;
NPU_CHECK_ERROR(c10_npu::acl::AclrtPointerGetAttributes(ptr, &attributes), "aclrtPointerGetAttributes");
+24
View File
@@ -6,6 +6,7 @@
#include "torch_npu/csrc/core/npu/NPUAffinityController.h"
#include "torch_npu/csrc/core/npu/register/OptionsManager.h"
#include "torch_npu/csrc/core/npu/GetCANNInfo.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
#include "third_party/acl/inc/acl/acl_rt.h"
#ifndef BUILD_LIBTORCH
#include "torch_npu/csrc/sanitizer/NPUTrace.h"
@@ -238,6 +239,9 @@ aclrtContext GetDeviceContext(int32_t device)
bool isDeviceCtxActive(int32_t device)
{
if (at_npu::native::env::CheckCompatibleImpl()) {
return hasPrimaryContext(device);
}
std::lock_guard<std::recursive_mutex> lock(mtx);
if (used_devices.find(device) == used_devices.end()) {
return false;
@@ -245,6 +249,26 @@ bool isDeviceCtxActive(int32_t device)
return used_devices[device] != nullptr;
}
std::optional<c10::DeviceIndex> getDeviceIndexWithPrimaryContext()
{
// check current device first
auto cur_device = current_device();
if (cur_device >= 0) {
if (isDeviceCtxActive(cur_device)) {
return cur_device;
}
}
for (const auto device_index : c10::irange(device_count())) {
if (device_index == cur_device) {
continue;
}
if (isDeviceCtxActive(device_index)) {
return device_index;
}
}
return std::nullopt;
}
c10::DeviceIndex current_device()
{
int cur_device = 0;
+3
View File
@@ -9,6 +9,7 @@
#include <c10/core/Device.h>
#include <c10/macros/Macros.h>
#include <optional>
#include "torch_npu/csrc/core/npu/NPUMacros.h"
#include "torch_npu/csrc/core/npu/NPUException.h"
@@ -182,6 +183,8 @@ bool IsContextInitialized();
bool hasPrimaryContext(c10::DeviceIndex device_index);
std::optional<c10::DeviceIndex> getDeviceIndexWithPrimaryContext();
C10_NPU_API void stream_synchronize(aclrtStream stream);
} // namespace c10_npu
+3 -3
View File
@@ -7,6 +7,7 @@
#include "torch_npu/csrc/core/npu/NPUFunctions.h"
#include "torch_npu/csrc/core/npu/NPUMacros.h"
#include "torch_npu/csrc/core/npu/NPUStream.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
namespace c10_npu {
@@ -71,11 +72,10 @@ C10_NPU_API CaptureStatus currentStreamCaptureStatusMayInitCtx();
inline CaptureStatus currentStreamCaptureStatus()
{
// don't create a context if we don't have to
if (c10_npu::IsContextInitialized()) {
if (c10_npu::isDeviceCtxActive(c10_npu::current_device())) {
return currentStreamCaptureStatusMayInitCtx();
} else {
return CaptureStatus::None;
}
return CaptureStatus::None;
}
inline void assertNotCapturing(const std::string &attempt)