如何通过代码为W&B运行设置失败告警?
在W&B中配置运行失败告警的正确方法
问题背景
尝试通过run.notify_on_failure()等方法为W&B项目配置运行失败告警时,触发AttributeError,提示'Run' object has no attribute 'notify_on_failure',相关代码及错误信息如下:
错误代码示例
import wandb mode = 'dryrun' run_name = 'my_run' num_batches = 50 path = '/data' name = 'experiment1' today = '2023-08-01' probabilities = [0.1, 0.9] batch_size = 32 data_mixture_name = 'mix1' debug = mode == 'dryrun' run = wandb.init(mode=mode, project="beyond-scale", name=run_name, save_code=True) wandb.config.update({ "num_batches": num_batches, "path": path, "name": name, "today": today, 'probabilities': probabilities, 'batch_size': batch_size, 'debug': debug, 'data_mixture_name': data_mixture_name }) # 无效的告警设置代码 run.notify_on_failure() run.notify_on_crash() run.notify_on_exit() run.notify_on_heartbeat() run.notify_on_abort()
错误信息
AttributeError: 'Run' object has no attribute 'notify_on_failure'
正确实现方案
W&B的Run对象并未提供上述直接的告警方法,可通过以下两种方式实现告警需求:
1. 代码中主动触发告警(wandb.alert())
在运行逻辑中捕获异常或检测到失败状态时,调用wandb.alert()主动发送通知:
import wandb import traceback mode = 'online' # 注意:dryrun模式不会发送实际告警,需改为online run_name = 'my_run' # 保留原有配置参数... debug = mode == 'dryrun' run = wandb.init(mode=mode, project="beyond-scale", name=run_name, save_code=True) wandb.config.update({ # 保留原有配置内容... }) try: # 替换为你的实际运行逻辑 for batch in range(num_batches): if batch == 20: # 模拟运行失败场景 raise RuntimeError(f"第{batch}批数据处理失败") # 正常执行的业务代码... except Exception as e: # 发送错误告警 wandb.alert( title=f"Run {run_name} 执行失败", text=f"错误详情:{str(e)}\n\n堆栈信息:\n{traceback.format_exc()}", level=wandb.AlertLevel.ERROR ) raise # 重新抛出异常,让W&B标记该运行为失败状态
2. 网页端配置项目自动告警规则
在W&B项目的网页后台设置自动告警,无需修改代码即可实现运行异常通知:
- 进入目标项目页面,点击右上角Settings
- 切换到Alerts标签页
- 添加告警规则:例如「当运行状态变为失败时」「当运行超过指定时间无心跳时」
- 配置通知渠道(邮件、Slack等),满足条件时自动发送告警
关键注意点
dryrun模式下,W&B不会同步数据或发送告警,需将mode设置为online才能生效wandb.alert()支持INFO、WARNING、ERROR三种告警级别,可根据场景选择
内容的提问来源于stack exchange,提问作者Charlie Parker
相关产品推荐
相关产品推荐

