BERT--学习

一、Transformer

Transformer,是由编码块和解码块两部分组成,其中编码块由多个编码器组成,解码块同样也是由多个解码块组成。

编码器:自注意力 + 全连接

  • **多头自注意力:**Q、K、V
  • 公式:

解码块:自注意力 + 编码 - 解码自注意力 +全连接

  • 多头自注意力
  • **编码---解码自注意力:**Q上个解码器的输出

K、V最后一个编码器输出

二、BERT

  • **bert,**是由Transformer的多个编码器组成。
  • **Base :**12层编码器,每个编码器有12个多头,隐藏维度为768。
  • Large: 24层编码器,每个编码器16个头,隐层维度为1024
  • bert结构 :
python 复制代码
import torch
class MultiHeadAttention(nn.Module):
    def__init__(self,hidden_size,head_num):
        super().__init__()
        self.head_size = hidden_size / head_num
        self.query = nn.Linear(hidden_size, hidden_size)
        self.key = nn.Linear(hidden_size, hidden_size)
        self.value = nn.Linear(hidden_size, hidden_size)
    def transpose_dim(self,x):
        x_new_shape = x.size()[:-1]+(self.head_num, head_size)
        x = x.view(*x_new_shape)
        return x.permute(0,2,1,3)

    def forward(self,x,attention_mask):
        Quary_layer = self.query(x)
        Key_layer = self.key(x)
        Value_layer = self.value(x)

        '''
        B = Quary_layer.shape[0]
        N = Quary_layer.shape[1]
        multi_quary = Quary_layer.view(B,N,self.head_num,self.head_size).transpose(1,2)
        '''
        
        multi_quary =self.transpose_dim(Quary_layer)
        multi_key =self.transpose_dim(Key_layer)
        multi_value =self.transpose_dim(Value_layer)

        attention_scores = torch.matmul(multi_quary, multi_key.transpose(-1,-2))
        attention_scores = attention_scores / math.sqrt(self.head_size)

        attention_probs = nn.Softmax(dim=-1)(attention_scores) 
        context_layer = torch.matmul(attention_probs,values_layer)
        context_layer = context_layer.permute(0,2,1,3).contiguous()
        context_layer_shape =  context_layer.size()[:-2]+(self.hidden_size)
        context_layer = cotext_layer.view(*context_layer_shape 

        return context_layer
        
        
相关推荐
财经资讯数据_灵砚智能3 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年4月7日
人工智能·python·信息可视化·自然语言处理·ai编程
AI视觉网奇6 分钟前
生成GeoGebra
人工智能·深度学习
deephub9 分钟前
向量数据库对比:Pinecone、Chroma、Weaviate 的架构与适用场景
人工智能·python·大语言模型·embedding·向量检索
星马梦缘13 分钟前
强化学习实战5——BaseLine3使用自定义环境训练【输入状态向量】
pytorch·python·jupyter·强化学习·baseline3·gymnasium
SteveSenna14 分钟前
强化学习4.1:基于价值——Q-learning
人工智能·学习·算法·机器人
Linux猿15 分钟前
植物病害图像数据集 YOLO 目标检测 | 可下载
人工智能·yolo·目标检测·yolo数据集·yolo目标检测·yolo目标检测数据集·植物病害图像数据集
Cosolar18 分钟前
LangChain实战:基于Streamlit+ LangChain + Qwen 快速构建一个多会话AI聊天页面
人工智能·llm·agent
扬帆破浪24 分钟前
麒麟系统安装察元 WPS AI 文档助手:免费、开源、离线部署说明
人工智能·开源·wps
古希腊掌管代码的神THU25 分钟前
【清华代码熊】图解 Gemma 4 架构设计细节
人工智能·深度学习·自然语言处理
Purple Coder25 分钟前
7-RNN 循环网络层
人工智能·rnn·深度学习