-
Notifications
You must be signed in to change notification settings - Fork 3.4k
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
Add Training Type Plugins Registry #6982
Merged
kaushikb11
merged 27 commits into
Lightning-AI:master
from
kaushikb11:feat/plugins_registry
Apr 16, 2021
Merged
Changes from 24 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
f0aed43
Add Plugins Registry
kaushikb11 38004f0
Update get
kaushikb11 25ca516
update
kaushikb11 62a3c9f
Add training type registry
kaushikb11 a05a0f9
Example
kaushikb11 4e9cec8
Update register plugin
kaushikb11 e85de51
Update registry
kaushikb11 40842af
add description
kaushikb11 7ce6f86
add docs
kaushikb11 8fb0a16
Update acc connector
kaushikb11 33e5329
Update acc connector
kaushikb11 73718d8
add register plugin method
kaushikb11 b691237
add call register plugins
kaushikb11 870bee5
Update
kaushikb11 388e487
fix code format
kaushikb11 adea1b4
add tests
kaushikb11 410fc61
Update tests
kaushikb11 7af1b65
update
kaushikb11 80bc1c5
update
kaushikb11 6ad2c62
update tests
kaushikb11 a201087
fix flake8
kaushikb11 ef080a8
Update pytorch_lightning/plugins/training_type/deepspeed.py
tchaton 57c609f
Update pytorch_lightning/plugins/training_type/deepspeed.py
kaushikb11 844d2a9
Update pytorch_lightning/plugins/training_type/deepspeed.py
kaushikb11 89b1e39
Apply code suggestions
kaushikb11 47a6d70
fix typo
kaushikb11 a6001b9
Merge branch 'feat/plugins_registry' of https://github.com/kaushikb11…
kaushikb11 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 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 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,146 @@ | ||
# Copyright The PyTorch Lightning team. | ||
# | ||
# 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 importlib | ||
import os | ||
from collections import UserDict | ||
from inspect import getmembers, isclass | ||
from pathlib import Path | ||
from typing import Any, Callable, List, Optional | ||
|
||
from pytorch_lightning.plugins.training_type.training_type_plugin import TrainingTypePlugin | ||
from pytorch_lightning.utilities.exceptions import MisconfigurationException | ||
|
||
|
||
class _TrainingTypePluginsRegistry(UserDict): | ||
""" | ||
This class is a Registry that stores information about the Training Type Plugins. | ||
|
||
The Plugins are mapped to strings. These strings are names that idenitify | ||
a plugin, eg., "deepspeed". It also returns Optional description and | ||
kaushikb11 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
parameters to initialize the Plugin, which were defined durng the | ||
registeration. | ||
kaushikb11 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
The motivation for having a TrainingTypePluginRegistry is to make it convenient | ||
for the Users to try different Plugins by passing just strings | ||
to the plugins flag to the Trainer. | ||
|
||
Example:: | ||
|
||
@TrainingTypePluginsRegistry.register("lightning", description="Super fast", a=1, b=True) | ||
class LightningPlugin: | ||
def __init__(self, a, b): | ||
... | ||
|
||
or | ||
|
||
TrainingTypePluginsRegistry.register("lightning", LightningPlugin, description="Super fast", a=1, b=True) | ||
|
||
""" | ||
|
||
def register( | ||
self, | ||
name: str, | ||
plugin: Optional[Callable] = None, | ||
description: Optional[str] = None, | ||
override: bool = False, | ||
**init_params: Any, | ||
) -> Callable: | ||
""" | ||
Registers a plugin mapped to a name and with required metadata. | ||
|
||
Args: | ||
name (str): the name that identifies a plugin, e.g. "deepspeed_stage_3" | ||
plugin (callable): plugin class | ||
description (str): plugin description | ||
override (bool): overrides the registered plugin, if True | ||
init_params: parameters to initialize the plugin | ||
kaushikb11 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
if not (name is None or isinstance(name, str)): | ||
raise TypeError(f'`name` must be a str, found {name}') | ||
|
||
if name in self and not override: | ||
raise MisconfigurationException( | ||
f"'{name}' is already present in the registry." | ||
" HINT: Use `override=True`." | ||
) | ||
|
||
data = {} | ||
data["description"] = description if description is not None else "" | ||
|
||
data["init_params"] = init_params | ||
|
||
def do_register(plugin: Callable) -> Callable: | ||
data["plugin"] = plugin | ||
self[name] = data | ||
return plugin | ||
|
||
if plugin is not None: | ||
return do_register(plugin) | ||
|
||
return do_register | ||
|
||
def get(self, name: str) -> Any: | ||
""" | ||
Calls the registered plugin with the required parameters | ||
and returns the plugin object | ||
|
||
Args: | ||
name (str): the name that identifies a plugin, e.g. "deepspeed_stage_3" | ||
""" | ||
if name in self: | ||
data = self[name] | ||
return data["plugin"](**data["init_params"]) | ||
|
||
err_msg = "'{}' not found in registry. Available names: {}" | ||
available_names = ", ".join(sorted(self.keys())) or "none" | ||
raise KeyError(err_msg.format(name, available_names)) | ||
|
||
def remove(self, name: str) -> None: | ||
"""Removes the registered plugin by name""" | ||
self.pop(name) | ||
|
||
def available_plugins(self) -> List: | ||
"""Returns a list of registered plugins""" | ||
return list(self.keys()) | ||
|
||
def __str__(self) -> str: | ||
return "Registered Plugins: {}".format(", ".join(self.keys())) | ||
|
||
|
||
TrainingTypePluginsRegistry = _TrainingTypePluginsRegistry() | ||
|
||
|
||
def is_register_plugins_overriden(plugin: Callable) -> bool: | ||
kaushikb11 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
method_name = "register_plugins" | ||
plugin_attr = getattr(plugin, method_name) | ||
super_attr = getattr(TrainingTypePlugin, method_name) | ||
|
||
if hasattr(plugin_attr, 'patch_loader_code'): | ||
is_overridden = plugin_attr.patch_loader_code != str(super_attr.__code__) | ||
else: | ||
is_overridden = plugin_attr.__code__ is not super_attr.__code__ | ||
return is_overridden | ||
|
||
|
||
def call_training_type_register_plugins(root: Path, base_module: str) -> None: | ||
# Ref: https://github.com/facebookresearch/ClassyVision/blob/master/classy_vision/generic/registry_utils.py#L14 | ||
directory = "training_type" | ||
for file in os.listdir(root / directory): | ||
if file.endswith(".py") and not file.startswith("_"): | ||
module = file[:file.find(".py")] | ||
module = importlib.import_module(".".join([base_module, module])) | ||
for _, mod in getmembers(module, isclass): | ||
if issubclass(mod, TrainingTypePlugin) and is_register_plugins_overriden(mod): | ||
kaushikb11 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
mod.register_plugins(TrainingTypePluginsRegistry) | ||
break |
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
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
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
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,83 @@ | ||
# Copyright The PyTorch Lightning team. | ||
# | ||
# 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 pytest | ||
|
||
from pytorch_lightning import Trainer | ||
from pytorch_lightning.plugins import TrainingTypePluginsRegistry | ||
kaushikb11 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from pytorch_lightning.plugins.training_type.deepspeed import DeepSpeedPlugin | ||
from tests.helpers.runif import RunIf | ||
|
||
|
||
def test_training_type_plugins_registry_with_new_plugin(): | ||
|
||
class TestPlugin: | ||
|
||
def __init__(self, param1, param2): | ||
self.param1 = param1 | ||
self.param2 = param2 | ||
|
||
plugin_name = "test_plugin" | ||
plugin_description = "Test Plugin" | ||
|
||
TrainingTypePluginsRegistry.register( | ||
plugin_name, TestPlugin, description=plugin_description, param1="abc", param2=123 | ||
) | ||
|
||
assert plugin_name in TrainingTypePluginsRegistry | ||
assert TrainingTypePluginsRegistry[plugin_name]["description"] == plugin_description | ||
assert TrainingTypePluginsRegistry[plugin_name]["init_params"] == {"param1": "abc", "param2": 123} | ||
assert isinstance(TrainingTypePluginsRegistry.get(plugin_name), TestPlugin) | ||
|
||
TrainingTypePluginsRegistry.remove(plugin_name) | ||
assert plugin_name not in TrainingTypePluginsRegistry | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"plugin_name, init_params", | ||
[ | ||
("deepspeed", {}), | ||
("deepspeed_stage_2", { | ||
"stage": 2 | ||
}), | ||
("deepspeed_stage_2_offload", { | ||
"stage": 2, | ||
"cpu_offload": True | ||
}), | ||
("deepspeed_stage_3", { | ||
"stage": 3 | ||
}), | ||
("deepspeed_stage_3_offload", { | ||
"stage": 3, | ||
"cpu_offload": True | ||
}), | ||
], | ||
) | ||
def test_training_type_plugins_registry_with_deepspeed_plugins(plugin_name, init_params): | ||
|
||
assert plugin_name in TrainingTypePluginsRegistry | ||
assert TrainingTypePluginsRegistry[plugin_name]["init_params"] == init_params | ||
assert TrainingTypePluginsRegistry[plugin_name]["plugin"] == DeepSpeedPlugin | ||
|
||
|
||
@RunIf(deepspeed=True) | ||
@pytest.mark.parametrize("plugin", ["deepspeed", "deepspeed_stage_2_offload", "deepspeed_stage_3"]) | ||
def test_training_type_plugins_registry_with_trainer(tmpdir, plugin): | ||
|
||
trainer = Trainer( | ||
default_root_dir=tmpdir, | ||
plugins=plugin, | ||
precision=16, | ||
) | ||
|
||
assert isinstance(trainer.training_type_plugin, DeepSpeedPlugin) |
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.
should we maybe make this a general registry and reuse this with flash? We also have a registry in flash and duplicating this does not make sense...
I think you only have to change the naming of the fields...
cc @tchaton
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.
I did think of a generic
LightningRegistry
that could be used for different types. But for now, there has only been a need forTrainingTypePlugins
, we could change it down the road as well, as_TrainingTypePluginsRegistry
is internal.