You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不修改库代码的情况下屏蔽torchmetrics的UserWarning?

解决torchmetrics中SMAPE的full_state_update警告问题

你遇到的警告内容如下:

/Users/dev/miniconda/envs/pytorch/lib/python3.10/site-packages/torchmetrics/utilities/prints.py:36:
UserWarning: Torchmetrics v0.9 introduced a new argument class
property called full_state_update that has not been set for this
class (SMAPE). The property determines if update by default needs
access to the full metric state. If this is not the case, significant
speedups can be achieved and we recommend setting this to False. We
provide an checking function from torchmetrics.utilities import check_forward_no_full_state that can be used to check if the
full_state_update=True (old and potential slower behaviour, default
for now) or if full_state_update=False can be used safely.

你尝试用warnings上下文管理器屏蔽但无效,确实是因为torchmetrics通过自定义的_warn函数触发警告,普通的上下文过滤没覆盖到。下面给你两种不修改库代码的解决方法:

方法一:设置SMAPE的full_state_update属性(推荐)

这不仅能消除警告,还能按官方建议优化性能:

  1. 先检查是否可以安全设置为False:
from torchmetrics import SMAPE
from torchmetrics.utilities import check_forward_no_full_state

# 运行后如果输出True,就可以安全启用快速模式
can_use_fast_mode = check_forward_no_full_state(SMAPE)
print(can_use_fast_mode)
  1. 启用快速模式(二选一即可):
    • 单个实例生效:
    metric = SMAPE(full_state_update=False)
    
    • 所有SMAPE实例全局生效:
    SMAPE.full_state_update = False
    

方法二:精准屏蔽该特定警告

如果不想修改metric参数,可以通过精准匹配警告的来源和内容来屏蔽:

import warnings

# 只屏蔽来自torchmetrics.prints模块的这条特定SMAPE警告
warnings.filterwarnings(
    "ignore",
    message=r".*full_state_update that has not been set for this class \(SMAPE\).*",
    category=UserWarning,
    module=r"torchmetrics\.utilities\.prints"
)

这种方式不会影响其他正常警告的输出。

内容的提问来源于stack exchange,提问作者chronosynclastic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:45:33