PyTorch中stacklevel的含义
Meaning of stacklevel in PyTorch
我在 PyTorch 中遇到过许多以 _stacklevel
作为参数的函数。这是使用 Softmax 模块 s
forward()` 方法的示例:
def forward(self, input: Tensor) -> Tensor:
return F.softmax(input, self.dim, _stacklevel=5)
_stacklevel
是什么意思?它有什么用?
stacklevel
用于 python 以指示警告机制必须在堆栈中向上移动多远才能找到调用发出警告的函数的行。例如,下面的代码通过使用 stacklevel=2
使警告引用 deprecation()
的调用者,而不是 deprecation()
本身的来源。 stacklevel=3
会引用 deprecation()
的来电者的来电者,依此类推。
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
有关详细信息,请参阅此 page。
关于你提到的具体情况,在PyTorch的F.softmax
、F.softmin
和F.log_softmax
函数中,这个参数与dim
不存在时发出的警告有关指定的。然而,它似乎应该被删除,因为遗留的 softmax dim
行为已经消失,或者至少在文档中得到了澄清。目前,这仅在 pytorch repo 的以下未解决问题中提到:
它可能会在未来得到修复或澄清,但目前我的建议是简单地忽略它。
我在 PyTorch 中遇到过许多以 _stacklevel
作为参数的函数。这是使用 Softmax 模块 s
forward()` 方法的示例:
def forward(self, input: Tensor) -> Tensor:
return F.softmax(input, self.dim, _stacklevel=5)
_stacklevel
是什么意思?它有什么用?
stacklevel
用于 python 以指示警告机制必须在堆栈中向上移动多远才能找到调用发出警告的函数的行。例如,下面的代码通过使用 stacklevel=2
使警告引用 deprecation()
的调用者,而不是 deprecation()
本身的来源。 stacklevel=3
会引用 deprecation()
的来电者的来电者,依此类推。
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
有关详细信息,请参阅此 page。
关于你提到的具体情况,在PyTorch的F.softmax
、F.softmin
和F.log_softmax
函数中,这个参数与dim
不存在时发出的警告有关指定的。然而,它似乎应该被删除,因为遗留的 softmax dim
行为已经消失,或者至少在文档中得到了澄清。目前,这仅在 pytorch repo 的以下未解决问题中提到:
它可能会在未来得到修复或澄清,但目前我的建议是简单地忽略它。