-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feature: Add Framework Version support for PyTorch compilation (Neo) #2133
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
12 commits
Select commit
Hold shift + click to select a range
53687c6
feature: Add Framework Version support for PyTorch compilation (Neo)
80fbb8b
Merge branch 'master' into framework-versioning
metrizable 46954ad
Merge branch 'master' into framework-versioning
metrizable 5c12d5a
Merge branch 'master' into framework-versioning
metrizable 7534416
Merge branch 'master' into framework-versioning
metrizable 91b92a7
Merge branch 'master' into framework-versioning
metrizable 9897e19
Merge branch 'master' into framework-versioning
ahsan-z-khan 2f35471
Merge branch 'master' into framework-versioning
ahsan-z-khan 12d669a
Merge branch 'master' into framework-versioning
ahsan-z-khan 0c9baa3
Merge branch 'master' into framework-versioning
ahsan-z-khan 1b0ecee
Merge branch 'master' into framework-versioning
a245d45
Merge branch 'master' into framework-versioning
ahsan-z-khan 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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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,90 @@ | ||
# Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). You | ||
# may not use this file except in compliance with the License. A copy of | ||
# the License is located at | ||
# | ||
# http://aws.amazon.com/apache2.0/ | ||
# | ||
# or in the "license" file accompanying this file. This file is | ||
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF | ||
# ANY KIND, either express or implied. See the License for the specific | ||
# language governing permissions and limitations under the License. | ||
import io | ||
import json | ||
import logging | ||
import os | ||
import pickle | ||
|
||
import numpy as np | ||
import torch | ||
import neopytorch | ||
import torchvision.transforms as transforms | ||
from PIL import Image # Training container doesn't have this package | ||
|
||
logger = logging.getLogger(__name__) | ||
logger.setLevel(logging.DEBUG) | ||
|
||
|
||
def transform_fn(model, payload, request_content_type, response_content_type): | ||
|
||
logger.info("Invoking user-defined transform function") | ||
|
||
if request_content_type != "application/octet-stream": | ||
raise RuntimeError( | ||
"Content type must be application/octet-stream. Provided: {0}".format( | ||
request_content_type | ||
) | ||
) | ||
|
||
# preprocess image | ||
decoded = Image.open(io.BytesIO(payload)) | ||
preprocess = transforms.Compose( | ||
[ | ||
transforms.Resize(256), | ||
transforms.CenterCrop(224), | ||
transforms.ToTensor(), | ||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | ||
] | ||
) | ||
normalized = preprocess(decoded) | ||
batchified = normalized.unsqueeze(0) | ||
|
||
# predict | ||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
batchified = batchified.to(device) | ||
result = model.forward(batchified) | ||
|
||
# Softmax (assumes batch size 1) | ||
result = np.squeeze(result.cpu().numpy()) | ||
result_exp = np.exp(result - np.max(result)) | ||
result = result_exp / np.sum(result_exp) | ||
|
||
response_body = json.dumps(result.tolist()) | ||
content_type = "application/json" | ||
|
||
return response_body, content_type | ||
|
||
|
||
def model_fn(model_dir): | ||
|
||
logger.info("model_fn") | ||
neopytorch.config(model_dir=model_dir, neo_runtime=True) | ||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
# The compiled model is saved as "compiled.pt" | ||
model = torch.jit.load(os.path.join(model_dir, "compiled.pt"), map_location=device) | ||
|
||
# It is recommended to run warm-up inference during model load | ||
sample_input_path = os.path.join(model_dir, "sample_input.pkl") | ||
with open(sample_input_path, "rb") as input_file: | ||
model_input = pickle.load(input_file) | ||
if torch.is_tensor(model_input): | ||
model_input = model_input.to(device) | ||
model(model_input) | ||
elif isinstance(model_input, tuple): | ||
model_input = (inp.to(device) for inp in model_input if torch.is_tensor(inp)) | ||
model(*model_input) | ||
else: | ||
print("Only supports a torch tensor or a tuple of torch tensors") | ||
|
||
return model |
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.
Recommendation generated by Amazon CodeGuru Reviewer. Leave feedback on this recommendation by replying to the comment or by reacting to the comment using emoji.
Analysis of this code determined that this line of code contains a resource that might not have closed properly. A resource leak can slow down or crash your system. Programs are strongly recommended to use the built in
with
keyword to open a resource or to use atry-finally
block to open and close resources explicitly. The contextlib module provides helpful utilities for using thewith
statement.Learn more