pytorch
115 строк · 3.4 Кб
1import torch
2from torch._export import aot_compile
3from torch.export import Dim
4
5
6torch.manual_seed(1337)
7
8
9class Net(torch.nn.Module):
10def __init__(self, device):
11super().__init__()
12self.w_pre = torch.randn(4, 4, device=device)
13self.w_add = torch.randn(4, 4, device=device)
14
15def forward(self, x):
16w_transpose = torch.transpose(self.w_pre, 0, 1)
17w_relu = torch.nn.functional.relu(w_transpose)
18w = w_relu + self.w_add
19return torch.matmul(x, w)
20
21
22class NetWithTensorConstants(torch.nn.Module):
23def __init__(self) -> None:
24super().__init__()
25self.w = torch.randn(30, 1, device="cuda")
26
27def forward(self, x, y):
28z = self.w * x * y
29return z[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17]]
30
31
32data = {}
33data_with_tensor_constants = {}
34
35
36# Basice AOTI model test generation.
37def generate_basic_tests():
38for device in ["cpu", "cuda"] if torch.cuda.is_available() else ["cpu"]:
39for use_runtime_constant_folding in [True, False]:
40if device == "cpu" and use_runtime_constant_folding:
41# We do not test runtime const folding for cpu mode.
42continue
43model = Net(device).to(device=device)
44x = torch.randn((4, 4), device=device)
45with torch.no_grad():
46ref_output = model(x)
47
48torch._dynamo.reset()
49with torch.no_grad():
50dim0_x = Dim("dim0_x", min=1, max=1024)
51dynamic_shapes = {"x": {0: dim0_x}}
52model_so_path = aot_compile(
53model,
54(x,),
55dynamic_shapes=dynamic_shapes,
56options={
57"aot_inductor.use_runtime_constant_folding": use_runtime_constant_folding
58},
59)
60
61suffix = f"{device}"
62if use_runtime_constant_folding:
63suffix += "_use_runtime_constant_folding"
64data.update(
65{
66f"model_so_path_{suffix}": model_so_path,
67f"inputs_{suffix}": [x],
68f"outputs_{suffix}": [ref_output],
69f"w_pre_{suffix}": model.w_pre,
70f"w_add_{suffix}": model.w_add,
71}
72)
73
74
75# AOTI model which will create additional tensors during autograd.
76def generate_test_with_additional_tensors():
77if not torch.cuda.is_available():
78return
79
80model = NetWithTensorConstants()
81x = torch.randn((30, 1), device="cuda")
82y = torch.randn((30, 1), device="cuda")
83with torch.no_grad():
84ref_output = model(x, y)
85
86torch._dynamo.reset()
87with torch.no_grad():
88model_so_path = aot_compile(model, (x, y))
89
90data_with_tensor_constants.update(
91{
92"model_so_path": model_so_path,
93"inputs": [x, y],
94"outputs": [ref_output],
95"w": model.w,
96}
97)
98
99
100generate_basic_tests()
101generate_test_with_additional_tensors()
102
103
104# Use this to communicate tensors to the cpp code
105class Serializer(torch.nn.Module):
106def __init__(self, data):
107super().__init__()
108for key in data:
109setattr(self, key, data[key])
110
111
112torch.jit.script(Serializer(data)).save("data.pt")
113torch.jit.script(Serializer(data_with_tensor_constants)).save(
114"data_with_tensor_constants.pt"
115)
116