2019-12-04 12:32:47 +00:00
|
|
|
import inspect
|
2019-12-04 15:57:32 +00:00
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
2019-11-27 03:39:18 +00:00
|
|
|
from pytorch_lightning.core.lightning import LightningModule
|
2019-10-22 01:16:51 +00:00
|
|
|
|
|
|
|
|
2019-12-04 15:57:32 +00:00
|
|
|
class TrainerModelHooksMixin(ABC):
|
2019-10-22 01:16:51 +00:00
|
|
|
|
|
|
|
def is_function_implemented(self, f_name):
|
|
|
|
model = self.get_model()
|
|
|
|
f_op = getattr(model, f_name, None)
|
|
|
|
return callable(f_op)
|
|
|
|
|
2020-03-20 19:51:14 +00:00
|
|
|
def is_overriden(self, method_name: str, model: LightningModule = None) -> bool:
|
2020-02-25 03:23:25 +00:00
|
|
|
if model is None:
|
|
|
|
model = self.get_model()
|
2019-10-22 01:16:51 +00:00
|
|
|
super_object = LightningModule
|
|
|
|
|
2020-03-20 19:51:14 +00:00
|
|
|
if not hasattr(model, method_name):
|
|
|
|
# in case of calling deprecated method
|
|
|
|
return False
|
|
|
|
|
2020-04-03 12:40:02 +00:00
|
|
|
instance_attr = getattr(model, method_name)
|
2020-04-16 02:16:40 +00:00
|
|
|
if not instance_attr:
|
|
|
|
return False
|
2020-04-03 12:40:02 +00:00
|
|
|
super_attr = getattr(super_object, method_name)
|
|
|
|
|
|
|
|
# when code pointers are different, it was implemented
|
|
|
|
if hasattr(instance_attr, 'patch_loader_code'):
|
|
|
|
# cannot pickle __code__ so cannot verify if PatchDataloader
|
|
|
|
# exists which shows dataloader methods have been overwritten.
|
|
|
|
# so, we hack it by using the string representation
|
|
|
|
is_overriden = instance_attr.patch_loader_code != str(super_attr.__code__)
|
|
|
|
else:
|
|
|
|
is_overriden = instance_attr.__code__ is not super_attr.__code__
|
2019-10-22 01:16:51 +00:00
|
|
|
return is_overriden
|
2019-12-04 12:32:47 +00:00
|
|
|
|
|
|
|
def has_arg(self, f_name, arg_name):
|
|
|
|
model = self.get_model()
|
|
|
|
f_op = getattr(model, f_name, None)
|
|
|
|
return arg_name in inspect.signature(f_op).parameters
|
2019-12-04 15:57:32 +00:00
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def get_model(self):
|
2020-02-27 21:21:14 +00:00
|
|
|
"""Warning: this is just empty shell for code implemented in other class."""
|