"""用于统一 NPU/CUDA 调用的兼容性辅助函数。 该模块提供了一组在仓库中复用的轻量函数,优先使用 `torch.npu` 或 `torch_npu`(如果可用)的 NPU 能力;若无则回退到 CUDA;再无则使用 CPU。 仅提供小而明确的辅助,避免对现有代码做大规模侵入式改动。 """ from __future__ import annotations import contextlib import typing import torch import importlib import warnings import os _HAS_TORCH_NPU = False try: # 部分 NPU 发行版直接提供 `torch.npu`,或通过独立的 `torch_npu` 包暴露接口。 if hasattr(torch, "npu"): _HAS_TORCH_NPU = True else: # 在导入 torch_npu 时屏蔽常见的冗余告警 with warnings.catch_warnings(): warnings.filterwarnings( "ignore", category=ImportWarning, module=r"torch_npu\.contrib\.transfer_to_npu", ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message=r".*torch\.jit\.script.*", ) importlib.import_module("torch_npu") _HAS_TORCH_NPU = True except Exception: _HAS_TORCH_NPU = False def is_npu_available() -> bool: """返回 NPU 运行时是否可用。""" if _HAS_TORCH_NPU and hasattr(torch, "npu"): try: return torch.npu.is_available() except Exception: return True return False # 返回可用设备数量(优先 NPU) def device_count() -> int: if is_npu_available() and hasattr(torch, "npu"): try: return torch.npu.device_count() except Exception: return 0 # 查询当前设备的可用/总内存,优先 NPU def mem_get_info() -> typing.Tuple[int, int]: """返回当前设备的 (free, total) 内存信息(字节)。 """ # 若存在 torch.npu 且提供 mem_get_info 风格的接口则优先使用 if is_npu_available() and hasattr(torch, "npu"): try: if hasattr(torch.npu, "mem_get_info"): return torch.npu.mem_get_info() except Exception: pass # 尝试 torch_npu 包(许多发行版在此暴露 NPU 辅助接口) try: tn = importlib.import_module("torch_npu") # 常见位置:torch_npu.npu.memory_stats / memory_stats_as_nested_dict npu_mod = getattr(tn, "npu", None) # 从统计字典中抽取 free/total 的辅助函数 def _extract_free_total(stats) -> typing.Optional[typing.Tuple[int, int]]: # 非字典则直接放弃 if not isinstance(stats, dict): return None # 直接键命中 if "total" in stats and "free" in stats: try: return int(stats["free"]), int(stats["total"]) except Exception: pass # 常见模式:total 与 used/allocated -> free = total - used if "total" in stats and ("used" in stats or "allocated" in stats): try: used = int(stats.get("used", stats.get("allocated"))) total = int(stats["total"]) return max(total - used, 0), total except Exception: pass # reserved/allocated 模式 if "reserved" in stats and "allocated" in stats: try: total = int(stats.get("reserved")) allocated = int(stats.get("allocated")) return max(total - allocated, 0), total except Exception: pass # 展平嵌套字典并搜索可能的键 def _walk(d): for k, v in d.items(): if isinstance(v, dict): for sub in _walk(v): yield sub else: yield (k, v) flat = dict(_walk(stats)) # 尝试找到数值候选项 nums = {k: v for k, v in flat.items() if isinstance(v, (int, float))} if not nums: return None # 启发式:优先包含 'total' 与 'free'/'avail'/'used' 的键 total_key = None free_key = None for k in nums: lk = k.lower() if "total" in lk or "reserved" in lk: total_key = k break for k in nums: lk = k.lower() if "free" in lk or "avail" in lk or "available" in lk: free_key = k break if total_key and free_key: try: return int(nums[free_key]), int(nums[total_key]) except Exception: pass # 回退:若有 total 与任一 allocated/used,则计算 free if total_key: for k in nums: lk = k.lower() if "used" in lk or "alloc" in lk: try: return max(int(nums[total_key]) - int(nums[k]), 0), int(nums[total_key]) except Exception: pass return None # 若可用,优先使用 npu.memory_stats if npu_mod is not None: try: if hasattr(npu_mod, "memory_stats"): stats = npu_mod.memory_stats(device=None) got = _extract_free_total(stats) if got: return got if hasattr(npu_mod, "memory_stats_as_nested_dict"): stats = npu_mod.memory_stats_as_nested_dict(device=None) got = _extract_free_total(stats) if got: return got # 尝试其他辅助接口 if hasattr(npu_mod, "memory_summary"): # memory_summary 返回字符串,为安全起见不解析 pass except Exception: pass # 最后尝试 torch_npu 顶层的相关辅助 for name in ["memory_stats", "memory_stats_as_nested_dict", "memory_snapshot", "memory_summary"]: fn = getattr(tn, name, None) if callable(fn): try: stats = fn() if name != "memory_summary" else None if stats is not None: got = _extract_free_total(stats) if got: return got except Exception: pass except Exception: pass # NPU/CUDA 内存接口均不可用:返回安全默认值 try: import warnings warnings.warn("npu_compat.mem_get_info: no NPU mem API found and CUDA unavailable; returning (0,0)") except Exception: pass return (0, 0) # 获取设备的峰值已分配显存(优先 NPU) def max_memory_allocated(device: typing.Optional[int] = None) -> int: if is_npu_available() and hasattr(torch, "npu"): try: if device is None: return torch.npu.max_memory_allocated() return torch.npu.max_memory_allocated(device) except Exception: pass # 重置峰值已分配显存统计(优先 NPU) def reset_max_memory_allocated(device: typing.Optional[int] = None): if is_npu_available() and hasattr(torch, "npu"): try: if device is None: return torch.npu.reset_max_memory_allocated() return torch.npu.reset_max_memory_allocated(device) except Exception: pass # 重置峰值显存统计(优先 NPU) def reset_peak_memory_stats(): if is_npu_available() and hasattr(torch, "npu"): try: return torch.npu.reset_peak_memory_stats() except Exception: pass # 清理缓存显存(优先 NPU) def empty_cache(): if is_npu_available() and hasattr(torch, "npu"): try: return torch.npu.empty_cache() except Exception: pass # 为所有设备设置随机种子(优先 NPU) def manual_seed_all(seed: int): if is_npu_available(): torch.npu.manual_seed_all(seed) else: logging.warning("manual_seed_all: NPU not available, falling back to CUDA if available") # 设备同步(优先 NPU,再到 CUDA) def synchronize(): """同步设备;优先 NPU,再到 CUDA,尽力而为。""" if is_npu_available() and hasattr(torch, "npu"): try: if hasattr(torch.npu, "synchronize"): return torch.npu.synchronize() except Exception: pass # 返回自动混合精度上下文应使用的设备类型 def manual_device_type() -> str: """返回自动混合精度/上下文优选的设备类型字符串:'npu'|'cpu'。""" if is_npu_available(): return "npu" return "cpu" # 设置当前活动设备(优先 NPU) def set_device(index: int) -> None: """按索引选择 NPU 的活动设备。 - NPU:优先 `torch.npu.set_device(index)`,若用户已设置 `ASCEND_VISIBLE_DEVICES` 亦尊重。 - CPU:不执行任何操作。 可在模型创建前的程序启动阶段安全调用。 """ try: if index is None: return # Normalize index to int idx = int(index) except Exception: return # Prefer NPU if available if is_npu_available() and hasattr(torch, "npu"): try: # If the environment already constrains visible devices, we still set current device if hasattr(torch.npu, "set_device"): torch.npu.set_device(idx) return except Exception: pass # Fallback: some distros may expose set_device under torch_npu.npu try: tn = importlib.import_module("torch_npu") if hasattr(tn, "npu") and hasattr(tn.npu, "set_device"): tn.npu.set_device(idx) return except Exception: pass # CPU: nothing to do return def safe_set_device(index: typing.Optional[int]) -> int: """安全设置活动设备索引,并返回最终生效的索引。 - 将传入索引规范化为 `int`;若无效则回退为 0。 - 使用 `device_count()` 对索引进行边界裁剪,避免越界或负值。 - 调用 `set_device()` 应用设备选择(优先 NPU,回退 CUDA)。 - 返回最终使用的设备索引。 """ try: idx = int(index) if index is not None else 0 except Exception: idx = 0 try: visible = device_count() except Exception: visible = None if visible and (idx < 0 or idx >= visible): idx = 0 set_device(idx) return idx,visible # 将张量移动到可用设备(优先 NPU) def to_device(t: torch.Tensor) -> torch.Tensor: """若有 NPU 则迁移到 NPU,否则若有 CUDA 则迁移到 CUDA,否则保持不变。""" if is_npu_available(): try: return t.npu() except Exception: return t.to("npu") return t # 获取自动混合精度的 GradScaler(优先 NPU) def amp_grad_scaler(enabled: bool = True): """返回可用设备的 AMP GradScaler(优先 NPU)。""" # 若存在 torch.npu.amp 则优先 if is_npu_available() and hasattr(torch, "npu") and hasattr(torch, "amp") and hasattr(torch.amp, "GradScaler"): try: # Some NPU distributions expose amp under torch.amp return torch.amp.GradScaler(enabled=enabled) except Exception: pass # 根据优选设备类型封装 autocast 上下文 @contextlib.contextmanager def autocast(dtype=torch.float16, enabled=True): """为优选设备类型封装 torch.autocast 的上下文管理器。""" device_type = manual_device_type() if device_type == "cpu": # CPU 不支持或无需 autocast:直接空操作 yield else: # torch.autocast 支持 device_type 字符串 with torch.autocast(device_type=device_type, dtype=dtype, enabled=enabled): yield # 设备名称查询(优先 NPU,再到 CUDA) def get_device_name(index: typing.Optional[int] = None) -> typing.Optional[str]: """返回指定设备索引的设备名称/芯片型号。 - NPU:优先使用 `torch.npu.get_device_name`,回退到 `torch_npu.get_device_name` 或 `torch_npu.npu.get_device_name`(若可用)。 - CPU:返回 None。 """ try: idx = int(index) if index is not None else None except Exception: idx = None if is_npu_available() and hasattr(torch, "npu"): try: if hasattr(torch.npu, "get_device_name"): return str(torch.npu.get_device_name(idx if idx is not None else 0)) except Exception: pass try: tn = importlib.import_module("torch_npu") if hasattr(tn, "get_device_name"): return str(tn.get_device_name(idx if idx is not None else 0)) if hasattr(tn, "npu") and hasattr(tn.npu, "get_device_name"): return str(tn.npu.get_device_name(idx if idx is not None else 0)) except Exception: pass return None def current_device_index() -> typing.Optional[int]: """返回当前活动设备索引(优先 NPU,再到 CUDA)。若不可用则返回 None。""" if is_npu_available() and hasattr(torch, "npu"): try: if hasattr(torch.npu, "current_device"): return int(torch.npu.current_device()) except Exception: pass return 0 return None def get_active_device_info() -> typing.Tuple[typing.Optional[str], typing.Optional[int], typing.Optional[int], typing.Optional[str]]: """返回当前活跃设备信息 (dev_type, dev_idx, total_gb, device_name)。 - dev_type: 'npu' | None(CPU/未知) - dev_idx: 设备索引(若未知则 0,CPU 则 None) - total_gb: 设备总显存(GB,若不可得则 None) - device_name: 设备名称/芯片型号(若不可得则 None) """ dev_type: typing.Optional[str] = None dev_idx: typing.Optional[int] = None total_gb: typing.Optional[int] = None device_name: typing.Optional[str] = None try: if is_npu_available(): dev_type = "npu" try: dev_idx = current_device_index() if dev_idx is None: dev_idx = 0 except Exception: dev_idx = 0 try: _, total_b = mem_get_info() total_gb = int(total_b / 1024 ** 3) if total_b else None except Exception: total_gb = None try: device_name = get_device_name(dev_idx) except Exception: device_name = None except Exception: logging.warning("get_active_device_info: failed to get device info", exc_info=True) return dev_type, dev_idx, total_gb, device_name def collect_npu_memory_metrics() -> dict: """收集设备显存指标(优先 NPU,回退 CUDA),返回用于日志的字典。 指标包括: - npu_mem_free_gb / npu_mem_used_gb / npu_mem_total_gb - npu_mem_peak_gb(所有设备峰值分配总和) - 以及可选的 allocated/reserved 当前/峰值(若 torch_npu.memory_stats 可用) """ metrics: dict = {} # 基础 free/total/used try: free_bytes, total_bytes = mem_get_info() used_bytes = max((total_bytes or 0) - (free_bytes or 0), 0) if total_bytes: metrics["npu_mem_free_gb"] = free_bytes / 1024 ** 3 metrics["npu_mem_used_gb"] = used_bytes / 1024 ** 3 metrics["npu_mem_total_gb"] = total_bytes / 1024 ** 3 except Exception: pass # 峰值统计(汇总所有设备) try: peak_bytes = 0 for device_id in range(device_count()): peak_bytes += max_memory_allocated(device_id) if peak_bytes: metrics["npu_mem_peak_gb"] = peak_bytes / 1024 ** 3 except Exception: pass # 详细统计(若 torch_npu 可用) try: tn = importlib.import_module("torch_npu") # 可选依赖 stats = None if hasattr(tn, "npu") and hasattr(tn.npu, "memory_stats"): stats = tn.npu.memory_stats() elif hasattr(tn, "memory_stats"): stats = tn.memory_stats() if isinstance(stats, dict): current_alloc = stats.get("allocated_bytes.all.current") peak_alloc = stats.get("allocated_bytes.all.peak") reserved_alloc = stats.get("reserved_bytes.all.current") if current_alloc is not None: metrics["npu_mem_allocated_gb"] = current_alloc / 1024 ** 3 if peak_alloc is not None: metrics["npu_mem_allocated_peak_gb"] = peak_alloc / 1024 ** 3 if reserved_alloc is not None: metrics["npu_mem_reserved_gb"] = reserved_alloc / 1024 ** 3 except Exception: pass return metrics