autodl-projects/lib/xlayers/super_linear.py

178 lines
6.2 KiB
Python
Raw Normal View History

2021-03-18 11:32:26 +01:00
#####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.03 #
#####################################################
2021-03-18 13:15:50 +01:00
import torch
2021-03-17 11:06:29 +01:00
import torch.nn as nn
2021-03-19 08:17:49 +01:00
import torch.nn.functional as F
2021-03-17 11:06:29 +01:00
2021-03-18 11:32:26 +01:00
import math
2021-03-19 11:22:58 +01:00
from typing import Optional, Union, Callable
2021-03-18 11:32:26 +01:00
import spaces
2021-03-18 13:15:50 +01:00
from .super_module import SuperModule
from .super_module import SuperRunMode
2021-03-18 11:32:26 +01:00
IntSpaceType = Union[int, spaces.Integer, spaces.Categorical]
BoolSpaceType = Union[bool, spaces.Categorical]
2021-03-18 08:04:14 +01:00
2021-03-18 09:02:55 +01:00
class SuperLinear(SuperModule):
"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`"""
2021-03-18 08:04:14 +01:00
2021-03-18 11:32:26 +01:00
def __init__(
self,
in_features: IntSpaceType,
out_features: IntSpaceType,
bias: BoolSpaceType = True,
) -> None:
2021-03-18 09:02:55 +01:00
super(SuperLinear, self).__init__()
2021-03-18 11:32:26 +01:00
# the raw input args
self._in_features = in_features
self._out_features = out_features
self._bias = bias
2021-03-18 13:44:22 +01:00
# weights to be optimized
2021-03-18 13:15:50 +01:00
self._super_weight = torch.nn.Parameter(
2021-03-18 11:32:26 +01:00
torch.Tensor(self.out_features, self.in_features)
)
2021-03-18 13:15:50 +01:00
if self.bias:
self._super_bias = torch.nn.Parameter(torch.Tensor(self.out_features))
2021-03-18 08:04:14 +01:00
else:
2021-03-18 11:32:26 +01:00
self.register_parameter("_super_bias", None)
2021-03-18 08:04:14 +01:00
self.reset_parameters()
2021-03-18 11:32:26 +01:00
@property
def in_features(self):
return spaces.get_max(self._in_features)
@property
def out_features(self):
return spaces.get_max(self._out_features)
@property
def bias(self):
return spaces.has_categorical(self._bias, True)
2021-03-19 08:17:49 +01:00
@property
2021-03-18 13:15:50 +01:00
def abstract_search_space(self):
2021-03-18 13:44:22 +01:00
root_node = spaces.VirtualNode(id(self))
if not spaces.is_determined(self._in_features):
2021-03-19 11:22:58 +01:00
root_node.append(
"_in_features", self._in_features.abstract(reuse_last=True)
)
2021-03-18 13:44:22 +01:00
if not spaces.is_determined(self._out_features):
2021-03-19 11:22:58 +01:00
root_node.append(
"_out_features", self._out_features.abstract(reuse_last=True)
)
2021-03-18 13:44:22 +01:00
if not spaces.is_determined(self._bias):
2021-03-19 11:22:58 +01:00
root_node.append("_bias", self._bias.abstract(reuse_last=True))
2021-03-18 13:44:22 +01:00
return root_node
2021-03-18 13:15:50 +01:00
2021-03-18 08:04:14 +01:00
def reset_parameters(self) -> None:
2021-03-18 11:32:26 +01:00
nn.init.kaiming_uniform_(self._super_weight, a=math.sqrt(5))
if self.bias:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self._super_weight)
2021-03-18 08:04:14 +01:00
bound = 1 / math.sqrt(fan_in)
2021-03-18 11:32:26 +01:00
nn.init.uniform_(self._super_bias, -bound, bound)
2021-03-18 08:04:14 +01:00
2021-03-19 08:17:49 +01:00
def forward_candidate(self, input: torch.Tensor) -> torch.Tensor:
# check inputs ->
if not spaces.is_determined(self._in_features):
expected_input_dim = self.abstract_child["_in_features"].value
else:
expected_input_dim = spaces.get_determined_value(self._in_features)
if input.size(-1) != expected_input_dim:
raise ValueError(
"Expect the input dim of {:} instead of {:}".format(
expected_input_dim, input.size(-1)
)
)
# create the weight matrix
if not spaces.is_determined(self._out_features):
out_dim = self.abstract_child["_out_features"].value
else:
out_dim = spaces.get_determined_value(self._out_features)
candidate_weight = self._super_weight[:out_dim, :expected_input_dim]
# create the bias matrix
if not spaces.is_determined(self._bias):
if self.abstract_child["_bias"].value:
candidate_bias = self._super_bias[:out_dim]
else:
candidate_bias = None
else:
if spaces.get_determined_value(self._bias):
candidate_bias = self._super_bias[:out_dim]
else:
candidate_bias = None
return F.linear(input, candidate_weight, candidate_bias)
2021-03-18 13:15:50 +01:00
def forward_raw(self, input: torch.Tensor) -> torch.Tensor:
2021-03-18 11:32:26 +01:00
return F.linear(input, self._super_weight, self._super_bias)
2021-03-18 08:04:14 +01:00
def extra_repr(self) -> str:
2021-03-18 09:02:55 +01:00
return "in_features={:}, out_features={:}, bias={:}".format(
2021-03-18 11:32:26 +01:00
self.in_features, self.out_features, self.bias
2021-03-18 08:04:14 +01:00
)
2021-03-18 09:02:55 +01:00
2021-03-19 08:17:49 +01:00
class SuperMLP(SuperModule):
"""An MLP layer: FC -> Activation -> Drop -> FC -> Drop."""
2021-03-18 09:02:55 +01:00
def __init__(
self,
2021-03-19 11:22:58 +01:00
in_features: IntSpaceType,
hidden_features: IntSpaceType,
out_features: IntSpaceType,
act_layer: Callable[[], nn.Module] = nn.GELU,
2021-03-18 09:02:55 +01:00
drop: Optional[float] = None,
):
2021-03-19 08:17:49 +01:00
super(SuperMLP, self).__init__()
2021-03-19 11:22:58 +01:00
self._in_features = in_features
self._hidden_features = hidden_features
self._out_features = out_features
self._drop_rate = drop
self.fc1 = SuperLinear(in_features, hidden_features)
2021-03-18 09:02:55 +01:00
self.act = act_layer()
2021-03-19 11:22:58 +01:00
self.fc2 = SuperLinear(hidden_features, out_features)
2021-03-19 08:17:49 +01:00
self.drop = nn.Dropout(drop or 0.0)
2021-03-18 09:02:55 +01:00
2021-03-19 11:22:58 +01:00
@property
def abstract_search_space(self):
root_node = spaces.VirtualNode(id(self))
space_fc1 = self.fc1.abstract_search_space
space_fc2 = self.fc2.abstract_search_space
if not spaces.is_determined(space_fc1):
root_node.append("fc1", space_fc1)
if not spaces.is_determined(space_fc2):
root_node.append("fc2", space_fc2)
return root_node
2021-03-19 16:57:23 +01:00
def apply_candidate(self, abstract_child: spaces.VirtualNode):
super(SuperMLP, self).apply_candidate(abstract_child)
if "fc1" in abstract_child:
self.fc1.apply_candidate(abstract_child["fc1"])
if "fc2" in abstract_child:
self.fc2.apply_candidate(abstract_child["fc2"])
2021-03-19 11:22:58 +01:00
def forward_candidate(self, input: torch.Tensor) -> torch.Tensor:
2021-03-19 16:57:23 +01:00
return self._unified_forward(input)
2021-03-19 11:22:58 +01:00
def forward_raw(self, input: torch.Tensor) -> torch.Tensor:
2021-03-19 16:57:23 +01:00
return self._unified_forward(input)
2021-03-19 11:22:58 +01:00
def _unified_forward(self, x):
2021-03-18 09:02:55 +01:00
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
2021-03-19 11:22:58 +01:00
def extra_repr(self) -> str:
return "in_features={:}, hidden_features={:}, out_features={:}, drop={:}, fc1 -> act -> drop -> fc2 -> drop,".format(
self._in_features,
self._hidden_features,
self._out_features,
self._drop_rate,
)