编写Dynamo ATen降低通道¶
降低传递的基础知识¶
ATen 降低过程是 Python 函数,它们以 ATen 操作符的图作为输入,应用一些所需的修改,如操作符合并/融合、操作符替换、子图重写、自定义操作符插入或在 torch.fx.GraphModule 上执行其他操作,然后将修改后的图返回给调用者。这些降低过程通常会在原地修改图并返回相同的输入对象。
降低通过要求¶
Torch-TRT 中的 ATen 降低传递函数必须满足两个要求: - 该函数必须接受一个 torch.fx.GraphModule 和一个 torch 张量序列 Sequence[torch.Tensor] 作为输入,并返回降低后的 torch.fx.GraphModule - 该函数必须使图保持有效且可调用的状态,包括执行任何必要的代码检查和重新编译
请参阅此链接以获取有关FX中图形操作的信息。请参阅以下示例,了解如何通过降低传递修复具有输入也是输出的图形,这是TRT引擎不允许的配置。
示例降低传递¶
def repair_input_as_output(gm: torch.fx.GraphModule, sample_inputs: Sequence[torch.Tensor]) -> torch.fx.GraphModule:
"""Repair scenarios where inputs are also outputs of the graph
TRT does not allow such cases, so we insert a clone (identity) layer
"""
modified_graph = False
# Extract graph placeholder Tensors
placeholders = [
node
for node in gm.graph.nodes
if (
node.op == "placeholder"
and isinstance(node.type, type)
and issubclass(node.type, torch.Tensor)
)
]
for placeholder in placeholders:
# If any placeholder has any users which are direct graph outputs
if len(placeholder.users) >= 1 and any(
user.op == "output" for user in placeholder.users
):
modified_graph = True
# Get direct graph outputs which are direct uses of placeholders
direct_outputs = [user for user in placeholder.users if user.op == "output"]
# Insert clone node for placeholder to ensure
# placeholder is not a direct output
with gm.graph.inserting_after(placeholder):
cloned_placeholder = gm.graph.call_function(
torch.ops.aten.clone.default,
args=(placeholder,),
)
# Replace placeholder as output with cloned version
for output in direct_outputs:
output.replace_input_with(placeholder, cloned_placeholder)
# If the graph was modified, clean up the graph and ensure it is up-to-date
if modified_graph:
gm.graph.eliminate_dead_code()
gm.graph.lint()
gm.recompile()
logger.debug(f"Graph after repair_input_as_output:\n{gm.graph}")
return gm
注册降低传递¶
目前,降低通道在py/torch_tensorrt/dynamo/lowering/passes/__init__.py中注册,使用torch.fx.passes.pass_manager.PassManager工具以所需顺序组装通道列表。直接添加到该列表中的新通道将应用于Torch-TensorRT torch.compile后端中的图。目前,为了方便起见,我们提供了一个ATen降低通道注册装饰器,可以直接调用,也可以使用可选的index关键字参数来控制降低通道在通道列表中的插入位置。
例如,要在默认位置(列表末尾)插入密码,可以使用以下代码:
@_aten_lowering_pass
def my_custom_pass(gm: torch.fx.GraphModule, sample_inputs: Sequence[torch.Tensor]) -> torch.fx.GraphModule:
...
或者,要在passlist中的自定义索引(例如列表的前面)插入pass,可以使用以下代码:
@_aten_lowering_pass(index=0)
def my_custom_pass(gm: torch.fx.GraphModule, sample_inputs: Sequence[torch.Tensor]) -> torch.fx.GraphModule:
...
在torch_tensorrt.dynamo.lowering.passes中还提供了实用工具,用于显示当前可用的降级传递列表,将这些传递应用于任意的torch.fx.GraphModule,以及删除特定索引处的降级传递。
# Print all lowering passes in the list
print(dump_lowering_passes())
# Apply lowering passes to a GraphModule
apply_lowering_passes(graph_module, sample_inputs)
# Remove the lowering pass at index 1
_remove_lowering_pass(index=1)
注意: 上述API可能会随着降低传递系统的发展而发生变化。