-
Notifications
You must be signed in to change notification settings - Fork 7
/
module_init_typing.py
52 lines (36 loc) · 1.22 KB
/
module_init_typing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
https://github.com/rwth-i6/i6_models/pull/21#discussion_r1242054557
"""
from __future__ import annotations
from typing import TypeVar, Generic, Type
from torch import nn
from dataclasses import dataclass
@dataclass
class ModelConfiguration:
pass
ConfigType = TypeVar("ConfigType", bound=ModelConfiguration)
ModuleType = TypeVar("ModuleType", bound=nn.Module)
@dataclass
class ModuleFactoryV1(Generic[ConfigType, ModuleType]):
"""
Dataclass for a combination of a Subassembly/Part and the corresponding configuration.
Also provides a function to construct the corresponding object through this dataclass
"""
module_class: Type[ModuleType]
cfg: ConfigType
def __call__(self) -> ModuleType:
"""Constructs an instance of the given module class"""
return self.module_class(self.cfg)
@dataclass
class MyModuleConfiguration(ModelConfiguration):
pass
class MyModule(nn.Module):
def __init__(self, cfg: MyModuleConfiguration):
super().__init__()
self.cfg = cfg
def forward(self, x):
return x
def test():
mod_factory = ModuleFactoryV1(MyModule, MyModuleConfiguration())
mod = mod_factory()
assert isinstance(mod, mod_factory.module_class)