|
| 1 | +# Copyright The PyTorch Lightning team. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import importlib |
| 15 | +from inspect import getmembers, isclass |
| 16 | +from typing import Any, Callable, Dict, List, Optional |
| 17 | + |
| 18 | +from pytorch_lightning.accelerators.accelerator import Accelerator |
| 19 | +from pytorch_lightning.utilities.exceptions import MisconfigurationException |
| 20 | +from pytorch_lightning.utilities.registry import _is_register_method_overridden |
| 21 | + |
| 22 | + |
| 23 | +class _AcceleratorRegistry(dict): |
| 24 | + """This class is a Registry that stores information about the Accelerators. |
| 25 | +
|
| 26 | + The Accelerators are mapped to strings. These strings are names that identify |
| 27 | + an accelerator, e.g., "gpu". It also returns Optional description and |
| 28 | + parameters to initialize the Accelerator, which were defined during the |
| 29 | + registration. |
| 30 | +
|
| 31 | + The motivation for having a AcceleratorRegistry is to make it convenient |
| 32 | + for the Users to try different accelerators by passing mapped aliases |
| 33 | + to the accelerator flag to the Trainer. |
| 34 | +
|
| 35 | + Example:: |
| 36 | +
|
| 37 | + @AcceleratorRegistry.register("sota", description="Custom sota accelerator", a=1, b=True) |
| 38 | + class SOTAAccelerator(Accelerator): |
| 39 | + def __init__(self, a, b): |
| 40 | + ... |
| 41 | +
|
| 42 | + or |
| 43 | +
|
| 44 | + AcceleratorRegistry.register("sota", SOTAAccelerator, description="Custom sota accelerator", a=1, b=True) |
| 45 | + """ |
| 46 | + |
| 47 | + def register( |
| 48 | + self, |
| 49 | + name: str, |
| 50 | + accelerator: Optional[Callable] = None, |
| 51 | + description: str = "", |
| 52 | + override: bool = False, |
| 53 | + **init_params: Any, |
| 54 | + ) -> Callable: |
| 55 | + """Registers a accelerator mapped to a name and with required metadata. |
| 56 | +
|
| 57 | + Args: |
| 58 | + name : the name that identifies a accelerator, e.g. "gpu" |
| 59 | + accelerator : accelerator class |
| 60 | + description : accelerator description |
| 61 | + override : overrides the registered accelerator, if True |
| 62 | + init_params: parameters to initialize the accelerator |
| 63 | + """ |
| 64 | + if not (name is None or isinstance(name, str)): |
| 65 | + raise TypeError(f"`name` must be a str, found {name}") |
| 66 | + |
| 67 | + if name in self and not override: |
| 68 | + raise MisconfigurationException(f"'{name}' is already present in the registry. HINT: Use `override=True`.") |
| 69 | + |
| 70 | + data: Dict[str, Any] = {} |
| 71 | + |
| 72 | + data["description"] = description |
| 73 | + data["init_params"] = init_params |
| 74 | + |
| 75 | + def do_register(name: str, accelerator: Callable) -> Callable: |
| 76 | + data["accelerator"] = accelerator |
| 77 | + data["accelerator_name"] = name |
| 78 | + self[name] = data |
| 79 | + return accelerator |
| 80 | + |
| 81 | + if accelerator is not None: |
| 82 | + return do_register(name, accelerator) |
| 83 | + |
| 84 | + return do_register |
| 85 | + |
| 86 | + def get(self, name: str, default: Optional[Any] = None) -> Any: |
| 87 | + """Calls the registered accelerator with the required parameters and returns the accelerator object. |
| 88 | +
|
| 89 | + Args: |
| 90 | + name (str): the name that identifies a accelerator, e.g. "gpu" |
| 91 | + """ |
| 92 | + if name in self: |
| 93 | + data = self[name] |
| 94 | + return data["accelerator"](**data["init_params"]) |
| 95 | + |
| 96 | + if default is not None: |
| 97 | + return default |
| 98 | + |
| 99 | + err_msg = "'{}' not found in registry. Available names: {}" |
| 100 | + available_names = self.available_accelerators() |
| 101 | + raise KeyError(err_msg.format(name, available_names)) |
| 102 | + |
| 103 | + def remove(self, name: str) -> None: |
| 104 | + """Removes the registered accelerator by name.""" |
| 105 | + self.pop(name) |
| 106 | + |
| 107 | + def available_accelerators(self) -> List[str]: |
| 108 | + """Returns a list of registered accelerators.""" |
| 109 | + return list(self.keys()) |
| 110 | + |
| 111 | + def __str__(self) -> str: |
| 112 | + return "Registered Accelerators: {}".format(", ".join(self.available_accelerators())) |
| 113 | + |
| 114 | + |
| 115 | +AcceleratorRegistry = _AcceleratorRegistry() |
| 116 | + |
| 117 | + |
| 118 | +def call_register_accelerators(base_module: str) -> None: |
| 119 | + module = importlib.import_module(base_module) |
| 120 | + for _, mod in getmembers(module, isclass): |
| 121 | + if issubclass(mod, Accelerator) and _is_register_method_overridden(mod, Accelerator, "register_accelerators"): |
| 122 | + mod.register_accelerators(AcceleratorRegistry) |
0 commit comments