-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add pytorch-lightning decorator to nano #3181
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
yangw1234
merged 31 commits into
intel:branch-2.0
from
zhentaocc:pytorch_lightning_wrapper
Nov 11, 2021
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
b185867
added decorator to create a pytorch lightning model from torch
8151c8a
added unit test for pytorch lightning decorator
5e4b992
refactoring - renaming, adding hints and docstring
c6f5127
moved lightning extension to nano/pytorch
6580715
remove loss, optim creator and directly pass loss and optimizer to in…
06f4b88
added another implementation for pytorch to lightning
ff2f028
use LightningModuleFromTorch to create lightning module from pytorch
aae8fe9
remove temporary change
6af7535
remove redundant part
c02c13e
added trainer.compile to convert pytorch to pytorch-lightning
4b930f2
added unit test for trainer.compile
6aa2dc1
fixed return when input is pl model
d5bb5c1
added type hint for LightningModuleFromTorch.copy
a893aa3
Renamed copy as _copy
c6fb693
Modified comment of compile
596e4e6
added input checking
db4466b
refactored docstring
90eabc7
Reformat docstring
153c1a2
Tiny changes
c642dc9
reformat
1caa2f1
correct the import
f38dff2
type check and
9dbd8f0
assign model as a member variable
293e54a
override load_state_dict
d3c20d5
fix test_trainer_compile
6fabec3
fix test_lightning
d50e403
try lightning module and then self.model
6646454
rename _forward as forward
3dc152d
type check
36b8b6c
optimize imports
daa9b27
Merge branch 'branch-2.0' into pytorch_lightning_wrapper
yangw1234 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # | ||
| # Copyright 2016 The BigDL Authors. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License 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. | ||
| # | ||
| from collections import OrderedDict | ||
|
|
||
| from pytorch_lightning import LightningModule | ||
| from torch import nn, Tensor | ||
| from torch.nn.modules.loss import _Loss | ||
| from torch.optim import Optimizer | ||
|
|
||
|
|
||
| class LightningModuleFromTorch(LightningModule): | ||
| def __init__(self, model: nn.Module, loss: _Loss, optimizer: Optimizer): | ||
| """ | ||
| Integrate pytorch modules, loss, optimizer to pytorch-lightning model. | ||
|
|
||
| :param model: Pytorch model to be converted. | ||
| :param loss: A torch loss function. | ||
| :param optimizer: A torch optimizer. | ||
| """ | ||
| super().__init__() | ||
| self.model = model | ||
| self.loss = loss | ||
| self.optimizer = optimizer | ||
|
|
||
| def forward(self, batch): | ||
| # Handle different numbers of input for various models | ||
| nargs = self.model.forward.__code__.co_argcount | ||
| return self.model(*(batch[:nargs - 1])) | ||
|
|
||
| def training_step(self, batch, batch_idx): | ||
| x, y = batch | ||
| y_hat = self(batch) | ||
| loss = self.loss(y_hat, y) | ||
| return loss | ||
|
|
||
| def validation_step(self, batch, batch_idx): | ||
| x, y = batch | ||
| y_hat = self(batch) | ||
| loss = self.loss(y_hat, y) | ||
| return loss | ||
|
|
||
| def test_step(self, batch, batch_idx): | ||
| x, y = batch | ||
| y_hat = self(batch) | ||
| loss = self.loss(y_hat, y) | ||
| return loss | ||
|
|
||
| def configure_optimizers(self): | ||
| return self.optimizer | ||
|
|
||
| def load_state_dict(self, state_dict: 'OrderedDict[str, Tensor]', | ||
| strict: bool = True): | ||
| try: | ||
| super().load_state_dict(state_dict) | ||
| except RuntimeError: | ||
| self.model.load_state_dict(state_dict) |
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,69 @@ | ||
| # | ||
| # Copyright 2016 The BigDL Authors. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License 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 os | ||
| from unittest import TestCase | ||
|
|
||
| import torch | ||
| from torch import nn | ||
|
|
||
| from _train_torch_lightning import create_data_loader, data_transform | ||
| from bigdl.nano.pytorch.lightning import LightningModuleFromTorch | ||
| from bigdl.nano.pytorch.trainer import Trainer | ||
| from bigdl.nano.pytorch.vision.models import vision | ||
|
|
||
| num_classes = 10 | ||
| batch_size = 256 | ||
| num_workers = 0 | ||
| data_dir = os.path.join(os.path.dirname(__file__), "data") | ||
|
|
||
|
|
||
| class ResNet18(nn.Module): | ||
| def __init__(self, pretrained=True, include_top=False, freeze=True): | ||
| super().__init__() | ||
| backbone = vision.resnet18(pretrained=pretrained, include_top=include_top, freeze=freeze) | ||
| output_size = backbone.get_output_size() | ||
| head = nn.Linear(output_size, num_classes) | ||
| self.model = torch.nn.Sequential(backbone, head) | ||
|
|
||
| def forward(self, x): | ||
| return self.model(x) | ||
|
|
||
|
|
||
| model = ResNet18(pretrained=True, include_top=False, freeze=True) | ||
| loss = nn.CrossEntropyLoss() | ||
| optimizer = torch.optim.Adam(model.parameters(), lr=0.01) | ||
|
|
||
|
|
||
| class TestLightningModuleFromTorch(TestCase): | ||
|
|
||
| def test_resnet18(self): | ||
| pl_model = LightningModuleFromTorch(model, loss, optimizer) | ||
| train_loader = create_data_loader(data_dir, batch_size, num_workers, data_transform) | ||
| trainer = Trainer(max_epochs=1) | ||
| trainer.fit(pl_model, train_loader) | ||
|
|
||
| def test_load_state_dict_from_torch(self): | ||
| torch.save(model.state_dict(), "resnet18_test.pth") | ||
| pl_model = LightningModuleFromTorch(model, loss, optimizer) | ||
| state_dict = torch.load("resnet18_test.pth") | ||
| pl_model.load_state_dict(state_dict) | ||
|
|
||
| def test_load_state_dict_from_lightning(self): | ||
| pl_model = LightningModuleFromTorch(model, loss, optimizer) | ||
| torch.save(pl_model.state_dict(), "lightning_resnet18_test.pth") | ||
| state_dict = torch.load("lightning_resnet18_test.pth") | ||
| pl_model.load_state_dict(state_dict) |
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
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.
Uh oh!
There was an error while loading. Please reload this page.