Shortcuts

(测试版) 使用 TORCH_LOGS python API 与 torch.compile

创建于:2024年1月24日 | 最后更新:2024年1月31日 | 最后验证:2024年11月5日

作者: Michael Lazos

import logging

本教程介绍了TORCH_LOGS环境变量以及Python API,并演示了如何应用它来观察torch.compile的各个阶段。

注意

本教程需要 PyTorch 2.2.0 或更高版本。

设置

在这个例子中,我们将设置一个简单的Python函数,该函数执行逐元素加法,并使用TORCH_LOGS Python API观察编译过程。

注意

还有一个环境变量 TORCH_LOGS,可以用于在命令行中更改日志设置。每个示例中都显示了等效的环境变量设置。

import torch

# exit cleanly if we are on a device that doesn't support torch.compile
if torch.cuda.get_device_capability() < (7, 0):
    print("Skipping because torch.compile is not supported on this device.")
else:
    @torch.compile()
    def fn(x, y):
        z = x + y
        return z + 2


    inputs = (torch.ones(2, 2, device="cuda"), torch.zeros(2, 2, device="cuda"))


# print separator and reset dynamo
# between each example
    def separator(name):
        print(f"==================={name}=========================")
        torch._dynamo.reset()


    separator("Dynamo Tracing")
# View dynamo tracing
# TORCH_LOGS="+dynamo"
    torch._logging.set_logs(dynamo=logging.DEBUG)
    fn(*inputs)

    separator("Traced Graph")
# View traced graph
# TORCH_LOGS="graph"
    torch._logging.set_logs(graph=True)
    fn(*inputs)

    separator("Fusion Decisions")
# View fusion decisions
# TORCH_LOGS="fusion"
    torch._logging.set_logs(fusion=True)
    fn(*inputs)

    separator("Output Code")
# View output code generated by inductor
# TORCH_LOGS="output_code"
    torch._logging.set_logs(output_code=True)
    fn(*inputs)

    separator("")
Skipping because torch.compile is not supported on this device.

结论

在本教程中,我们通过实验一些可用的日志选项,介绍了TORCH_LOGS环境变量和python API。要查看所有可用选项的描述,请运行任何导入torch的python脚本,并将TORCH_LOGS设置为“help”。

或者,您可以查看torch._logging文档以查看所有可用日志记录选项的描述。

有关torch.compile的更多信息,请参阅torch.compile教程

脚本总运行时间: ( 0 分钟 0.002 秒)

Gallery generated by Sphinx-Gallery

优云智算