Shortcuts

(测试版) 使用TORCH_LOGS Python API 和 torch.compile

Created On: Jan 24, 2024 | Last Updated: Jan 31, 2024 | Last Verified: Nov 05, 2024

作者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("")

结论

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

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

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

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

由Sphinx-Gallery生成的图集

文档

访问 PyTorch 的详细开发者文档

查看文档

教程

获取针对初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并获得问题的解答

查看资源