refactor: simplify options manager mode validation

Co-authored-by: chujinjin<chujinjin52@huawei.com>



# message auto-generated for no-merge-commit merge:
!46410 merge refactor/options-manager-mode-validation into master

refactor: simplify options manager mode validation

Created-by: chujinjin
Commit-by: chujinjin
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->

# 【合入来源】
> <font color="red">**如有社区issue,请关联issue链接**</font>\
> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font>

- [ ] 需求
- [ ] 问题单
- [ ] issue/工单
- [x] 重构优化
- [ ] 资料更新

# 【修改方案】

- 1. 将 OptionsManager.h 中用于校验环境变量取值的模式映射移至 OptionsManager.cpp 的匿名命名空间,并让相关校验函数直接使用这些映射。原先的映射获取函数定义在头文件中,下游项目即使没有调用它们,只要包含该头文件就可能产生 -Wunused-function 警告。迁移后,头文件不再引入这些未使用的函数定义。此项修改对应 issue #5054 (https://gitcode.com/Ascend/pytorch/issues/5054)。

- 2. 保留各环境变量原有的默认值、合法取值和异常处理逻辑。此次调整只改变模式映射的存放位置及使用方式,不改变 OptionsManager 对环境变量的校验结果。
- 3. 将原本依赖头文件内容的公开环境变量模式兼容性检查移至 tools/check_public_environments.py。脚本读取 torch_npu_schema.json 和 OptionsManager.cpp,规范化空白字符后检查模式定义是否仍与 schema 一致;同时更新受排版调整影响的 schema记录。

- 4. 在 CMake 中添加兼容性检查目标,并将其设为插件构建的依赖,使构建过程继续执行这项检查。

# 【资料变更】
> 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及”

# 【接口变更】
> 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及”

# 【功能验证】
> 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\
> 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图

# 【CheckList】
> PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]

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


See merge request: Ascend/pytorch!46410
This commit is contained in:
chujinjin
2026-09-29 15:47:29 +08:00
committed by ascend-robot
parent 555ecb4488
commit 2516c6185f
6 changed files with 108 additions and 110 deletions
+14
View File
@@ -13,6 +13,19 @@ endif()
project(TORCHNPU CXX C)
add_compile_options(-fmacro-prefix-map=${CMAKE_SOURCE_DIR}/=)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
set(PUBLIC_ENV_CHECK_SCRIPT ${PROJECT_SOURCE_DIR}/tools/check_public_environments.py)
set(PUBLIC_ENV_SCHEMA ${PROJECT_SOURCE_DIR}/test/torch_npu_schema.json)
set(PUBLIC_ENV_SOURCE ${PROJECT_SOURCE_DIR}/torch_npu/csrc/core/npu/register/OptionsManager.cpp)
add_custom_target(check_public_environments
COMMAND ${Python3_EXECUTABLE} ${PUBLIC_ENV_CHECK_SCRIPT}
--schema ${PUBLIC_ENV_SCHEMA}
--source ${PUBLIC_ENV_SOURCE}
DEPENDS ${PUBLIC_ENV_CHECK_SCRIPT} ${PUBLIC_ENV_SCHEMA} ${PUBLIC_ENV_SOURCE}
COMMENT "Checking public environment variable modes"
VERBATIM)
find_program(MOLD_LINKER mold)
if(MOLD_LINKER)
add_link_options(-fuse-ld=mold)
@@ -321,6 +334,7 @@ else()
endif()
add_library(torch_npu_objs OBJECT ${CPP_SRCS})
add_dependencies(torch_npu_objs check_public_environments)
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-fvisibility=hidden" COMPILER_SUPPORTS_HIDDEN_VISIBILITY)
if(${COMPILER_SUPPORTS_HIDDEN_VISIBILITY})
+8 -35
View File
@@ -48,7 +48,7 @@ NOT_IMPORT_LIST = [
def set_failure_list(api_str, value, signature, failure_list):
failure_list.append(f"# {api_str}:")
failure_list.append(f" - function signature is different: ")
failure_list.append(" - function signature is different: ")
failure_list.append(f" - the base signature is {value}.")
failure_list.append(f" - now it is {signature}.")
@@ -220,8 +220,8 @@ def _discover_path_importables(pkg_pth, pkg_name):
yield from (
pkg_path
for _, pkg_path, _ in pkgutil.walk_packages(
(str(pkg_dir_path),), prefix=f'{pkg_pref}.',
)
(str(pkg_dir_path),), prefix=f'{pkg_pref}.',
)
)
@@ -319,9 +319,11 @@ class TestPublicApiCompatibility(TestCase):
return
modname = allow_dict["being_migrated"].get(modname, modname)
elem_modname_starts_with_mod = elem_module is not None and \
elem_module.startswith(modname) and \
'._' not in elem_module
elem_modname_starts_with_mod = (
elem_module is not None
and elem_module.startswith(modname)
and '._' not in elem_module
)
looks_public = not elem.startswith('_') and elem_modname_starts_with_mod
is_public_api = False
@@ -418,34 +420,5 @@ class TestPublicApiCompatibility(TestCase):
self.assertTrue(not failure_list, msg)
def test_public_environments(self):
torch_npu_path = os.path.abspath(os.path.dirname(torch_npu.__file__))
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)), "torch_npu_schema.json")) as fp:
base_schema = json.load(fp)
failure_list = []
file = "torch_npu/csrc/core/npu/register/OptionsManager.h"
path = os.path.join(torch_npu_path, "include", file)
with open(path, mode='r') as fp:
context = fp.read()
for key, value in base_schema.items():
if key.startswith("torch_npu_public_env"):
base_mode = value["mode"]
if base_mode not in context:
key = key.replace("torch_npu_public_env: ", "")
failure_list.append(f"# {key}:")
failure_list.append(f" - the mode of the environment variable {key} has been changed.")
msg = "All the environment variable's mode below do not meet the compatibility guidelines. "
msg += "If the change timeline has been reached, you can modify the torch_npu_schema.json to make it OK."
msg += "\n\nFull list:\n"
msg += "\n".join(map(str, failure_list))
# empty lists are considered false in python
self.assertTrue(not failure_list, msg)
if __name__ == '__main__':
run_tests()
+2 -2
View File
@@ -2463,13 +2463,13 @@
"mode": " std::unordered_map<int32_t, std::string> launchBlockingMode = {{0, \"disable\"}, {1, \"enable\"}};"
},
"torch_npu_public_env: TORCH_HCCL_ASYNC_ERROR_HANDLING": {
"mode": " std::unordered_map<int32_t, std::string> asyncErrorHandlingMode = {\n {0, \"NoHandling\"}, {1, \"TearDown\"}, {2, \"CleanUpOnly\"}, {3, \"SkipCleanUp\"}};"
"mode": " std::unordered_map<int32_t, std::string> asyncErrorHandlingMode = {\n {0, \"NoHandling\"},\n {1, \"TearDown\"},\n {2, \"CleanUpOnly\"},\n {3, \"SkipCleanUp\"}};"
},
"torch_npu_public_env: TORCH_HCCL_DESYNC_DEBUG": {
"mode": " std::unordered_map<int32_t, std::string> desyncDebugMode = {{0, \"close\"}, {1, \"open\"}};"
},
"torch_npu_public_env: ASCEND_GLOBAL_LOG_LEVEL": {
"mode": " std::unordered_map<int32_t, std::string> logLevelMode = {\n {0, \"debug\"}, {1, \"info\"}, {2, \"warning\"}, {3, \"error\"}, {4, \"null\"}};"
"mode": " std::unordered_map<int32_t, std::string> logLevelMode =\n {{0, \"debug\"}, {1, \"info\"}, {2, \"warning\"}, {3, \"error\"}, {4, \"null\"}};"
},
"torch_npu_public_env: PYTORCH_NO_NPU_MEMORY_CACHING": {
"mode": " std::unordered_map<int32_t, std::string> memoryCacheMode = {{0, \"open\"}, {1, \"close\"}};"
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path
PUBLIC_ENV_PREFIX = "torch_npu_public_env: "
def normalize_whitespace(value):
return re.sub(r"\s+", " ", value).strip()
def check_public_environments(schema_path, source_path):
with schema_path.open(encoding="utf-8") as schema_file:
schema = json.load(schema_file)
source = normalize_whitespace(source_path.read_text(encoding="utf-8"))
failures = []
for key, value in schema.items():
if not key.startswith(PUBLIC_ENV_PREFIX):
continue
if normalize_whitespace(value["mode"]) not in source:
env_name = key.removeprefix(PUBLIC_ENV_PREFIX)
failures.append(f"the mode of the environment variable {env_name} has been changed")
return failures
def main():
parser = argparse.ArgumentParser(description="Check public environment variable modes.")
parser.add_argument("--schema", required=True, type=Path)
parser.add_argument("--source", required=True, type=Path)
args = parser.parse_args()
failures = check_public_environments(args.schema, args.source)
if failures:
for failure in failures:
print(f"ERROR: {failure}")
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -32,6 +32,40 @@ namespace option {
using namespace std;
namespace {
std::unordered_map<int32_t, std::string> hcclZeroCopyMode = {{0, "close"}, {1, "open"}};
std::unordered_map<int32_t, std::string> infNanMode = {{0, "max"}, {1, "inf_nan"}};
std::unordered_map<int32_t, std::string> disableInfNanMode = {{0, "enable"}, {1, "disable"}};
std::unordered_map<int32_t, std::string> combinedEnableMode = {{0, "close"}, {1, "open"}};
std::unordered_map<int32_t, std::string> launchBlockingMode = {{0, "disable"}, {1, "enable"}};
std::unordered_map<int32_t, std::string> asyncErrorHandlingMode = {
{0, "NoHandling"},
{1, "TearDown"},
{2, "CleanUpOnly"},
{3, "SkipCleanUp"}};
std::unordered_map<int32_t, std::string> desyncDebugMode = {{0, "close"}, {1, "open"}};
std::unordered_map<int32_t, std::string> logLevelMode =
{{0, "debug"}, {1, "info"}, {2, "warning"}, {3, "error"}, {4, "null"}};
std::unordered_map<int32_t, std::string> memoryCacheMode = {{0, "open"}, {1, "close"}};
std::unordered_map<int32_t, std::string> taskQueueEnableMode = {{0, "close"}, {1, "level 1"}, {2, "level 2"}};
std::unordered_map<int32_t, std::string> aclOpInitMode = {
{0, "aclops init"},
{1, "aclops lazy init"},
{2, "aclops disabled"}};
} // namespace
std::atomic<int32_t> g_task_queue_enable_mode{TASK_QUEUE_ENABLE_ENV};
char* get_and_log_env(const char* env_str) {
@@ -45,7 +79,6 @@ char* get_and_log_env(const char* env_str) {
bool OptionsManager::IsHcclZeroCopyEnable() {
const static bool isHcclZeroCopyEnable = []() -> bool {
int32_t enable = OptionsManager::GetBoolTypeOption("TORCH_HCCL_ZERO_COPY", 0);
std::unordered_map<int32_t, std::string> hcclZeroCopyMode = getHcclZeroCopyMode();
if (hcclZeroCopyMode.find(enable) == hcclZeroCopyMode.end()) {
TORCH_CHECK(false, "TORCH_HCCL_ZERO_COPY should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -131,7 +164,6 @@ ReuseMode OptionsManager::GetMultiStreamMemoryReuse() {
bool OptionsManager::CheckInfNanModeEnable() {
const static bool checkInfNanModeEnable = []() -> bool {
int32_t enable = OptionsManager::GetBoolTypeOption("INF_NAN_MODE_ENABLE", 1);
std::unordered_map<int32_t, std::string> infNanMode = getInfNanMode();
if (infNanMode.find(enable) == infNanMode.end()) {
TORCH_CHECK(false, "INF_NAN_MODE_ENABLE should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -143,7 +175,6 @@ bool OptionsManager::CheckInfNanModeEnable() {
bool OptionsManager::CheckInfNanModeForceDisable() {
const static bool checkInfNanModeForceDisable = []() -> bool {
int32_t disable = OptionsManager::GetBoolTypeOption("INF_NAN_MODE_FORCE_DISABLE", 0);
std::unordered_map<int32_t, std::string> disableInfNanMode = getDisableInfNanMode();
if (disableInfNanMode.find(disable) == disableInfNanMode.end()) {
TORCH_CHECK(false, "INF_NAN_MODE_FORCE_DISABLE should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -155,7 +186,6 @@ bool OptionsManager::CheckInfNanModeForceDisable() {
bool OptionsManager::CheckBlockingEnable() {
const static bool checkBlockingEnable = []() -> bool {
int32_t blocking_enable = OptionsManager::GetBoolTypeOption("ASCEND_LAUNCH_BLOCKING", 0);
std::unordered_map<int32_t, std::string> launchBlockingMode = getLaunchBlockingMode();
if (launchBlockingMode.find(blocking_enable) == launchBlockingMode.end()) {
TORCH_CHECK(false, "ASCEND_LAUNCH_BLOCKING should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -167,7 +197,6 @@ bool OptionsManager::CheckBlockingEnable() {
bool OptionsManager::CheckCombinedOptimizerEnable() {
const static bool checkCombinedOptimizerEnable = []() -> bool {
int32_t combined_optimize = OptionsManager::GetBoolTypeOption("COMBINED_ENABLE");
std::unordered_map<int32_t, std::string> combinedEnableMode = getCombinedEnableMode();
if (combinedEnableMode.find(combined_optimize) == combinedEnableMode.end()) {
TORCH_CHECK(false, "COMBINED_ENABLE should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -261,7 +290,6 @@ uint32_t OptionsManager::CheckUseHcclAsyncErrorHandleEnable() {
}
}
int64_t envFlag = (env_val != nullptr) ? strtol(env_val, nullptr, 10) : 1;
std::unordered_map<int32_t, std::string> asyncErrorHandlingMode = getAsyncErrorHandlingMode();
if (asyncErrorHandlingMode.find(envFlag) == asyncErrorHandlingMode.end()) {
TORCH_CHECK(false, "TORCH_HCCL_ASYNC_ERROR_HANDLING should be 0, 1, 2, or 3.", PTA_ERROR(ErrCode::VALUE));
}
@@ -282,7 +310,6 @@ uint32_t OptionsManager::CheckUseDesyncDebugEnable() {
}
}
int64_t envFlag = (env_val != nullptr) ? strtol(env_val, nullptr, 10) : 0;
std::unordered_map<int32_t, std::string> desyncDebugMode = getDesyncDebugMode();
if (desyncDebugMode.find(envFlag) == desyncDebugMode.end()) {
TORCH_CHECK(false, "TORCH_HCCL_DESYNC_DEBUG should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -298,7 +325,6 @@ bool OptionsManager::isACLGlobalLogOn(aclLogLevel level) {
char* env_val = std::getenv("ASCEND_GLOBAL_LOG_LEVEL");
TORCH_NPU_LOGI(c10_npu::GetEnvLogger(), "get env ASCEND_GLOBAL_LOG_LEVEL = %s", env_val);
int64_t envFlag = (env_val != nullptr) ? strtol(env_val, nullptr, 10) : ACL_ERROR;
std::unordered_map<int32_t, std::string> logLevelMode = getLogLevelMode();
if (logLevelMode.find(envFlag) == logLevelMode.end()) {
TORCH_CHECK(false, "ASCEND_GLOBAL_LOG_LEVEL should be 0, 1, 2, 3 or 4.", PTA_ERROR(ErrCode::VALUE));
}
@@ -565,8 +591,7 @@ uint32_t OptionsManager::GetAclOpInitMode() {
", automatically switched to 2.");
return default_mode;
}
auto acl_op_init_mode_map = getAclOpInitMode();
if (acl_op_init_mode_map.find(static_cast<int32_t>(env_mode)) == acl_op_init_mode_map.end()) {
if (aclOpInitMode.find(static_cast<int32_t>(env_mode)) == aclOpInitMode.end()) {
TORCH_NPU_WARN_ONCE(
"Get env ACL_OP_INIT_MODE not in [0, 1, 2], so reset it to the default value ", default_mode, ".");
return default_mode;
@@ -609,7 +634,6 @@ uint32_t OptionsManager::GetTaskQueueEnable() {
const static uint32_t task_queue_enable = []() -> uint32_t {
char* env_val = get_and_log_env("TASK_QUEUE_ENABLE");
int64_t task_queue_enable = (env_val != nullptr) ? strtol(env_val, nullptr, 10) : 1;
std::unordered_map<int32_t, std::string> taskQueueEnableMode = getTaskQueueEnableMode();
if (taskQueueEnableMode.find(task_queue_enable) == taskQueueEnableMode.end()) {
TORCH_CHECK(false, "TASK_QUEUE_ENABLE should be 0, 1 or 2", PTA_ERROR(ErrCode::VALUE));
}
@@ -619,9 +643,8 @@ uint32_t OptionsManager::GetTaskQueueEnable() {
}
void OptionsManager::SetTaskQueueEnable(int32_t mode) {
auto valid_modes = getTaskQueueEnableMode();
TORCH_CHECK(
valid_modes.find(mode) != valid_modes.end(),
taskQueueEnableMode.find(mode) != taskQueueEnableMode.end(),
"TASK_QUEUE_ENABLE should be 0, 1 or 2, but got ",
mode,
PTA_ERROR(ErrCode::VALUE));
@@ -645,7 +668,6 @@ uint32_t OptionsManager::GetPerStreamQueue() {
bool OptionsManager::CheckForceUncached() {
const static bool force_uncached = []() -> bool {
bool force_uncached = OptionsManager::GetBoolTypeOption("PYTORCH_NO_NPU_MEMORY_CACHING");
std::unordered_map<int32_t, std::string> memoryCacheMode = getMemoryCacheMode();
if (memoryCacheMode.find(force_uncached) == memoryCacheMode.end()) {
TORCH_CHECK(false, "PYTORCH_NO_NPU_MEMORY_CACHING should be 0 or 1.", PTA_ERROR(ErrCode::VALUE));
}
@@ -2,10 +2,10 @@
#include <atomic>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "torch_npu/csrc/core/npu/NPUException.h"
#include "torch_npu/csrc/core/npu/NPUMacros.h"
@@ -38,68 +38,10 @@ enum SilenceCheckMode {
PRINT_ALL_LOG = 3,
};
static std::unordered_map<int32_t, std::string> getHcclZeroCopyMode() {
std::unordered_map<int32_t, std::string> hcclZeroCopyMode = {{0, "close"}, {1, "open"}};
return hcclZeroCopyMode;
}
static std::unordered_map<int32_t, std::string> getInfNanMode() {
std::unordered_map<int32_t, std::string> infNanMode = {{0, "max"}, {1, "inf_nan"}};
return infNanMode;
}
static std::unordered_map<int32_t, std::string> getDisableInfNanMode() {
std::unordered_map<int32_t, std::string> disableInfNanMode = {{0, "enable"}, {1, "disable"}};
return disableInfNanMode;
}
static std::unordered_map<int32_t, std::string> getCombinedEnableMode() {
std::unordered_map<int32_t, std::string> combinedEnableMode = {{0, "close"}, {1, "open"}};
return combinedEnableMode;
}
static std::unordered_map<int32_t, std::string> getLaunchBlockingMode() {
std::unordered_map<int32_t, std::string> launchBlockingMode = {{0, "disable"}, {1, "enable"}};
return launchBlockingMode;
}
static std::unordered_map<int32_t, std::string> getAsyncErrorHandlingMode() {
std::unordered_map<int32_t, std::string> asyncErrorHandlingMode = {
{0, "NoHandling"}, {1, "TearDown"}, {2, "CleanUpOnly"}, {3, "SkipCleanUp"}};
return asyncErrorHandlingMode;
}
static std::unordered_map<int32_t, std::string> getDesyncDebugMode() {
std::unordered_map<int32_t, std::string> desyncDebugMode = {{0, "close"}, {1, "open"}};
return desyncDebugMode;
}
static std::unordered_map<int32_t, std::string> getLogLevelMode() {
std::unordered_map<int32_t, std::string> logLevelMode = {
{0, "debug"}, {1, "info"}, {2, "warning"}, {3, "error"}, {4, "null"}};
return logLevelMode;
}
static std::unordered_map<int32_t, std::string> getMemoryCacheMode() {
std::unordered_map<int32_t, std::string> memoryCacheMode = {{0, "open"}, {1, "close"}};
return memoryCacheMode;
}
static std::unordered_map<int32_t, std::string> getTaskQueueEnableMode() {
std::unordered_map<int32_t, std::string> taskQueueEnableMode = {{0, "close"}, {1, "level 1"}, {2, "level 2"}};
return taskQueueEnableMode;
}
// Sentinel value: user has not called set_task_queue_enable, fallback to env var
constexpr int32_t TASK_QUEUE_ENABLE_ENV = -1;
extern std::atomic<int32_t> g_task_queue_enable_mode;
static std::unordered_map<int32_t, std::string> getAclOpInitMode() {
std::unordered_map<int32_t, std::string> aclOpInitMode = {
{0, "aclops init"}, {1, "aclops lazy init"}, {2, "aclops disabled"}};
return aclOpInitMode;
}
class OptionsManager {
public:
static bool IsHcclZeroCopyEnable();