-
-
Notifications
You must be signed in to change notification settings - Fork 293
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor out onnx conversion + use data for ncnn input name (#2360)
* Refactor out onnx conversion + use data for ncnn input name * better size requirements for auto inference * throw error
- Loading branch information
1 parent
f13c00f
commit f1402cc
Showing
4 changed files
with
62 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
from io import BytesIO | ||
|
||
import torch | ||
from spandrel import ModelDescriptor | ||
|
||
|
||
def convert_to_onnx_impl( | ||
model: ModelDescriptor, | ||
device: torch.device, | ||
use_half: bool = False, | ||
input_name: str = "input", | ||
output_name: str = "output", | ||
) -> bytes: | ||
# https://github.com/onnx/onnx/issues/654 | ||
dynamic_axes = { | ||
input_name: {0: "batch_size", 2: "height", 3: "width"}, | ||
output_name: {0: "batch_size", 2: "height", 3: "width"}, | ||
} | ||
size = max(model.size_requirements.minimum, 3) | ||
size = size + (size % model.size_requirements.multiple_of) | ||
dummy_input = torch.rand(1, model.input_channels, size, size) | ||
dummy_input = dummy_input.to(device) | ||
|
||
if use_half: | ||
if not model.supports_half: | ||
raise ValueError( | ||
f"Model of arch {model.architecture} does not support half precision." | ||
) | ||
model.model.half() | ||
dummy_input = dummy_input.half() | ||
else: | ||
model.model.float() | ||
dummy_input = dummy_input.float() | ||
|
||
with BytesIO() as f: | ||
torch.onnx.export( | ||
model.model, | ||
dummy_input, | ||
f, | ||
opset_version=14, | ||
verbose=False, | ||
input_names=[input_name], | ||
output_names=[output_name], | ||
dynamic_axes=dynamic_axes, | ||
do_constant_folding=True, | ||
) | ||
f.seek(0) | ||
return f.read() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters