-
Notifications
You must be signed in to change notification settings - Fork 0
Updated model with current best practices, added getting started notebook #5
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
4 commits
Select commit
Hold shift + click to select a range
675bc6e
Updating the example model to show current Hyrax best practices. Crea…
drewoldag 7f17d03
Fixing linting errors.
drewoldag 6789823
Apply suggestions from code review
drewoldag 783593f
Fixing up prepare_data for train vs. infer mode.
drewoldag 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
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| from .example_model import ExampleModel | ||
| from .models.vgg11 import VGG11 | ||
|
|
||
| __all__ = ["ExampleModel"] | ||
| __all__ = ["VGG11"] |
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 |
|---|---|---|
| @@ -1,3 +1,9 @@ | ||
| [model] | ||
| [model.ExampleModel] | ||
| layer = 10 | ||
| [external_hyrax_example] | ||
|
|
||
| [external_hyrax_example.VGG11] | ||
| dropout = 0.5 | ||
| num_classes = 10 | ||
| batch_norm = true | ||
|
|
||
| # The libpath that would be used for runtime config | ||
| # name = "external_hyrax_example.models.vgg11.VGG11" |
This file was deleted.
Oops, something went wrong.
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,109 @@ | ||
| from typing import Union, cast | ||
|
|
||
| import torch | ||
| import torch.nn as nn | ||
| from hyrax.models.model_registry import hyrax_model | ||
|
|
||
| cfgs = { | ||
| "A": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], | ||
| } | ||
|
|
||
|
|
||
| @hyrax_model | ||
| class VGG11(nn.Module): | ||
| """Copy of the PyTorch VGG11 model for testing and demonstration | ||
| purposes. | ||
| https://docs.pytorch.org/vision/main/models/generated/torchvision.models.vgg11.html#torchvision.models.vgg11 | ||
| """ | ||
|
|
||
| def __init__(self, config, data_sample=None): | ||
| """Basic initialization with architecture definition""" | ||
| super().__init__() | ||
|
drewoldag marked this conversation as resolved.
|
||
| if data_sample is None: | ||
| raise ValueError( | ||
| "VGG11 expected 'data_sample' to be provided at construction time " | ||
| "so that input channel dimensions can be inferred, but received None." | ||
| ) | ||
| image_sample = data_sample[0] | ||
| self.in_channels, width, height = image_sample.shape | ||
|
drewoldag marked this conversation as resolved.
|
||
| self.config = config | ||
|
|
||
| dropout = self.config["external_hyrax_example"]["VGG11"]["dropout"] | ||
| num_classes = self.config["external_hyrax_example"]["VGG11"]["num_classes"] | ||
| batch_norm = self.config["external_hyrax_example"]["VGG11"]["batch_norm"] | ||
|
|
||
| self.features = self._make_layers(cfgs["A"], batch_norm=batch_norm) | ||
| self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) | ||
| self.classifier = nn.Sequential( | ||
| nn.Linear(512 * 7 * 7, 4096), | ||
| nn.ReLU(True), | ||
| nn.Dropout(p=dropout), | ||
| nn.Linear(4096, 4096), | ||
| nn.ReLU(True), | ||
| nn.Dropout(p=dropout), | ||
| nn.Linear(4096, num_classes), | ||
| ) | ||
|
|
||
| def _make_layers(self, cfg: list[Union[str, int]], batch_norm: bool = False) -> nn.Sequential: | ||
| """Helper function to create the convolutional layers of the VGG11 architecture""" | ||
| layers: list[nn.Module] = [] | ||
| in_channels = self.in_channels | ||
| for v in cfg: | ||
| if v == "M": | ||
| layers += [nn.MaxPool2d(kernel_size=2, stride=2)] | ||
| else: | ||
| v = cast(int, v) | ||
| conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) | ||
| if batch_norm: | ||
| layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] | ||
| else: | ||
| layers += [conv2d, nn.ReLU(inplace=True)] | ||
| in_channels = v | ||
| return nn.Sequential(*layers) | ||
|
|
||
| def forward(self, batch: tuple) -> torch.Tensor: | ||
| """The innermost logic in the forward pass""" | ||
| x, _ = batch | ||
| x = self.features(x) | ||
| x = self.avgpool(x) | ||
| x = torch.flatten(x, 1) | ||
| x = self.classifier(x) | ||
| return x | ||
|
|
||
| def infer_batch(self, batch): | ||
| """The innermost logic in the inference loop""" | ||
| return self(batch) | ||
|
|
||
| def train_batch(self, batch): | ||
| """The innermost logic in the training loop""" | ||
| _, labels = batch | ||
| self.optimizer.zero_grad() | ||
| outputs = self(batch) | ||
| loss = self.criterion(outputs, labels) | ||
| loss.backward() | ||
| self.optimizer.step() | ||
| return {"loss": loss.item()} | ||
|
drewoldag marked this conversation as resolved.
|
||
|
|
||
| def validate_batch(self, batch): | ||
| """The innermost logic in the validation loop""" | ||
| _, labels = batch | ||
| outputs = self(batch) | ||
| loss = self.criterion(outputs, labels) | ||
| return {"loss": loss.item()} | ||
|
|
||
| def test_batch(self, batch): | ||
| """The innermost logic in the testing loop""" | ||
| _, labels = batch | ||
| outputs = self(batch) | ||
| loss = self.criterion(outputs, labels) | ||
| return {"loss": loss.item()} | ||
|
|
||
| @staticmethod | ||
| def prepare_data(data_dict): | ||
| """Method that converts the data in dictionary into the form the model expects""" | ||
| image = data_dict["data"]["image"] | ||
|
|
||
| label = None | ||
| if "label" in data_dict["data"]: | ||
| label = data_dict["data"]["label"] | ||
| return (image, label) | ||
|
drewoldag marked this conversation as resolved.
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.