Describe the feature🚀
我们希望Plugin Pattern能够实现如下效果,注意,如果需要共享参数,应由用户在构造时完成共享。
class TestModule(torch.nn.Module):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.w = torch.nn.Parameter(torch.rand(1024, 1024))
self.bias = torch.Tensor(1024)
def forward(self, x):
return (x @ self.w + self.bias,)
class AnotherModule(torch.nn.Module):
def __init__(self, weight, *args, **kwargs):
super().__init__(*args, **kwargs)
self.w = torch.nn.Parameter(weight)
def forward(self, x):
return x + self.w
weight = torch.rand(1024, 1024)
register_plugin_pattern(
TestModule(), (torch.empty(1024, 1024),), AnotherModule(weight), target=Target.none
)
config = XpuGraphConfig(
is_training=False,
target=Target.none,
vendor_compiler_config={},
debug=True,
enable_cache=False,
freeze=True,
)
compiler = XpuGraph(config)
input_tensor = torch.rand(1024, 1024)
with torch.inference_mode():
compiled = torch.compile(TestModule(), fullgraph=True, dynamic=False, backend=compiler)
assert is_similar(compiled(input_tensor)[0], AnotherModule(weight)(input_tensor)) is True
在不开启parameter freezing的场景下
class Matmul:
def __init__(self, w):
self.w = w
def forward(self, x):
return self.w @ x
class Replace:
def __init__(self, w):
self.w = w
def forward(self, x):
return self.w + x
w = torch.empty(1024,1024)
# 对于Matmul(w) -> Replace(w)
# pattern和replace共享某些参数,我们建议使用如下方式match&rewrite
def matmul(x, w):
return x@w
def replace(x, w):
return x+w
# 修改对应的module实现来实现代码复用
class Matmul:
def __init__(self, w):
self.w = w
def forward(self, x):
return matmul(x,self.w)
class Replace:
def __init__(self, w):
self.w = w
def forward(self, x):
return replace(x, self.w)
# 即使不共享参数,在不使能paramter freezing下,pattern也应该只注册function 而不是module
def matmul(x, w):
return x@w
class Matmul:
def __init__(self, w):
self.w = w
def forward(self, x):
return matmul(x,self.w)
# replacement即可以注册function,也可以注册module
def replace(x, w):
return x+w
class Replace:
def __init__(self, w):
self.w = w
def forward(self, x):
return x + self.w
References
https://github.com/pytorch/pytorch/blob/main/torch/_functorch/_aot_autograd/graph_capture_wrappers.py#L1323
Environment details
PyTorch: 2.5.1
torch_npu : 2.5.1
XpuGraph: 0.4.0
Describe the feature🚀
我们希望Plugin Pattern能够实现如下效果,注意,如果需要共享参数,应由用户在构造时完成共享。
在不开启
parameter freezing的场景下References
https://github.com/pytorch/pytorch/blob/main/torch/_functorch/_aot_autograd/graph_capture_wrappers.py#L1323
Environment details
PyTorch: 2.5.1
torch_npu : 2.5.1
XpuGraph: 0.4.0