-
Notifications
You must be signed in to change notification settings - Fork 279
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
#235 Added Notebook Example for Torchscript #794
Open
Shashank1202
wants to merge
1
commit into
microsoft:main
Choose a base branch
from
Shashank1202:torchscript
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
Binary file not shown.
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,92 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 1, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"import torch\n", | ||
"import torch.nn as nn\n", | ||
"import torch.optim as optim\n", | ||
"import torch.utils.data as data" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 2, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"class SimpleModel(nn.Module):\n", | ||
" def __init__(self):\n", | ||
" super(SimpleModel, self).__init__()\n", | ||
" self.fc = nn.Linear(10, 5)\n", | ||
"\n", | ||
" def forward(self, x):\n", | ||
" return self.fc(x)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 3, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"model = SimpleModel()\n", | ||
"scripted_model = torch.jit.script(model)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 4, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"scripted_model.save(\"simple_model_scripted.pt\")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": 5, | ||
"metadata": {}, | ||
"outputs": [ | ||
{ | ||
"name": "stdout", | ||
"output_type": "stream", | ||
"text": [ | ||
"tensor([[ 0.4575, 0.6755, 0.1485, -0.5884, -1.2903]],\n", | ||
" grad_fn=<AddmmBackward0>)\n" | ||
] | ||
} | ||
], | ||
"source": [ | ||
"loaded_model = torch.jit.load(\"simple_model_scripted.pt\")\n", | ||
"x = torch.randn(1, 10)\n", | ||
"output = loaded_model(x)\n", | ||
"print(output)\n" | ||
] | ||
} | ||
], | ||
"metadata": { | ||
"kernelspec": { | ||
"display_name": "bot", | ||
"language": "python", | ||
"name": "python3" | ||
}, | ||
"language_info": { | ||
"codemirror_mode": { | ||
"name": "ipython", | ||
"version": 3 | ||
}, | ||
"file_extension": ".py", | ||
"mimetype": "text/x-python", | ||
"name": "python", | ||
"nbconvert_exporter": "python", | ||
"pygments_lexer": "ipython3", | ||
"version": "3.8.19" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 2 | ||
} |
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,61 @@ | ||
import torch | ||
import unittest | ||
import numpy as np | ||
|
||
class TestTorchScriptModel(unittest.TestCase): | ||
|
||
@classmethod | ||
def setUpClass(cls): | ||
# Load the TorchScript model | ||
cls.model = torch.jit.load('notebooks/simple_model_scripted.pt') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We like to avoid checking in the model binaries. Can you please recreate it here and use it for your test, and then remove the binary file? |
||
cls.model.eval() # Set the model to evaluation mode | ||
|
||
def test_model_output_shape(self): | ||
"""Test if the model outputs the correct shape.""" | ||
input_tensor = torch.randn(1, 5) # Adjust shape based on model input requirements | ||
output_tensor = self.model(input_tensor) | ||
self.assertEqual(output_tensor.shape, (1, 5), "Output shape mismatch") | ||
|
||
def test_model_output_values(self): | ||
"""Test if the model output values are within an expected range.""" | ||
input_tensor = torch.randn(1, 5) | ||
output_tensor = self.model(input_tensor) | ||
# Example: Check if all output values are within the range -1 to 1 | ||
self.assertTrue(torch.all(output_tensor >= -1) and torch.all(output_tensor <= 1), | ||
"Output values out of expected range") | ||
|
||
def test_model_with_different_inputs(self): | ||
"""Test the model with various types of inputs to ensure robustness.""" | ||
inputs = [ | ||
torch.zeros(1, 5), | ||
torch.ones(1, 5), | ||
torch.randn(1, 5), | ||
torch.full((1, 5), 0.5) | ||
] | ||
for input_tensor in inputs: | ||
output_tensor = self.model(input_tensor) | ||
self.assertEqual(output_tensor.shape, (1, 5), "Output shape mismatch with different inputs") | ||
|
||
def test_model_gradients(self): | ||
"""Test if the model's gradients are computed correctly.""" | ||
input_tensor = torch.randn(1, 5, requires_grad=True) | ||
output_tensor = self.model(input_tensor) | ||
output_tensor.sum().backward() | ||
self.assertIsNotNone(input_tensor.grad, "Gradients were not computed") | ||
|
||
def test_scripted_model_serialization(self): | ||
"""Test if the scripted model can be reloaded and produce consistent outputs.""" | ||
input_tensor = torch.randn(1, 5) | ||
output_original = self.model(input_tensor) | ||
|
||
# Save and reload the scripted model | ||
torch.jit.save(self.model, 'test_scripted_model.pt') | ||
reloaded_model = torch.jit.load('test_scripted_model.pt') | ||
reloaded_model.eval() | ||
|
||
output_reloaded = reloaded_model(input_tensor) | ||
self.assertTrue(torch.allclose(output_original, output_reloaded), | ||
"Outputs differ after reloading the scripted model") | ||
|
||
if __name__ == '__main__': | ||
unittest.main() |
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.
Please rename the file to start with
test_
to match the others in the folder