在读一篇关于模型蒸馏的知乎文章《文本 × 分类:简单网络可以替代BERT》的时候我有所启发,文中说蒸馏到了一个小模型中,小模型的开头是BERT的Embedding层直接拿过来的,并且删除了拖慢速度的 nn.LayerNorm 和 position_embedding 等。
所以到底有没有必要删除源代码中的这些部分呢?
原始BertEmbeddings
首先看看 🤗 的源码,其中 config 下的一些参数放在这里,当然也可以看源文档 BertConfig :
- vocab_size:21128,对于中文BERT来说是21128个token
- hidden_size:768
- pad_token_id:0
- max_position_embeddings:512,也就是最大序列长度
- type_vocab_size:2,也就是上下句的标记种类
- layer_norm_eps:层归一化的
参数
hidden_dropout_prob:0.1 的 dropout 率
class BertEmbeddings(nn.Module):"""Construct the embeddings from word, position and token_type embeddings."""def __init__(self, config):super().__init__()self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load# any TensorFlow checkpoint fileself.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)self.dropout = nn.Dropout(config.hidden_dropout_prob)# position_ids (1, len position emb) is contiguous in memory and exported when serializedself.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):if input_ids is not None:input_shape = input_ids.size()else:input_shape = inputs_embeds.size()[:-1]seq_length = input_shape[1]if position_ids is None:position_ids = self.position_ids[:, :seq_length]if token_type_ids is None:token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)if inputs_embeds is None:inputs_embeds = self.word_embeddings(input_ids)position_embeddings = self.position_embeddings(position_ids)token_type_embeddings = self.token_type_embeddings(token_type_ids)embeddings = inputs_embeds + position_embeddings + token_type_embeddingsembeddings = self.LayerNorm(embeddings)embeddings = self.dropout(embeddings)return embeddings
简化BertEmbeddings
去掉position和token_type
在通常任务中,我们是不需要
position_ids和token_type_ids这两个输入参数的,因此可以直接干掉。
经过化简以后的代码如下: ```python from torch import Tensor from torch import nn
class BertEmbeddings(nn.Module): “”” Construct the embeddings from word, position and token_type embeddings. 魔改一下,只保留word_embeddings和layer_norm “””
def __init__(self):super().__init__()self.word_embeddings = nn.Embedding(21128, 768, padding_idx=0)# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load# any TensorFlow checkpoint fileself.LayerNorm = nn.LayerNorm(768, eps=1e-12)self.dropout = nn.Dropout(0.1)def forward(self, input_ids: Tensor = None) -> Tensor:"""前向传播过程。参考输入如下:>>> test_seq = [ 101, 704, 1290, 1957, 2094, 2110, 7368, 8038, 3315, 4906, 2231,3613, 788, 122, 683, 689, 2875, 4511, 4495, 102, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0]>>> test_seq_inputs = torch.tensor(test_seq).clone().detach().unsqueeze(0)>>> print(test_seq_inputs)tensor([[ 101, 704, 1290, 1957, 2094, 2110, 7368, 8038, 3315, 4906, 2231, 3613,788, 122, 683, 689, 2875, 4511, 4495, 102, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0]])>>> bert_embedding = BertEmbeddings()>>> res = bert_embedding(input_ids=test_seq_inputs)>>> print(res)torch.Size([1, 32])tensor([[[ 0.8166, -1.1873, 1.2912, ..., 1.6106, -0.4729, -1.5941],[-0.2341, -0.1526, 0.3441, ..., -1.6328, 1.7635, 0.4524],[ 1.2200, 1.1668, -0.1776, ..., 0.5772, -0.5337, -1.8260],...,[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000]]],grad_fn=<MulBackward0>)>>> print(res.size())torch.Size([1, 32, 768])```Args:input_ids (Tensor, optional): 句子的 token_ids. Defaults to None.Raises:ValueError: 如果输入不是ids则报错。注意这里修改为不接受 embedding 输入Returns:Tensor: 返回 embedding 句子结果"""if input_ids is not None:input_shape = input_ids.size()else:raise ValueError("检查input_ids是否正确,不接受传现成的embedding")# print(input_shape)inputs_embeds = self.word_embeddings(input_ids)embeddings = inputs_embedsembeddings = self.LayerNorm(embeddings)embeddings = self.dropout(embeddings)return embeddings
<a name="aS5Ox"></a>## 去掉LayerNorm```pythonfrom torch import Tensorfrom torch import nnclass BertEmbeddingsWithoutLayerNorm(nn.Module):"""Construct the embeddings from word, position and token_type embeddings.魔改一下,只保留word_embeddings,连LayerNorm也删掉"""def __init__(self):super().__init__()self.word_embeddings = nn.Embedding(21128, 768, padding_idx=0)self.dropout = nn.Dropout(0.1)def forward(self, input_ids: Tensor = None) -> Tensor:"""前向传播过程。参考输入如下:>>> test_seq = [ 101, 704, 1290, 1957, 2094, 2110, 7368, 8038, 3315, 4906, 2231,3613, 788, 122, 683, 689, 2875, 4511, 4495, 102, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0]>>> test_seq_inputs = torch.tensor(test_seq).clone().detach().unsqueeze(0)>>> print(test_seq_inputs)tensor([[ 101, 704, 1290, 1957, 2094, 2110, 7368, 8038, 3315, 4906, 2231, 3613,788, 122, 683, 689, 2875, 4511, 4495, 102, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0]])>>> bert_embedding_no_layernorm = BertEmbeddingsWithoutLayerNorm()>>> res2 = bert_embedding_no_layernorm(input_ids=test_seq_inputs)>>> print(res2)torch.Size([1, 32])tensor([[[ 0.8470, -0.5573, -1.4137, ..., 0.1017, 2.5658, -1.5135],[ 1.3631, 0.1439, -1.0117, ..., 0.5226, -0.7416, -0.5690],[ 0.9139, 0.5850, -0.4989, ..., 1.9164, -0.1690, 0.1694],...,[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000]]],grad_fn=<MulBackward0>)>>> print(res2.size())torch.Size([1, 32, 768])
Args:input_ids (Tensor, optional): 句子的 token_ids. Defaults to None.Raises:ValueError: 如果输入不是ids则报错。注意这里修改为不接受 embedding 输入Returns:Tensor: 返回 embedding 句子结果"""if input_ids is not None:input_shape = input_ids.size()else:raise ValueError("检查input_ids是否正确,不接受传现成的embedding")# print(input_shape)inputs_embeds = self.word_embeddings(input_ids)embeddings = inputs_embedsembeddings = self.dropout(embeddings)return embeddings
``
在上述代码中,我进一步删掉了nn.LayerNorm` 。
注意,这里的输出维度是一样的。所以理论上要不要LayerNorm,至少程序上是不会报错的。
LayerNorm的作用
问题是,去掉了nn.LayerNorm 可以加速,但是效果会不会有所降低?
首先看看 nn.LayerNorm 的作用。在 NIPS19 的一篇论文《Understanding and Improving Layer Normalization》中有提到:
其中: 是 LayerNorm 的输出
是点乘操作
和
是输入的均值和标准差
偏差(bias)和
增益(gain)是与
维度一致的参数。
传统研究认为,正向归一化(forward normalization)是 LayerNorm 的决定性因素,而这篇论文的作者认为,正向归一化与有效性无关,而均值和方差的导数在LayerNorm中起重要作用。
Transformer结构中LayerNorm是一个重要的部分,但是在这里的Embedding层并不是不可替代的,所以我认为在这里采用更简单的、去掉了nn.LayerNorm 的 BertEmbeddingsWithoutLayerNorm 是完全可以的。
当然实际上还需要进一步实验检验。
