自定义编译器 Pass 和 分区器¶
Passes¶
Passes 大致可分为几个维度
维度 A
创建一对多映射(例如,分解)
创建多对一映射(例如,融合)
维度 B
执行前向迭代(例如,形状传播)
执行后向迭代(例如,死代码消除)
维度 C
依赖于局部节点信息(例如,out 变体转换)
依赖于全局图信息(例如,内存规划)
我们对这些用例发生频率的预测是
A.1, B.1, C.1
A.2
B.2, C.2
级别 1¶
对于级别 1 的用例(创建一对多映射、执行前向迭代以及查看局部节点信息),我们可以使用一个名为 ExportPass
的辅助类。这是一种基于解释器的方式,我们执行每个节点并根据指定的转换重新创建图。这使我们能够通过确保 Pass 期间创建的所有节点都符合 IR 规范来保留 IR 规范,包括确保堆栈跟踪、FakeTensor 值和 torch.nn.Module 层次结构等元数据得到保留并根据所做的转换进行更新。
要实现这个 Pass,我们可以创建一个 ExportPass
的子类并实现公开的函数。当使用一个图模块调用时,它会运行该图模块并创建一个包含 Pass 指定更改的新图。这意味着传入的图模块必须能够在 CPU 上运行,并且在 Pass 运行后会保持这个不变性。
一对一 Pass¶
一对一映射的一个示例是,如果我们想用另一个 op B 替换 op A,我们可以运行给定的 fx.GraphModule
,并且每次看到 op A 时,返回 op B。
考虑以下示例
class ReplaceInPlaceReluWithOutOfPlaceReluPass(ExportPass):
"""
relu_ is the in-place version. Replace it with relu, which is the
out-of-place version
"""
def call_operator(self, op, args, kwargs, meta):
if op != torch.ops.aten.relu_.default:
return super().call_operator(op, args, kwargs, meta)
return super().call_operator(Op(torch.ops.aten.relu.default), args, kwargs, meta)
# To create a pass
replace_pass = ReplaceInPlaceReluWithOutOfPlaceReluPass()
# To run a pass
new_graph_module = replace_pass(graph_module).graph_module
`super().call_operator(op, args, kwargs, meta)` 调用会创建一个 call_function
FX 节点,并返回使用给定参数运行该算子的结果。
一对多 Pass¶
如果我们想进行一对多映射,例如用另外两个 op B 和 C 替换 op A,那么我们将对 super().call_operator
进行两次调用,创建两个 FX 节点,一个使用 op B,另一个使用 op C,并返回运行 op C 的结果。
例如
class ReplaceAddWithMulSub(ExportPass):
"""
Original:
def f(x, y):
return x + y
After pass:
def f(x, y):
z = x * y
return z - y
"""
def call_operator(self, op, args, kwargs, meta):
if op != torch.ops.aten.add.default:
return super().call_operator(op, args, kwargs, meta)
x, y = args
mul_res = super().call_operator(
torch.ops.aten.mul.default,
args,
{},
meta
)
return super().call_operator(
torch.ops.aten.sub.default,
(mul_res, y),
{},
meta
)
一对无 Pass¶
如果我们想移除一个 op,我们可以直接返回传递给函数的值
class RemoveDetachPass(ExportPass):
def call_operator(self, op, args, kwargs, meta):
if op not in (
torch.ops.aten.detach.default,
torch.ops.aten.detach_copy.default,
):
return super().call_operator(op, args, kwargs, meta)
assert len(args) == 1
return args[0]
利用局部信息¶
利用局部节点信息的一个示例是,如果我们想将图中的所有标量转换为张量,我们可以运行给定的 fx.GraphModule
,对于包含标量的每个参数,我们将其转换为张量。它可能看起来像这样
def args_map(op, fn, args, kwargs):
assert isinstance(args, tuple)
assert isinstance(kwargs, dict)
args = list(args)
kwargs = kwargs.copy()
# Update the argument based on the function passed
def update(key, args, schema):
args[key] = fn(args[key], schema)
# Update each argument in the schema
for i, schema in enumerate(self.op._schema.arguments):
if schema.name in kwargs:
update(schema.name, kwargs, schema)
elif not schema.kwarg_only and i < len(args):
update(i, args, schema)
class ScalarToTensorPass(ExportPass):
def call_operator(self, op, args, kwargs):
def try_coerce(value, arg):
return (
torch.tensor(value)
if isinstance(value, (float, int, bool))
and type(arg.type) == torch.TensorType
else value
)
args, kwargs = args_map(op, try_coerce, args, kwargs)
return super().call_operator(op, args, kwargs)
级别 2¶
为了创建多对一映射,我们可以利用 FX 的子图重写器。给定一个 pattern
,它会创建一个与该模式匹配的算子子图,然后将每个匹配的子图替换为 replacement
。
注意
This is an inplace operation.
`pattern` 和 replacement
输入必须是可调用函数,它们使用与您要匹配的 EXIR 图中使用的相同算子 (ATen 算子) 编写,以便子图重写器可以在图中找到正确的模式。pattern/replacement 可调用函数的输入将被视为通配符。
考虑以下示例
from torch.fx import subgraph_rewriter
def replace_patterns(graph_module):
def pattern(x, y):
x = torch.ops.aten.add.Tensor(x, y)
x = torch.ops.aten.mul.Tensor(x, y)
return x
def replacement(x, y):
return torch.ops.aten.sub.Tensor(x, y)
replaced_patterns = subgraph_rewriter.replace_pattern_with_filters(
traced_module, pattern, replacement
)
子图重写器返回一个 ReplacedPatterns
列表
@dataclass
class ReplacedPatterns:
# Node from which the match was found
anchor: Node
# Maps nodes in the pattern subgraph to nodes in the larger graph
nodes_map: Dict[Node, Node]
# List of nodes that were added into the graph
replacements: List[Node]
注意
The nodes created by the subgraph rewriter will not have the metadata that
is normally in EXIR nodes (`stack_trace`, `val`, `nn_module_stack`).
级别 3¶
创建 Pass 的第三种方式是利用最基本的 PassBase
。要创建一个 Pass,我们可以子类化它并实现包含 Pass 内容的 call
函数。此外,我们可以实现 requires
和 ensures
函数,它们将在 call
函数之前和之后被调用。请注意,这些函数也可以在 ExportPass
中被覆盖。要在图模块上运行 Pass,我们可以将图模块直接传递给该类的一个实例。
考虑以下示例
class ReplaceAddPass(PassBase):
def __init__(self, replace_op):
self.replace_op = replace_op
def call(self, graph_module):
for node in gm.graph.nodes:
if node.op == "call_function" and node.target == torch.add:
node.target = self.replace_op
# Optional to implement, will be called before call()
def requires(self, graph_module) -> None:
for node in graph_module.graph.nodes:
if node.op == "call_function" and node.target == torch.add:
return
raise ValueError("No torch.add ops!")
# Optional to implement, will be called after call()
def ensures(self, graph_module: torch.fx.GraphModule) -> None:
pass
# To create a pass
replace_add_with_div = ReplaceAddPass(torch.div)
# To run a pass
replace_add_with_div(graph_module)
Pass Manager¶
PassManager
是一个用于在给定图模块上运行多个 Pass 的类。初始化 PassManager
实例时,我们传入要运行的 Pass 列表并设置一些标志。要在图模块上运行这一系列 Pass,我们可以将图模块直接传递给 PassManager
实例。
一个示例
from executorch.exir.pass_manager import PassManager
pm = PassManager(
passes=[replace_add_with_div, replace_div_with_mul],
run_checks_after_each_pass=True,
suppress_check_failures=False,
)
graph_module_out = pm(graph_module)
要添加一组在每个 Pass 运行后执行的常见检查,我们可以调用接受可调用函数作为输入的 set_checks(check: Callable)
函数。如果设置了 run_checks_after_each_pass
标志,则在每个 Pass 在图模块上运行后,将调用 check
。
一个示例
pm = PassManager(passes=[replace_add_with_div, replace_div_with_mul])
def check_div_target(graph_module):
for node in graph_module.graph.nodes:
if node.op == "call_function" and node.target != torch.div:
raise ValueError("Target should be div!")
pm.add_checks(check_div_target)
pm(graph_module) # raises ValueError after replace_div_with_mul pass
分区器¶
有一些常见的基于 FX 图的分区器可用于对图进行分区。但是,这些分区器不一定能生成符合 IR 规范的图,因此在使用时请小心。
子图匹配器¶
为了在图中找到匹配特定模式的子图,我们可以利用 FX 的SubgraphMatcher
。
类属性
pattern (Graph)
:目标匹配模式。图中的占位符节点在匹配时将被视为通配符。match_output (bool)
:如果为 True,模式图中的输出节点将被视为目标模式的一部分。如果为 False,匹配时将忽略输出节点。match_placeholder (bool)
:如果为 True,模式图中的占位符节点将被视为目标模式的一部分。如果为 False,占位符节点将用作通配符。remove_overlapping_matches (bool)
:如果为 True,在匹配重叠的情况下,只返回第一个匹配项。ignore_literals (bool)
:如果为 True,将不检查字面量是否相等,而是将其视为通配符。
考虑以下示例
from torch.fx.passes.utils.matcher_utils import SubgraphMatcher
class LargeModel(torch.nn.Module):
def __init__(self):
super().__init__()
self._weight = torch.nn.Parameter(torch.ones(3, 3))
self._bias = torch.nn.Parameter(torch.ones(3, 3))
def forward(self, x):
return torch.ops.aten.addmm.default(self._bias, x, self._weight)
large_model_graph = to_edge(export(LargeModel(), large_inputs)).exported_program().graph_module.graph
class PatternModel(torch.nn.Module):
def __init__(self):
super().__init__()
self._weight_1 = torch.nn.Parameter(torch.ones(5, 5))
self._bias_1 = torch.nn.Parameter(torch.ones(5, 5))
def forward(self, x):
return torch.ops.aten.addmm.default(self._bias_1, x, self._weight_1)
pattern_graph = to_edge(export(PatternModel(), pattern_inputs)).exported_program().graph_module.graph
subgraph_matcher = SubgraphMatcher(pattern_graph)
match_result = subgraph_matcher.match(large_model_graph)
match
函数返回一个 InternalMatch
列表
@dataclass
class InternalMatch():
# Nodes from which the match was found
anchors: List[Node]
# Maps nodes in the pattern subgraph to nodes in the larger graph
nodes_map: Dict[Node, Node] = field(default_factory=dict)
# Nodes in target graph that are matched placeholder in pattern
placeholder_nodes: List[Node] = field(default_factory=list)
# Nodes in matched subgraph returned by output
returning_nodes: List[Node] = field(default_factory=list)
基于能力的分区器¶
为了找到支持特定不变性的最大节点子图,我们可以利用 FX 的CapabilityBasedPartitioner
。
类属性
graph_module (torch.fx.GraphModule)
:我们要对其进行分区的图模块。operator_support (OperatorSupportBase)
:用于确定图中某个节点是否在分区中受支持的对象。allows_single_node_partition (bool)
:如果为 True,则允许形成单节点分区。non_compute_ops (Optional[Sequence[str]])
:一组被认为是“非计算”的算子(例如torch.ops.aten.view
和_operator.getitem
),这样分区器就不会创建仅包含这些非计算算子的图allowed_single_node_partition_ops (Optional[Sequence[str]])
:允许出现在单节点分区中的一组算子。
OperatorSupportBase
类由分区器使用,以确定图中某个特定节点是否属于该分区。这是通过覆盖 is_node_supported
函数来实现的。您可以使用 chain
(如果任何 OperatorSupportBase 返回 False,则返回 False)和 any_chain
(如果任何 OperatorSupportBase 返回 True,则返回 True)来链式组合多个 OperatorSuppportBase
。
考虑以下示例
from torch.fx.passes.infra.partitioner import CapabilityBasedPartitioner
from torch.fx.passes.operator_support import any_chain, OperatorSupportBase
class AddMulOperatorSupport(OperatorSupportBase):
def is_node_supported(self, submodules, node: torch.fx.Node) -> bool:
return node.op == "call_function" and node.target in [
torch.ops.aten.add.Tensor, torch.ops.aten.mul.Tensor,
]
capability_partitioner = CapabilityBasedPartitioner(
graph_module,
op_support,
)
# Returns a list of partitions (list of nodes that belong in each partition)
partition_list = capability_partitioner.propose_partitions()
如果您查看基于能力的分区器,您可能还会发现一个 fuse_partition
函数,它将返回一个修改后的图,其中分区作为子模块,并通过 call_module
节点在顶层图中调用这些子模块。然而,这不符合 IR 规范,因为我们不允许 call_module
节点。
组合¶
我们还提供了一个组合辅助函数:generate_pattern_op_partitions
参数
graph_module (fx.GraphModule)
:我们要分区的模块patterns (List[torch.fx.Graph])
:以 torch.fx.Graph 形式表示的模式列表。这些图可以通过 exir.capture 获取的 GraphModule 的graph
字段获得(推荐),或者通过符号跟踪获得(可能无法产生准确的 edge dialect 图),或者通过手动创建图模块获得。op_support (OperatorSupportBase)
:可以通过以下方式创建的 OperatorSupportBase直接子类化并实现
is_node_supported()
获取
create_op_support()
的结果获取
create_pattern_support()
的结果使用
chain()
或any_chain()
链式组合多个 OperatorSupportBase 类
返回
包含由给定 OperatorSupportBase 对象和给定模式图的并集支持的节点的(最大可能子图)分区列表。
源分区器¶
对于更复杂的用例,用户希望基于更高级别的模块(torch.nn.Linear
或 torch.nn.functional.Linear
)进行分区,这些模块现已被分解为其算子(aten.permute
, aten.addmm
),我们有以下辅助函数
get_source_partitions(graph: torch.fx.Graph, wanted_sources: List[Any]) -> Dict[Any, SourcePartition]
参数
graph
:我们要分区的图wanted_sources
:从该源分解而来的节点源列表。这可以是函数(例如torch.nn.functional.linear
)或叶模块类型(例如torch.nn.Linear
)
返回
将源(例如
torch.nn.modules.linear.Linear
)映射到与从该类型模块展平的节点列表相对应的SourcePartitions
列表的字典。
@dataclass
class SourcePartition():
# Nodes in a particular partition
nodes: List[Node]
# Module type
module_type: Type
# Nodes in the graph that are needed as inputs to the partition
input_nodes: List[Node] = field(default_factory=list)
# Nodes in the partition that are being used by nodes outside of the partition
output_nodes: List[Node] = field(default_factory=list)
# Parameters that are being used
params: List[str] = field(default_factory=list)
一个示例
class M(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear1 = torch.nn.Linear(3, 3)
self.relu = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(3, 5)
def forward(self, x):
x = self.linear1(x)
x = self.linear1(x)
x = self.relu(x)
x = self.linear2(x)
return x
inputs = (torch.randn(3, 3),)
edge_graph = to_edge(export(M(), inputs)).exported_program().graph_module.graph
print(edge_graph)
"""
graph():
%arg0 : [#users=1] = placeholder[target=arg0]
%_param_constant0 : [#users=1] = get_attr[target=_param_constant0]
%permute_default : [#users=1] = call_function[target=torch.ops.aten.permute_copy.default](args = (%_param_constant0,), kwargs = {})
%_param_constant1 : [#users=1] = get_attr[target=_param_constant1]
%addmm_default : [#users=1] = call_function[target=torch.ops.aten.addmm.default](args = (%_param_constant1, %arg0, %t_default), kwargs = {})
%_param_constant0_1 : [#users=1] = get_attr[target=_param_constant0]
%permute_default_1 : [#users=1] = call_function[target=torch.ops.aten.permute_copy.default](args = (%_param_constant0_1,), kwargs = {})
%_param_constant1_1 : [#users=1] = get_attr[target=_param_constant1]
%addmm_default_1 : [#users=1] = call_function[target=torch.ops.aten.addmm.default](args = (%_param_constant1_1, %addmm_default, %t_default_1), kwargs = {})
%relu_default : [#users=1] = call_function[target=torch.ops.aten.relu.default](args = (%addmm_default_1,), kwargs = {})
%_param_constant2 : [#users=1] = get_attr[target=_param_constant2]
%permute_default_2 : [#users=1] = call_function[target=torch.ops.aten.permute_copy.default](args = (%_param_constant2,), kwargs = {})
%_param_constant3 : [#users=1] = get_attr[target=_param_constant3]
%addmm_default_2 : [#users=1] = call_function[target=torch.ops.aten.addmm.default](args = (%_param_constant3, %relu_default, %t_default_2), kwargs = {})
return [addmm_default_2]
"""
module_partitions = get_source_partitions(edge_graph, [torch.nn.Linear, torch.nn.ReLU])
print(module_partitions)
"""
{<class 'torch.nn.modules.linear.Linear'>: [
ModulePartition(nodes=[_param_constant0, t_default, _param_constant1, addmm_default], module_type=<class 'torch.nn.modules.linear.Linear'>, input_nodes=[arg0], output_nodes=[addmm_default], params=["_param_constant0", "_param_constant1"]),
ModulePartition(nodes=[_param_constant0_1, t_default_1, _param_constant1_1, addmm_default_1], module_type=<class 'torch.nn.modules.linear.Linear'>, input_nodes=[addmm_default], output_nodes=[addmm_default_1], params=["_param_constant0_1", "_param_constant1_1"]),
ModulePartition(nodes=[_param_constant2, t_default_2, _param_constant3, addmm_default_2], module_type=<class 'torch.nn.modules.linear.Linear'>, input_nodes=[relu_default], output_nodes=[addmm_default_2], params=["_param_constant2", "_param_constant3"])],
<class 'torch.nn.modules.activation.ReLU'>: [
ModulePartition(nodes=[relu_default], module_type=<class 'torch.nn.modules.activation.ReLU'>, input_nodes=[addmm_default_1], output_nodes=[relu_default], params=[])]}
"""