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
        
        
相关推荐
Keep_Trying_Go几秒前
基于Zero-Shot的目标计数算法详解(Open-world Text-specified Object Counting)
人工智能·pytorch·python·算法·多模态·目标统计
AKAMAI15 分钟前
Akamai 宣布收购功能即服务公司 Fermyon
人工智能·云计算
河南博为智能科技有限公司22 分钟前
高集成度国产八串口联网服务器:工业级多设备联网解决方案
大数据·运维·服务器·数据库·人工智能·物联网
光路科技1 小时前
人工智能时代,工业以太网正在“进化”成什么样?
人工智能
翔云 OCR API1 小时前
承兑汇票识别接口技术解析-开发者接口
开发语言·前端·数据库·人工智能·ocr
roman_日积跬步-终至千里1 小时前
【模式识别与机器学习(16)】聚类分析【1】:基础概念与常见方法
人工智能·机器学习
nvd111 小时前
一个简单的GitHub AI Agent 实现指南
人工智能·langchain
阿里云大数据AI技术2 小时前
【新模型速递】PAI-Model Gallery云上一键部署DeepSeek-V3.2模型
人工智能
阿恩.7702 小时前
2026年1月最新计算机、人工智能、经济管理国际会议:选对会议 = 论文成功率翻倍
人工智能·经验分享·笔记·计算机网络·金融·区块链
高-老师2 小时前
WRF模式与Python融合技术在多领域中的应用及精美绘图
人工智能·python·wrf模式