Mindspore 公开课 - BERT

这篇具有很好参考价值的文章主要介绍了Mindspore 公开课 - BERT。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

BERT

BERT模型本质上是结合了 ELMo 模型与 GPT 模型的优势。

  • 相比于ELMo,BERT仅需改动最后的输出层,而非模型架构,便可以在下游任务中达到很好的效果;
  • 相比于GPT,BERT在处理词元表示时考虑到了双向上下文的信息;

BERT 结构

BERT(Bidirectional Encoder Representation from Transformers)是一个仅有 Encoder 的Transformer。

我们调用 BertModel 来搭建BERT模型,并通过 BertConfig 配置模型相关参数。

from pretrain.src.bert import BertModel
from pretrain.src.config import BertConfig

BERT 输入

Transformer:Encoder接受源句子(source sentence),Decoder接受目标句子(target sentence);

  • BERT:
    • 针对句子对相关任务,将两个句子合并为一个句子对输入到Encoder中,<cls> + 第一个句子 + <sep> + 第二个句子 + <sep>;
    • 针对单个文本相关任务,<cls> + 句子 + <sep>。

Mindspore 公开课 - BERT,bert,人工智能,深度学习

BERT Embedding

BERT Embedding与Transformer中的Embedding操作类似,包含词嵌入(word embedding)与位置嵌入(positional embedding)。

但与Transformer不同的是,BERT使用了可学习的位置信息,并额外增加了表示区分不同句子的段嵌入(segment embedding)。
Mindspore 公开课 - BERT,bert,人工智能,深度学习

import mindspore
from mindspore import nn
import mindspore.common.dtype as mstype
from mindspore.common.initializer import initializer, TruncatedNormal

class BertEmbeddings(nn.Cell):
    """
    Embeddings for BERT, include word, position and token_type
    """
    def __init__(self, config):
        super().__init__()
        self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, embedding_table=TruncatedNormal(config.initializer_range))
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size, embedding_table=TruncatedNormal(config.initializer_range))
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size, embedding_table=TruncatedNormal(config.initializer_range))
        self.layer_norm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps)
        self.dropout = nn.Dropout(1 - config.hidden_dropout_prob)

    def construct(self, input_ids, token_type_ids=None, position_ids=None):
        seq_len = input_ids.shape[1]
        if position_ids is None:
            position_ids = mnp.arange(seq_len)
            position_ids = position_ids.expand_dims(0).expand_as(input_ids)
        if token_type_ids is None:
            token_type_ids = ops.zeros_like(input_ids)
        
        words_embeddings = self.word_embeddings(input_ids)
        position_embeddings = self.position_embeddings(position_ids)
        token_type_embeddings = self.token_type_embeddings(token_type_ids)
        embeddings = words_embeddings + position_embeddings + token_type_embeddings
        embeddings = self.layer_norm(embeddings)
        embeddings = self.dropout(embeddings)
        return embeddings

BERT 模型构建

BERT模型的构建与上一节课程的Transformer Encoder构建类似。

分别构建multi-head attention层,feed-forward network,并在中间用add&norm连接,最后通过线性层与softmax层进行输出。

BERT 预训练

BERT通过Masked LM(masked language model)与NSP(next sentence prediction)获取词语和句子级别的特征。
Mindspore 公开课 - BERT,bert,人工智能,深度学习

Masked Language Model (Masked LM)

BERT模型通过Masked LM捕捉词语层面的信息。

我们随机将每个句子中15%的词语进行遮盖,替换成掩码。在训练过程中,模型会对句子进行“完形填空”,预测这些被遮盖的词语是什么,通过减小被mask词语的损失值来对模型进行优化。
Mindspore 公开课 - BERT,bert,人工智能,深度学习
由于<mask>仅在预训练中出现,为了让预训练和微调中的数据处理尽可能接近,我们在随机mask的时候进行如下操作:

  • 80%的概率替换为<mask>
  • 10%的概率替换为文本中的随机词
  • 10%的概率不进行替换,保持原有的词元
    Mindspore 公开课 - BERT,bert,人工智能,深度学习
    我们通过BERTPredictionHeadTranform实现单层感知机,对被遮盖的词元进行预测。在前向网络中,我们需要输入BERT模型的编码结果hidden_states。
activation_map = {
    'relu': nn.ReLU(),
    'gelu': nn.GELU(False),
    'gelu_approximate': nn.GELU(),
    'swish':nn.SiLU()
}

class BertPredictionHeadTransform(nn.Cell):
    def __init__(self, config):
        super().__init__()
        self.dense = nn.Dense(config.hidden_size, config.hidden_size, weight_init=TruncatedNormal(config.initializer_range))
        self.transform_act_fn = activation_map.get(config.hidden_act, nn.GELU(False))
        self.layer_norm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps)
    
    def construct(self, hidden_states):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.transform_act_fn(hidden_states)
        hidden_states = self.layer_norm(hidden_states)
        return hidden_states

根据被遮盖的词元位置masked_lm_positions,获得这些词元的预测输出。

import mindspore.ops as ops
import mindspore.numpy as mnp
from mindspore import Parameter, Tensor

class BertLMPredictionHead(nn.Cell):
    def __init__(self, config):
        super(BertLMPredictionHead, self).__init__()
        self.transform = BertPredictionHeadTransform(config)

        self.decoder = nn.Dense(config.hidden_size, config.vocab_size, has_bias=False, weight_init=TruncatedNormal(config.initializer_range))

        self.bias = Parameter(initializer('zeros', config.vocab_size), 'bias')

    def construct(self, hidden_states, masked_lm_positions):
        batch_size, seq_len, hidden_size = hidden_states.shape
        if masked_lm_positions is not None:
            flat_offsets = mnp.arange(batch_size) * seq_len
            flat_position = (masked_lm_positions + flat_offsets.reshape(-1, 1)).reshape(-1)
            flat_sequence_tensor = hidden_states.reshape(-1, hidden_size)
            hidden_states = ops.gather(flat_sequence_tensor, flat_position, 0)
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states) + self.bias
        return hidden_states

Next Sentence Prediction (NSP)

BERT通过NSP捕捉句子级别的信息,使其可以理解句子与句子之间的联系,从而能够应用于问答或者推理任务。

NSP本质上是一个二分类任务,通过输入一个句子对,判断两句话是否为连续句子。输入的两个句子A和B中,B有50%的概率是A的下一句。

另外,输入的内容最好是document-level的语料,而非sentence-level的语料,这样训练出的模型可以具备抓取长序列特征的能力。

在这里,我们使用一个单隐藏层的多层感知机 BERTPooler 进行二分类预测。因为特殊占位符 <cls>在预训练中对应了句子级别的特征信息,所以多层感知机分类器只需要输出 <cls>对应的隐藏层输出。

class BertPooler(nn.Cell):
    def __init__(self, config):
        super(BertPooler, self).__init__()
        self.dense = nn.Dense(config.hidden_size, config.hidden_size, activation='tanh', weight_init=TruncatedNormal(config.initializer_range))
    
    def construct(self, hidden_states):
        first_token_tensor = hidden_states[:, 0]
        pooled_output = self.dense(first_token_tensor)
        return pooled_output

最后,多层感知机分类器的输出通过一个线性层self.seq_relationship,输出对nsp的预测。

在BERTPreTrainingHeads中,我们对以上提到的两种方式进行整合。最终输出Maked LM(prediction scores)和NSP(seq_realtionship_score)的预测结果

class BertPreTrainingHeads(nn.Cell):
    def __init__(self, config):
        super(BertPreTrainingHeads, self).__init__()
        self.predictions = BertLMPredictionHead(config)
        self.seq_relationship = nn.Dense(config.hidden_size, 2, weight_init=TruncatedNormal(config.initializer_range))
    
    def construct(self, sequence_output, pooled_output, masked_lm_positions):
        prediction_scores = self.predictions(sequence_output, masked_lm_positions)
        seq_relationship_score = self.seq_relationship(pooled_output)
        return prediction_scores, seq_relationship_score

BERT预训练代码整合

我们将上述的类进行实例化,并借此回顾一下BERT预训练的整体流程。文章来源地址https://www.toymoban.com/news/detail-793552.html

  1. BertModel构建BERT模型;
  2. BertPretrainingHeads整合了Masked LM与NSP两个训练任务, 输出预测结果;
    • BertLMPredictionHead:输入BERT编码与的位置,输出对应位置词元的预测;
    • BERTPooler:输入BERT编码,输出对的隐藏状态,并在BertPretrainingHeads中通过线性层输出预测结果;
class BertForPretraining(nn.Cell):
    def __init__(self, config, *args, **kwargs):
        super().__init__(config, *args, **kwargs)
        self.bert = BertModel(config)
        self.cls = BertPreTrainingHeads(config)
        self.vocab_size = config.vocab_size

        self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.embedding_table

    def construct(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, masked_lm_positions=None):
        outputs = self.bert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask
        )

        sequence_output, pooled_output = outputs[:2]
        prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output, masked_lm_positions)

        outputs = (prediction_scores, seq_relationship_score,) + outputs[2:]

        return outputs

到了这里,关于Mindspore 公开课 - BERT的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 昇思MindSpore技术公开课:探索AI世界的新奇之旅

    MindSpore的LLaMA这个课程让我在AI世界探索出了一条新奇的之旅。我觉得这个项目很大胆很有想法,里面有一位老师的话让我印象深刻,他说华为的这个平台,就像是一辆汽车(当然肯定是起始阶段的,发展阶段的汽车),而TensorFlow这些平台就像一架舒服马车,目前看可能这个

    2024年01月24日
    浏览(33)
  • 基于Bert+Attention+LSTM智能校园知识图谱问答推荐系统——NLP自然语言处理算法应用(含Python全部工程源码及训练模型)+数据集

    这个项目充分利用了Google的Bert模型,这是一种基于Attention的大规模语料预训练模型,以及LSTM命名实体识别网络。项目的目标是设计一套通用的问答系统处理逻辑,以实现智能问答任务。 首先,我们采用了Bert模型,这是一种在自然语言处理领域非常强大的预训练模型。它具备

    2024年02月09日
    浏览(47)
  • Bert基础(十七)--Bert实战:中文情感识别

    前面说了中文分类的过程,这次说一下情感分类相关的代码,其实情感分类也属于中文多分类的一种,知识情感分类一般会专门区分出来,但是代码基本是一致的, 基本步骤: 数据集我们使用hugging face上的数据集,打开hugging face–》datasets task选择 “Text Classification“ langua

    2024年04月28日
    浏览(22)
  • BERT原理&Fine Tuning&Bert变种

    BERT全称为Bidirectional Encoder Representation from Transformer,从名字可以知道,BERT是Transformer的Encoder部分。BERT的最大的改进是在模型的训练核数据的输入部分。 BERT是一个动态词向量模型,其主要功能就是抽取每个词在句子中的语义信息,并且表示出来。 训练时的任务 BERT在训练时,

    2024年02月05日
    浏览(24)
  • 什么是狭义人工智能、通用人工智能和超级人工智能?

    人工智能 (AI) 是一种机器智能,它模仿人类思维的解决问题和决策能力来执行各种任务。 。 人工智能使用机器学习和深度学习等算法和技术来学习、发展并在分配的任务中逐渐做得更好。根据人工智能可以复制的人类特征、现实世界的应用和心智理论的先决条件,人工智能

    2024年02月11日
    浏览(42)
  • 探索人工智能:深度学习、人工智能安全和人工智能编程(文末送书)

    人工智能知识对于当今的互联网技术人来说已经是刚需。但人工智能的概念、流派、技术纷繁复杂,选择哪本书入门最适合呢? 这部被誉为人工智能“百科全书”的《人工智能(第3版)》,可以作为每个技术人进入 AI 世界的第一本书。 购书链接,限时特惠5折 这本书是美国

    2024年02月03日
    浏览(80)
  • 【人工智能】人工智能和双曲几何

            作为人工智能技术的理论支撑,几何学是必不可少的;目前直接的几何技术有:计算几何--对集合体如点云处理有用;射影几何--对3d重构有用;双曲几何--在自然语言的词嵌入做基础数学模型,另外深度学习国外有双曲网络在应用。本文针对双曲几何进行探讨。

    2024年02月09日
    浏览(46)
  • 快速上手Pytorch实现BERT,以及BERT后接CNN/LSTM

    本项目采用HuggingFace提供的工具实现BERT模型案例,并在BERT后接CNN、LSTM等 HuggingFace官网 一、实现BERT(后接线性层) 1.引用案例源码: 程序会自行下载模型和配置文件,也可自行在官网上手动下载 模型返回的参数 2. 自定义类调用数据集 squeeze(0)的作用: 举个栗子 input_ids: te

    2024年02月05日
    浏览(33)
  • 【使用 BERT 的问答系统】第 5 章 :BERT模型应用:问答系统

         🔎大家好,我是Sonhhxg_柒,希望你看完之后,能对你有所帮助,不足请指正!共同学习交流🔎 📝个人主页-Sonhhxg_柒的博客_CSDN博客 📃 🎁欢迎各位→点赞👍 + 收藏⭐️ + 留言📝​ 📣系列专栏 - 机器学习【ML】 自然语言处理【NLP】  深度学习【DL】 ​  🖍forew

    2024年02月01日
    浏览(22)
  • Sentence-BERT:使用Siamese BERT网络进行句子嵌入

    Siamese BERT 基于BERT模型的孪生网络结构,Siamese 一词表示网络结构共享参数和权重。 Siamese BERT常用于处理文本相似度任务,如句子对匹配、问答系统等。 它通过两个输入句子分别输入到两个共享参数的BERT模型中,获取句子的语义表示。然后,通过对比两个句子的语义表示,可

    2024年02月16日
    浏览(25)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包