PyTorch torch._assert 函数

约 375 字 更新于 2026-11-18 5iyo.com

PyTorch torch._assert 函数

torch._assert 是 PyTorch 中用于断言检查的函数。如果条件为 False,则抛出 RuntimeError。

函数定义


torch._assert(condition, message)


使用示例

实例

import torch

# 示例代码
condition = True
torch._assert(condition, "Assertion failed!")
print("Assertion passed!")

# 失败示例
try:
    torch._assert(False, "This will fail")
except RuntimeError as e:
    print(f"Caught error: {e}")