This repository has been archived by the owner on Sep 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_mlir_module_torch_mlir.py
76 lines (55 loc) · 2.21 KB
/
generate_mlir_module_torch_mlir.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import argparse
import os
import pathlib
import numpy as np
import torch_mlir
import torch
class Conv2DModule(torch.nn.Module):
def __init__(self, padding: tuple[int, int] = (1, 1)):
super().__init__()
self.conv = torch.nn.Conv2d(
1, 1, kernel_size=(3, 3), stride=(1, 1), padding=padding, bias=False
)
def forward(self, x):
return self.conv(x)
def generate_module(
padding: tuple[int, int], module_input: np.ndarray, work_dir: pathlib.Path
):
os.makedirs(name=work_dir, exist_ok=True)
os.makedirs(name=work_dir / "linalg", exist_ok=True)
os.makedirs(name=work_dir / "tosa", exist_ok=True)
torch_module = Conv2DModule(padding=padding).to(torch.device("cpu"))
# Infer shape
torch_module.eval()
torch_output = torch_module(torch.tensor(module_input))
np.save(file=work_dir / "expected_output", arr=torch_output.detach().numpy())
# Compile
# Linalg
compiled = torch_mlir.compile(torch_module, torch.tensor(module_input), output_type=torch_mlir.OutputType.LINALG_ON_TENSORS)
mlir_module_path = work_dir / "linalg" / "module.mlir"
with open(mlir_module_path, "w", encoding="utf-8") as f:
f.write(str(compiled))
# TOSA
compiled = torch_mlir.compile(torch_module, torch.tensor(module_input), output_type=torch_mlir.OutputType.TOSA)
mlir_module_path = work_dir / "tosa" / "module.mlir"
with open(mlir_module_path, "w", encoding="utf-8") as f:
f.write(str(compiled))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--pad_x", type=int, required=True)
parser.add_argument("--pad_y", type=int, required=True)
args = parser.parse_args()
np.random.seed(42)
torch.manual_seed(0)
work_dir = pathlib.Path(__file__).parent / "output" / "torch-mlir"
os.makedirs(name=work_dir, exist_ok=True)
input_shape = (1, 1, 16, 16)
module_input = np.random.rand(*input_shape).astype(np.float32)
np.save(file=work_dir.parent / "module_input", arr=module_input)
generate_module(
padding=(args.pad_x, args.pad_y),
module_input=module_input,
work_dir=work_dir / f"padding_{args.pad_x}_{args.pad_y}",
)
if __name__ == "__main__":
main()