评价此页

torch.monitor#

创建于: 2022年1月12日 | 最后更新于: 2025年6月11日

警告

此模块为原型发布,其接口和功能在未来的 PyTorch 版本中可能在不通知的情况下发生变化。

torch.monitor 提供了一个用于记录 PyTorch 事件和计数器的接口。

统计接口旨在用于跟踪定期记录的高级指标,以便用于监控系统性能。由于统计数据以特定窗口大小进行聚合,因此您可以在关键循环中记录它们,同时将性能影响降至最低。

对于不经常发生的事件或值,例如损失、准确性、使用情况跟踪,可以直接使用事件接口。

可以注册事件处理程序来处理事件并将其传递到外部事件接收器。

API 参考#

class torch.monitor.Aggregation#

这些是可以用于累积统计数据的聚合类型。

成员

VALUE

VALUE 返回最后添加的值。

MEAN

MEAN 计算所有添加值的算术平均值。

COUNT

COUNT 返回添加值的总数。

SUM

SUM 返回添加值的总和。

MAX

MAX 返回添加值的最大值。

MIN

MIN 返回添加值的最小值。

property name#
class torch.monitor.Stat#

Stat 用于在固定间隔内以高性能方式计算汇总统计数据。Stat 每隔 window_size 持续时间记录一次统计数据作为事件。当窗口关闭时,统计数据将通过事件处理程序作为 torch.monitor.Stat 事件记录。

window_size 应设置为相对较高的值,以避免记录大量事件。例如:60秒。Stat 使用毫秒精度。

如果设置了 max_samples,则当 max_samples 添加发生后,该统计数据将通过丢弃 add 调用来限制每个窗口的样本数。如果未设置,则窗口期间的所有 add 调用都将包括在内。这是一个可选字段,用于在样本数可能变化时使聚合在不同窗口之间更具可比性。

当 Stat 被销毁时,即使窗口尚未过去,它也会记录任何剩余数据。

__init__(self: torch._C._monitor.Stat, name: str, aggregations: list[torch._C._monitor.Aggregation], window_size: datetime.timedelta, max_samples: int = 9223372036854775807) None#

构造 Stat

add(self: torch._C._monitor.Stat, v: float) None#

向统计数据添加一个值,该值将根据配置的统计类型和聚合进行聚合。

property count#

当前已收集的数据点数量。事件记录后重置。

get(self: torch._C._monitor.Stat) dict[torch._C._monitor.Aggregation, float]#

返回统计数据的当前值,主要用于测试目的。如果统计数据已记录且没有添加其他值,则此值为零。

property name#

创建时设置的统计数据名称。

class torch.monitor.data_value_t#

data_value_t 是 strfloatintbool 之一。

class torch.monitor.Event#

Event 表示要记录的特定类型事件。这可以表示每周期的高级数据点,例如损失或准确性,或更低级的聚合,例如通过此库提供的统计数据。

所有相同类型的 Event 应具有相同的名称,以便下游处理程序可以正确处理它们。

__init__(self: torch._C._monitor.Event, name: str, timestamp: datetime.datetime, data: dict[str, data_value_t]) None#

构造 Event

property data#

Event 中包含的结构化数据。

property name#

Event 的名称。

property timestamp#

Event 发生时的时间戳。

class torch.monitor.EventHandlerHandle#

EventHandlerHandle 是由 register_event_handler 返回的包装类型,用于通过 unregister_event_handler 注销处理程序。此类型不能直接初始化。

torch.monitor.log_event(event: torch._C._monitor.Event) None#

log_event 将指定的事件记录到所有已注册的事件处理程序中。由事件处理程序负责将事件记录到相应的事件接收器中。

如果没有注册事件处理程序,则此方法不执行任何操作。

torch.monitor.register_event_handler(callback: Callable[[torch._C._monitor.Event], None]) torch._C._monitor.EventHandlerHandle#

register_event_handler 注册一个回调函数,以便在通过 log_event 记录事件时调用。这些处理程序应避免阻塞主线程,因为它们在 log_event 调用期间运行,这可能会干扰训练。

torch.monitor.unregister_event_handler(handler: torch._C._monitor.EventHandlerHandle) None#

unregister_event_handler 注销调用 register_event_handler 后返回的 EventHandlerHandle。此函数返回后,事件处理程序将不再接收事件。

class torch.monitor.TensorboardEventHandler(writer)[源]#

TensorboardEventHandler 是一个事件处理程序,它将已知事件写入提供的 SummaryWriter。

目前仅支持 torch.monitor.Stat 事件,这些事件将作为标量记录。

示例

>>> from torch.utils.tensorboard import SummaryWriter
>>> from torch.monitor import TensorboardEventHandler, register_event_handler
>>> writer = SummaryWriter("log_dir")
>>> register_event_handler(TensorboardEventHandler(writer))
__init__(writer)[源]#

构造 TensorboardEventHandler