diff options
| author | Kai Li (李凯) <tsinghua.kaili@gmail.com> | 2024-09-07 01:23:39 +0800 |
|---|---|---|
| committer | Kai Li (李凯) <tsinghua.kaili@gmail.com> | 2024-09-07 01:23:39 +0800 |
| commit | d72b12cf8b5d9b80acdbe8082f0451389afc6407 (patch) | |
| tree | 4f8f0554de3e4513fee7afa0cd2707338fe99011 /look2hear/utils/get_layer_from_string.py | |
| download | apollo-gfx803-d72b12cf8b5d9b80acdbe8082f0451389afc6407.tar.gz | |
First Commit
Diffstat (limited to 'look2hear/utils/get_layer_from_string.py')
| -rw-r--r-- | look2hear/utils/get_layer_from_string.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/look2hear/utils/get_layer_from_string.py b/look2hear/utils/get_layer_from_string.py new file mode 100644 index 0000000..3987a8d --- /dev/null +++ b/look2hear/utils/get_layer_from_string.py @@ -0,0 +1,43 @@ +import difflib + +import torch + + +def get_layer(l_name, library=torch.nn): + """Return layer object handler from library e.g. from torch.nn + + E.g. if l_name=="elu", returns torch.nn.ELU. + + Args: + l_name (string): Case insensitive name for layer in library (e.g. .'elu'). + library (module): Name of library/module where to search for object handler + with l_name e.g. "torch.nn". + + Returns: + layer_handler (object): handler for the requested layer e.g. (torch.nn.ELU) + + """ + + all_torch_layers = [x for x in dir(torch.nn)] + match = [x for x in all_torch_layers if l_name.lower() == x.lower()] + if len(match) == 0: + close_matches = difflib.get_close_matches( + l_name, [x.lower() for x in all_torch_layers] + ) + raise NotImplementedError( + "Layer with name {} not found in {}.\n Closest matches: {}".format( + l_name, str(library), close_matches + ) + ) + elif len(match) > 1: + close_matches = difflib.get_close_matches( + l_name, [x.lower() for x in all_torch_layers] + ) + raise NotImplementedError( + "Multiple matchs for layer with name {} not found in {}.\n " + "All matches: {}".format(l_name, str(library), close_matches) + ) + else: + # valid + layer_handler = getattr(library, match[0]) + return layer_handler
\ No newline at end of file |
