-
Notifications
You must be signed in to change notification settings - Fork 0
Refactor models conversions #135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e50cde7
move and rename model conversion scripts
Sarah5567 ebf5dfa
validate model export with validate_onnx_vs_pytorch.py
Sarah5567 57ed036
rename function
Sarah5567 52d85c0
update references
Sarah5567 fa3e65e
change wornge path
Sarah5567 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,79 @@ | ||
| #!/usr/bin/env python3 | ||
| import argparse | ||
| from pathlib import Path | ||
| import subprocess | ||
|
|
||
| import torch | ||
|
|
||
| from src.inference import MobileNetInference, ResNetInference | ||
| from src.path_utils import ensure_clean_directory | ||
|
|
||
| NUM_CLASSES = 83 | ||
| INPUT_SIZE = (256, 256) | ||
| DEVICE = "cpu" | ||
| MODELS_DIR_PATH = Path("models") | ||
|
|
||
|
|
||
| def get_model(model_name: str): | ||
| if model_name == "resnet18": | ||
| return ResNetInference( | ||
| device=DEVICE, | ||
| weights_path=MODELS_DIR_PATH / "pytorch" / f"{model_name}.pt", | ||
| num_classes=NUM_CLASSES, | ||
| ) | ||
| elif model_name == "mobilenet": | ||
| return MobileNetInference( | ||
| device=DEVICE, | ||
| weights_path=MODELS_DIR_PATH / "pytorch" / f"{model_name}.pt", | ||
| num_classes=NUM_CLASSES, | ||
| ) | ||
| else: | ||
| raise ValueError(f"Unsupported model: {model_name}") | ||
|
|
||
|
|
||
| def main(model_name: str): | ||
| pytorch_model = get_model(model_name) | ||
|
|
||
| # Detect parameter dtype (fp16/fp32) and match input accordingly | ||
| param_dtype = next( | ||
| (p.dtype for p in pytorch_model.model.parameters() if p.is_floating_point()), | ||
| torch.float32, | ||
| ) | ||
|
|
||
| # Fixed input size: 256x256, 3 channels, batch=1 | ||
| dummy = torch.zeros(1, 3, INPUT_SIZE[0], INPUT_SIZE[1], dtype=param_dtype) | ||
|
|
||
| # ONNX path/name | ||
| onnx_dir = MODELS_DIR_PATH / "onnx" | ||
| ensure_clean_directory(onnx_dir) | ||
| onnx_path = onnx_dir / f"{model_name}.onnx" | ||
| dynamic_axes = {"input": {0: "batch"}, "output": {0: "batch"}} | ||
|
|
||
| with torch.inference_mode(): | ||
| torch.onnx.export( | ||
| pytorch_model.model, | ||
| dummy, | ||
| onnx_path.as_posix(), | ||
| input_names=["input"], | ||
| output_names=["output"], | ||
| dynamic_axes=dynamic_axes, | ||
| opset_version=17, | ||
| do_constant_folding=True, | ||
| ) | ||
|
|
||
| subprocess.run(["python3", "src/model_conversion/validate_onnx_vs_pytorch.py", model_name], check=True) | ||
|
|
||
| print(f"Exported: {onnx_path}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| p = argparse.ArgumentParser("Export PyTorch model to ONNX (fixed 256x256 input)") | ||
| p.add_argument( | ||
| "model_name", | ||
| type=str, | ||
| choices=["resnet18", "mobilenet"], | ||
| help="Name of the model to export (must exist in models directory)", | ||
| ) | ||
| args = p.parse_args() | ||
|
|
||
| main(args.model_name) | ||
This file contains hidden or 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,116 @@ | ||
| #!/usr/bin/env python3 | ||
| import argparse | ||
| import os | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| import torch | ||
| from PIL import Image | ||
|
|
||
| from src.inference import ID_TO_NAME, ClassifierInferenceBase, MobileNetInference, ResNetInference | ||
| from src.onnx_model import OnnxClassifierInferenceBase | ||
|
|
||
| NUM_CLASSES = 83 | ||
| INPUT_SIZE = (256, 256) | ||
|
|
||
| MODELS_DIR_PATH = Path("models") | ||
| IMAGES_DIR_PATH = Path("assets/test_images") | ||
| DEVICE = "cpu" | ||
| INPUT_SHAPE = (1, 3, *INPUT_SIZE) | ||
|
|
||
|
|
||
| def assert_the_same_shapes( | ||
| model_name: str, | ||
| onnx_clf: OnnxClassifierInferenceBase, | ||
| ): | ||
| onnx_inputs = [input.shape for input in onnx_clf.session.get_inputs()] | ||
| onnx_outputs = [output.shape for output in onnx_clf.session.get_outputs()] | ||
|
|
||
| assert onnx_inputs == [["batch", 3, *INPUT_SIZE]], "ONNX input shape mismatch" | ||
| assert onnx_outputs == [ | ||
| ["batch", NUM_CLASSES] | ||
| ], f"Number of outputs mismatch: {onnx_outputs} is not [['batch', {NUM_CLASSES}]]" | ||
|
|
||
|
|
||
| def assert_numerical_accuracy( | ||
| model_name: str, | ||
| torch_clf: ClassifierInferenceBase, | ||
| onnx_clf: OnnxClassifierInferenceBase, | ||
| rtol: float = 1e-3, | ||
| atol: float = 1e-5, | ||
| ): | ||
| with torch.inference_mode(): | ||
| param_dtype = next((p.dtype for p in torch_clf.model.parameters() if p.is_floating_point()), torch.float32) | ||
| torch_input = torch.randn(*INPUT_SHAPE, dtype=param_dtype) | ||
| torch_logits = torch_clf.model(torch_input).to(torch.float32) | ||
| torch_np = torch_logits.detach().cpu().numpy() | ||
|
|
||
| onnx_logits = onnx_clf._forward(torch_input.to(torch.float32)) | ||
| onnx_np = onnx_logits.detach().cpu().numpy() | ||
|
|
||
| assert np.allclose(torch_np, onnx_np, rtol=rtol, atol=atol) | ||
|
|
||
|
|
||
| def assert_same_predictions( | ||
| model_name: str, | ||
| torch_clf: ClassifierInferenceBase, | ||
| onnx_clf: OnnxClassifierInferenceBase, | ||
| ): | ||
| torch_results = {} | ||
| onnx_results = {} | ||
| img_extensions = {".jpg", ".jpeg", ".png", ".bmp"} | ||
|
|
||
| for filename in os.listdir(IMAGES_DIR_PATH): | ||
| file_ext = os.path.splitext(filename)[1].lower() | ||
| if file_ext in img_extensions: | ||
| image_path = os.path.join(IMAGES_DIR_PATH, filename) | ||
| image = Image.open(image_path) | ||
|
|
||
| torch_pred = torch_clf.infer(image) | ||
| onnx_pred = onnx_clf.infer(image) | ||
|
|
||
| torch_results[filename] = torch_pred[0]["class_id"] | ||
| onnx_results[filename] = onnx_pred[0]["class_id"] | ||
|
|
||
| assert torch_results == onnx_results | ||
|
|
||
|
|
||
| def main(model_name: str): | ||
| if model_name == "resnet18": | ||
| torch_model = ResNetInference( | ||
| device=DEVICE, | ||
| weights_path=MODELS_DIR_PATH / "pytorch" / f"{model_name}.pt", | ||
| num_classes=NUM_CLASSES, | ||
| strict=True, | ||
| ) | ||
| elif model_name == "mobilenet": | ||
| torch_model = MobileNetInference( | ||
| device=DEVICE, | ||
| weights_path=MODELS_DIR_PATH / "pytorch" / f"{model_name}.pt", | ||
| num_classes=NUM_CLASSES, | ||
| strict=True, | ||
| ) | ||
| else: | ||
| raise ValueError(f"Unsupported model: {model_name}") | ||
| onnx_model = OnnxClassifierInferenceBase( | ||
| device=DEVICE, | ||
| weights_path=MODELS_DIR_PATH / "onnx" / f"{model_name}.onnx", | ||
| class_mapping=ID_TO_NAME, | ||
| topk=1, | ||
| ) | ||
|
|
||
| assert_the_same_shapes(model_name, onnx_model) | ||
| assert_numerical_accuracy(model_name, torch_model, onnx_model) | ||
| assert_same_predictions(model_name, torch_model, onnx_model) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| p = argparse.ArgumentParser("Validate ONNX model against PyTorch") | ||
| p.add_argument( | ||
| "model_name", | ||
| type=str, | ||
| choices=["resnet18", "mobilenet"], | ||
| help="Name of the model to validate", | ||
| ) | ||
| args = p.parse_args() | ||
| main(args.model_name) |
File renamed without changes.
This file contains hidden or 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 hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since both scripts are written in Python, best practice in this case is to import those functions instead of using subprocesses.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In general that's right, specificly here I preferd do it like this to avoid creating the models objects, because their creation is gonna change (in #134 and #130)