-
Notifications
You must be signed in to change notification settings - Fork 6
/
Export_StyleGAN2GeneratorClean_to_ONNX.py
69 lines (52 loc) · 2.4 KB
/
Export_StyleGAN2GeneratorClean_to_ONNX.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
# -*- coding: utf-8 -*-
import cv2
from basicsr.utils import img2tensor, tensor2img
from torchvision.transforms.functional import normalize
import torch
import onnx
import onnxruntime as ort
from onnxsim import simplify
#from colorizers import eccv16, siggraph17
from gfpgan.archs.stylegan2_clean_arch import StyleGAN2GeneratorClean
def convert_static_GFPGANv1Clean_1_3_onnx():
onnx_path = "./pretrained/StyleGAN2GeneratorClean.onnx"
sim_onnx_path = "./pretrained/StyleGAN2GeneratorClean_sim.onnx"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_path = 'GFPGANv1.3.pth'
inference_model = StyleGAN2GeneratorClean(
out_size=512,
num_style_feat=512,
channel_multiplier=2,
num_mlp=8,
narrow=1).to(device)
loadnet = torch.load(model_path)
if 'params_ema' in loadnet:
keyname = 'params_ema'
else:
keyname = 'params'
inference_model.load_state_dict(loadnet[keyname], strict=False)
inference_model = inference_model.eval()
style_code = torch.rand((1, 512), dtype=torch.float32)
conditions = torch.randn(1, 1, 1)
torch.onnx.export(inference_model, # model being run
([style_code], conditions), # model input (or a tuple for multiple inputs)
onnx_path, # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=11, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
verbose=True,
input_names=['input'], # the model's input names
output_names=['out_ab'] # the model's output names
)
print("export StyleGAN2GeneratorClean onnx done.")
onnx_model = onnx.load(onnx_path)
onnx.checker.check_model(onnx_model)
model_simp, check = simplify(onnx_model, check_n=3)
onnx.save(model_simp, sim_onnx_path)
print("export StyleGAN2GeneratorClean onnx sim done.")
if __name__ == "__main__":
#convert_static_GFPGANv1Clean_1_3_onnx()
convert_static_GFPGANv1Clean_1_3_onnx()
"""cmd
PYTHONPATH=. python3 ./export_onnx.py
"""