Merged
[feat] pin_memory support PCIE_through HVA #30210
gleaming-sparkAdd on Jan 29
[feat] pin_memory support PCIE_through HVA #30210
Merged
gleaming-sparkAdd on Jan 29
Total: 8 files changed+156-3
@@ -54,6 +54,10 @@
54 54 
55 默认为False。如果设置为True,此设置将指示pin_memory缓存分配器内存池物理内存申请粒度为20MB(不可配置),创建的内存块后续可以扩展,以便能更好地处理内存使用中频繁变更内存大小的情况,同时pin_memory内存块计数相关统计指标不参与统计(默认值:0)。如果设置为False,关闭pin_memory内存池扩展段功能,使用原有的内存申请方式。55 默认为False。如果设置为True,此设置将指示pin_memory缓存分配器内存池物理内存申请粒度为20MB(不可配置),创建的内存块后续可以扩展,以便能更好地处理内存使用中频繁变更内存大小的情况,同时pin_memory内存块计数相关统计指标不参与统计(默认值:0)。如果设置为False,关闭pin_memory内存池扩展段功能,使用原有的内存申请方式。
56 56 
57+- pinned\_mem\_register:<value\>,设置pin_memory内存是否启用host register功能。
58+ 
59+ 默认为False。如果设置为True,此设置将指示pin_memory内存启用host register功能,将pin_memory内存映射注册为Device可访问的内存地址。如果设置为False,关闭host register功能。
60+ 
57 61 
58> [!NOTE] 62> [!NOTE]
59> 用户使用Ascend Extension for PyTorch 6.0.RC3及之后版本配套的驱动(Ascend HDK 24.1.RC3及之后),开启虚拟内存特性时,可以使用单进程多卡特性;用户使用Ascend Extension for PyTorch 6.0.RC3之前版本配套的驱动(Ascend HDK 24.1.RC3之前版本),开启虚拟内存特性时,不能使用单进程多卡特性。63> 用户使用Ascend Extension for PyTorch 6.0.RC3及之后版本配套的驱动(Ascend HDK 24.1.RC3及之后),开启虚拟内存特性时,可以使用单进程多卡特性;用户使用Ascend Extension for PyTorch 6.0.RC3之前版本配套的驱动(Ascend HDK 24.1.RC3之前版本),开启虚拟内存特性时,不能使用单进程多卡特性。
@@ -111,6 +115,13 @@ export PYTORCH_NPU_ALLOC_CONF=pinned_use_background_threads:True
111export PYTORCH_NPU_ALLOC_CONF=pin_memory_expandable_segments:True115export PYTORCH_NPU_ALLOC_CONF=pin_memory_expandable_segments:True
112```116```
113 117 
118+ 
119+示例八:
120+ 
121+```bash
122+export PYTORCH_NPU_ALLOC_CONF=pinned_mem_register:True
123+```
124+ 
114## 使用约束125## 使用约束
115 126 
116- expandable\_segments特性需在Ascend HDK 23.0.0及以上版本上使用。127- expandable\_segments特性需在Ascend HDK 23.0.0及以上版本上使用。
@@ -126,6 +137,9 @@ export PYTORCH_NPU_ALLOC_CONF=pin_memory_expandable_segments:True
126 137 
127 - 当申请内存小于等于1MB时:配置page\_size也不生效,内存申请粒度为2MB。138 - 当申请内存小于等于1MB时:配置page\_size也不生效,内存申请粒度为2MB。
128- pin_memory_expandable_segments特性要求最低Ascend Extension for PyTorch 7.3.0之后版本、Ascend HDK 25.5.0及以上版本、CANN商发8.5.0及以上版本使用。139- pin_memory_expandable_segments特性要求最低Ascend Extension for PyTorch 7.3.0之后版本、Ascend HDK 25.5.0及以上版本、CANN商发8.5.0及以上版本使用。
140+- pinned_mem_register使用注意事项如下:
141+ - 特性要求Ascend Extension for PyTorch 26.0.0及以上版本、Ascend HDK 25.5.0及以上版本、CANN商发8.5.0及以上版本使用。
142+ - 与pin_memory_expandable_segments特性不支持同时配置。
129 143 
130## 支持的型号144## 支持的型号
131 145 
@@ -64,6 +64,9 @@ extern "C" {
64#define ACL_RT_VMM_EXPORT_FLAG_DEFAULT 0x0UL64#define ACL_RT_VMM_EXPORT_FLAG_DEFAULT 0x0UL
65#define ACL_RT_VMM_EXPORT_FLAG_DISABLE_PID_VALIDATION 0x1UL65#define ACL_RT_VMM_EXPORT_FLAG_DISABLE_PID_VALIDATION 0x1UL
66 66 
67+#define ACL_HOST_REG_MAPPED 0x2UL
68+#define ACL_HOST_REG_PINNED 0X10000000UL
69+ 
67#define ACL_VALUE_WAIT_EQ 0x170#define ACL_VALUE_WAIT_EQ 0x1
68 71 
69#define ACL_IPC_EVENT_HANDLE_SIZE 64U72#define ACL_IPC_EVENT_HANDLE_SIZE 64U
@@ -1125,6 +1128,19 @@ ACL_FUNC_VISIBILITY aclError aclrtMallocCached(void **devPtr,
1125ACL_FUNC_VISIBILITY aclError aclrtPointerGetAttributes(const void *ptr,1128ACL_FUNC_VISIBILITY aclError aclrtPointerGetAttributes(const void *ptr,
1126 aclrtPtrAttributes *attributes);1129 aclrtPtrAttributes *attributes);
1127 1130 
1131+/**
1132+ * @ingroup AscendCL
1133+ * @brief register an existing host memory range
1134+ *
1135+ * @param ptr [IN] host pointer to memory to page-lock
1136+ * @param size [IN] size in bytes of the address range to page-lock in bytes
1137+ * @param flag [IN] flag for allocation request
1138+ *
1139+ * @retval ACL_SUCCESS The function is successfully executed.
1140+ * @retval OtherValues Failure
1141+ */
1142+ACL_FUNC_VISIBILITY aclError aclrtHostRegisterV2(void *ptr, uint64_t size, uint32_t flag);
1143+ 
1128/**1144/**
1129 * @ingroup AscendCL1145 * @ingroup AscendCL
1130 * @brief flush cache data to ddr1146 * @brief flush cache data to ddr
@@ -194,14 +194,50 @@ private:
194 c10_npu::SetCurrentDevice();194 c10_npu::SetCurrentDevice();
195 }195 }
196 196 
197+ bool host_registered = false;
197 auto start = std::chrono::steady_clock::now();198 auto start = std::chrono::steady_clock::now();
198- aclError err = aclrtMallocHost(ptr, size);199+ static bool va_feature_support = true;
199- if (err != ACL_ERROR_NONE) {200+ if (c10_npu::acl::AclrtMallocHostWithCfgExist() && va_feature_support) {
200- CHECK_AND_THROW_ERROR_WITH_SPECIFIC_MESSAGE(err);201+ aclrtMallocAttrValue attrValue;
202+ attrValue.vaFlag = 1;
203+ 
204+ aclrtMallocAttribute attributes[1];
205+ attributes[0].attr = ACL_RT_MEM_ATTR_VA_FLAG;
206+ attributes[0].value = attrValue;
207+ 
208+ aclrtMallocConfig cfg;
209+ cfg.numAttrs = 1;
210+ cfg.attrs = attributes;
211+ 
212+ aclError mallocError = c10_npu::acl::AclrtMallocHostWithCfg(ptr, size, &cfg);
213+ bool pinned_mem_register = c10_npu::NPUCachingAllocator::CachingAllocatorConfig::pinned_mem_register();
214+ // if feature not support, then fall back to the old logic
215+ if (ACL_ERROR_RT_FEATURE_NOT_SUPPORT == mallocError) {
216+ va_feature_support = false;
217+ if (pinned_mem_register) {
218+ TORCH_NPU_WARN_ONCE("The pinned_mem_register configuration does not take effect, the current driver version does not support this feature."
219+ "To use this feature, you need to upgrade to version 25.5.0 or higher");
220+ }
221+ NPU_CHECK_ERROR(aclrtMallocHost(ptr, size), "aclrtMallocHost");
222+ } else {
223+ NPU_CHECK_ERROR(mallocError, "aclrtMallocHostWithCfg");
224+ if (pinned_mem_register) {
225+ NPU_CHECK_ERROR(c10_npu::acl::AclrtHostRegisterV2(*ptr, size, ACL_HOST_REG_MAPPED), "aclrtHostRegister failed.");
226+ host_registered = true;
227+ }
228+ }
229+ } else {
230+ aclError err = aclrtMallocHost(ptr, size);
231+ if (err != ACL_ERROR_NONE) {
232+ CHECK_AND_THROW_ERROR_WITH_SPECIFIC_MESSAGE(err);
233+ }
201 }234 }
235+ 
202 if (*ptr != nullptr) { // we add the segment pointer here when initialization, but it does not matter236 if (*ptr != nullptr) { // we add the segment pointer here when initialization, but it does not matter
203 std::lock_guard<std::mutex> g(npu_ptrs_mutex_);237 std::lock_guard<std::mutex> g(npu_ptrs_mutex_);
204 npu_ptrs_.insert(*ptr);238 npu_ptrs_.insert(*ptr);
239+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(use_host_register.count(*ptr) == 0);
240+ use_host_register[*ptr] = host_registered;
205 }241 }
206 auto end = std::chrono::steady_clock::now();242 auto end = std::chrono::steady_clock::now();
207 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);243 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
@@ -216,12 +252,22 @@ private:
216 {252 {
217 auto start = std::chrono::steady_clock::now();253 auto start = std::chrono::steady_clock::now();
218 void* ptr = block->ptr_;254 void* ptr = block->ptr_;
255+ bool use_register = false;
256+ {
257+ std::lock_guard<std::mutex> g(npu_ptrs_mutex_);
258+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(use_host_register.count(ptr) == 1);
259+ use_register = use_host_register[ptr];
260+ }
261+ if (use_register) {
262+ NPU_CHECK_ERROR(c10_npu::acl::AclrtHostUnregister(ptr), "aclrtHostUnregister");
263+ }
219 aclError err = aclrtFreeHost(block->ptr_);264 aclError err = aclrtFreeHost(block->ptr_);
220 if (err != ACL_ERROR_NONE) {265 if (err != ACL_ERROR_NONE) {
221 CHECK_AND_THROW_ERROR_WITH_SPECIFIC_MESSAGE(err);266 CHECK_AND_THROW_ERROR_WITH_SPECIFIC_MESSAGE(err);
222 }267 }
223 if (ptr != nullptr) {268 if (ptr != nullptr) {
224 std::lock_guard<std::mutex> g(npu_ptrs_mutex_);269 std::lock_guard<std::mutex> g(npu_ptrs_mutex_);
270+ use_host_register.erase(ptr);
225 npu_ptrs_.erase(block->ptr_);271 npu_ptrs_.erase(block->ptr_);
226 }272 }
227 auto end = std::chrono::steady_clock::now();273 auto end = std::chrono::steady_clock::now();
@@ -264,6 +310,7 @@ private:
264private:310private:
265 std::mutex npu_ptrs_mutex_;311 std::mutex npu_ptrs_mutex_;
266 ska::flat_hash_set<void*> npu_ptrs_;312 ska::flat_hash_set<void*> npu_ptrs_;
313+ ska::flat_hash_map<void*, bool> use_host_register;
267};314};
268 315 
269 316 
@@ -40,6 +40,17 @@ TORCH_NPU_API bool CachingHostAllocator_recordEvent(void* ptr, void* ctx, c10_np
40TORCH_NPU_API void CachingHostAllocator_emptyCache();40TORCH_NPU_API void CachingHostAllocator_emptyCache();
41 41 
42inline TORCH_NPU_API bool CachingHostAllocator_isPinned(void* ptr) {42inline TORCH_NPU_API bool CachingHostAllocator_isPinned(void* ptr) {
43+ if (c10_npu::acl::AclrtPointerGetAttributesExist()) {
44+ if (!c10_npu::NpuSysCtrl::GetInstance().GetInitFlag()) {
45+ return false;
46+ }
47+ if (c10_npu::GetLocalDevice() < 0) {
48+ c10_npu::SetCurrentDevice();
49+ }
50+ aclrtPtrAttributes attributes;
51+ NPU_CHECK_ERROR(c10_npu::acl::AclrtPointerGetAttributes(ptr, &attributes), "aclrtPointerGetAttributes");
52+ return ACL_MEM_LOCATION_TYPE_HOST == attributes.location.type;
53+ }
43 return at_npu::native::ptr_exist(ptr);54 return at_npu::native::ptr_exist(ptr);
44}55}
45 56 
@@ -132,6 +132,19 @@ namespace c10_npu {
132 return i;132 return i;
133 }133 }
134 134 
135+ size_t CachingAllocatorConfig::parsePinnedMemRegister(const std::vector<std::string> &config, size_t i)
136+ {
137+ consumeToken(config, ++i, ':');
138+ if (++i < config.size()) {
139+ TORCH_CHECK(i < config.size() && (config[i] == "True" || config[i] == "False"),
140+ "Expected a single True/False argument for pinned_mem_register", OPS_ERROR(ErrCode::PARAM));
141+ m_pinned_mem_register = (config[i] == "True");
142+ } else {
143+ TORCH_CHECK(false, "Error, expecting m_pinned_mem_register value", OPS_ERROR(ErrCode::VALUE));
144+ }
145+ return i;
146+ }
147+ 
135 size_t CachingAllocatorConfig::parseAddrAlignSize(const std::vector<std::string> &config, size_t i)148 size_t CachingAllocatorConfig::parseAddrAlignSize(const std::vector<std::string> &config, size_t i)
136 {149 {
137 consumeToken(config, ++i, ':');150 consumeToken(config, ++i, ':');
@@ -300,6 +313,8 @@ namespace c10_npu {
300 i = parseExpandableSegments(config, i);313 i = parseExpandableSegments(config, i);
301 } else if (config[i] == "pin_memory_expandable_segments") {314 } else if (config[i] == "pin_memory_expandable_segments") {
302 i = parsePinMemoryExpandableSegments(config, i);315 i = parsePinMemoryExpandableSegments(config, i);
316+ } else if (config[i] == "pinned_mem_register") {
317+ i = parsePinnedMemRegister(config, i);
303 } else if (config[i] == "base_addr_aligned_kb") {318 } else if (config[i] == "base_addr_aligned_kb") {
304 i = parseAddrAlignSize(config, i);319 i = parseAddrAlignSize(config, i);
305 } else if (config[i] == "page_size") {320 } else if (config[i] == "page_size") {
@@ -329,6 +344,20 @@ namespace c10_npu {
329 "`expandable_segments` is changed to `False` by default.");344 "`expandable_segments` is changed to `False` by default.");
330 }345 }
331 }346 }
347+ 
348+ if (m_pinned_mem_register) {
349+ if (!c10_npu::acl::AclrtMallocHostWithCfgExist()) {
350+ TORCH_NPU_WARN_ONCE("pinned_mem_register setting failure, the current cann version does not support this feature, now change to `False`."
351+ "To use this feature, you need to upgrade to version 8.5.0 or higher");
352+ m_pinned_mem_register = false;
353+ }
354+ 
355+ if (m_pinned_mem_register && m_pin_memory_expandable_segments) {
356+ m_pinned_mem_register = false;
357+ TORCH_NPU_WARN_ONCE("pinned_mem_register setting failure, this feature is not supported when pin_memory_expandable_segments is set to `True`,"
358+ " now change to `False`.");
359+ }
360+ }
332 }361 }
333 362 
334 } // namespace NPUCachingAllocator363 } // namespace NPUCachingAllocator
@@ -36,6 +36,11 @@ namespace c10_npu {
36 return instance().m_pin_memory_expandable_segments;36 return instance().m_pin_memory_expandable_segments;
37 }37 }
38 38 
39+ static bool pinned_mem_register()
40+ {
41+ return instance().m_pinned_mem_register;
42+ }
43+ 
39 static size_t base_addr_aligned_size()44 static size_t base_addr_aligned_size()
40 {45 {
41 return instance().m_base_addr_aligned_size;46 return instance().m_base_addr_aligned_size;
@@ -75,6 +80,8 @@ namespace c10_npu {
75 80 
76 bool m_pin_memory_expandable_segments;81 bool m_pin_memory_expandable_segments;
77 82 
83+ bool m_pinned_mem_register;
84+ 
78 bool set_expandable_segments_flag = false;85 bool set_expandable_segments_flag = false;
79 86 
80 size_t m_base_addr_aligned_size = kAlignRoundLarge;87 size_t m_base_addr_aligned_size = kAlignRoundLarge;
@@ -90,6 +97,7 @@ namespace c10_npu {
90 m_garbage_collection_threshold(0),97 m_garbage_collection_threshold(0),
91 m_expandable_segments(false),98 m_expandable_segments(false),
92 m_pin_memory_expandable_segments(false),99 m_pin_memory_expandable_segments(false),
100+ m_pinned_mem_register(false),
93 m_base_addr_aligned_size(kAlignRoundLarge),101 m_base_addr_aligned_size(kAlignRoundLarge),
94 m_segment_size_mb(0),102 m_segment_size_mb(0),
95 m_roundup_power2_divisions(kRoundUpPowerOfTwoIntervals, 0)103 m_roundup_power2_divisions(kRoundUpPowerOfTwoIntervals, 0)
@@ -107,6 +115,8 @@ namespace c10_npu {
107 115 
108 size_t parsePinMemoryExpandableSegments(const std::vector<std::string> &config, size_t i);116 size_t parsePinMemoryExpandableSegments(const std::vector<std::string> &config, size_t i);
109 117 
118+ size_t parsePinnedMemRegister(const std::vector<std::string> &config, size_t i);
119+ 
110 size_t parseAddrAlignSize(const std::vector<std::string> &config, size_t i);120 size_t parseAddrAlignSize(const std::vector<std::string> &config, size_t i);
111 121 
112 size_t parsePageSize(const std::vector<std::string> &config, size_t i);122 size_t parsePageSize(const std::vector<std::string> &config, size_t i);
@@ -87,6 +87,7 @@ LOAD_FUNCTION(aclmdlRICaptureTaskUpdateBegin)
87LOAD_FUNCTION(aclmdlRICaptureTaskUpdateEnd)87LOAD_FUNCTION(aclmdlRICaptureTaskUpdateEnd)
88LOAD_FUNCTION(aclmdlRIDebugJsonPrint)88LOAD_FUNCTION(aclmdlRIDebugJsonPrint)
89LOAD_FUNCTION(aclrtHostRegister)89LOAD_FUNCTION(aclrtHostRegister)
90+LOAD_FUNCTION(aclrtHostRegisterV2)
90LOAD_FUNCTION(aclrtHostUnregister)91LOAD_FUNCTION(aclrtHostUnregister)
91LOAD_FUNCTION(aclrtIpcMemGetExportKey)92LOAD_FUNCTION(aclrtIpcMemGetExportKey)
92LOAD_FUNCTION(aclrtIpcMemSetImportPid)93LOAD_FUNCTION(aclrtIpcMemSetImportPid)
@@ -1108,6 +1109,18 @@ aclError AclrtHostRegister(void *ptr, uint64_t size, aclrtHostRegisterType type,
1108 return func(ptr, size, type, devPtr);1109 return func(ptr, size, type, devPtr);
1109}1110}
1110 1111 
1112+aclError AclrtHostRegisterV2(void *ptr, uint64_t size, uint32_t flag)
1113+{
1114+ typedef aclError (*AclrtHostRegisterV2)(void *ptr, uint64_t size, uint32_t flag);
1115+ static AclrtHostRegisterV2 func = nullptr;
1116+ if (func == nullptr) {
1117+ func = (AclrtHostRegisterV2) GET_FUNC(aclrtHostRegisterV2);
1118+ }
1119+ 
1120+ TORCH_CHECK(func, "Failed to find function aclrtHostRegisterV2", PTA_ERROR(ErrCode::NOT_FOUND));
1121+ return func(ptr, size, flag);
1122+}
1123+ 
1111aclError AclrtHostUnregister(void *ptr)1124aclError AclrtHostUnregister(void *ptr)
1112{1125{
1113 typedef aclError (*AclrtHostUnregister)(void *);1126 typedef aclError (*AclrtHostUnregister)(void *);
@@ -248,6 +248,19 @@ aclError AclmdlRIDebugJsonPrint(aclmdlRI modelRI, const char* path);
248 */248 */
249aclError AclrtHostRegister(void *ptr, uint64_t size, aclrtHostRegisterType type, void **devPtr);249aclError AclrtHostRegister(void *ptr, uint64_t size, aclrtHostRegisterType type, void **devPtr);
250 250 
251+/**
252+ * @ingroup AscendCL
253+ * @brief register an existing host memory range
254+ *
255+ * @param ptr [IN] host pointer to memory to page-lock
256+ * @param size [IN] size in bytes of the address range to page-lock in bytes
257+ * @param flag [IN] flag for allocation request
258+ *
259+ * @retval ACL_SUCCESS The function is successfully executed.
260+ * @retval OtherValues Failure
261+ */
262+aclError AclrtHostRegisterV2(void *ptr, uint64_t size, uint32_t flag);
263+ 
251/**264/**
252 * @ingroup AscendCL265 * @ingroup AscendCL
253 * @brief unregister host memory266 * @brief unregister host memory