autodl-projects/lib/xlayers/super_module.py

72 lines
2.1 KiB
Python
Raw Normal View History

2021-03-18 09:02:55 +01:00
#####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.01 #
#####################################################
import abc
2021-03-17 11:06:29 +01:00
import torch.nn as nn
2021-03-18 11:32:26 +01:00
from enum import Enum
2021-03-19 08:17:49 +01:00
import spaces
2021-03-18 11:32:26 +01:00
class SuperRunMode(Enum):
"""This class defines the enumerations for Super Model Running Mode."""
FullModel = "fullmodel"
2021-03-19 08:17:49 +01:00
Candidate = "candidate"
2021-03-18 11:32:26 +01:00
Default = "fullmodel"
2021-03-17 11:06:29 +01:00
2021-03-18 13:15:50 +01:00
class SuperModule(abc.ABC, nn.Module):
2021-03-18 09:02:55 +01:00
"""This class equips the nn.Module class with the ability to apply AutoDL."""
def __init__(self):
super(SuperModule, self).__init__()
2021-03-18 13:15:50 +01:00
self._super_run_type = SuperRunMode.Default
2021-03-19 08:17:49 +01:00
self._abstract_child = None
2021-03-18 09:02:55 +01:00
2021-03-19 08:17:49 +01:00
def set_super_run_type(self, super_run_type):
def _reset_super_run(m):
if isinstance(m, SuperModule):
m._super_run_type = super_run_type
self.apply(_reset_super_run)
def apply_candiate(self, abstract_child):
if not isinstance(abstract_child, spaces.VirtualNode):
raise ValueError(
"Invalid abstract child program: {:}".format(abstract_child)
)
self._abstract_child = abstract_child
@property
2021-03-18 09:02:55 +01:00
def abstract_search_space(self):
raise NotImplementedError
2021-03-18 11:32:26 +01:00
@property
def super_run_type(self):
return self._super_run_type
2021-03-19 08:17:49 +01:00
@property
def abstract_child(self):
return self._abstract_child
2021-03-18 11:32:26 +01:00
@abc.abstractmethod
def forward_raw(self, *inputs):
2021-03-19 08:17:49 +01:00
"""Use the largest candidate for forward. Similar to the original PyTorch model."""
raise NotImplementedError
@abc.abstractmethod
def forward_candidate(self, *inputs):
2021-03-18 11:32:26 +01:00
raise NotImplementedError
def forward(self, *inputs):
if self.super_run_type == SuperRunMode.FullModel:
return self.forward_raw(*inputs)
2021-03-19 08:17:49 +01:00
elif self.super_run_type == SuperRunMode.Candidate:
return self.forward_candidate(*inputs)
2021-03-18 11:32:26 +01:00
else:
raise ModeError(
"Unknown Super Model Run Mode: {:}".format(self.super_run_type)
)