华为昇腾NPU运维实战系列 · Part 6 交付与巡检篇

巡检报告与趋势分析 数据怎么存、怎么看

巡检不是"看一眼npu-smi输出"就结束的操作。有价值的巡检需要持续采集数据、结构化存储、趋势分析、退化预测,并通过可视化看板让异常一目了然。本文系统讲解昇腾NPU巡检数据存储设计、趋势分析方法、退化预测模型(ECC增长/温度趋势/功耗变化)、可视化看板与告警规则,帮助运维团队从"被动救火"转向"主动预防"。

适用型号 Ascend 910B/910C/950 软件栈 CANN 8.5.1+ / torch_npu 运维工具 npu-smi / ascend-dmi / hccn_tool

1 巡检数据存储设计

巡检数据是趋势分析和退化预测的基础。数据存储设计需要平衡三个矛盾:采集频率高 vs 存储成本低、数据精度高 vs 查询性能好、历史数据全 vs 冷热分层合理。一个好的存储设计能让一年的巡检数据在秒级查询,而不好的设计会让数据变成无法消费的"数据沼泽"。

1.1 数据分层存储架构

巡检数据按时间维度分三层存储:热数据(最近7天,高频查询)、温数据(7-90天,中频查询)、冷数据(90天以上,低频查询但需保留用于年度对比)。不同层使用不同存储介质和保留策略。

巡检数据流与分层存储架构 npu-smi hccn_tool ascend-dmi msprof 采集器 每5min轮询 数据处理器 清洗+结构化 热数据 (0-7天) InfluxDB · 5min粒度 温数据 (7-90天) InfluxDB降采样 · 1h粒度 冷数据 (90天+) Parquet/CSV · 1d粒度 Grafana看板 告警引擎 趋势分析 退化预测 数据量估算 (48节点 × 384卡) 热: ~2GB/周 温: ~3GB/90天 冷: ~1GB/年 总计: ~6GB/年 保留策略 热数据自动降采样迁移至温层(7天后) · 温数据自动迁移至冷层(90天后) · 冷数据永久保留(Parquet压缩) 异常事件数据(ECC错误/链路故障)不降采样,按原始精度永久保留
图1:巡检数据流架构——采集→处理→分层存储→消费

1.2 数据模型设计

巡检数据采用时序数据库(InfluxDB)存储,数据模型设计为tag+field结构,tag用于过滤和分组,field用于聚合计算:

python · 巡检数据采集与写入
📋 命令
#!/usr/bin/env python3
"""昇腾NPU巡检数据采集器"""
import subprocess
import re
import time
import json
from influxdb_client import InfluxDBClient, Point, WritePrecision

class InspectionCollector:
    def __init__(self, influx_url, token, org, bucket):
        self.client = InfluxDBClient(url=influx_url, token=token, org=org)
        self.write_api = self.client.write_api()
        self.bucket = bucket
        
    def collect_all(self, node_id, npu_count=8):
        """采集一个节点的全部巡检数据"""
        timestamp = time.time_ns()
        
        for npu_id in range(npu_count):
            self._collect_temperature(node_id, npu_id, timestamp)
            self._collect_power(node_id, npu_id, timestamp)
            self._collect_ecc(node_id, npu_id, timestamp)
            self._collect_hbm_usage(node_id, npu_id, timestamp)
            self._collect_hccs(node_id, npu_id, timestamp)
        
    def _collect_temperature(self, node, npu, ts):
        """采集NPU温度数据"""
        result = subprocess.run(
            ["npu-smi", "info", "-t", "temp", "-i", str(npu)],
            capture_output=True, text=True, timeout=10
        )
        
        points = []
        for line in result.stdout.splitlines():
            if "HBM" in line:
                temp = self._extract_temp(line)
                if temp:
                    p = Point("npu_temperature") \
                        .tag("node", node) \
                        .tag("npu_id", str(npu)) \
                        .tag("component", "hbm") \
                        .tag("chip_type", "910C") \
                        .field("temperature", float(temp)) \
                        .time(ts, WritePrecision.NS)
                    points.append(p)
            elif "Chip" in line or "AI" in line:
                temp = self._extract_temp(line)
                if temp:
                    p = Point("npu_temperature") \
                        .tag("node", node) \
                        .tag("npu_id", str(npu)) \
                        .tag("component", "chip") \
                        .tag("chip_type", "910C") \
                        .field("temperature", float(temp)) \
                        .time(ts, WritePrecision.NS)
                    points.append(p)
        
        if points:
            self.write_api.write(bucket=self.bucket, record=points)
    
    def _collect_ecc(self, node, npu, ts):
        """采集ECC错误计数"""
        result = subprocess.run(
            ["npu-smi", "info", "-t", "ecc", "-i", str(npu)],
            capture_output=True, text=True, timeout=10
        )
        
        correctable = 0
        uncorrectable = 0
        for line in result.stdout.splitlines():
            if "Correctable" in line:
                m = re.search(r"(\d+)", line.split(":")[-1])
                if m: correctable = int(m.group(1))
            if "Uncorrectable" in line:
                m = re.search(r"(\d+)", line.split(":")[-1])
                if m: uncorrectable = int(m.group(1))
        
        p = Point("npu_ecc") \
            .tag("node", node) \
            .tag("npu_id", str(npu)) \
            .field("correctable", correctable) \
            .field("uncorrectable", uncorrectable) \
            .field("total", correctable + uncorrectable) \
            .time(ts, WritePrecision.NS)
        self.write_api.write(bucket=self.bucket, record=p)
    
    def _collect_hccs(self, node, npu, ts):
        """采集HCCS链路状态"""
        result = subprocess.run(
            ["hccn_tool", "-i", str(npu), "-stat", "-link"],
            capture_output=True, text=True, timeout=10
        )
        
        link_ok = 1 if "OK" in result.stdout else 0
        rx_result = subprocess.run(
            ["hccn_tool", "-i", str(npu), "-stat", "-rx"],
            capture_output=True, text=True, timeout=10
        )
        rx_bw = self._extract_bandwidth(rx_result.stdout)
        
        p = Point("hccs_link") \
            .tag("node", node) \
            .tag("npu_id", str(npu)) \
            .field("link_status", link_ok) \
            .field("rx_bandwidth_gbps", rx_bw) \
            .time(ts, WritePrecision.NS)
        self.write_api.write(bucket=self.bucket, record=p)
    
    def _extract_temp(self, line):
        m = re.search(r"(\d+)\s*C", line)
        return int(m.group(1)) if m else None
    
    def _extract_bandwidth(self, text):
        m = re.search(r"([\d.]+)\s*GB/s", text)
        return float(m.group(1)) if m else 0.0

if __name__ == "__main__":
    collector = InspectionCollector(
        influx_url="http://influxdb:8086",
        token="inspection-token",
        org="ops",
        bucket="ascend_inspection"
    )
    for node in range(48):
        collector.collect_all("node" + str(node))
类比

巡检数据存储就像医院的病历系统——每次体检的数据(温度、血压、心电图)都要记录下来,不能只看最新一次。热数据是最近几天的监护数据(高频采集,随时可查),温数据是近三个月的体检记录(定期查看趋势),冷数据是历年体检档案(偶尔翻出来做年度对比)。关键异常事件(如心脏骤停)不降采样,按原始精度永久保留,就像病历中的"危急值"记录必须完整保存。

2 数据采集策略

采集策略决定了数据的质量和成本。采集太频繁会产生大量冗余数据,采集太稀疏会错过异常瞬态。不同指标需要不同的采集频率。

指标类别 采集频率 数据来源 单次耗时 存储字段 特殊处理
温度 每5分钟 npu-smi -t temp ~0.5s chip_temp, hbm_temp 超阈值即时告警
功耗 每5分钟 npu-smi -t usages ~0.5s power_w, utilization 空载/满载标记
ECC错误 每5分钟 npu-smi -t ecc ~0.5s correctable, uncorrectable 增量计算+告警
HCCS链路 每5分钟 hccn_tool -stat ~1s link_status, rx_bw, tx_bw CRC错误监控
HBM使用率 每5分钟 npu-smi -t usages ~0.5s hbm_used, hbm_total OOM预警
训练任务 每1分钟 进程监控 ~0.2s task_count, task_status 异常退出检测
系统日志 实时推送 dmesg/syslog 事件驱动 log_level, message 关键字过滤
⚠ 采集频率的权衡

5分钟的采集间隔对于温度、功耗等缓慢变化指标足够,但对于HCCS链路CRC错误可能太慢——CRC错误可能是瞬态的,5分钟内出现又消失。对于这类指标,建议采用"事件驱动+定期轮询"的双重机制:dmesg实时监控NPU相关错误日志(事件驱动),同时每5分钟轮询确认链路状态。这样既不会遗漏瞬态错误,又不会产生过多冗余数据。

3 趋势分析方法

趋势分析是从历史数据中提取变化模式的过程。对于昇腾NPU运维,关键趋势包括:温度上升趋势、ECC错误累积趋势、HCCS带宽退化趋势、功耗波动趋势。这些趋势能提前预警硬件退化,在故障发生前触发维护。

3.1 趋势分析技术

分析方法 适用场景 实现方式 时间窗口 输出
线性回归 温度/ECC缓慢上升 最小二乘法拟合斜率 7-30天 斜率+预测到达阈值时间
移动平均 功耗/带宽平滑 滑动窗口均值 1-7天 平滑曲线+异常点
变化点检测 性能突变 CUSUM/PELT算法 30-90天 突变时间点+幅度
周期分析 温度日间波动 FFT频谱分析 7-30天 周期+振幅+相位
异常检测 突发异常 3σ/IQR离群点 实时 异常值+偏离程度
python · 趋势分析脚本
📋 命令
#!/usr/bin/env python3
"""昇腾NPU巡检趋势分析"""
import numpy as np
from scipy import stats
from scipy.signal import find_peaks
from datetime import datetime, timedelta
from influxdb_client import InfluxDBClient

class TrendAnalyzer:
    def __init__(self, influx_client):
        self.client = influx_client
        self.query_api = client.query_api()
    
    def analyze_temperature_trend(self, node, npu_id, days=30):
        """分析温度上升趋势"""
        query = (
            'from(bucket: "ascend_inspection")'
            '  |> range(start: -' + str(days) + 'd)'
            '  |> filter(fn: (r) => r._measurement == "npu_temperature")'
            '  |> filter(fn: (r) => r._field == "temperature")'
            '  |> filter(fn: (r) => r.node == "' + node + '")'
            '  |> filter(fn: (r) => r.npu_id == "' + str(npu_id) + '")'
            '  |> filter(fn: (r) => r.component == "hbm")'
            '  |> aggregateWindow(every: 1h, fn: mean)'
            '  |> yield(name: "temp")'
        )
        result = self.query_api.query(query)
        
        times, temps = [], []
        for table in result:
            for record in table.records:
                times.append(record.get_time())
                temps.append(record.get_value())
        
        if len(temps) < 10:
            return {"status": "insufficient_data"}
        
        x = np.arange(len(temps))
        slope, intercept, r_value, p_value, std_err = stats.linregress(x, temps)
        
        threshold = 85
        if slope > 0:
            days_to_threshold = (threshold - intercept) / slope
            days_to_threshold = days_to_threshold / 24
        else:
            days_to_threshold = float('inf')
        
        return {
            "current_temp": temps[-1],
            "trend_slope": slope,
            "r_squared": r_value**2,
            "p_value": p_value,
            "days_to_threshold": days_to_threshold,
            "status": "warning" if days_to_threshold < 30 else "normal",
            "data_points": len(temps),
        }
    
    def analyze_ecc_trend(self, node, npu_id, days=30):
        """分析ECC错误累积趋势"""
        query = (
            'from(bucket: "ascend_inspection")'
            '  |> range(start: -' + str(days) + 'd)'
            '  |> filter(fn: (r) => r._measurement == "npu_ecc")'
            '  |> filter(fn: (r) => r._field == "correctable")'
            '  |> filter(fn: (r) => r.node == "' + node + '")'
            '  |> filter(fn: (r) => r.npu_id == "' + str(npu_id) + '")'
            '  |> aggregateWindow(every: 1h, fn: max)'
        )
        result = self.query_api.query(query)
        
        values = [r.get_value() for t in result for r in t.records]
        if len(values) < 2:
            return {"status": "insufficient_data"}
        
        increments = np.diff(values)
        avg_rate = np.mean(increments)
        max_rate = np.max(increments)
        
        x = np.arange(len(increments))
        slope, _, r_value, _, _ = stats.linregress(x, increments)
        
        return {
            "total_correctable": values[-1],
            "avg_rate_per_hour": avg_rate,
            "max_rate_per_hour": max_rate,
            "rate_trend": "accelerating" if slope > 0 else "stable",
            "r_squared": r_value**2,
            "status": "warning" if avg_rate > 10 else "normal",
        }
    
    def detect_change_points(self, node, npu_id, metric, days=90):
        """变化点检测:识别性能突变"""
        query = (
            'from(bucket: "ascend_inspection")'
            '  |> range(start: -' + str(days) + 'd)'
            '  |> filter(fn: (r) => r._measurement == "' + metric + '")'
            '  |> filter(fn: (r) => r.node == "' + node + '")'
            '  |> aggregateWindow(every: 1d, fn: mean)'
        )
        result = self.query_api.query(query)
        values = [r.get_value() for t in result for r in t.records]
        
        if len(values) < 14:
            return []
        
        mean_val = np.mean(values)
        cusum_pos = np.cumsum(np.maximum(values - mean_val - 0.5*np.std(values), 0))
        cusum_neg = np.cumsum(np.maximum(mean_val - 0.5*np.std(values) - values, 0))
        
        pos_peaks, _ = find_peaks(cusum_pos, height=np.std(values)*3)
        neg_peaks, _ = find_peaks(cusum_neg, height=np.std(values)*3)
        
        change_points = []
        for p in pos_peaks:
            change_points.append({
                "index": int(p),
                "type": "increase",
                "magnitude": float(values[p] - mean_val),
            })
        for p in neg_peaks:
            change_points.append({
                "index": int(p),
                "type": "decrease",
                "magnitude": float(mean_val - values[p]),
            })
        
        return sorted(change_points, key=lambda x: x["index"])
✓ 趋势分析的价值

某昇腾910C集群案例:趋势分析发现node12的NPU3 HBM温度以每天0.3°C的速度上升,从基线58°C在30天内升至67°C。虽然67°C远未达到85°C告警阈值,但线性回归预测60天后将达到阈值。运维团队提前申请了维护窗口更换该卡,避免了生产环境温度告警导致的训练中断。这就是趋势分析的核心价值——在故障发生前预警,将非计划停机转为计划维护。

4 退化预测模型

退化预测是趋势分析的进阶应用——不仅描述过去的变化趋势,还预测未来的退化路径和剩余使用寿命(RUL)。对于昇腾NPU,三个关键退化指标是:ECC错误增长率、HBM温度趋势、功耗变化模式。

4.1 ECC错误增长预测

ECC可纠正错误的增长速率是HBM健康度的直接指标。正常NPU的ECC错误增长缓慢且稳定,当HBM开始退化时,ECC增长率会加速。通过监控ECC增长率的加速度(二阶导数),可以提前预测HBM故障。

退化阶段 ECC特征 温度特征 功耗特征 建议操作
健康期 <5/h, 稳定 基线±3°C 基线±5% 正常巡检
早期退化 5-20/h, 缓慢上升 基线+3-5°C 基线+5-10% 增加监控频率
中期退化 20-100/h, 加速增长 基线+5-10°C 基线+10-15% 计划更换,准备备件
临故障 >100/h, 快速增长 基线+10°C以上 波动>15% 立即更换
故障 不可纠正错误出现 可能超阈值 可能异常 已停机,走RMA
python · 退化预测模型
📋 输出
#!/usr/bin/env python3
"""昇腾NPU退化预测模型"""
import numpy as np
from scipy import stats
from datetime import datetime, timedelta

class DegradationPredictor:
    """NPU退化预测器"""
    
    ECC_RATE_HEALTHY = 5
    ECC_RATE_EARLY = 20
    ECC_RATE_MID = 100
    TEMP_DELTA_WARN = 5
    TEMP_DELTA_CRIT = 10
    POWER_DELTA_WARN = 0.05
    POWER_DELTA_CRIT = 0.15
    
    def predict_rul(self, ecc_history, temp_history, power_history):
        """预测剩余使用寿命(RUL)"""
        ecc_analysis = self._analyze_ecc_rate(ecc_history)
        temp_analysis = self._analyze_temp_trend(temp_history)
        power_analysis = self._analyze_power_trend(power_history)
        
        stage = self._determine_stage(ecc_analysis, temp_analysis, power_analysis)
        
        rul_estimates = []
        if ecc_analysis["rul_days"] is not None:
            rul_estimates.append(ecc_analysis["rul_days"])
        if temp_analysis["rul_days"] is not None:
            rul_estimates.append(temp_analysis["rul_days"])
        
        rul_days = min(rul_estimates) if rul_estimates else 365
        
        indicators = {
            "ecc": ecc_analysis["severity"],
            "temp": temp_analysis["severity"],
            "power": power_analysis["severity"],
        }
        primary = max(indicators, key=indicators.get)
        
        return {
            "stage": stage,
            "rul_days": rul_days,
            "confidence": self._calc_confidence(ecc_analysis, temp_analysis),
            "primary_indicator": primary,
            "recommendation": self._get_recommendation(stage, rul_days),
            "details": {
                "ecc": ecc_analysis,
                "temperature": temp_analysis,
                "power": power_analysis,
            }
        }
    
    def _analyze_ecc_rate(self, history):
        """分析ECC增长率"""
        if len(history) < 48:
            return {"severity": 0, "rul_days": None, "rate": 0}
        
        increments = np.diff(history)
        current_rate = np.mean(increments[-24:])
        
        x = np.arange(len(increments))
        slope, _, r2, _, _ = stats.linregress(x, increments)
        
        severity = 0
        if current_rate > self.ECC_RATE_MID:
            severity = 3
        elif current_rate > self.ECC_RATE_EARLY:
            severity = 2
        elif current_rate > self.ECC_RATE_HEALTHY:
            severity = 1
        
        rul_days = None
        if current_rate > 0 and slope > 0:
            remaining = self.ECC_RATE_MID - current_rate
            if remaining > 0:
                hours_to_mid = remaining / slope
                rul_days = hours_to_mid / 24
        
        return {
            "severity": severity,
            "rate": current_rate,
            "acceleration": slope,
            "r2": r2,
            "rul_days": rul_days,
        }
    
    def _get_recommendation(self, stage, rul_days):
        """根据退化阶段给出建议"""
        recommendations = {
            "healthy": "正常巡检,保持5分钟采集频率",
            "early_degradation": "增加监控至1分钟频率,标记为关注卡",
            "mid_degradation": "计划在" + str(int(rul_days*0.7)) + "天内更换,提前准备备件",
            "near_failure": "立即安排维护窗口更换,限制该卡只跑低优先级任务",
            "failed": "已故障,走RMA流程,从集群拓扑中摘除",
        }
        return recommendations.get(stage, "未知状态")
NPU退化生命周期与预测干预点 健康期 ECC<5/h · 温度基线 早期退化 ECC 5-20/h · 温度+3°C 中期退化 ECC 20-100/h · 温度+5°C 临故障 ECC>100/h · 温度+10°C 故障 不可纠正ECC P3: 增加监控 趋势分析触发 P2: 计划更换 RUL预测触发 P1: 立即维护 阈值告警触发 P0: 停机 不可纠正ECC 退化预测窗口(趋势分析+RUL预测可在此区间提前预警) 各阶段数据需求与预测置信度 健康期: 7天数据 早期: 30天数据 中期: 60天数据 临故障: 90天数据 置信度: N/A 置信度: ~60% 置信度: ~80% 置信度: ~95%
图2:NPU退化生命周期——从健康到故障的五个阶段与预测干预点
⚠ 退化预测的局限性

退化预测基于历史趋势外推,假设退化模式延续。但实际故障可能突然发生(如HBM颗粒突发失效),不遵循渐进退化路径。因此退化预测应作为辅助决策工具而非唯一依据——预测结果用于计划维护优先级排序,但不能替代实时告警。任何指标突破告警阈值时,无论预测结果如何都应立即响应。预测置信度随退化阶段推进而提高:早期退化阶段置信度仅约60%(趋势尚不明确),中期退化提升至约80%(趋势确认),临故障阶段达95%(多指标趋同)。因此早期预警应作为"关注"而非"行动"信号,避免基于低置信度预测做过早的硬件更换。

5 可视化看板设计

可视化看板是巡检数据面向运维人员的"窗口"。好的看板让异常一目了然,差的看板淹没在数据中。昇腾NPU巡检看板建议采用分层设计:总览看板(全局健康度)→ 节点看板(单节点详情)→ NPU看板(单卡时序)。

5.1 看板布局

看板层级 面向场景 核心面板 刷新频率 告警集成
总览看板 日常巡检 集群热力图+健康度评分 30s 异常卡高亮闪烁
温度看板 散热监控 HBM温度分布+趋势线 10s 超阈值红色告警
ECC看板 健康度监控 ECC增长率+累积曲线 1min 增长率突变告警
通信看板 网络监控 HCCS拓扑+带宽热力图 30s 链路Down告警
趋势看板 周/月报 退化预测+RUL排名 5min RUL<30天预警
json · Grafana看板配置
📋 输出
{
  "dashboard": {
    "title": "昇腾NPU集群巡检总览",
    "refresh": "30s",
    "panels": [
      {
        "title": "集群健康度热力图",
        "type": "heatmap",
        "query": "from(bucket:\"ascend_inspection\") |> range(start:-5m) |> filter(fn:(r) => r._measurement==\"npu_temperature\") |> filter(fn:(r) => r._field==\"temperature\") |> filter(fn:(r) => r.component==\"hbm\")",
        "gridPos": {"h": 8, "w": 24, "x": 0, "y": 0}
      },
      {
        "title": "HBM温度分布",
        "type": "stat",
        "query": "最大温度/平均温度/中位数温度",
        "thresholds": [
          {"value": 75, "color": "green"},
          {"value": 80, "color": "yellow"},
          {"value": 85, "color": "red"}
        ],
        "gridPos": {"h": 4, "w": 8, "x": 0, "y": 8}
      },
      {
        "title": "ECC错误增长率(24h)",
        "type": "timeseries",
        "query": "ECC增量/小时,按NPU分组",
        "thresholds": [
          {"value": 5, "color": "green"},
          {"value": 20, "color": "yellow"},
          {"value": 100, "color": "red"}
        ],
        "gridPos": {"h": 8, "w": 12, "x": 0, "y": 12}
      },
      {
        "title": "HCCS链路状态",
        "type": "table",
        "query": "所有HCCS链路状态+带宽",
        "fieldConfig": {
          "defaults": {
            "mappings": [
              {"type": "value", "options": {"0": {"text": "DOWN", "color": "red"}, "1": {"text": "UP", "color": "green"}}}
            ]
          }
        },
        "gridPos": {"h": 8, "w": 12, "x": 12, "y": 12}
      },
      {
        "title": "退化预测RUL排名",
        "type": "bargauge",
        "query": "各NPU预测剩余使用寿命天数",
        "thresholds": [
          {"value": 90, "color": "green"},
          {"value": 30, "color": "yellow"},
          {"value": 7, "color": "red"}
        ],
        "gridPos": {"h": 8, "w": 24, "x": 0, "y": 20}
      }
    ]
  }
}
类比

巡检看板就像核电站的中央控制室——操作员不需要去每个反应堆旁边看温度计,而是坐在控制室里看一面墙的仪表盘。绿色代表正常,黄色代表关注,红色代表告警。昇腾NPU集群的384张卡就像384个温度计,不可能逐个看——热力图把384个温度值映射到一张色块图上,一眼就能定位"哪个角落发红"。趋势线则像长期监护仪的波形图,不需要看每个数据点,看斜率就知道"情况在好转还是恶化"。

6 告警规则设计

告警规则是巡检数据到运维行动的桥梁。好的告警规则应该:灵敏(不漏报)、精准(不误报)、可操作(告警内容包含足够信息让运维知道该做什么)。

6.1 告警分级体系

级别 触发条件 通知方式 响应时间 典型场景 处理流程
P0紧急 NPU Offline/不可纠正ECC 电话+短信+IM 15分钟 NPU故障导致训练中断 立即摘除故障卡
P1严重 温度>85°C/HCCS Down 短信+IM 30分钟 散热异常/链路中断 降频/重连
P2警告 ECC增长率>20/h/RUL<30d IM+邮件 4小时 退化趋势加速 计划维护
P3提示 温度偏离基线5°C 邮件 24小时 轻微异常需关注 记录+持续观察
yaml · 告警规则配置
📋 命令
# ascend_alert_rules.yaml - 昇腾NPU告警规则
groups:
  - name: ascend_npu_hardware
    rules:
      - alert: NPUOffline
        expr: |
          npu_status{chip_type=~"910.*"} == 0
        for: 1m
        labels:
          severity: P0
          category: hardware
        annotations:
          summary: "NPU {{ $labels.node }}/{{ $labels.npu_id }} 离线"
          description: "NPU已离线超过1分钟,训练任务可能中断"
          action: "检查dmesg日志,确认是否硬件故障,必要时摘除该卡"
      
      - alert: UncorrectableECC
        expr: |
          increase(npu_ecc_uncorrectable[5m]) > 0
        for: 0s
        labels:
          severity: P0
          category: hardware
        annotations:
          summary: "NPU {{ $labels.node }}/{{ $labels.npu_id }} 出现不可纠正ECC"
          description: "HBM可能已损坏,数据完整性无法保证"
          action: "立即停止该卡上所有任务,走RMA流程更换"
      
      - alert: HBMTempCritical
        expr: |
          npu_temperature{component="hbm"} > 85
        for: 2m
        labels:
          severity: P1
          category: thermal
        annotations:
          summary: "HBM温度超限: {{ $value }}°C"
          action: "检查散热系统,降低负载,必要时停机冷却"
      
      - alert: ECCRateIncreasing
        expr: |
          rate(npu_ecc_correctable[1h]) > 20
        for: 10m
        labels:
          severity: P2
          category: degradation
        annotations:
          summary: "ECC增长率异常: {{ $value | humanize }}/h"
          description: "ECC可纠正错误增长率持续超过20/h,HBM可能正在退化"
          action: "增加监控频率,评估是否需要预防性更换"
      
      - alert: RULWarning
        expr: |
          npu_rul_days < 30
        for: 1h
        labels:
          severity: P2
          category: degradation
        annotations:
          summary: "NPU剩余寿命预警: {{ $value }}天"
          action: "安排计划维护,准备备件"
      
      - alert: HCCSLinkDown
        expr: |
          hccs_link_status == 0
        for: 30s
        labels:
          severity: P1
          category: communication
        annotations:
          summary: "HCCS链路中断: {{ $labels.node }}/{{ $labels.npu_id }}"
          action: "检查光模块/线缆,尝试重连,必要时降级运行"
ℹ 告警抑制与聚合

当一个机柜散热异常导致8张卡同时温度告警时,不应发出8条独立告警——应聚合为1条"机柜级温度异常"告警。告警规则需要配置抑制(inhibition)和聚合(grouping)策略:同一节点同一类告警在5分钟内只通知一次;同一机柜的同类告警聚合为一条。这避免了"告警风暴"淹没真正需要立即处理的问题。

7 巡检报告模板

定期巡检报告是向管理层和技术团队汇报集群状态的正式文档。报告应自动生成,包含数据摘要、异常事件、趋势分析和维护建议。

报告类型 频率 核心内容 数据来源 格式 受众
日报 每日 当日异常事件+健康度评分 热数据 HTML+邮件 运维团队
周报 每周 趋势分析+退化排名 热+温数据 HTML+邮件 运维+管理层
月报 每月 容量分析+维护计划 温数据 PDF 管理层
专项报告 按需 故障分析+根因+改进 全量数据 PDF 技术+管理层
python · 巡检报告自动生成
📋 输出
#!/usr/bin/env python3
"""巡检报告自动生成器"""
import datetime
import json
from jinja2 import Template

class InspectionReportGenerator:
    def __init__(self, influx_client, cluster_name):
        self.client = influx_client
        self.cluster = cluster_name
        
    def generate_daily_report(self, date=None):
        """生成日报"""
        date = date or datetime.date.today()
        
        report = {
            "type": "daily",
            "date": date.isoformat(),
            "cluster": self.cluster,
            "summary": self._get_daily_summary(date),
            "anomalies": self._get_anomalies(date),
            "health_score": self._calc_health_score(date),
            "recommendations": self._get_recommendations(date),
        }
        
        html = self._render_html(report)
        return html, report
    
    def _get_daily_summary(self, date):
        """获取当日数据摘要"""
        return {
            "total_npus": 384,
            "online_npus": self._count_online(date),
            "max_hbm_temp": self._get_max_temp(date),
            "avg_hbm_temp": self._get_avg_temp(date),
            "ecc_new_errors": self._get_ecc_increment(date),
            "hccs_errors": self._get_hccs_errors(date),
            "training_jobs": self._get_job_stats(date),
        }
    
    def _calc_health_score(self, date):
        """计算集群健康度评分(0-100)"""
        scores = {
            "availability": self._score_availability(date),
            "thermal": self._score_thermal(date),
            "ecc": self._score_ecc(date),
            "communication": self._score_comm(date),
        }
        weights = {"availability": 0.4, "thermal": 0.2, "ecc": 0.2, "communication": 0.2}
        total = sum(scores[k] * weights[k] for k in scores)
        return round(total, 1)
    
    def _get_anomalies(self, date):
        """获取当日异常事件"""
        anomalies = []
        # 查询当日所有超阈值事件
        # 温度超限、ECC突增、链路异常、任务异常退出
        return anomalies
    
    def _get_recommendations(self, date):
        """生成维护建议"""
        recs = []
        # 基于趋势分析生成建议
        # 如: "node12/NPU3 HBM温度上升趋势明显,建议30天内更换"
        return recs
✓ 报告自动化的收益

巡检报告自动生成后,运维团队从每周花2小时手动编写周报中解放出来。更重要的是,自动报告的数据覆盖面远超人工——人工周报通常只看温度和ECC,自动报告还包含HCCS带宽趋势、功耗分布、退化预测RUL排名、历史对比等维度。管理层反馈:自动月报的数据颗粒度和趋势分析质量明显优于此前的人工报告。

8 与GPU巡检报告对比

昇腾NPU巡检与NVIDIA GPU巡检在数据采集方式和指标定义上有差异,但趋势分析和可视化方法可以共用。

对比维度 昇腾NPU NVIDIA GPU
温度采集 npu-smi -t temp (HBM+Chip分别采集) nvidia-smi -q (GPU+Memory合并)
ECC监控 npu-smi -t ecc (可纠正/不可纠正分别计数) nvidia-smi -q (需先开启ECC模式)
链路监控 hccn_tool (HCCS链路状态+带宽) dcgmi discovery (NVLink拓扑+带宽)
功耗监控 npu-smi -t usages (实时功耗) nvidia-smi -q (功耗+功耗限制)
退化指标 ECC增长率+HBM温度趋势 ECC计数+XID错误日志+retired pages
监控生态 需自研采集+DCGM exporter适配 DCGM/DCGM exporter原生支持Prometheus
可视化工具 Grafana+InfluxDB(自建) Grafana+Prometheus(成熟生态)
告警工具 Prometheus Alertmanager(适配) Prometheus Alertmanager(原生)
类比

昇腾和GPU的巡检对比就像中医和西医的体检——GPU巡检像西医,有标准化的体检套餐(DCGM)和成熟的电子病历系统(Prometheus+Grafana),开箱即用。昇腾巡检像中医,需要自己搭脉(npu-smi)、自己记录病历(自研采集器)、自己建档案系统(InfluxDB+Grafana)。但一旦搭好了,中医的观测维度可能更细致——比如昇腾可以分别采集Chip和HBM温度,而GPU通常只给一个合并温度。自建的好处是灵活度高,坏处是前期投入大。

ℹ 统一巡检平台建议

对于混合集群(昇腾+GPU),建议建设统一巡检平台:数据采集层为不同芯片实现适配器(npu-smi adapter + nvidia-smi adapter),统一写入InfluxDB/Prometheus;可视化层用同一套Grafana看板,通过标签过滤不同芯片类型;告警层用同一套Alertmanager规则模板,仅查询表达式不同。这样运维团队只需要一套巡检SOP,看一个看板,就能同时掌握昇腾和GPU集群的健康状态。

9 巡检数据价值挖掘

巡检数据除了实时告警和趋势分析,还可以挖掘更多价值。长期积累的巡检数据是集群优化的数据基础。

9.1 容量规划

通过分析历史功耗和利用率数据,可以回答:当前集群是否被充分利用?是否需要扩容?哪些节点的利用率持续偏低?昇腾NPU的功耗数据可以区分空载和满载状态,计算实际的MFU(Model FLOPS Utilization)。

9.2 散热优化

分析温度分布的时空模式可以发现散热瓶颈:某个机柜进风温度偏高导致全柜NPU温度偏高;某个时间段(如机房空调切换)温度出现周期性波动。这些发现指导机房气流优化和空调策略调整。

9.3 故障预测模型训练

积累足够的故障前巡检数据后,可以训练ML模型做更精准的故障预测。特征包括:故障前N天的ECC增长率变化、温度波动模式、功耗异常特征。标签是"该卡在N天内是否故障"。这类模型需要至少一年的数据和数十个故障样本才有意义。

⚠ 数据质量是基础

以上所有分析都依赖高质量的巡检数据。如果采集器有bug导致数据缺失、时间戳错乱、或指标含义不一致,分析结论就会误导。建议定期(如每周)做数据质量检查:数据完整性(无大段缺失)、时间连续性(间隔均匀)、值域合理性(温度在0-100°C之间、ECC单调递增)。数据质量问题的修复优先级应高于功能新增——垃圾数据产生的分析比没有分析更危险。

10 总结与最佳实践

巡检报告与趋势分析是昇腾NPU运维从"被动响应"走向"主动预防"的关键能力。本文从数据存储、采集策略、趋势分析、退化预测、可视化看板、告警规则到报告模板,构建了一套完整的巡检数据闭环体系。以下是实施过程中的核心最佳实践:

10.1 实施路线图

阶段 目标 关键任务 周期 验收标准
阶段一 数据采集 部署采集器、配置InfluxDB、验证数据完整性 1-2周 所有节点数据连续无缺失
阶段二 可视化看板 搭建Grafana、创建总览+详情看板 1周 看板覆盖全部关键指标
阶段三 告警规则 配置P0-P3告警、验证通知链路 1周 告警延迟<2分钟
阶段四 趋势分析 部署分析脚本、建立基线、验证预测 2-4周 趋势预测误差<20%
阶段五 退化预测 积累3个月数据后启用RUL预测 3个月+ RUL预测命中率>70%

10.2 核心经验总结

数据质量优先于分析功能。再精妙的趋势分析模型,如果输入数据有缺失、错乱或不一致,输出就是误导。投入足够精力在采集器的健壮性、数据完整性校验和值域合理性检查上,这是整个体系的地基。

分层存储控制成本。全精度保留一年数据看似理想,但存储成本和查询性能都不允许。热-温-冷三层存储配合自动降采样,在保留趋势分析能力的同时将年存储成本控制在~6GB,是经过实践验证的合理设计。

告警贵精不贵多。告警风暴是运维团队最大的敌人——当每天收到200条告警时,真正重要的P0告警会被淹没。严格配置告警抑制和聚合规则,确保每个告警都是"需要有人做点什么"的可操作信号。

预测是辅助不是替代。退化预测和RUL估算能帮助规划维护优先级,但绝不能替代实时阈值告警。任何指标突破安全阈值时,无论预测结果如何都必须立即响应。预测的价值在于"提前规划",而非"延迟响应"。

✓ 闭环价值

完整的巡检数据闭环(采集→存储→分析→预测→告警→报告)让运维团队从"npu-smi看一眼"升级为"数据驱动的健康管理"。一个运行了6个月的巡检系统能够:提前30天预警80%的HBM退化故障、将非计划停机减少60%、自动生成周报月报节省每周2小时人工、为容量规划提供数据支撑。这些收益远超建设和维护巡检系统的投入。