autodl-projects/xautodl/xlayers/super_transformer.py

128 lines
4.8 KiB
Python
Raw Permalink Normal View History

2021-03-20 15:28:23 +01:00
#####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.03 #
#####################################################
import math
from typing import Optional, Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
2021-05-19 07:00:33 +02:00
from xautodl import spaces
2021-03-20 15:28:23 +01:00
from .super_module import IntSpaceType
from .super_module import BoolSpaceType
2021-03-23 12:13:51 +01:00
from .super_module import LayerOrder
2021-03-20 15:28:23 +01:00
from .super_module import SuperModule
from .super_linear import SuperMLPv2
from .super_norm import SuperLayerNorm1D
2021-05-22 10:41:54 +02:00
from .super_attention import SuperSelfAttention
2021-03-20 15:28:23 +01:00
class SuperTransformerEncoderLayer(SuperModule):
"""TransformerEncoderLayer is made up of self-attn and feedforward network.
This is a super model for TransformerEncoderLayer that can support search for the transformer encoder layer.
Reference:
- Paper: Attention Is All You Need, NeurIPS 2017
- PyTorch Implementation: https://pytorch.org/docs/stable/_modules/torch/nn/modules/transformer.html#TransformerEncoderLayer
Details:
2021-03-23 12:13:51 +01:00
the original post-norm version: MHA -> residual -> norm -> MLP -> residual -> norm
the pre-norm version: norm -> MHA -> residual -> norm -> MLP -> residual
2021-03-20 15:28:23 +01:00
"""
def __init__(
self,
2021-03-24 13:33:52 +01:00
d_model: IntSpaceType,
2021-03-20 15:28:23 +01:00
num_heads: IntSpaceType,
qkv_bias: BoolSpaceType = False,
mlp_hidden_multiplier: IntSpaceType = 4,
2021-06-09 14:39:35 +02:00
dropout: Optional[float] = None,
att_dropout: Optional[float] = None,
2021-05-13 15:33:34 +02:00
norm_affine: bool = True,
2021-03-20 15:28:23 +01:00
act_layer: Callable[[], nn.Module] = nn.GELU,
2021-03-23 12:13:51 +01:00
order: LayerOrder = LayerOrder.PreNorm,
2021-05-22 17:04:24 +02:00
use_mask: bool = False,
2021-03-20 15:28:23 +01:00
):
super(SuperTransformerEncoderLayer, self).__init__()
2021-05-22 10:41:54 +02:00
mha = SuperSelfAttention(
2021-03-24 13:33:52 +01:00
d_model,
d_model,
2021-03-20 15:28:23 +01:00
num_heads=num_heads,
qkv_bias=qkv_bias,
2021-06-09 14:39:35 +02:00
attn_drop=att_dropout,
proj_drop=None,
2021-05-22 17:04:24 +02:00
use_mask=use_mask,
2021-03-20 15:28:23 +01:00
)
2021-03-23 12:13:51 +01:00
mlp = SuperMLPv2(
2021-03-24 13:33:52 +01:00
d_model,
2021-03-20 15:28:23 +01:00
hidden_multiplier=mlp_hidden_multiplier,
2021-03-24 13:33:52 +01:00
out_features=d_model,
2021-03-20 15:28:23 +01:00
act_layer=act_layer,
2021-06-09 14:39:35 +02:00
drop=dropout,
2021-03-20 15:28:23 +01:00
)
2021-03-23 12:13:51 +01:00
if order is LayerOrder.PreNorm:
2021-05-13 15:33:34 +02:00
self.norm1 = SuperLayerNorm1D(d_model, elementwise_affine=norm_affine)
2021-03-23 12:13:51 +01:00
self.mha = mha
2021-06-09 14:39:35 +02:00
self.drop = nn.Dropout(dropout or 0.0)
2021-05-13 15:33:34 +02:00
self.norm2 = SuperLayerNorm1D(d_model, elementwise_affine=norm_affine)
2021-03-23 12:13:51 +01:00
self.mlp = mlp
2021-03-24 13:33:52 +01:00
elif order is LayerOrder.PostNorm:
2021-03-23 12:13:51 +01:00
self.mha = mha
2021-06-09 14:39:35 +02:00
self.drop1 = nn.Dropout(dropout or 0.0)
2021-05-13 15:33:34 +02:00
self.norm1 = SuperLayerNorm1D(d_model, elementwise_affine=norm_affine)
2021-03-23 12:13:51 +01:00
self.mlp = mlp
2021-06-09 14:39:35 +02:00
self.drop2 = nn.Dropout(dropout or 0.0)
2021-05-13 15:33:34 +02:00
self.norm2 = SuperLayerNorm1D(d_model, elementwise_affine=norm_affine)
2021-03-23 12:13:51 +01:00
else:
raise ValueError("Unknown order: {:}".format(order))
2021-03-24 13:33:52 +01:00
self._order = order
2021-03-20 15:28:23 +01:00
@property
def abstract_search_space(self):
root_node = spaces.VirtualNode(id(self))
xdict = dict(
mha=self.mha.abstract_search_space,
norm1=self.norm1.abstract_search_space,
mlp=self.mlp.abstract_search_space,
norm2=self.norm2.abstract_search_space,
)
for key, space in xdict.items():
if not spaces.is_determined(space):
root_node.append(key, space)
return root_node
def apply_candidate(self, abstract_child: spaces.VirtualNode):
super(SuperTransformerEncoderLayer, self).apply_candidate(abstract_child)
valid_keys = ["mha", "norm1", "mlp", "norm2"]
for key in valid_keys:
if key in abstract_child:
getattr(self, key).apply_candidate(abstract_child[key])
2021-06-09 14:39:35 +02:00
def forward_candidate(self, inputs: torch.Tensor) -> torch.Tensor:
return self.forward_raw(inputs)
2021-03-20 15:28:23 +01:00
2021-06-09 14:39:35 +02:00
def forward_raw(self, inputs: torch.Tensor) -> torch.Tensor:
2021-03-24 13:33:52 +01:00
if self._order is LayerOrder.PreNorm:
2021-06-09 14:39:35 +02:00
# https://github.com/google-research/vision_transformer/blob/master/vit_jax/models.py#L135
x = self.norm1(inputs)
x = self.mha(x)
x = self.drop(x)
x = x + inputs
# feed-forward layer -- MLP
y = self.norm2(x)
outs = x + self.mlp(y)
2021-03-24 13:33:52 +01:00
elif self._order is LayerOrder.PostNorm:
2021-06-09 14:39:35 +02:00
# https://pytorch.org/docs/stable/_modules/torch/nn/modules/transformer.html#TransformerEncoder
2021-03-23 12:13:51 +01:00
# multi-head attention
2021-06-09 14:39:35 +02:00
x = self.mha(inputs)
x = inputs + self.drop1(x)
2021-03-23 12:13:51 +01:00
x = self.norm1(x)
2021-06-09 14:39:35 +02:00
# feed-forward layer -- MLP
y = self.mlp(x)
y = x + self.drop2(y)
outs = self.norm2(y)
2021-03-23 12:13:51 +01:00
else:
2021-03-24 13:33:52 +01:00
raise ValueError("Unknown order: {:}".format(self._order))
2021-06-09 14:39:35 +02:00
return outs