Skip to content

Commit 55ebafa

Browse files
committed
feat: PyTorch PT2 Model Generation
This change adds the generation of PT2 format serialized PyTorch model files to the QA model generation scripts.
1 parent d8704c4 commit 55ebafa

3 files changed

Lines changed: 208 additions & 4 deletions

File tree

qa/L0_backend_python/python_based_backends/test.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ CLIENT_LOG="./python_based_backends_client.log"
3535
TEST_RESULT_FILE="./test_results.txt"
3636
CLIENT_PY="./python_based_backends_test.py"
3737
GEN_PYTORCH_MODEL_PY="../../common/gen_qa_pytorch_model.py"
38+
GEN_PYTORCH2_MODEL_PY="../../common/gen_qa_pytorch2_model.py"
3839
RET=0
3940

4041
rm -rf ${MODEL_REPOSITORY}

qa/common/gen_qa_models.py

Lines changed: 86 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1283,6 +1283,55 @@ def forward(self, INPUT0, INPUT1):
12831283
traced.save(model_version_dir + "/model.pt")
12841284

12851285

1286+
def create_libtorch2_modelfile(
1287+
models_dir,
1288+
max_batch,
1289+
model_version,
1290+
input_shape,
1291+
output0_shape,
1292+
output1_shape,
1293+
input_dtype,
1294+
output0_dtype,
1295+
output1_dtype,
1296+
swap=False,
1297+
):
1298+
if not tu.validate_for_libtorch_model(
1299+
input_dtype,
1300+
output0_dtype,
1301+
output1_dtype,
1302+
input_shape,
1303+
output0_shape,
1304+
output1_shape,
1305+
max_batch,
1306+
):
1307+
return
1308+
1309+
model_name = tu.get_model_name(
1310+
"libtorch2",
1311+
input_dtype,
1312+
output0_dtype,
1313+
output1_dtype,
1314+
)
1315+
1316+
model_version_dir = models_dir + "/" + model_name + "/" + str(model_version)
1317+
1318+
try:
1319+
os.makedirs(model_version_dir)
1320+
except OSError:
1321+
pass # ignore existing dir
1322+
1323+
class AddSubNet2(nn.Module):
1324+
def forward(self, INPUT0, INPUT1):
1325+
op0 = INPUT0 + INPUT1
1326+
op1 = INPUT0 - INPUT1
1327+
return op0, op1
1328+
1329+
ep = torch.export.export(
1330+
AddSubNet2(), (torch.randn(*input_shape), torch.randn(*input_shape))
1331+
)
1332+
torch.export.save(ep, model_version_dir + "/model.pt2")
1333+
1334+
12861335
def create_libtorch_modelconfig(
12871336
models_dir,
12881337
max_batch,
@@ -1295,6 +1344,7 @@ def create_libtorch_modelconfig(
12951344
output1_dtype,
12961345
output0_label_cnt,
12971346
version_policy,
1347+
torch2=False,
12981348
):
12991349
if not tu.validate_for_libtorch_model(
13001350
input_dtype,
@@ -1307,6 +1357,10 @@ def create_libtorch_modelconfig(
13071357
):
13081358
return
13091359

1360+
if torch2 and max_batch != 0:
1361+
# TorchScript models with batching are not supported in torch2 backend
1362+
return
1363+
13101364
# Unpack version policy
13111365
version_policy_str = "{ latest { num_versions: 1 }}"
13121366
if version_policy is not None:
@@ -1320,15 +1374,15 @@ def create_libtorch_modelconfig(
13201374

13211375
# Use a different model name for the non-batching variant
13221376
model_name = tu.get_model_name(
1323-
"libtorch_nobatch" if max_batch == 0 else "libtorch",
1377+
"libtorch_nobatch" if max_batch == 0 else "libtorch2" if torch2 else "libtorch",
13241378
input_dtype,
13251379
output0_dtype,
13261380
output1_dtype,
13271381
)
13281382
config_dir = models_dir + "/" + model_name
13291383
config = """
13301384
name: "{}"
1331-
platform: "pytorch_libtorch"
1385+
platform: "{}"
13321386
max_batch_size: {}
13331387
version_policy: {}
13341388
input [
@@ -1358,6 +1412,7 @@ def create_libtorch_modelconfig(
13581412
]
13591413
""".format(
13601414
model_name,
1415+
"pytorch2_libtorch" if torch2 else "pytorch_libtorch",
13611416
max_batch,
13621417
version_policy_str,
13631418
np_to_model_dtype(input_dtype),
@@ -1691,7 +1746,7 @@ def create_models(
16911746
output1_dtype,
16921747
)
16931748

1694-
if FLAGS.libtorch:
1749+
if FLAGS.libtorch or FLAGS.libtorch2:
16951750
# max-batch 8
16961751
create_libtorch_modelconfig(
16971752
models_dir,
@@ -1705,6 +1760,7 @@ def create_models(
17051760
output1_dtype,
17061761
output0_label_cnt,
17071762
version_policy,
1763+
FLAGS.libtorch2,
17081764
)
17091765
create_libtorch_modelfile(
17101766
models_dir,
@@ -1716,6 +1772,7 @@ def create_models(
17161772
input_dtype,
17171773
output0_dtype,
17181774
output1_dtype,
1775+
FLAGS.libtorch2,
17191776
)
17201777
# max-batch 0
17211778
create_libtorch_modelconfig(
@@ -1730,6 +1787,7 @@ def create_models(
17301787
output1_dtype,
17311788
output0_label_cnt,
17321789
version_policy,
1790+
FLAGS.libtorch2,
17331791
)
17341792
create_libtorch_modelfile(
17351793
models_dir,
@@ -1741,6 +1799,7 @@ def create_models(
17411799
input_dtype,
17421800
output0_dtype,
17431801
output1_dtype,
1802+
FLAGS.libtorch2,
17441803
)
17451804

17461805
if FLAGS.openvino:
@@ -1933,6 +1992,12 @@ def create_fixed_models(
19331992
action="store_true",
19341993
help="Generate Pytorch LibTorch models",
19351994
)
1995+
parser.add_argument(
1996+
"--libtorch2",
1997+
required=False,
1998+
action="store_true",
1999+
help="Generate Pytorch LibTorch models using PT2",
2000+
)
19362001
parser.add_argument(
19372002
"--openvino",
19382003
required=False,
@@ -1959,7 +2024,7 @@ def create_fixed_models(
19592024
import tensorrt as trt
19602025
if FLAGS.onnx:
19612026
import onnx
1962-
if FLAGS.libtorch:
2027+
if FLAGS.libtorch or FLAGS.libtorch2:
19632028
import torch
19642029
from torch import nn
19652030
if FLAGS.openvino:
@@ -2116,6 +2181,7 @@ def create_fixed_models(
21162181
create_onnx_modelfile(
21172182
FLAGS.models_dir, 0, 3, (16,), (16,), (16,), vt, vt, vt, swap=True
21182183
)
2184+
21192185
if FLAGS.libtorch:
21202186
for vt in [np.float32, np.int32, np.int16, np.int8]:
21212187
create_libtorch_modelfile(
@@ -2130,6 +2196,22 @@ def create_fixed_models(
21302196
create_libtorch_modelfile(
21312197
FLAGS.models_dir, 0, 3, (16,), (16,), (16,), vt, vt, vt, swap=True
21322198
)
2199+
2200+
if FLAGS.libtorch2:
2201+
for vt in [np.float32, np.int32, np.int16, np.int8]:
2202+
create_libtorch2_modelfile(
2203+
FLAGS.models_dir, 8, 2, (16,), (16,), (16,), vt, vt, vt, swap=True
2204+
)
2205+
create_libtorch2_modelfile(
2206+
FLAGS.models_dir, 8, 3, (16,), (16,), (16,), vt, vt, vt, swap=True
2207+
)
2208+
create_libtorch2_modelfile(
2209+
FLAGS.models_dir, 0, 2, (16,), (16,), (16,), vt, vt, vt, swap=True
2210+
)
2211+
create_libtorch2_modelfile(
2212+
FLAGS.models_dir, 0, 3, (16,), (16,), (16,), vt, vt, vt, swap=True
2213+
)
2214+
21332215
if FLAGS.openvino:
21342216
for vt in [np.float16, np.float32, np.int8, np.int16, np.int32]:
21352217
create_openvino_modelfile(

qa/common/gen_qa_pytorch2_model.py

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# Copyright 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
#
3+
# Redistribution and use in source and binary forms, with or without
4+
# modification, are permitted provided that the following conditions
5+
# are met:
6+
# * Redistributions of source code must retain the above copyright
7+
# notice, this list of conditions and the following disclaimer.
8+
# * Redistributions in binary form must reproduce the above copyright
9+
# notice, this list of conditions and the following disclaimer in the
10+
# documentation and/or other materials provided with the distribution.
11+
# * Neither the name of NVIDIA CORPORATION nor the names of its
12+
# contributors may be used to endorse or promote products derived
13+
# from this software without specific prior written permission.
14+
#
15+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
16+
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18+
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
19+
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20+
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21+
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22+
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23+
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26+
27+
28+
import argparse
29+
import os
30+
31+
import torch
32+
from torch import nn
33+
34+
35+
class AddSubNet(nn.Module):
36+
def __init__(self):
37+
super(AddSubNet, self).__init__()
38+
39+
def forward(self, input0, input1):
40+
return (input0 + input1), (input0 - input1)
41+
42+
43+
def generate_model(model_dir):
44+
model = AddSubNet()
45+
46+
os.makedirs(model_dir, exist_ok=True)
47+
model_path = os.path.join(model_dir, "model.pt2")
48+
49+
ep = torch.export.export(model, (torch.randn(4), torch.randn(4)),)
50+
51+
torch.export.save(ep, model_path)
52+
53+
54+
def generate_config(config_path):
55+
with open(f"{config_path}/config.pbtxt", "w") as f:
56+
f.write(
57+
"""
58+
backend: "pytorch"
59+
input [
60+
{
61+
name: "INPUT0"
62+
data_type: TYPE_FP32
63+
dims: [ 4 ]
64+
}
65+
]
66+
input [
67+
{
68+
name: "INPUT1"
69+
data_type: TYPE_FP32
70+
dims: [ 4 ]
71+
}
72+
]
73+
output [
74+
{
75+
name: "OUTPUT0"
76+
data_type: TYPE_FP32
77+
dims: [ 4 ]
78+
}
79+
]
80+
output [
81+
{
82+
name: "OUTPUT1"
83+
data_type: TYPE_FP32
84+
dims: [ 4 ]
85+
}
86+
]
87+
"""
88+
)
89+
90+
91+
if __name__ == "__main__":
92+
parser = argparse.ArgumentParser()
93+
parser.add_argument(
94+
"-m",
95+
"--model-directory",
96+
type=str,
97+
required=True,
98+
help="The path to the model repository.",
99+
)
100+
parser.add_argument(
101+
"--model-name",
102+
type=str,
103+
required=False,
104+
default="add_sub_pytorch",
105+
help="Model name",
106+
)
107+
parser.add_argument(
108+
"--version",
109+
type=str,
110+
required=False,
111+
default="1",
112+
help="Model version",
113+
)
114+
115+
args = parser.parse_args()
116+
117+
model_directory = os.path.join(args.model_directory, args.model_name)
118+
os.makedirs(model_directory, exist_ok=True)
119+
120+
generate_model(model_dir=os.path.join(model_directory, args.version))
121+
generate_config(model_directory)

0 commit comments

Comments
 (0)