├── .gitignore ├── README.md └── bert_study ├── 3_BERT Post-Training for Review Reading Comprehension and Aspect based Sentiment Analysis.pdf ├── ACL2020_UnsupervisedBert ├── UnsupervisedBert.pdf ├── img │ └── 20200901081852.png └── readme.md ├── BART ├── img │ ├── 微信截图_20211122170950.png │ ├── 微信截图_20211122171023.png │ ├── 微信截图_20211122172500.png │ ├── 微信截图_20211122182304.png │ └── 微信截图_20211122183547.png └── readme.md ├── BERT 蒸馏在垃圾舆情识别中的探索.pdf ├── BERTintoSimpleNeuralNetworks ├── 1903.12136.pdf ├── img │ ├── 微信图片_20210218221305.png │ ├── 微信截图_20210209220018.png │ ├── 微信截图_20210209220803.png │ ├── 微信截图_20210209221917.png │ ├── 微信截图_20210209222035.png │ └── 微信截图_20210209222158.png └── readme.md ├── Bert_zip ├── img │ ├── 20200731202733.png │ ├── 20200801191212.png │ ├── 20200801191434.png │ ├── 20200927153839.png │ ├── 20200927154643.png │ └── 20200927191946.png ├── readme.md └── readme.png ├── Chinese └── ChineseBERT │ ├── ChineseBert.ipynb │ ├── img │ ├── 微信截图_20210808214524.png │ ├── 微信截图_20210808221829.png │ ├── 微信截图_20210808222042.png │ ├── 微信截图_20210808222750.png │ ├── 微信截图_20210808225751.png │ ├── 微信截图_20210808225813.png │ ├── 微信截图_20210808225931.png │ ├── 微信截图_20210808230114.png │ ├── 微信截图_20210808230214.png │ ├── 微信截图_20210808230235.png │ ├── 微信截图_20210808230407.png │ ├── 微信截图_20210808230830.png │ └── 微信截图_20210808230922.png │ └── readme.md ├── ELECTRA ├── document.pdf ├── img │ ├── 20201015170627.png │ ├── 20201015192142.png │ ├── 20201015192526.png │ ├── 20201015193303.png │ ├── 20201015193420.png │ ├── 20201015193507.png │ └── 20201015194517.png └── readme.md ├── ELMo Deep contextualized word representations.pdf ├── FastBERT ├── FastBERT.pdf ├── code.md ├── img │ ├── 20200731202558.png │ ├── 20200731202733.png │ └── 20200731203505.png └── readme.md ├── FlanT5 ├── img │ ├── 20230228075007.png │ ├── 20230228075443.png │ ├── 20230228075718.png │ ├── 20230228080041.png │ ├── 20230228080124.png │ ├── 20230228080222.png │ ├── 微信截图_20230228080254.png │ ├── 微信截图_20230228080323.png │ ├── 微信截图_20230228080347.png │ ├── 微信截图_20230228080407.png │ └── 微信截图_20230228080427.png └── readme.md ├── LLMs.md ├── MacBERT └── readme.md ├── SIGIR2020_MarkedBERT ├── img │ ├── 20200901083934.png │ ├── 20200901084025.png │ └── 20200901084101.png └── readme.md ├── SelfTrainingImprovesPreTraining ├── 2010.02194.pdf ├── img │ ├── 20201027210757.png │ ├── 20201027211251.png │ ├── 微信截图_20210415194221.png │ ├── 微信截图_20210415194442.png │ ├── 微信截图_20210415194618.png │ ├── 微信截图_20210415194833.png │ ├── 微信截图_20210415195007.png │ └── 微信截图_20210417132422.png └── readme.md ├── SpanBERT ├── paper.pdf └── readme.md ├── T1_bert ├── BERT Pre-training of Deep Bidirectional Transformers for Language Understanding.pdf ├── bert │ ├── .gitignore │ ├── CONTRIBUTING.md │ ├── LICENSE │ ├── README.md │ ├── __init__.py │ ├── create_pretraining_data.py │ ├── extract_features.py │ ├── modeling.py │ ├── modeling_test.py │ ├── multilingual.md │ ├── optimization.py │ ├── optimization_test.py │ ├── predicting_movie_reviews_with_bert_on_tf_hub.ipynb │ ├── requirements.txt │ ├── run_classifier.py │ ├── run_classifier_with_tfhub.py │ ├── run_pretraining.py │ ├── run_squad.py │ ├── sample_text.txt │ ├── tokenization.py │ └── tokenization_test.py ├── bertCode.md ├── bertCode1_modeling.md ├── bertCode2_pretraining.md ├── bertCode3_fineTune.md ├── bertCode4_word2embedding.md ├── bertCode5_similarity.md ├── img │ ├── 20200528133755.png │ ├── 20200624080740.png │ ├── 20200624084515.png │ ├── 20200629083749.png │ ├── 20200629084400.png │ ├── 20200629085428.png │ ├── 20200629085533.png │ ├── 20200629085712.png │ ├── 20200629085906.png │ ├── 20200629092209.png │ ├── 20200629203527.png │ ├── 20200630084746.png │ ├── 20200701082543.png │ ├── 20200701091112.png │ ├── 20201130205012.png │ ├── 20201130205229.png │ ├── 20201130205325.png │ ├── 20201130205357.png │ ├── v2-02f5f0a3a2bc5c8a0931e677df2a78a6_r.jpg │ ├── zg.png │ ├── 微信截图_20200625082324.png │ ├── 微信截图_20200625101800.png │ └── 微信截图_20201128130050.png ├── readme - 副本.md ├── readme.md └── readme.png ├── T2020_GRAPH_BERT ├── 2001.05140.pdf ├── img │ └── model.png └── readme.md ├── T2_XLNet ├── XLNet.pdf ├── img │ ├── fun1.png │ ├── fun2.png │ ├── plm.png │ └── two_attention.png └── readme.md ├── T4_RoBERTa ├── RoBERTa.md └── RoBERTa.pdf ├── T5_ALBERT ├── ALBERT A Lite BERT for Self supervised Learning of Language Representations.pdf ├── img │ ├── 1.png │ ├── 2.png │ ├── 3.png │ └── 4.png └── readme.md ├── TinyBERT ├── 1909.10351.pdf ├── img │ ├── 20200927190511.png │ ├── 20200927190613.png │ ├── 20200927191001.png │ ├── 20200927191946.png │ ├── 20200927194101.png │ ├── 20200927194629.png │ ├── 20200927194737.png │ ├── 20200927194815.png │ ├── 20200927194927.png │ ├── 20200927195206.png │ ├── 20200927195319.png │ └── 20200927195725.png └── readme.md ├── bert_trick └── UNK_process │ ├── img │ └── 微信截图_20220917161347.png │ ├── readme.md │ └── ukn_test.ipynb ├── distilbert ├── img │ ├── 20200801191212.png │ └── 20200801191434.png └── readme.md ├── img ├── 20201015170627.png ├── 20201026153603.png ├── 20201026153725.png ├── 20201026154010.png ├── 20201026154623.png ├── 20230321223629.png ├── 微信截图_20210910210322.png ├── 微信截图_20210910210729.png ├── 微信截图_20210910210907.png ├── 微信截图_20210910211607.png ├── 微信截图_20210910212046.png ├── 微信截图_20210910212205.png ├── 微信截图_20210910212307.png ├── 微信截图_20210910213336.png ├── 微信截图_20210910213420.png └── 微信截图_20210910213837.png ├── readme.md ├── readme.png └── 基于知识增强的语言表示模型.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | # Local .terraform directories 2 | **/.terraform/* 3 | **/w2v_model/ 4 | **/saved/ 5 | **/runs/* 6 | **/.idea/ 7 | **/__pycache__/ 8 | **/.ipynb_checkpoints/ 9 | **/summarys/ 10 | model/ 11 | **/model/ 12 | **/models/ 13 | **/outputs/ 14 | **/saved_models/ 15 | version/ 16 | **/version/ 17 | **/gitinfo/ 18 | **/mywork/* 19 | 20 | T1_Relation_Classification_via_CDNN/saved_models/* 21 | 22 | text_simple_study/RE2_study/simple-effective-text-matching-pytorch/* 23 | 24 | # .tfstate files 25 | *.tfstate 26 | *.tfstate.* 27 | *checkpoint 28 | **/model.ckpt* 29 | *.ckpt* 30 | # .tfvars files 31 | *.tfvars 32 | *.all 33 | *.hdf5 34 | task/.idea/* 35 | *.xml 36 | *.zip 37 | *.rar 38 | *.bin 39 | *.vec 40 | *.model 41 | *.gz 42 | *.bz2 43 | *.word 44 | *.pkl 45 | **/mywork/* 46 | 47 | -------------------------------------------------------------------------------- /bert_study/3_BERT Post-Training for Review Reading Comprehension and Aspect based Sentiment Analysis.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/3_BERT Post-Training for Review Reading Comprehension and Aspect based Sentiment Analysis.pdf -------------------------------------------------------------------------------- /bert_study/ACL2020_UnsupervisedBert/UnsupervisedBert.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ACL2020_UnsupervisedBert/UnsupervisedBert.pdf -------------------------------------------------------------------------------- /bert_study/ACL2020_UnsupervisedBert/img/20200901081852.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ACL2020_UnsupervisedBert/img/20200901081852.png -------------------------------------------------------------------------------- /bert_study/ACL2020_UnsupervisedBert/readme.md: -------------------------------------------------------------------------------- 1 | # Perturbed Masking: Parameter-free Probing for Analyzing and Interpreting BERT 2 | 3 | > 作者:杨夕 4 | > 5 | > 项目地址:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 8 | > 9 | > 论文链接:https://arxiv.org/pdf/2004.14786.pdf 10 | > 11 | > 代码链接:https://github.com/bojone/perturbed_masking 12 | > 13 | > 【注:手机阅读可能图片打不开!!!】 14 | 15 | ## 摘要 16 | 17 | By introducing a small set of additional parameters, a probe learns to solve specific linguistic tasks (e.g., dependency parsing) in a supervised manner using feature representations (e.g., contextualized embeddings). The effectiveness of such probing tasks is taken as evidence that the pre-trained model encodes linguistic knowledge. 18 | 19 | However, this approach of evaluating a language model is undermined by the uncertainty of the amount of knowledge that is learned by the probe itself. Complementary to those works, we propose a parameter-free probing technique for analyzing pre-trained language models (e.g., BERT). Our method does not require direct supervision from the probing tasks, nor do we introduce additional parameters to the probing process. 20 | 21 | Our experiments on BERT show that syntactic trees recovered from BERT using our method are significantly better than linguistically-uninformed baselines. We further feed the empirically induced dependency structures into a downstream sentiment classification task and find its improvement compatible with or even superior to a human-designed dependency schema. 22 | 23 | 通过引入少量的附加参数,probe learns 在监督方式中使用特征表示(例如,上下文嵌入)来 解决特定的语言任务(例如,依赖解析)。这样的probe tasks 的有效性被视为预训练模型编码语言知识的证据。 24 | 25 | 但是,这种评估语言模型的方法会因 probe 本身所学知识量的不确定性而受到破坏。作为这些工作的补充,我们提出了一种无参数的 probe 技术来分析预训练的语言模型(例如BERT)。我们的方法不需要 probe 任务的直接监督,也不需要在 probing 过程中引入其他参数。 26 | 27 | 我们在BERT上进行的实验表明,使用我们的方法从BERT恢复的语法树比语言上不了解的基线要好得多。我们进一步将根据经验引入的依存关系结构输入到下游的情感分类任务中,并发现它的改进与人工设计的依存关系兼容甚至更好。 28 | 29 | ## 介绍 30 | 31 | probe 是简单的神经网络(具有少量附加参数),其使用预先训练的模型(例如,隐藏状态激活,注意权重)生成的特征表示,并经过训练以执行监督任务(例如,依赖性 标签)。 假设所测得的质量主要归因于预先训练的语言模型,则使用 probe 的性能来测量所生成表示的质量。 32 | 33 | ## 方法介绍 34 | 35 | - Perturbed Masking 36 | - 介绍:parameter-free probing technique 37 | - 目标:analyze and interpret pre-trained models,测量一个单词xj对预测另一个单词xi的影响,然后从该单词间信息中得出全局语言属性(例如,依赖树)。 38 | 39 | 整体思想很直接,句法结构,其实本质上描述的是词和词之间的某种关系,如果我们能从BERT当中拿到词和词之间相互“作用”的信息,就能利用一些算法解析出句法结构。具体的做法可以看下面这张图。 40 | 41 | ![](img/20200901081852.png) 42 | 43 | 比如说你想知道“谭”这个字对 “哥”这个字有多大影响。 44 | 45 | 1. 我们先把“哥”从原始的句子中mask掉(左图),然后拿到BERT基于上下文生成的“哥”的向量e6, 46 | 47 | 2. 接下来我们再次去改动句子,这次我们把“谭”和“哥”同时mask掉(右图)。然后再次拿到“哥”对应的向量表达e6’, 48 | 49 | 3. 通过计算这两个向量之间的差异,比如向量距离:d(e6,e6’),我们能够得到这么一个信息:在缺失了“谭”这个字的上下文中,BERT是如何model“哥”这个字的。我们在文中把这个信息称做“谭”对“哥”的影响。 50 | 51 | 把上面这个过程在每两个字之间重复一遍,我们可以得到一个描述了这个句子中,字和字之间关系的矩阵。之后我们就可以利用一些经典的基于图的parsing算法从这个矩阵里解析出句法结构。通过把我们生成的树和语言学家们标注好的句法树进行比较,我们就可以量化地知道BERT到底学到了什么程度的句法知识。 52 | 53 | 那么d(e6,,e'6)有什么直观上的解释吗: 54 | 55 | 想象一下,如果BERT对“友好的哥谭市民”的理解是“友好/的哥/谭市民”,那么d(e6,e6’) 这个距离不会特别大,因为“谭”对于预测“哥”来说不是特别重要,后面完全可以是张市民,李市民,陈市民。而如果BERT将其理解为“友好的/哥谭/市民”,那么显而易见的,缺失了“谭”会对“哥”的向量产生比较大的影响,导致d(e6,e6’) 的增大。 56 | 57 | 58 | 59 | 60 | ## 参考资料 61 | 62 | 1. [ACL2020 | 无监督?无监督!你没试过的BERT的全新用法](https://aminer.cn/research_report/5f0d6f7b21d8d82f52e59dab) 63 | 2. [无监督分词和句法分析!原来BERT还可以这样用 科学空间](https://kexue.fm/archives/7476) 64 | -------------------------------------------------------------------------------- /bert_study/BART/img/微信截图_20211122170950.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BART/img/微信截图_20211122170950.png -------------------------------------------------------------------------------- /bert_study/BART/img/微信截图_20211122171023.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BART/img/微信截图_20211122171023.png -------------------------------------------------------------------------------- /bert_study/BART/img/微信截图_20211122172500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BART/img/微信截图_20211122172500.png -------------------------------------------------------------------------------- /bert_study/BART/img/微信截图_20211122182304.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BART/img/微信截图_20211122182304.png -------------------------------------------------------------------------------- /bert_study/BART/img/微信截图_20211122183547.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BART/img/微信截图_20211122183547.png -------------------------------------------------------------------------------- /bert_study/BART/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 Bart】 那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 论文:Bart: Denoising sequence-to-sequence pre-training for natural language generation, translation, and comprehension 6 | > 7 | > 来源:Facebook 8 | > 9 | > 论文地址:https://mp.weixin.qq.com/s/42rYlyjQsh4loFKRdhJlIg 10 | > 11 | > 开源代码:https://github.com/renatoviolin/Bart_T5-summarization 12 | > 13 | > NLP论文学习笔记:https://github.com/km1994/nlp_paper_study 14 | > 15 | > **[手机版NLP论文学习笔记](https://mp.weixin.qq.com/s?__biz=MzAxMTU5Njg4NQ==&mid=100005719&idx=1&sn=14d34d70a7e7cbf9700f804cca5be2d0&chksm=1bbff26d2cc87b7b9d2ed12c8d280cd737e270cd82c8850f7ca2ee44ec8883873ff5e9904e7e&scene=18#wechat_redirect)** 16 | > 17 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 18 | > 19 | > NLP 百面百搭 地址:https://github.com/km1994/NLP-Interview-Notes 20 | > 21 | > **[手机版NLP百面百搭](https://mp.weixin.qq.com/s?__biz=MzAxMTU5Njg4NQ==&mid=100005719&idx=3&sn=5d8e62993e5ecd4582703684c0d12e44&chksm=1bbff26d2cc87b7bf2504a8a4cafc60919d722b6e9acbcee81a626924d80f53a49301df9bd97&scene=18#wechat_redirect)** 22 | > 23 | > 推荐系统 百面百搭 地址:https://github.com/km1994/RES-Interview-Notes 24 | > 25 | > **[手机版推荐系统百面百搭](https://mp.weixin.qq.com/s/b_KBT6rUw09cLGRHV_EUtw)** 26 | 27 | ## 一、引言 28 | 29 | - 论文方法: 30 | - BART,一种用于预训练序列到序列模型的去噪自动编码器。 31 | - BART 通过以下方式进行训练: 32 | - (1) 使用任意噪声函数破坏文本; 33 | - (2) 学习模型以重建原始文本。 34 | - 优点:它使用标准的基于 Transformer 的神经机器翻译架构,尽管它很简单,但可以看作是对 BERT(由于双向编码器)、GPT(带有从左到右的解码器)和许多其他最近的预训练方案的泛化. 35 | - 实验结果: 36 | - 我们评估了许多噪声方法,通过随机打乱原始句子的顺序和使用新颖的填充方案来找到最佳性能,其中文本的跨度被替换为单个掩码标记。 BART 在针对文本生成进行微调时特别有效,但也适用于理解任务。 37 | - 它将 RoBERTa 的性能与 GLUE 和 SQuAD 上的可比训练资源相匹配,在一系列抽象对话、问答和总结任务上取得了最新的最新成果,增益高达 6 ROUGE。 38 | - BART 还为机器翻译提供了 1.1 BLEU 比反向翻译系统增加了 1.1 BLEU,只有目标语言预训练。 39 | - 报告了在 BART 框架内复制其他预训练方案的消融实验,以更好地衡量哪些因素对最终任务性能影响最大。 40 | 41 | ## 二、动机 42 | 43 | 1. BERT:用掩码替换随机 token,双向编码文档。由于缺失 token 被单独预测,因此 BERT 较难用于生成任务; 44 | 45 | ![](img/微信截图_20211122170950.png) 46 | 47 | 2. GPT:使用自回归方式预测 token,这意味着 GPT 可用于生成任务。但是,该模型仅基于左侧上下文预测单词,无法学习双向交互 48 | 49 | ![](img/微信截图_20211122171023.png) 50 | 51 | ## 三、Bart 模型介绍 52 | 53 | ### 3.1 Bart 处理 逻辑 54 | 55 | BART:编码器输入与解码器输出无需对齐,即允许任意噪声变换。使用掩码符号替换文本段,从而破坏文本。使用双向模型编码被破坏的文本(左),然后使用自回归解码器计算原始文档的似然(右)。至于微调,未被破坏的文档是编码器和解码器的输入,研究者使用来自解码器最终隐藏状态的表征。 56 | 57 | ![](img/微信截图_20211122172500.png) 58 | 59 | ### 3.2 Bart 与 BERT 的 区别 60 | 61 | 1. 解码器的每个层对编码器最终隐藏层额外执行 cross-attention(和 Transformer 序列到序列模型一样); 62 | 2. BERT 在词预测之前使用了额外的前馈网络,而 BART 没有。 63 | 3. BART 相比同等规模的 BERT 模型大约多出 10% 的参数。 64 | 65 | ### 3.3 BART 预训练 66 | 67 | BART 是**通过破坏文档再优化重建损失**(即解码器输出和原始文档之间的交叉熵)训练得到的。 68 | 69 | 与目前仅适合特定噪声机制的去噪自编码器不同,BART 可应用于任意类型的文档破坏。极端情况下,当源文本信息全部缺失时,BART 也等同于语言模型。 70 | 71 | - 破坏原始文本的噪声方法: 72 | - Token Masking(token 掩码):按照 BERT 模型,BART 采样随机 token,并用 [MASK]标记 替换它们; 73 | - Sentence Permutation(句子排列变换):按句号将文档分割成多个句子,然后以随机顺序打乱这些句子; 74 | - Document Rotation(文档旋转):随机均匀地选择 token,旋转文档使文档从该 token 开始。该任务的目的是训练模型识别文档开头; 75 | - Token Deletion(token 删除):从输入中随机删除 token。与 token 掩码不同,模型必须确定缺失输入的位置; 76 | - Text Infilling(文本填充):采样多个文本段,文本段长度取决于泊松分布 (λ = 3)。用单个掩码 token 替换每个文本段。长度为 0 的文本段对应掩码 token 的插入; 77 | 78 | ### 3.4 BART 微调 79 | 80 | #### 3.4.1 Sequence Classification Task 序列分类任务 81 | 82 | 对于序列分类任务,将相同的输入,输入到encoder和decoder中,最后将decoder的最后一个隐藏节点作为输出,输入到分类层(全连接层)中,获取最终的分类的结果。 83 | 84 | ![](img/微信截图_20211122182304.png) 85 | 86 | > 注:其中,decoder的最后一个隐藏节点是一个特殊标记,相当于BERT模型中的[CLS]。 87 | 88 | #### 3.4.2 Token Classification Task 序列分类任务 89 | 90 | 对于 token 分类任务,将完整文档输入到编码器和解码器中,使用解码器最上方的隐藏状态作为每个单词的表征。该表征的用途是分类 token。 91 | 92 | #### 3.4.3 Sequence Generation Task 序列生成任务 93 | 94 | 由于 BART 具备自回归解码器,因此它可以针对序列生成任务进行直接微调,如抽象问答和摘要。在这两项任务中,信息复制自输入但是经过了处理,这与去噪预训练目标紧密相关。这里,编码器的输入是输入序列,解码器以自回归的方式生成输出。 95 | 96 | #### 3.4.4 Machine Translation 机器翻译 97 | 98 | 将BART的encoder端的embedding层替换成randomly initialized encoder,新的encoder也可以用不同的vocabulary。通过新加的Encoder,我们可以将新的语言映射到BART能解码到English(假设BART是在English的语料上进行的预训练)的空间。具体的finetune过程分两阶段: 99 | 100 | 1. 第一步只更新randomly initialized encoder + BART positional embedding + BART的encoder第一层的self-attention 输入映射矩阵。 101 | 2. 第二步更新全部参数,但是只训练很少的几轮。 102 | 103 | ![](img/微信截图_20211122183547.png) 104 | 105 | ## 参考 106 | 107 | 1. [Lewis, Mike, et al. "Bart: Denoising sequence-to-sequence pre-training for natural language generation, translation, and comprehension." arXiv preprint arXiv:1910.13461 (2019)](https://arxiv.org/abs/1910.13461) 108 | 2. [多项NLP任务新SOTA,Facebook提出预训练模型BART​](https://zhuanlan.zhihu.com/p/90173832) 109 | 3. [【论文精读】生成式预训练之BART](https://zhuanlan.zhihu.com/p/173858031) 110 | 4. [回顾BART模型](https://zhuanlan.zhihu.com/p/399169880) 111 | 5. [BART原理简介与代码实战](https://zhuanlan.zhihu.com/p/121788986) 112 | -------------------------------------------------------------------------------- /bert_study/BERT 蒸馏在垃圾舆情识别中的探索.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERT 蒸馏在垃圾舆情识别中的探索.pdf -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/1903.12136.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/1903.12136.pdf -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/img/微信图片_20210218221305.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/img/微信图片_20210218221305.png -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209220018.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209220018.png -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209220803.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209220803.png -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209221917.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209221917.png -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209222035.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209222035.png -------------------------------------------------------------------------------- /bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209222158.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/BERTintoSimpleNeuralNetworks/img/微信截图_20210209222158.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/img/20200731202733.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/img/20200731202733.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/img/20200801191212.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/img/20200801191212.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/img/20200801191434.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/img/20200801191434.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/img/20200927153839.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/img/20200927153839.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/img/20200927154643.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/img/20200927154643.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/img/20200927191946.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/img/20200927191946.png -------------------------------------------------------------------------------- /bert_study/Bert_zip/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 Bert 压缩】 那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 项目地址:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 8 | > 9 | 10 | ## 目录 11 | 12 | - [【关于 Bert 压缩】 那些你不知道的事](#关于-bert-压缩-那些你不知道的事) 13 | - [目录](#目录) 14 | - [动机](#动机) 15 | - [对比表](#对比表) 16 | - [模型压缩方法介绍](#模型压缩方法介绍) 17 | - [论文介绍](#论文介绍) 18 | - [ALBERT: A Lite Bert for self-supervisedLearning of Language Representations【低秩因式分解 + 跨层参数共享】](#albert-a-lite-bert-for-self-supervisedlearning-of-language-representations低秩因式分解--跨层参数共享) 19 | - [Q-BERT: Hessian Based Ultra Low Precision Quantization of BERT 【量化】](#q-bert-hessian-based-ultra-low-precision-quantization-of-bert-量化) 20 | - [Extreme Language Model Compression withOptimal Subwords and Shared Projections 【蒸馏】](#extreme-language-model-compression-withoptimal-subwords-and-shared-projections-蒸馏) 21 | - [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter 【蒸馏】](#distilbert-a-distilled-version-of-bert-smaller-faster-cheaper-and-lighter-蒸馏) 22 | - [FastBERT: a Self-distilling BERT with Adaptive Inference Time 【蒸馏】](#fastbert-a-self-distilling-bert-with-adaptive-inference-time-蒸馏) 23 | - [TinyBERT: Distilling BERT for Natural Language Understanding 【蒸馏】](#tinybert-distilling-bert-for-natural-language-understanding-蒸馏) 24 | - [个人总结](#个人总结) 25 | - [参考](#参考) 26 | 27 | ## 动机 28 | 29 | - Bert 优点: 30 | - 对下游任务进行微调后,显著提高了模型的表现; 31 | - Bert 缺点: 32 | - 内存占用; 33 | - 功耗过高; 34 | - 带来很高的延迟; 35 | - 限制了 Bert 系列模型在移动和物联网等嵌入式设备上的部署; 36 | 37 | ## 对比表 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 |
论文剪枝低秩因式分解知识蒸馏参数共享量化预训练微调
ALBERT: A Lite Bert for self-supervisedLearning of Language Representations111
Q-BERT: Hessian Based Ultra Low Precision Quantization of BERT111
Extreme Language Model Compression withOptimal Subwords and Shared Projections11
DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter11
FastBERT: a Self-distilling BERT with Adaptive Inference Time11
TinyBERT: Distilling BERT for Natural Language Understanding111
111 | 112 | ## 模型压缩方法介绍 113 | 114 | - BERT 瘦身来提升速度 115 | - trick: 116 | - 低秩因式分解:在输入层和输出层使用嵌入大小远小于原生Bert的嵌入大小,再使用简单的映射矩阵使得输入层的输出或者最后一层隐藏层的输出可以通过映射矩阵输入到第一层的隐藏层或者输出层; 117 | - 跨层参数共享:隐藏层中的每一层都使用相同的参数,用多种方式共享参数,例如只共享每层的前馈网络参数或者只共享每层的注意力子层参数。默认情况是共享每层的所有参数; 118 | - 剪枝:剪掉多余的连接、多余的注意力头、甚至LayerDrop[1]直接砍掉一半Transformer层 119 | - 量化:把FP32改成FP16或者INT8; 120 | - 蒸馏:用一个学生模型来学习大模型的知识,不仅要学logits,还要学attention score; 121 | - 问题: 122 | - 精度的下降 123 | - 低秩因式分解 and 跨层参数共享 计算量并没有下降; 124 | - 剪枝会直接降低模型的拟合能力; 125 | - 量化虽然有提升但也有瓶颈; 126 | - 蒸馏的不确定性最大,很难预知你的BERT教出来怎样的学生; 127 | 128 | ## 论文介绍 129 | 130 | ### ALBERT: A Lite Bert for self-supervisedLearning of Language Representations【低秩因式分解 + 跨层参数共享】 131 | 132 | - 论文地址:https://openreview.net/forum?id=H1eA7AEtvS 133 | - 论文源码:https://github.com/google-research/ALBERT 134 | - 收录期刊:ICLR 2020 spotlight presentation收录 135 | - 模型压缩方法:低秩因式分解 + 跨层参数共享 136 | - 模型压缩方法介绍: 137 | - 低秩因式分解: 138 | - 动机:Bert的参数量大部分集中于模型的隐藏层架构上,在嵌入层中只有30,000词块,其所占据的参数量只占据整个模型参数量的小部分; 139 | - 方法:将输入层和输出层的权重矩阵分解为两个更小的参数矩阵; 140 | - 思路:在输入层和输出层使用嵌入大小远小于原生Bert的嵌入大小,再使用简单的映射矩阵使得输入层的输出或者最后一层隐藏层的输出可以通过映射矩阵输入到第一层的隐藏层或者输出层; 141 | - 优点:在不显著增加词嵌入大小的情况下能够更容易增加隐藏层大小; 142 | - 参数共享【跨层参数共享】: 143 | - 动机:隐藏层 参数 大小 一致; 144 | - 方法:隐藏层中的每一层都使用相同的参数,用多种方式共享参数,例如只共享每层的前馈网络参数或者只共享每层的注意力子层参数。默认情况是共享每层的所有参数; 145 | - 优点:防止参数随着网络深度的增加而增大; 146 | - 其他改进策略: 147 | - **句子顺序预测损失(SOP)**代替**Bert中的下一句预测损失(NSP)**: 148 | - 动机:通过实验证明,Bert中的下一句预测损失(NSP) 作用不大; 149 | - 介绍:用预测两个句子是否连续出现在原文中替换为两个连续的句子是正序或是逆序,用于进一步提高下游任务的表现 150 | - 优点:参数量上有所降低; 151 | - 缺点:其加速指标仅展示了训练过程,由于ALBERT的隐藏层架构**采用跨层参数共享策略并未减少训练过程的计算量**,加速效果更多来源于低维的嵌入层; 152 | 153 | ### Q-BERT: Hessian Based Ultra Low Precision Quantization of BERT 【量化】 154 | 155 | - 论文地址:https://arxiv.org/abs/1909.05840 156 | - 论文源码: 157 | - 收录期刊:AAAI 2020 收录 158 | - 模型压缩方法:量化 159 | 160 | > 量化技术介绍:通过减少用于表示每个权重值的精度来压缩模型。例如模型使用float32标准定义参数的精度进行训练,然后我们可以使用量化技术选择float16,甚至int8表示参数的精度用于压缩模型。 161 | 162 | - 模型压缩方法介绍: 163 | - 混合精确量化: 164 | - 介绍:由于不同的编码器层负责不同的语义表示,预计他们表现出不同的灵敏度。因此该工作为更敏感的层分配更高的精度以保证模型表现。通过海森关注量化(HAWQ)计算每一层参数的海森频谱(例如特征值),具有更高海森频谱的网络层是对量化更敏感的,需要更高的精度; 165 | - 思路: 166 | - step 1:在执行海森关注量化时对于不同的训练数据获得每一层的平均最大特征值和其方差作为指标来决定每一层的量化精度; 167 | - step 2:然后根据所选的精度设置执行量化包括每一层的参数和激活函数,并微调模型 168 | - 分组量化: 169 | - 介绍:在编码器层中的每一个自注意力头有四个参数矩阵,即和输出权重矩阵。将此四个矩阵作为一个具有相同量化范围的整体直接量化会显著降低模型准确性。该工作将每个自注意力头对应的四个权重矩阵作为一个组,所以有12个组(12个自注意力头)。此外,在每一组中,将顺序的输出神经元分组,比如每一自注意力子层有4*12*64=3072个神经元,其中64为输出神经元,每6个输出神经元为一个子组,所以总共有12×64/6= 128个子组,每个子组可以有自己的量化范围。分层量化以及分组量化可由下图阐述。 170 | 171 | ![](img/20200927153839.png) 172 | 173 | ### Extreme Language Model Compression withOptimal Subwords and Shared Projections 【蒸馏】 174 | 175 | ![](img/20200927154643.png) 176 | 177 | - 论文地址:https://openreview.net/forum?id=S1x6ueSKPr 178 | - 模型压缩方法:知识蒸馏 179 | - 模型压缩方法介绍: 180 | - 减少学生模型的词汇表中词块的数量: 181 | - 动机:训练词汇量过大; 182 | - 方法:使学生模型在蒸馏的过程中学习到一个更小的词汇表; 183 | - 思路: 184 | - 对偶训练:在蒸馏过程中,对于给定的输入到教师模型的训练序列,该工作混合使用教师词汇表和学生词汇表。通过从序列中随机选择部分单词,使用学生词汇表来分割,对于其它单词使用教师词汇表来分割,这鼓励根据老师和学生的词汇表来对齐同一单词的表示形式。这也是通过掩码语言建模任务来实现的该策略的效果。需要注意的是我们仅对教师模型执行对偶训练。在使用掩码语言建模训练时,模型针对老师和学生的词汇表使用不同的softmax层,具体取决于需预测的单词使用了哪一个词汇表来分割。 185 | - 减少隐藏层大小: 186 | - 动机:尽量不损害模型性能,仅仅依靠教师模型的输出去训练学生模型并不具备高泛化能力; 187 | - 思路: 188 | - 共享映射:将教师模型和隐藏层大小较小的学生模型的参数投影到相同的空间再最小化两者的信息损失。详细地,该工作将教师模型的每一层中的每个可训练变量投影为与学生模型中相应变量相同的形状,记为向下映射,并计算2-范式损失,相似地,将学生模型的每一层中的每个可训练变量投影为与教师模型中相应变量相同的形状,记为向上映射,并计算2-范式损失,最后将损失相加作为目标函数的一部分,另外一部分为掩码语言建模预测损失。 189 | 190 | ### DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter 【蒸馏】 191 | 192 | ![](img/20200927154643.png) 193 | 194 | - 论文地址:https://arxiv.org/abs/1910.01108 195 | - 模型压缩方法:知识蒸馏 196 | - 模型压缩方法介绍: 197 | - 通过知识蒸馏(在 logits,hidden_states 上计算学生与教师的 loss)训练一个小(主要是层数)模型实现和大模型类似的效果; 198 | - 损失函数 199 | 200 | ![](img/20200801191212.png) 201 | 202 | > $t_i$ 老师的概率估计 203 | > $s_i$ 学生的概率估计 204 | 205 | - 使用了 softmax-temperature: 206 | 207 | ![](img/20200801191434.png) 208 | 209 | > T 控制输出分布的平滑程度,推理时设置为 1 变为标准的 Softmax; 210 | > $z_i$ 表示类别 i 的分数。 211 | 212 | 最终的损失函数是 Lce 和 masked language modeling loss Lmlm 的线性组合,另外作者发现添加余弦嵌入损失(Lcos)有利于使学生和教师隐藏状态向量的方向一致。 213 | 214 | - 学生架构 215 | - 具有和老师一般的体系结构; 216 | - 移除了 Token type embedding 和 pooler; 217 | - 层数减少为 1/2:作者调查发现改变隐层维度对计算效率的影响比其他因素的变化要小(比如层数)。 218 | 219 | 从老师的两层中选择一层来初始化学生。蒸馏应用了Liu et al. [2019] 提出的 BERT 模型训练最佳实践。语料和 Bert 使用的一致。 220 | 221 | ### FastBERT: a Self-distilling BERT with Adaptive Inference Time 【蒸馏】 222 | 223 | ![](img/20200731202733.png) 224 | 225 | - 论文地址:https://arxiv.org/pdf/2004.02178 226 | - 模型压缩方法:知识蒸馏 227 | - 模型压缩方法介绍: 228 | - 样本自适应机制(Sample-wise adaptive mechanism) 229 | - 思路: 230 | - 在每层Transformer后都去预测样本标签,如果某样本预测结果的置信度很高,就不用继续计算了,就是自适应调整每个样本的计算量,容易的样本通过一两层就可以预测出来,较难的样本则需要走完全程。 231 | - 操作: 232 | - 给每层后面接一个分类器,毕竟分类器比Transformer需要的成本小多了 233 | - 自蒸馏(Self-distillation) 234 | - 思路: 235 | - 在预训练和精调阶段都只更新主干参数; 236 | - 精调完后freeze主干参数,用分支分类器(图中的student)蒸馏主干分类器(图中的teacher)的概率分布 237 | - 优点: 238 | - 非蒸馏的结果没有蒸馏要好 239 | - 不再依赖于标注数据。蒸馏的效果可以通过源源不断的无标签数据来提升 240 | 241 | ### TinyBERT: Distilling BERT for Natural Language Understanding 【蒸馏】 242 | 243 | ![](img/20200927191946.png) 244 | 245 | - 论文地址:https://arxiv.org/pdf/1909.10351.pdf 246 | - 模型压缩方法:知识蒸馏 247 | - tinybert的创新点:学习了teacher Bert中更多的层数的特征表示; 248 | - 模型压缩方法介绍: 249 | - 基于transformer的知识蒸馏模型压缩 250 | - 学习了teacher Bert中更多的层数的特征表示; 251 | - 特征表示: 252 | - 词向量层的输出; 253 | - Transformer layer的输出以及注意力矩阵; 254 | - 预测层输出(仅在微调阶段使用); 255 | - bert知识蒸馏的过程 256 | - 左图:整体概括了知识蒸馏的过程 257 | - 左边:Teacher BERT; 258 | - 右边:Student TinyBERT 259 | - 目标:将Teacher BERT学习到的知识迁移到TinyBERT中 260 | - 右图:描述了知识迁移的细节; 261 | - 在训练过程中选用Teacher BERT中每一层transformer layer的attention矩阵和输出作为监督信息 262 | 263 | 264 | ## 个人总结 265 | 266 | 上述的各项对BERT进行模型压缩的工作都在该领域取得一定的进展,例如参数效率都取得很好的成果,但每一项工作还是有的各种限制,例如训练与推断速度在多种场景下也是极其重要的,所幸的是,以上所介绍的方法并不完全互相冲突,在工业界应用中尝试将多种方法协同使用也是不错的选择。除此之外,上述工作的共有限制是由经验老道的作者针对BERT模型的各项缺点进行定向分析来提出模型压缩的办法,即以手动的启发式或者规则的方法,这种方式往往是次优的。那么能不能由机器去自动学习如何压缩和加速模型,这可以从AutoML等领域研究,我们期待并努力着。 267 | 268 | ## 参考 269 | 270 | 1. [关于BERT的模型压缩简介](https://zhuanlan.zhihu.com/p/110934513) 271 | -------------------------------------------------------------------------------- /bert_study/Bert_zip/readme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Bert_zip/readme.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/ChineseBert.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# ChineseBert" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 2, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "ename": "ModuleNotFoundError", 17 | "evalue": "No module named 'transformers.modeling_bert'", 18 | "output_type": "error", 19 | "traceback": [ 20 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 21 | "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", 22 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mfrom\u001b[0m \u001b[0mChineseBert\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmodels\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmodeling_glycebert\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mGlyceBertForMaskedLM\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 23 | "\u001b[1;32mF:\\document\\读书笔记\\自然语言处理\\nlp_paper_study\\bert_study\\Chinese\\ChineseBERT\\ChineseBert\\models\\modeling_glycebert.py\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 14\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mtorch\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mnn\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 15\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mtorch\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mnn\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mCrossEntropyLoss\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mMSELoss\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 16\u001b[1;33m \u001b[1;32mfrom\u001b[0m \u001b[0mtransformers\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmodeling_bert\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mBertEncoder\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mBertPooler\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mBertOnlyMLMHead\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mBertPreTrainedModel\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 17\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mtransformers\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmodeling_bert\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mBertModel\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 18\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mtransformers\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmodeling_outputs\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mBaseModelOutputWithPooling\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mMaskedLMOutput\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mSequenceClassifierOutput\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m\\\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 24 | "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'transformers.modeling_bert'" 25 | ] 26 | } 27 | ], 28 | "source": [ 29 | "from ChineseBert.models.modeling_glycebert import GlyceBertForMaskedLM" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "chinese_bert = GlyceBertForMaskedLM.from_pretrained(\"F:/document/datasets/nlpData/pretrain/ChineseBERT-base/\")" 39 | ] 40 | } 41 | ], 42 | "metadata": { 43 | "kernelspec": { 44 | "display_name": "Python 3", 45 | "language": "python", 46 | "name": "python3" 47 | }, 48 | "language_info": { 49 | "codemirror_mode": { 50 | "name": "ipython", 51 | "version": 3 52 | }, 53 | "file_extension": ".py", 54 | "mimetype": "text/x-python", 55 | "name": "python", 56 | "nbconvert_exporter": "python", 57 | "pygments_lexer": "ipython3", 58 | "version": "3.7.0" 59 | }, 60 | "toc": { 61 | "base_numbering": 1, 62 | "nav_menu": {}, 63 | "number_sections": true, 64 | "sideBar": true, 65 | "skip_h1_title": false, 66 | "title_cell": "Table of Contents", 67 | "title_sidebar": "Contents", 68 | "toc_cell": false, 69 | "toc_position": {}, 70 | "toc_section_display": true, 71 | "toc_window_display": false 72 | } 73 | }, 74 | "nbformat": 4, 75 | "nbformat_minor": 2 76 | } 77 | -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808214524.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808214524.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808221829.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808221829.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808222042.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808222042.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808222750.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808222750.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808225751.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808225751.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808225813.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808225813.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808225931.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808225931.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808230114.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808230114.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808230214.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808230214.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808230235.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808230235.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808230407.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808230407.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808230830.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808230830.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/img/微信截图_20210808230922.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/Chinese/ChineseBERT/img/微信截图_20210808230922.png -------------------------------------------------------------------------------- /bert_study/Chinese/ChineseBERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 ChineseBERT 】那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 论文名称:ChineseBERT: Chinese Pretraining Enhanced by Glyph and Pinyin Information 6 | > 7 | > 会议: ACL2021 8 | > 9 | > 论文地址:https://arxiv.org/abs/2106.16038 10 | > 11 | > 论文源码地址:https://github.com/ShannonAI/ChineseBert 12 | > 13 | > 模型下载:https://huggingface.co/hfl/chinese-bert-wwm-ext/tree/main 14 | > 15 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 16 | 17 | ## 一、摘要 18 | 19 | - 动机:最近的中文预训练模型忽略了中文特有的两个重要方面:字形和拼音,它们为语言理解携带重要的句法和语义信息。 20 | - 论文工作:提出了 ChineseBERT,它将汉字的 {\it glyph} 和 {\it pinyin} 信息合并到语言模型预训练中。 21 | - 字形嵌入是基于汉字的不同字体获得的,能够从视觉特征中捕捉字符语义; 22 | - 拼音嵌入表征汉字的发音,处理了汉语中非常普遍的异音现象(同一个字不同的读音,不同的意思)。 23 | - 实验结果:在大规模未标记的中文语料库上进行预训练,提出的 ChineseBERT 模型在训练步骤较少的情况下显着提高了基线模型的性能。 porpsoed 模型在广泛的中文 NLP 任务上实现了新的 SOTA 性能,包括机器阅读理解、自然语言推理、文本分类、句子对匹配和命名实体识别中的竞争性能。 24 | - 论文贡献: 25 | - 提出将汉字的字形与拼音信息融入到中文预训练模型中,增强模型对中文语料的建模能力; 26 | - 在中文机器阅读理解等 6 个任务上取得显著的效果提升,在小数据上取得更好的结果; 27 | - 开源 Base 版本与 Large 版本的预训练模型,供学界使用。 28 | 29 | ## 二、动机 30 | 31 | 1. 中文与英文不同,其包含 字形 和 拼音: 32 | 33 | - 字形:在 汉字中 字形 包含一些特殊的语义信息,而这些语义信息能够增强 中文自然语言处理任务模型的表达能力。 34 | 35 | > eg:“液”、“河”和“湖”都有“氵”,表示这些字符都与“水”的语义相关; 36 | 37 | - 拼音:利用 拼音 的 方式表示 汉字发音,在建模语义和语法信息是至关重要的; 38 | 39 | > 同样的汉字在不同的读音下,有着不同的涵义。例如: “乐”字,读“yuè”时表示音乐,读“lè” 时表示快乐;
40 | > 形近字发音类似。例如:“博” 和 “搏” 等; 41 | 42 | ## 三、方法介绍 43 | 44 | ### 3.1 模型整体架构介绍 45 | 46 | ![](img/微信截图_20210808214524.png) 47 | 48 | 1. embedding 层:将 字符嵌入(char embedding)、字形嵌入(glyph embedding)和拼音嵌入(pinyin embedding) 做拼接; 49 | 2. Fusion Layer 层:将 拼接后的 embedding 向量 做 Fusion 得到 一个 d 维的 Fusion embedding; 50 | 3. 位置拼接:将 Fusion embedding 和 位置嵌入(position embedding)、片段嵌入(segment embedding)相加; 51 | 4. Transformer-Encoder层 52 | 53 | ### 3.2 模型改进点介绍 54 | 55 | 1. 在底层的融合层(Fusion Layer)融合了除字嵌入(Char Embedding)之外的字形嵌入(Glyph Embedding)和拼音嵌入(Pinyin Embedding),得到融合嵌入(Fusion Embedding),再与位置嵌入相加,就形成模型的输入; 56 | 2. 抛弃预训练任务中的NSP任务。 由于预训练时没有使用NSP任务,因此模型结构图省略了片段嵌入(segment embedding)。实际上下游任务输入为多个段落时(例如:文本匹配、阅读理解等任务),是采用了segment embedding; 57 | 58 | ### 3.3 模型介绍 59 | 60 | #### 3.3.1 embedding 层介绍 61 | 62 | ##### 3.3.1.1 字形嵌入(Glyph Embedding) 63 | 64 | 字形嵌入使用不同字体的汉字图像得到。每个图像都是 24*24 的大小,将**仿宋、行楷和隶书这三种字体的图像向量化,拼接之后再经过一个全连接** ,就得到了汉字的字形嵌入。 65 | 66 | > 介绍图 67 | ![](img/微信截图_20210808221829.png) 68 | 69 | ##### 3.3.1.2 拼音嵌入(Pinyin Embedding) 70 | 71 | - 思路 72 | 73 | 1. 首先使用 pypinyin 将每个汉字的拼音转化为罗马化字的字符序列,其中也包含了音调。 74 | 75 | > eg:对汉字“猫”,其拼音字符序列就是“mao1”。对于多音字如“乐”,pypinyin能够非常准确地识别当前上下文中正确的拼音,因此ChineseBERT 直接使用 pypinyin 给出的结果。 76 | 77 | 2. 在获取汉字的拼音序列后,再对该序列使用宽度为 2 的 CNN 与最大池化,得到最终的拼音序列。 78 | 79 | ![](img/微信截图_20210808222042.png) 80 | 81 | 82 | > 注意:每个字符的拼音序列长度固定为8,当不满足长度时,使用“-”进行padding。 83 | 84 | ##### 3.3.1.3 字嵌入(Char Embedding) 85 | 86 | 字嵌入(Char Embedding) 与原始BERT模型中的token embedding一致,仅在字符粒度上进行embedding。 87 | 88 | #### 3.3.2 Fusion Layer 层 89 | 90 | - 思路 91 | 92 | 1. 将字符对应的字符嵌入、符号嵌入和拼音嵌入拼接起来; 93 | 2. 然后通过一个全连接层,最终得到融合嵌入。 94 | 95 | ![](img/微信截图_20210808222750.png) 96 | 97 | #### 3.3.3 Pretraining 预训练 98 | 99 | ##### 3.3.3.1 数据来源 100 | 101 | 预训练数据来自 [CommonCrawl](https://commoncrawl.org/),在经过数据清洗后,用于预训练 ChineseBERT 的数据规模为约 4B 个汉字。我们使用 LTP toolkit 识别词的边界。 102 | 103 | ##### 3.3.3.2 Masking 操作 104 | 105 | 预训练的一大关键步骤是确定如何掩码(Masking)输入文本。ChineseBERT 综合使用两种掩码策略:全词掩码(Whole Word Masking, WWM)与字掩码(Char Masking, CM)。 106 | 107 | - 字掩码(Char Masking, CM):最简洁最直观的掩码方法,以单个汉字为单位进行掩码。 108 | - 全词掩码(Whole Word Masking, WWM):以词为单位,将词中的所有字掩码。注意基本的输入单元依然是字,只是一个词包含的所有汉字都被掩码。比如,“我喜欢紫禁城”在掩码词“紫禁城”之后就是“我喜欢[M][M][M]”,而非“我喜欢[M]”。 109 | 110 | 使用两种掩码方式易于模型从不同的角度融合字、字形、拼音及上下文信息。 111 | 112 | ##### 3.3.3.3 预训练细节 113 | 114 | 由于 ChineseBERT 结构与原始 BERT 在输入层的结构不同,所以 ChineseBERT 从头开始预训练而不用 BERT 初始化。 115 | 116 | 为了习得短期上下文与长期上下文,ChineseBERT 在 Packed Input 与 Single Input 之间交替训练: 117 | 118 | - Packed Input 是将模型的输入扩展到最大长度 512,作为输入的概率为 0.9; 119 | - Single Input 则将单个句子作为输入,Single Input 作为输入的概率是 0.1。 120 | 121 | 无论是 Packed Input 还是 Single Input,都在 90% 的时间使用 WWM,在 10% 的时间使用 CM。除此之外,ChineseBERT 还使用了动态掩码策略,避免重复的预训练语料。 122 | 123 | > Base与Large模型的层数与原始BERT一致,分别是12层和24层,输入维度和头数分别为768/12和1024/16。Base模型训练了500K步,学习率为1e-4,warmup步数为20k,batch大小为3.2K。Base模型训练280K步,学习率为3e-4,warmup步数为90k,batch大小为8K。 124 | 125 | ## 四、实验结果 126 | 127 | ### 4.1 机器阅读理解 128 | 129 | 数据集介绍: 130 | 131 | - CMRC 2018 是抽取式机器阅读理解任务; 132 | - CJRC 则额外包含了“无答案”问题。 133 | 134 | ![](img/微信截图_20210808225751.png) 135 | 136 | ![](img/微信截图_20210808225813.png) 137 | 138 | ### 4.2 自然语言推理 139 | 140 | > 自然语言推理数据集为 XNLI,包含了 2.5K 的验证数据和 5K 的测试数据 141 | 142 | ![](img/微信截图_20210808225931.png) 143 | 144 | ### 4.3 文本分类 145 | 146 | 文本分类数据集: 147 | 148 | - THUC-News; 149 | - ChnSentiCorp; 150 | - TNEWS 151 | 152 | > 前两个数据集较为简单,即使是 vanilla BERT 模型都能取得超过 95% 的准确率,而 TNEW 数据集则是一个 15 类短文本新闻分类数据集,难度更大。 153 | 154 | ![](img/微信截图_20210808230114.png) 155 | 156 | ### 4.4 句对匹配 157 | 158 | 句对匹配数据集: 159 | 160 | - LCQMC 161 | - BQ Corpus, 162 | 163 | 每条数据给出两个句子,需要判断它们是否有语义相关性。 164 | 165 | ![](img/微信截图_20210808230214.png) 166 | 167 | ### 4.5 命名实体识别 168 | 169 | 命名实体识别数据集: 170 | 171 | - OntoNotes 4.0 包括 18 种实体类别 172 | - Weibo。包括 4 种实体类别。 173 | 174 | ![](img/微信截图_20210808230235.png) 175 | 176 | ### 4.6 中文分词 177 | 178 | 中文分词数据集: 179 | 180 | - MSRA 181 | - PKU 182 | 183 | ![](img/微信截图_20210808230407.png) 184 | 185 | ## 五、Ablation Studies 186 | 187 | ### 5.1 The Effect of Glyph Embeddings andPinyin Embeddings 188 | 189 | 首先我们探究字形嵌入和拼音嵌入是否对下游任务有效。我们在命名实体识别数据集 OntoNotes 4.0 上实验。我们分别去掉字形嵌入、拼音嵌入以及二者,检验它们在测试集上的效果。 190 | 191 | 结果如下表所示。可以看到,不管是移除字形嵌入还是拼音嵌入,都会严重损害模型效果:移除字形嵌入使 F1 值降低 1.52,移除拼音嵌入使模型 F1 值下降 1.17,而移除两者导致模型 F1 值下降 1.89。以上结果表明了,字形嵌入和拼音嵌入具备一定的信息增益效果。 192 | 193 | ![](img/微信截图_20210808230830.png) 194 | 195 | ### 5.2 The Effect of Training Data Size 196 | 197 | 因为引入了字形与拼音信息,我们猜测在更小的下游任务训练数据上,ChineseBERT 能有更好的效果。为此,我们随机从 OntoNotes 4.0 训练集中随机选择 10%~90% 的训练数据,并保持其中有实体的数据与无实体的数据的比例。 198 | 199 | 结果如下表所示。ChineseBERT 在小数据下的确具有更好的效果,尤其是当训练数据 >30% 时,ChineseBERT 的效果提升更加显著。这是因为,好的字形嵌入和拼音嵌入需要一定的训练数据才能习得,不充分的训练数据会使这二者不能得到充分训练。 200 | 201 | ![](img/微信截图_20210808230922.png) 202 | 203 | 204 | ## 参考 205 | 206 | 1. [ChineseBERT: Chinese Pretraining Enhanced by Glyph and Pinyin Information](https://arxiv.org/abs/2106.16038) 207 | 2. [ChineseBert github](https://github.com/ShannonAI/ChineseBert) 208 | 3. [ACL 2021 | ChineseBERT:香侬科技提出融合字形与拼音信息的中文预训练模型](https://tianguoguo.fun/2021/07/10/ACL-2021-ChineseBERT-香侬科技提出融合字形与拼音信息的中文预训练模型/) 209 | 4. [ACL2021论文之ChineseBERT:融合字形与拼音信息的中文预训练模型](https://zhuanlan.zhihu.com/p/393617564) 210 | 211 | 212 | -------------------------------------------------------------------------------- /bert_study/ELECTRA/document.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/document.pdf -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015170627.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015170627.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015192142.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015192142.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015192526.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015192526.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015193303.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015193303.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015193420.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015193420.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015193507.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015193507.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/img/20201015194517.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELECTRA/img/20201015194517.png -------------------------------------------------------------------------------- /bert_study/ELECTRA/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 ELECTRA 】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 个人github:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 论文链接:https://openreview.net/pdf?id=r1xMH1BtvB 8 | > 9 | > 代码链接:https://github.com/google-research/bert 10 | > 11 | > 【注:手机阅读可能图片打不开!!!】 12 | 13 | ## 目录 14 | 15 | - [【关于 ELECTRA 】 那些的你不知道的事](#关于-electra--那些的你不知道的事) 16 | - [目录](#目录) 17 | - [摘要](#摘要) 18 | - [动机](#动机) 19 | - [核心任务](#核心任务) 20 | - [判别器 & 生成器](#判别器--生成器) 21 | - [算法流程](#算法流程) 22 | - [Electra 与 GAN 不同 的原因](#electra-与-gan-不同-的原因) 23 | - [具体介绍](#具体介绍) 24 | - [参考](#参考) 25 | 26 | ## 摘要 27 | 28 | Masked language modeling (MLM) pre-training methods such as BERT corruptthe input by replacing some tokens with[MASK]and then train a model to re-construct the original tokens. 29 | 诸如BERT之类的掩码语言建模(MLM)预训练方法通过用[MASK]替换一些标记来破坏输入,然后训练模型以重建原始标记。 30 | 31 | While they produce good results when transferredto downstream NLP tasks, they generally require large amounts of compute to beeffective. As an alternative, we propose a more sample-efficient pre-training taskcalled replaced token detection. 32 | 虽然它们在转移到下游NLP任务时会产生良好的结果,但是它们通常需要大量计算才能有效。 33 | 34 | Instead of masking the input, our approach corrupts it by replacing some tokens with plausible alternatives sampled from a small generator network. Then, instead of training a model that predicts the original identities of the corrupted tokens, we train a discriminative model that predicts whether each token in the corrupted input was replaced by a generator sampleor not. 35 | 作为替代方案,我们提出了一种更有效的样本预训练任务,称为替换令牌检测。我们的方法不是掩盖输入,而是通过使用从 small generator network 采样的合理替代物替换一些令牌来破坏输入。然后,我们训练一个判别模型,该模型预测损坏的输入中的每个标记是否被生成器采样器代替,而不是训练一个预测损坏的令牌的原始身份的模型。 36 | 37 | Thorough experiments demonstrate this new pre-training task is more ef-ficient than MLM because the task is defined over alli nput tokens rather than just the small subset that was masked out. As a result, the contextual representations learned by our approach substantially outperform the ones learned by BERT given the same model size, data, and compute. The gains are particularly strongfor small models; for example, we train a model on one GPU for 4 days that outperforms GPT (trained using 30x more compute) on the GLUE natural lan-guage understanding benchmark. Our approach also works well at scale, where itperforms comparably to RoBERTa and XLNet while using less than 1/4 of their compute and outperforms them when using the same amount of compute. 38 | 全面的实验表明,这种新的预训练任务比MLM更有效,因为该任务是定义为整体输入标记,而不是仅被掩盖的较小子集。结果,在模型大小,数据和计算相同的情况下,我们的方法所学习的上下文表示大大优于BERT所学习的上下文表示。小型机型的收益尤为明显。例如,我们在一个GPU上训练了4天的模型,该模型在GLUE自然语言理解基准上胜过GPT(使用30倍的计算能力进行训练)。我们的方法在规模上也行之有效,在使用少于1/4的计算时,其性能与RoBERTa和XLNet相当,而在使用相同数量的计算时,其性能则优于RoBERTa和XLNet。 39 | 40 | ## 动机 41 | 42 | 在训练Bert的时候,在输入上操作把15%的词语给替换成Mask,然后这其中有80%是Mask,有10%是替换成其他词语,最后剩下10%保持原来的词语。 43 | 44 | 可以看到,Bert的训练中,每次相当于只有15%的输入上是会有loss的,而其他位置是没有的,这就导致了每一步的训练并没有被完全利用上,导致了训练速度慢。换句话说,就是模型只学习到 15%的 token 信息; 45 | 46 | ## 核心任务 47 | 48 | - 核心:将生成式的Masked language model(MLM)预训练任务改成了判别式的Replaced token detection(RTD)任务,判断当前token是否被语言模型替换过; 49 | - 思路:利用一个基于MLM的Generator来替换example中的某些个token,然后丢给Discriminator来判别 50 | 51 | ## 判别器 & 生成器 52 | 53 | 如下图所示,首先会训练一个生成器来生成假样本,然后Electra去判断每个token是不是被替换了。 54 | 55 | ![](img/20201015170627.png) 56 | 57 | ### 算法流程 58 | 59 | 1. Generator G: 60 | 1. 输入经过随机选择设置为[MASK]; 61 | 2. 输入给 G,G 负责把[MASK]变成替换过的词; 62 | 2. Discriminator D: 63 | 1. 预测 输入的句子 每个位置上的词语是否被替换过; 64 | 65 | > 注:
66 | > 1. Discriminator是训练完之后我们得到的预训练模型,Generator在训练完之后就没有用了 67 | 68 | ### Electra 与 GAN 不同 的原因 69 | 70 | ![](img/20201015194517.png) 71 | 72 | 1. D 的 loss 没有反向传播到 G:Generator并不像对抗神经网络那样需要等Discriminator中传回来的梯度,而是像Bert一样那样去尝试预测正确的词语,从而计算损失(Electra不是GAN的根本原因); 73 | 2. 如果 G 生成的 sample 是原始的 token,这个 token 将被看作 “real” 而不是 “fake”; 74 | 3. G 用极大似然法训练而不是对抗方法去迷惑 D 75 | 4. G 的 input 不是 GAN 中的噪声向量 76 | 77 | ### 具体介绍 78 | 79 | - 训练 两个 网络: 生成器 G 和 判别器 D,均包含了一个 Transformer 的 encoder(将 input 的序列表示成隐向量表示) 80 | - 生成器 G:给定位置 t,G 接 softmax 生成 xt: 81 | 82 | ![](img/20201015192142.png) 83 | 84 | > e 表示 token embedding 85 | 86 | - 判别器 D:对给定位置 t,D 判断 xt 来自 G 还是原始的数据分布: 87 | 88 | ![](img/20201015192526.png) 89 | 90 | - G 用来执行 MLM,给定输入序列 X(x1…xn),首先随机选择一组(15%)mask 的位置,这些位置的 token 被替换为 [MASK],G 要学习最大化 masked-out tokens 的似然,D 要区分被 G 生成的 sample 替换的 token。具体而言,通过替换 masked-out tokens 为 generator samples 创建损坏的 X 序列,然后训练判别器来识别 X 中的 tokens 和原始的 input 序列是否匹配: 91 | 92 | ![](img/20201015193303.png) 93 | 94 | - 损失函数 95 | 96 | ![](img/20201015193420.png) 97 | 98 | ![](img/20201015193507.png) 99 | 100 | ## 参考 101 | 102 | 1. [ELECTRA 论文笔记](https://yam.gift/2019/12/08/Paper/2019-12-08-ELECTRA-Paper/) 103 | 2. [Electra: 判别还是生成,这是一个选择](https://wemp.app/posts/54be8907-4c1e-4583-9219-0b2474ea3a29) 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /bert_study/ELMo Deep contextualized word representations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/ELMo Deep contextualized word representations.pdf -------------------------------------------------------------------------------- /bert_study/FastBERT/FastBERT.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FastBERT/FastBERT.pdf -------------------------------------------------------------------------------- /bert_study/FastBERT/img/20200731202558.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FastBERT/img/20200731202558.png -------------------------------------------------------------------------------- /bert_study/FastBERT/img/20200731202733.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FastBERT/img/20200731202733.png -------------------------------------------------------------------------------- /bert_study/FastBERT/img/20200731203505.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FastBERT/img/20200731203505.png -------------------------------------------------------------------------------- /bert_study/FastBERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 FastBERT】 那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 论文地址:https://arxiv.org/abs/2004.02178 5 | > github:https://github.com/autoliuweijie/FastBERT 6 | 7 | ## 目录 8 | 9 | - [【关于 FastBERT】 那些你不知道的事](#关于-fastbert-那些你不知道的事) 10 | - [目录](#目录) 11 | - [背景](#背景) 12 | - [动机](#动机) 13 | - [模型介绍](#模型介绍) 14 | - [模型训练与推理](#模型训练与推理) 15 | - [总结](#总结) 16 | - [参考](#参考) 17 | 18 | ## 背景 19 | 20 | 自从BERT问世以来,大多数NLP任务的效果都有了一次质的飞跃。BERT Large在GLUE test上甚至提升了7个点之多。但BERT同时也开启了模型的“做大做深”之路,普通玩家根本训不起,高端玩家虽然训得起但也不一定用得起。 21 | 22 | ## 动机 23 | 24 | - 计算资源 占用问题,eg:BERT Large、GPT2、Megatron-LM...; 25 | - BERT 瘦身来提升速度 26 | - trick: 27 | - 剪枝:剪掉多余的连接、多余的注意力头、甚至LayerDrop[1]直接砍掉一半Transformer层 28 | - 量化:把FP32改成FP16或者INT8; 29 | - 蒸馏:用一个学生模型来学习大模型的知识,不仅要学logits,还要学attention score; 30 | - 问题: 31 | - 精度的下降 32 | - 剪枝会直接降低模型的拟合能力; 33 | - 量化虽然有提升但也有瓶颈; 34 | - 蒸馏的不确定性最大,很难预知你的BERT教出来怎样的学生; 35 | 36 | ## 模型介绍 37 | 38 | - 思路: 39 | - 样本自适应机制(Sample-wise adaptive mechanism) 40 | - 思路: 41 | - 在每层Transformer后都去预测样本标签,如果某样本预测结果的置信度很高,就不用继续计算了,就是自适应调整每个样本的计算量,容易的样本通过一两层就可以预测出来,较难的样本则需要走完全程。 42 | - 操作: 43 | - 给每层后面接一个分类器,毕竟分类器比Transformer需要的成本小多了 44 | 45 | ![](img/20200731202558.png) 46 | 47 | - 模型结构 48 | 49 | ![](img/20200731202733.png) 50 | 51 | > 原BERT模型称为主干(Backbone); 52 | > 每个分类器称为分支(Branch) 53 | 54 | - 自蒸馏(Self-distillation) 55 | - 思路: 56 | - 在预训练和精调阶段都只更新主干参数; 57 | - 精调完后freeze主干参数,用分支分类器(图中的student)蒸馏主干分类器(图中的teacher)的概率分布 58 | - 优点: 59 | - 非蒸馏的结果没有蒸馏要好 60 | - 不再依赖于标注数据。蒸馏的效果可以通过源源不断的无标签数据来提升 61 | 62 | ## 模型训练与推理 63 | 64 | 了解模型结构之后,训练与推理也就很自然了。只比普通的BERT模型多了自蒸馏这个步骤: 65 | 66 | 1. Pre-training:同BERT系模型是一样的,网上那么多开源的模型也可以随意拿来~ 67 | 2. Fine-tuning for Backbone:主干精调,也就是给BERT最后一层加上分类器,用任务数据训练,这里也用不到分支分类器,可以尽情地优化 68 | 3. Self-distillation for branch:分支自蒸馏,用无标签任务数据就可以,将主干分类器预测的概率分布蒸馏给分支分类器。这里使用KL散度衡量分布距离,loss是所有分支分类器与主干分类器的KL散度之和 69 | 4. Adaptive inference:自适应推理,及根据分支分类器的结果对样本进行层层过滤,简单的直接给结果,困难的继续预测。这里作者定义了新的不确定性指标,用预测结果的熵来衡量,熵越大则不确定性越大: 70 | 71 | ![](img/20200731203505.png) 72 | 73 | ## 总结 74 | 75 | FastBERT是一个在工程上十分实用的模型,通过提前输出简单样本的预测结果,减少模型的计算负担,从而提高推理速度。虽然每层都多了一个分类器,但分类器的计算量也比Transformer小了两个数量级,对速度影响较小。后续的分支自蒸馏也设计的比较巧妙,可以利用无监督数据不断提升分支分类器的效果。 76 | 77 | 另外,Sample-wise adaptive mechanism和Self-distillation这两个idea也是在本文首次提出,相信会起到抛玉引玉的作用,衍生更多此类工作。论文本身也还有一些想象空间,比如分别优化每层分类器,因为在主干被freeze的情况下各个分支是独立的;或者自蒸馏后unfreeze主干,再加上有标签数据自蒸馏一把,说不定还会有性能提升。 78 | 79 | 80 | ## 参考 81 | 82 | 1. [FastBERT:又快又稳的推理提速方法](https://zhuanlan.zhihu.com/p/127869267) 83 | 2. [ACL2020论文阅读笔记-FastBERT: a Self-distilling BERT with Adaptive Inference Time](https://blog.csdn.net/ljp1919/article/details/107578008) -------------------------------------------------------------------------------- /bert_study/FlanT5/img/20230228075007.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/20230228075007.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/20230228075443.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/20230228075443.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/20230228075718.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/20230228075718.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/20230228080041.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/20230228080041.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/20230228080124.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/20230228080124.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/20230228080222.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/20230228080222.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/微信截图_20230228080254.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/微信截图_20230228080254.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/微信截图_20230228080323.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/微信截图_20230228080323.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/微信截图_20230228080347.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/微信截图_20230228080347.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/微信截图_20230228080407.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/微信截图_20230228080407.png -------------------------------------------------------------------------------- /bert_study/FlanT5/img/微信截图_20230228080427.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/FlanT5/img/微信截图_20230228080427.png -------------------------------------------------------------------------------- /bert_study/FlanT5/readme.md: -------------------------------------------------------------------------------- 1 | # Flan-T5: One Model for ALL Tasks 2 | 3 | > 论文:Scaling Instruction-Finetuned Language Models 4 | > 5 | > 论文地址:https://arxiv.org/abs/2210.11416 6 | > 7 | > 公开模型:https://huggingface.co/google/flan-t5-xxl 8 | > 9 | > 作者:杨夕 10 | > 11 | > NLP论文学习笔记 地址:https://github.com/km1994/nlp_paper_study 12 | > 13 | > 推荐系统论文学习笔记 地址: https://github.com/km1994/RS_paper_study 14 | > 15 | > GCN论文学习笔记 地址 https://github.com/km1994/GCN_study 16 | > 17 | > NLP 百面百搭地址:https://github.com/km1994/NLP-Interview-Notes 18 | > 19 | > 推荐系统 百面百搭地址:https://github.com/km1994/RES-Interview-Notes 20 | > 21 | > 推广搜 军火库地址: https://github.com/km1994/recommendation_advertisement_search 22 | 23 | ## 一、动机 24 | 25 | 目前,NLP任务百花齐放,各式各样,学习起来不知所措,特别是用于工程部署,一个任务需要训练一个模型,这不仅导致 开发者后期很难维护,同时需要硬件资源变得非常庞大。 26 | 27 | 那么,是否有这种方案:通过在超大规模的任务上进行微调,让语言模型具备了极强的泛化性能,做到单个模型就可以在1800多个NLP任务上都能有很好的表现呢?即 实现 **One model for ALL tasks**? 28 | 29 | 近日,来自谷歌的研究者分析了多种指令微调方法,包括扩展对指令微调的影响。实验表明,指令微调确实可以根据任务数量和模型大小实现良好的扩展,最大到 5400 亿参数的模型都能明显受益,未来的研究应该进一步扩大任务的数量和模型的大小。此外,该研究还分析了微调对模型执行推理能力的影响,结果都是很吸引人的。 30 | 31 | 由此产生的 Flan-T5 对 1800 余种语言任务进行了指令微调,明显提高了提示和多步推理能力,30 亿参数跑基准就能超过 GPT-3 的 1750 亿参数。 32 | 33 | ## 二、什么是 Flan-T5 34 | 35 | 这里的Flan 指的是(Instruction finetuning ),即"基于指令的微调";T5是2019年Google发布的一个语言模型了。注意这里的语言模型可以进行任意的替换(需要有Decoder部分,所以不包括BERT这类纯Encoder语言模型),论文的核心贡献是提出一套多任务的微调方案(Flan),来极大提升语言模型的泛化性。 36 | 37 | ![](img/20230228075007.png) 38 | 39 | > 例如下面文章中的例子,模型训练好之后,可直接让模型做问答 40 | > 41 | > 模型输入是:"Geoffrey Hinton和George Washington这两个人有没有交谈过?在回答之前想一想原因。“ 42 | > 43 | > 模型返回是:Geoffrey Hinton是一个计算机科学家,出生在1947年;而George Washington在1799年去世。所以这两个不可能有过交谈。所以答案时“没有”。 44 | 45 | ## 三、 Flan-T5 实现机制 46 | 47 | ![](img/20230228075443.png) 48 | > 1800+微调任务 49 | 50 | 1. step 1: 任务收集:收集一系列监督的数据,这里一个任务可以被定义成<数据集,任务类型的形式>,比如“基于SQuAD数据集的问题生成任务”。需要注意的是这里有9个任务是需要进行推理的任务,即Chain-of-thought (CoT)任务。 51 | 2. step 2: 形式改写:因为需要用单个语言模型来完成超过1800+种不同的任务,所以需要将任务都转换成相同的“输入格式”喂给模型训练,同时这些任务的输出也需要是统一的“输出格式”。 52 | 53 | ![](img/20230228075718.png) 54 | > 根据 “是否需要进行推理 (CoT)” 以及 “是否需要提供示例(Few-shot)” 55 | 56 | 可将输入输出划分成四种类型: 57 | 58 | - chain-of-thought : ❎ and few-shot: ❎ (图中左上) 59 | - 输入:指令 + 问题 60 | - 输出:答案 61 | - chain-of-thought : ✅ and few-shot: ❎ (图中右上) 62 | - 输入:指令 + CoT引导(by reasoning step by step) + 问题 63 | - 输出:理由 + 答案 64 | - chain-of-thought: ❎ and few-shot: ✅ (图中左下) 65 | - 输入:指令 + 示例问题 + 示例问题回答 + 指令 + 问题 66 | - 输出:答案 67 | - chain-of-thought: ✅ and few-shot: ✅(图中右下) 68 | - 输入:指令 + CoT引导 + 示例问题 + 示例问题理由 + 示例问题回答 + 指令 + CoT引导 + 问题 69 | - 输出:理由 + 答案 70 | 71 | 3. 训练过程:采用恒定的学习率以及Adafactor优化器进行训练;同时会将多个训练样本“打包”成一个训练样本,这些训练样本直接会通过一个特殊的“结束token”进行分割。训练时候在每个指定的步数会在“保留任务”上进行模型评估,保存最佳的checkpoint。 72 | 73 | ![](img/20230228080041.png) 74 | 75 | 尽管微调的任务数量很多,但是相比于语言模型本身的预训练过程,计算量小了非常多,只有0.2%。所以通过这个方案,大公司训练好的语言模型可以被再次有效的利用,我们只需要做好“微调”即可,不用重复耗费大量计算资源再去训一个语言模型。 76 | 77 | ![](img/20230228080124.png) 78 | 79 | ## 四、 Flan-T5 总结 80 | 81 | 1. 微调很重要 82 | 83 | ![](img/20230228080222.png) 84 | 85 | 与不微调相比,通过基于指令的微调(flan)可以大幅度提高语言模型的效果 86 | 87 | 2. 模型越大效果越好 88 | 89 | ![](img/微信截图_20230228080254.png) 90 | 91 | 3. 任务越多效果越好 92 | 93 | 伴随任务数量的增加(上图右),模型的性能也会跟着增加,但是当任务数量超过282个之后,提升就不是很明显了。因为继续增加新的任务,尤其任务形式跟之前一样,不会给模型带来新的知识;多任务微调的本质是模型能够更好的把从预训练学到的知识进行表达,超过一定任务之后,继续新增相似的任务,知识的表达能力不会继续有很大的收益。进一步统计全部微调数据集的token数,发现只占到了预训练数据token数的0.2%,这表明还是有很多的知识没有在微调阶段重新被激发。 94 | 95 | 4. 混杂CoT相关的任务很重要 96 | 97 | ![](img/微信截图_20230228080323.png) 98 | 99 | 尽管在1800多个任务中只有9个需要推理再给出回答的任务(CoT任务),但是混杂了这9个任务之后对整个模型的提升很大。在针对CoT相关任务的预测上,如果在微调中混淆CoT任务能带来明显的提升(左图中蓝色和绿色线);在针对非CoT相关任务的预测上,如果在微调中混淆了CoT任务也不会对模型带来伤害(右图中蓝色和绿色线)。 100 | 101 | ![](img/微信截图_20230228080347.png) 102 | 103 | 另外对于Zero-Shot的任务,微调中混淆CoT任务也能有明显的提升。 104 | 105 | ![](img/微信截图_20230228080407.png) 106 | 107 | 5. 整合起来 108 | 109 | 最终在多个不同尺寸的模型上进行实验,都可以获得一致性的结论:引入Flan微调方案,可以很好提高语言模型在超大规模任务上的整体效果。 110 | 111 | ![](img/微信截图_20230228080427.png) 112 | 113 | 总结一下,这篇工作提出了Flan的微调框架,核心有四点:统一的输入输出格式(4种类型),引入chain-of-thought,大幅提高任务数量,大幅提高模型体积;实现了用一个模型来解决超过1800种几乎全部的NLP任务,通过较低的成本,极大发掘了现有语言模型的泛化性能,让大家看到了通用模型的希望,即One Model for ALL Tasks。 114 | 115 | ## 参考 116 | 117 | 1. [Flan-T5: One Model for ALL Tasks (作者:nghuyong)](https://zhuanlan.zhihu.com/p/580468546) 118 | 2. [谷歌Flan-T5诞生!1800种语言任务超大规模微调](https://blog.csdn.net/xixiaoyaoww/article/details/127524968) 119 | 3. [Flan-PaLM&T5](https://mdnice.com/writing/522c525b7e214ccba7deba664a20dc37) -------------------------------------------------------------------------------- /bert_study/LLMs.md: -------------------------------------------------------------------------------- 1 | # LLMs 2 | 3 | ## 一、模型一览 4 | 5 | ![](img/20230321223629.png) 6 | 7 | ## LLaMA 8 | 9 | - 论文名称:LLaMA: Open and Efficient Foundation Language Models 10 | - 作者:Meta/Facebook AI 11 | - 论文地址:https://arxiv.org/pdf/2302.13971v1.pdf 12 | - 论文github:https://github.com/facebookresearch/llama 13 | - 时间:2023.02.27 14 | - 论文介绍:介绍了一系列公开发布的语言模型,这些模型与最先进的基础模型具有竞争力。最值得注意的是,LLaMA-13B比GPT-3小10倍以上,并且LLaMA-65B与Chinchilla-70B和PaLM-540B具有竞争力。与之前的研究不同,通过仅在公开可用数据上进行训练,而无需使用专有数据集,就可以实现最先进的性能。向研究界发布这些模型将加速大型语言模型的开发,并有助于提高其鲁棒性,缓解毒性和偏见等已知问题。此外,像Chung等人(2022)一样观察到,根据指令微调这些模型会产生有希望的结果,计划在未来的工作中进一步研究这一点。最后,计划在未来发布在更大的预训练语料库上训练的更大模型,因为在扩展时看到了性能的不断提高。 15 | 16 | ## OPT 17 | 18 | - 论文名称:OPT: Open Pre-trained Transformer Language Models 19 | - 作者:Meta/Facebook AI 20 | - 论文地址:https://arxiv.org/pdf/2205.01068.pdf 21 | - 论文github:https://github.com/facebookresearch/metaseq 22 | - 时间: 23 | - 论文介绍:介绍了 OPT,这是一个自回归语言模型的集合,参数大小从 125M 到 175B 不等。 我们的目标是复制 GPT-3 类模型的性能和大小,同时在数据管理和训练效率方面应用最新的最佳实践。 我们描述了训练细节,评估了许多 NLP 和对话设置中的表现,并描述了关于偏见、毒性和仇恨言论的行为。 我们还描述了模型的许多其他限制,并讨论了负责任地发布模型的一系列广泛考虑因素。 我们相信整个 AI 社区将从共同努力为负责任的 LLM 制定指南中受益,我们希望广泛使用这些类型的模型将增加定义此类技术的伦理考虑的声音的多样性。 24 | - 论文结论: 25 | - 结构:基于Transformers的模型结构,进行堆叠; 26 | - 模型大小:从125M 到 175B,大致匹配 GPT-3 类模型的性能和大小; 27 | - 训练语料:主要包含英语文本,存在少量非英语数据; 28 | - 数据量:GPT-2 BPE tokenizer,大约 180B 个tokens; 29 | - 训练效率:仅为GPT-3训练所需计算量的1/7; 30 | - 性能评估avg. accuracy: 31 | - Zero-shot: 与GPT-3 模型的表现相似,有些任务表现出高度不稳定 32 | - Multishot-shot: 大多数任务的性能与 GPT-3 大致相似,一些任务表现出不稳定的行为 33 | - 能力:诗歌生成,对话生成,few-shot翻译, 论文写作,算术,Python 编程。 34 | 35 | ## T5 36 | 37 | - 论文名称:T5: Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer 38 | - 作者:Google 39 | - 论文地址:https://arxiv.org/pdf/1910.10683.pdf 40 | - 论文github:https://github.com/google-research/text-to-text-transfer-transformer 41 | - 时间: 42 | - 论文介绍:介引入一个统一的自然语言处理迁移框架,该框架将所有的自然言语处理任务统一为text-to-text形式。本文系统研究比较了 预训练目标、系统架构、未标记数据集和迁移方法等其他因素对数十个自然语言理解任务的影响。本文其实并没有引入新的模型或者新的方法,而是将现有的方法和技术做一次集大成,进行统一。此外,本文还引入一个新的数据集:Colossal Clean Crawled Corpus,名为C4。该数据集引入的初衷是为了探索尺度规模(包括模型规模和数据规模)在NLP中的影响。本文最终在文本摘要、问答、文本分类等多个基准任务上取得SOTA结果。 43 | - 任务:机器翻译、问答、生成式摘要、文本分类(单句&双句) 44 | - 数据格式: 45 | - 输入:参考GPT2,直接把任务名称当作prefix和输入拼在一起 46 | - 输出:分类任务(如推断),需要输出"entailment", "neutral", "contradiction"这三种文本,否则都算错;回归任务输出str类型的浮点数。还有其他任务, 47 | - 训练 48 | - 预训练 49 | - 参考SpanBERT,mask掉15%,平均长度为3的span 50 | - 训练更长步数,1百万步*1024个样本 51 | - 使用Multi-task预训练,即混入在无监督数据中混入一定比例的任务数据 52 | - 精调 53 | - 也是Multi-task,将所有GLUE/SuperGLUE的数据拼在一起变成精调一个task,减少过拟合,但同时也会牺牲一些精度 54 | - batch size减小到8 55 | - 其实最后同时进行了多任务精调和单独精调,根据dev集选择最好的结果 56 | - 解码 57 | - 大部分使用Greedy decoding,对于输出句子较长的任务使用beam search 58 | 59 | ## mT5 60 | 61 | - 论文名称:mT5: A Massively Multilingual Pre-trained Text-to-Text Transformer 62 | - 作者:Google 63 | - 论文地址:https://arxiv.org/pdf/2010.11934.pdf 64 | - 论文github:https://huggingface.co/models?search=mt5 65 | - 时间:2021 66 | - 论文介绍:最近的“文本到文本传输转换器”(T5)利用统一的文本到文本格式和规模,在各种英语NLP任务上获得了最先进的结果。在本文中,我们介绍了 mT5,这是 T5 的多语言变体,它是在涵盖 101 种语言的基于 Common Crawl 的新数据集上预先训练的。我们详细介绍了mT5的设计和修改训练,并在许多多语言基准测试中展示了其最先进的性能。我们还描述了一种简单的技术,以防止在零镜头设置中“意外翻译”,其中生成模型选择(部分)将其预测翻译成错误的语言。这项工作中使用的所有代码和模型检查点都是公开的。 67 | 68 | ## UL2 and Flan-UL2 69 | 70 | - 论文名称:UL2 and Flan-UL2: Unifying Language Learning Paradigms 71 | - 作者:Google 72 | - 论文地址:https://arxiv.org/pdf/2205.05131.pdf 73 | - blog:https://www.yitay.net/blog/flan-ul2-20b 74 | - 论文github: 75 | - https://huggingface.co/google/ul2 76 | - https://huggingface.co/google/flan-ul2 77 | - 时间:2021 78 | - 论文介绍: 79 | - 1、提出了一种新的降噪器混合 (MoD) 预训练,它将多个预训练任务混合。 80 | - 2、引入了模式切换,一种将下游任务行为与上游预训练相关联的方法。 81 | - 论文效果:UL2 在大多数的有监督和少样本任务上始终优于 GPT 类模型和T5模型,在9个任务上优于 T5,归一化后的整体增益提升76.1%。最后,UL2 扩展到20B参数,并在60 个 NLP 任务进行了多样化的实验。结果表明,UL2 在其中的 50 个下游任务上都实现了SOTA的性能。 82 | 83 | ## PaLM 84 | 85 | - 论文名称:PaLM: Scaling Language Modeling with Pathways 86 | - 作者:Google 87 | - 论文地址:https://arxiv.org/pdf/2204.02311.pdf 88 | - 论文github: 89 | - 时间:2022 90 | - 论文动机: 91 | - 近些年,超大型神经网络在语言理解和生成的广泛任务上实现了令人惊讶的效果。这些模型通常是在大规模文本语料上,使用填充式的预训练目标和encoder-only或者encoder-decoder架构进行训练,然后通过微调来适应下游的具体任务。虽然这些模型在数千个自然语言任务上实现了state of the art,但缺点是其需要大量任务相关的训练样本来微调模型。此外,至少有一部分参数需要更新来拟合任务,这增加了模型训练和部署的复杂性; 92 | - GPT-3表明了超大的自回归语言模型可以用来进行few-shot预测,即仅给模型一些关于任务的自然语言描述,和一些少量的示例来表明任务该如何完成。这种类型的模型使用decoder-only和标准的left-to-right语言建模目标函数进行训练。few-shot的结果表明不需要大规模任务相关的数据收集或者模型参数的更新都能够实现非常好的效果。 93 | - 论文介绍:在7800亿token的高质量文本上训练一个5400亿参数的稠密自回归Transformer。该模型使用新的机器学习系统Pathways进行训练的,因此称新模型为Pathways Language Model(PaLM)。 94 | - 论文贡献: 95 | - 高效的扩展:首次展示了Pathways的大规模使用,其是一个能够跨数千上万加速芯片训练单个模型的新机器学习系统。本文使用Pathways在6144个TPU v4芯片上高效的训练了一个540B参数的语言模型,先前的模型无法达到这个规模。 96 | - 随着规模持续改善:在数百个自然语言、代码和数学推理任务上评估了PaLM,其在绝大多数基准上都实现了state-of-the-art的结果。这充分证明了大语言模型随着规模的改进还没有趋于稳定或者达到饱和点。 97 | - 突破能力:在许多困难任务上展示了语言理解和生成的突破性能力。在推理任务上,先前的最优结果是将任务相关的微调、领域相关的架构以及任务相关的验证相结合才实现好的结果。本文表明了当大模型与 chain-of-thought prompting 相结合就能够在广泛的推理任务上匹敌或者超过先前的微调模型。 98 | - 不连续改进:为了更好的理解规模的行为,本文呈现了不同参数规模的结果:8B、62B和540B。通常,从62B至540B带来的效果类似于从8B至62B,其与神经网络中经常观察到的"power law"一致。然而,对于某些任务,观察到了不连续的改善,相比于8B至62B的规模变化,从62B至540B在准确率上将带来戏剧性的跳跃。这表明当模型达到足够规模时,语言模型会涌现新的能力。 99 | - 多语言理解:现有的大语言模型通常会在多语言领域进行有限的评估。本文在机器翻译、摘要和问答上进行了更彻底的评估。即使在非英文数据占训练数据相对小比例(20%)的情况下,540B模型的few-shot的评估结果也能在非英文摘要上接近先前最优的微调方法,并在翻译任务上超越先前的最优。未来的工作需要进一步理解英文中的多语言数据比例的影响。 100 | - 偏见和毒性:本文还评估了模型在偏见和毒性上的表现,其带来几个洞见。首先,对于性别和职业的偏见,PaLM 540B在1-shot和few-shot设置下实现了新的state-of-the-art。其次,通过对种族/宗教/性别的prompt延续的共享分析表明,模型可能会错误的肯定刻板印象,例如将穆斯林和恐怖主义、极端主义和暴力联系在一起。最后,对prompt延续的毒性分析表明,相较于8B模型,62B和540B模型的毒性略高。然而,模型生成的毒性与prompt的毒性高度相关。这表明,与人类生成的文本相比,模型严重依赖于prompt的风格。 101 | 102 | ## LaMDA 103 | 104 | - 论文名称:LaMDA: Language Models for Dialog Applications 105 | - 作者:Google 106 | - 论文地址:https://arxiv.org/pdf/2201.08239.pdf 107 | - 论文博客:https://blog.google/technology/ai/lamda/ 108 | - 论文github: 109 | - 时间:2022 110 | - 论文介绍:LaMDA 模型使用多达 137B 个参数进行训练,它展示了接近人类水平的对话质量以及在安全性和事实基础方面具有显着改进。 111 | - LaMDA 预训练 & 微调: 112 | - LaMDA 预训练:在预训练阶段,谷歌首先从公共对话数据和其他公共网页文档中收集并创建了一个具有 1.56T 单词的数据集,是用于训练以往对话模型的单词量的近 40 倍。在将该数据集标记为 2.81T SentencePiece token 之后,谷歌使用 GSPMD 预训练模型,以预测句子中的所有下一个 token。预训练的 LaMDA 模型已被广泛应用于谷歌的自然语言处理研究中,包括程序合成、零样本学习、风格迁移等。 113 | - LaMDA 微调:在微调阶段,谷歌训练 LaMDA,执行混合生成任务以生成对给定上下文的自然语言响应,执行关于响应是否安全和高质量的分类任务,最终生成一个两种任务都能做的多任务模型。LaMDA 生成器被训练预测限制为两个作者之间来回对话的对话数据集上的下一个 token,LaMDA 分类器被训练预测使用注释数据在上下文中生成的响应的安全与质量(SSI)评级。 114 | - LaMDA 对话期间:LaMDA 生成器首先在给定当前多轮对话上下文时生成几个候选响应,然后 LaMDA 预测每个候选响应的 SSI 和安全分数。安全分数低的候选响应首先被过滤掉,剩下的候选响应根据 SSI 分数重新排名,并选择分数最高的作为最终响应。谷歌使用 LaMDA 分类器进一步过滤掉用于生成任务的训练数据,以增加高质量候选响应的密度。 115 | - 目标和度量:指导训练对话模型包括两个至关重要的因素:目标和度量。LaMDA 有三个主要目标——质量、安全和根基性(Groundedness)。 116 | - 质量:谷歌将质量分解为三个维度,即合理性、特异性和趣味性 (Sensibleness, Specificity, Interestingness,SSI),由人类评估者进行评估。 117 | - 合理性:指模型是否产生在对话上下文中有意义的响应(例如,没有常识错误,没有荒谬的回应,以及与先前的回应没有矛盾); 118 | - 特异性是通过判断系统的响应是否特定于前面的对话上下文来衡量的,而不是适用于大多数上下文的通用回应; 119 | - 趣味性:衡量模型是否产生了富有洞察力、出乎意料或机智的回应,因此更有可能创造更好的对话。 120 | - 安全性:谷歌还在开发和部署负责任 AI(Responsible AI)方面取得了重大进展。其安全度量由一组说明性的安全目标组成,这些目标捕捉模型应在对话中展示的行为。这些目标试图限制模型的输出,以避免任何可能对用户造成伤害的意外结果,并避免加剧不公平的偏见。 121 | - 根基性:当前这一代语言模型通常会生成看似合理但实际上与已知外部事实相矛盾的陈述。这激发了谷歌对 LaMDA 根基性的研究。不携带任何真实世界信息的随意回应都会影响信息性,但不会影响根基性。虽然在已知来源中建立 LaMDA 生成的响应本身并不能保证事实的准确性,但它允许用户或外部系统根据其来源的可靠性来判断响应的有效性。 122 | 123 | ## Flan-T5 and Flan-PaLM 124 | 125 | - 论文名称:Flan-T5 and Flan-PaLM: Scaling Instruction-Finetuned Language Models 126 | - 作者:Google 127 | - 论文地址:https://arxiv.org/pdf/2210.11416.pdf 128 | - 论文github:https://huggingface.co/google/flan-t5-large 129 | - 时间:2022 130 | - 论文介绍:分析了多种指令微调方法,包括扩展对指令微调的影响。实验表明,指令微调确实可以根据任务数量和模型大小实现良好的扩展,最大到 5400 亿参数的模型都能明显受益,未来的研究应该进一步扩大任务的数量和模型的大小。此外,该研究还分析了微调对模型执行推理能力的影响。 Flan-T5 对 1800 余种语言任务进行了指令微调,明显提高了提示和多步推理能力,30 亿参数跑基准就能超过 GPT-3 的 1750 亿参数。 131 | 132 | ## Flan: FINETUNED LANGUAGE MODELS ARE ZERO-SHOT LEARNERS 133 | 134 | - 论文名称:Flan: FINETUNED LANGUAGE MODELS ARE ZERO-SHOT LEARNERS 135 | - 作者:Google 136 | - 论文地址:https://arxiv.org/pdf/2109.01652.pdf 137 | - 论文github: 138 | - 时间:2022 139 | - 动机:为了提高语言模型对NLP instructions的响应能力 140 | - 论文介绍:本文探讨了一种提高语言模型零样本学习能力的简单方法。instruction tuning——在数据集集合上微调语言模型——大大提高了unseen 任务上的零样本性能。采用一个137B参数的预训练语言模型, 通过 natural language instruction templates在60多个NLP数据集上进行instruction tune。根据 unseen的任务类型来评估 instruction-tuned模型,称之为FLAN。FLAN大大提高了其unmodifified counterpart的性能,并在25个数据集中的20个上超过了零样本学习的175B GPT-3。FLAN甚至在ANLI、RTE、BoolQ、AI2-ARC、OpenbookQA和StoryCloze上都远远优于few-shot小样本学习的GPT-3。消融研究表明,数据集的数量和模型规模是 instruction tuning成功的关键组成部分。 141 | 142 | ## BLOOM 143 | 144 | - 论文名称:BLOOM: A 176B-Parameter Open-Access Multilingual Language Model 145 | - 作者:BigScience (非盈利兴趣组织) 146 | - 论文地址:https://arxiv.org/pdf/2211.05100.pdf 147 | - 论文github:https://huggingface.co/bigscience/bloom 148 | - 时间:2022 149 | - 动机:语言模型的性能随着模型的增大而增加(有时是可预测的,有时是突然的),这也导致了模型规模越来越多的趋势。抛开环境的问题,训练大语言模型(LLM)的代价仅有资源丰富的组织可以负担的起。此外,直至最终,大多数LLM都没有公开发布。 150 | - 论文介绍:BLOOM是在46种自然语言和13种编程语言上训练的1760亿参数语言模型,其是由数百名研究人员合作开发和发布的。训练BLOOM的计算力是由来自于法国公共拨款的GENCI和IDRIS,利用了IDRIS的Jean Zay超级计算机。为了构建BLOOM,对于每个组件进行了详细的设计,包括训练数据、模型架构和训练目标、以及分布式学习的工程策略。我们也执行了模型容量的分析。我们的总体目标不仅是公开发布一个能够和近期开发的系统相媲美的大规模多语言的语言模型,而且还记录其开发中的协调过程。 151 | 152 | ## T0 153 | 154 | - 论文名称:T0: MULTITASK PROMPTED TRAINING ENABLES ZERO-SHOT TASK GENERALIZATION 155 | - 作者:BigScience (非盈利兴趣组织) 156 | - 论文地址:https://arxiv.org/pdf/2110.08207.pdf 157 | - 论文github: 158 | - https://huggingface.co/bigscience/T0 159 | - https://github.com/bigscience-workshop/t-zero 160 | - 时间:ICLR 2022 161 | - 动机:训练一个模型能够在留出任务上泛化性更好,且不需要很大的模型规模,同时对于 prompt 的措辞选择更鲁棒。 162 | - 论文介绍:T0 证明了多任务提示训练可以在语言模型中实现强大的 zero-shot 泛化能力。这种方法为无监督语言模型预训练提供了一个有效的可替代方法,常使我们的 T0 模型优于数倍于其自身大小的模型。我们还进行了消融研究,展示了包括许多不同 prompt 的重要性,以及在每个任务中增加数据集数量的影响。 163 | 164 | ## BLOOMZ and mT0 165 | 166 | - 论文名称:BLOOMZ and mT0: Multilingual version of BLOOM and T0 167 | - 作者:BigScience (非盈利兴趣组织) 168 | - 论文地址:https://arxiv.org/pdf/2211.01786.pdf 169 | - 论文github: 170 | - https://huggingface.co/bigscience/bloomz-mt 171 | - 时间:2022 172 | 173 | ## GPT-NEO 174 | 175 | - 论文名称:GPT-NEO 176 | - 作者:EleutherAI 177 | - 论文地址:https://arxiv.org/abs/2101.00027 178 | - 论文github:https://github.com/EleutherAI/gpt-neo 179 | - 时间:2021 180 | 181 | ## GPT-NeoX 182 | 183 | - 论文名称:GPT-NeoX 184 | - 作者:EleutherAI 185 | - 论文地址:https://arxiv.org/pdf/2204.06745.pdf 186 | - 论文github:https://huggingface.co/EleutherAI/gpt-neox-20b 187 | - 时间:2021 188 | 189 | ## GPT 190 | 191 | - 论文名称:chatgpt 192 | - 作者:OpenAI 193 | - 论文地址: 194 | - 论文github: 195 | - 时间:2023 196 | 197 | ## Alpaca 198 | 199 | - 论文名称:Alpaca: A Strong Open-Source Instruction-Following Model 200 | - 作者:Stanford 201 | - 论文地址: 202 | - 官网地址:https://crfm.stanford.edu/2023/03/13/alpaca.html 203 | - 论文github:https://github.com/tatsu-lab/stanford_alpaca 204 | - 时间:2023 205 | - 论文介绍:Alpaca是由Meta的LLaMA 7B微调而来的全新模型,仅用了52k数据,性能约等于GPT-3.5。关键是训练成本奇低,不到600美元。在8个80GB A100上训练了3个小时,不到100美元;生成数据使用OpenAI的API,500美元。 206 | 207 | 208 | ## 参考 209 | 210 | 1. [总结当下可用的大模型LLMs](https://zhuanlan.zhihu.com/p/611403556) 211 | 2. [LLaMA: Open and Efficient Foundation Language Models](https://arxiv.org/pdf/2302.13971v1.pdf) 212 | 3. [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/pdf/2205.01068.pdf) 213 | 4. [T5: Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/pdf/1910.10683.pdf) 214 | 5. [mT5: A Massively Multilingual Pre-trained Text-to-Text Transformer](https://arxiv.org/pdf/2010.11934.pdf) 215 | 6. [UL2 and Flan-UL2: Unifying Language Learning Paradigms](https://arxiv.org/pdf/2205.05131.pdf) 216 | 7. [PaLM: Scaling Language Modeling with Pathways](https://arxiv.org/pdf/2204.02311.pdf) 217 | 8. [LaMDA: Language Models for Dialog Applications](https://arxiv.org/pdf/2201.08239.pdf) 218 | 9. [Flan-T5 and Flan-PaLM: Scaling Instruction-Finetuned Language Models](https://arxiv.org/pdf/2210.11416.pdf) 219 | 10. [Flan: FINETUNED LANGUAGE MODELS ARE ZERO-SHOT LEARNERS](https://arxiv.org/pdf/2109.01652.pdf) 220 | 11. [BLOOM: A 176B-Parameter Open-Access Multilingual Language Model](https://arxiv.org/pdf/2211.05100.pdf) 221 | 12. [T0: MULTITASK PROMPTED TRAINING ENABLES ZERO-SHOT TASK GENERALIZATION](https://arxiv.org/pdf/2110.08207.pdf) 222 | 13. [BLOOMZ and mT0: Multilingual version of BLOOM and T0](https://arxiv.org/pdf/2211.01786.pdf) 223 | 14. [GPT-NEO](https://arxiv.org/abs/2101.00027) 224 | 15. [GPT-NeoX](https://arxiv.org/pdf/2204.06745.pdf) 225 | 16. [Alpaca: A Strong Open-Source Instruction-Following Model](https://crfm.stanford.edu/2023/03/13/alpaca.html) 226 | 17. [大规模神经对话系统研究前沿趋势分析报告](https://mp.weixin.qq.com/s/d98AfgZZtCfskLW3ZUoVwA) 227 | 18. [总结当下可用的大模型LLMs](https://zhuanlan.zhihu.com/p/611403556) 228 | 229 | 230 | 231 | -------------------------------------------------------------------------------- /bert_study/MacBERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 MacBERT 】那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 论文名称:Revisiting Pre-trained Models for Chinese Natural Language Processing 6 | > 7 | > 会议:EMNLP 2020 8 | > 9 | > 论文地址:https://arxiv.org/abs/2004.13922 10 | > 11 | > 论文源码地址:https://github.com/ymcui/MacBERT 12 | > 13 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 14 | 15 | 16 | ## 一、动机 17 | 18 | 主要为了解决与训练阶段和微调阶段存在的差异性 19 | 20 | 21 | ## 二、解决方法 22 | 23 | ### 2.1 MLM 24 | 25 | 1. 使用Whole Word Masking、N-gram Masking:single token、2-gram、3-gram、4-gram分别对应比例为0.4、0.3、0.2、0.1; 26 | 2. 由于finetuning时从未见过[MASK]token,因此使用相似的word进行替换。使用工具Synonyms toolkit 获得相似的词。如果被选中的N-gram存在相似的词,则随机选择相似的词进行替换,否则随机选择任意词替换; 27 | 3. 对于一个输入文本,15%的词进行masking。其中80%的使用相似的词进行替换,10%使用完全随机替换,10%保持不变。 28 | 29 | ### 2.2 NSP 30 | 31 | 采用ALBERT提出的SOP替换NSP 32 | 33 | 34 | ## 参考 35 | 36 | 1. [Revisiting Pre-trained Models for Chinese Natural Language Processing ](https://arxiv.org/abs/2004.13922) 37 | 2. [MacBERT 的改进(Revisiting Pre-Trained Models for Chinese Natural Language Processing)](https://blog.csdn.net/weixin_40122615/article/details/109317504) 38 | 3. [学习笔记:Revisiting Pre-trained Models for Chinese Natural Language Processing](https://zhuanlan.zhihu.com/p/354664711) 39 | 4. [MacBERT:MLM as correction BERT](https://zhuanlan.zhihu.com/p/250595837) 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /bert_study/SIGIR2020_MarkedBERT/img/20200901083934.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SIGIR2020_MarkedBERT/img/20200901083934.png -------------------------------------------------------------------------------- /bert_study/SIGIR2020_MarkedBERT/img/20200901084025.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SIGIR2020_MarkedBERT/img/20200901084025.png -------------------------------------------------------------------------------- /bert_study/SIGIR2020_MarkedBERT/img/20200901084101.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SIGIR2020_MarkedBERT/img/20200901084101.png -------------------------------------------------------------------------------- /bert_study/SIGIR2020_MarkedBERT/readme.md: -------------------------------------------------------------------------------- 1 | # MarkedBERT: Integrating Traditional IR Cues in Pre-trained Language Models for Passage Retrieval 2 | 3 | > 编辑:杨夕 4 | > 5 | > 项目地址:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 8 | > 9 | > 论文链接:https://dl.acm.org/doi/10.1145/3397271.3401194 10 | > 11 | > 代码链接:https://github.com/BOUALILILila/markers_bert 12 | > 13 | > 【注:手机阅读可能图片打不开!!!】 14 | 15 | ## 前言 16 | 17 | 目前,将预训练语言模型(BERT等)应用到信息检索领域(Information Retrieval,IR)任务中,已经取得了较好的效果。主流的方法是“Retrieve+Rerank”的pipline机制,**Retrieve模块一般使用传统的BM25等检索算法进行文档集合的粗排序得到一个较小的文档集合;Rerank模块一般使用BERT模型对retrieve模块检索出的文档进行精排序,通常是将问题和检索到的每个文档进行拼接后,作为BERT模型的输入,最后进行选择**。 18 | 19 | > Q:上述描述的pipline机制中Rerank模块与Retrieve模块是脱节的,Rerank模块仅仅使用了Retrieve模块检索到的文档集合。那么如何将两个模块融合起来呢? 20 | > 21 | > A:在Retrieve模块中,可以提取出问题与每个文档的一些特征,例如:最大公共子串长度、词匹配个数、词匹配率等。在Rerank模块,可以将Retrieve模块提取到的特征拼接到bert模型的输出向量上,最后进行排序。 22 | 23 | 加入手工提取特征是可以将Rerank模块与Retrieve模块融合,但是特征如何构建、选择是一个至关重要的问题。 24 | 25 | 而MarkedBERT模型,提出将精确匹配线索加入到BERT模型中,最终提高rerank模块效果。它受到2019年一篇关系提取论文(Matching the Blanks: Distributional Similarity for Relation Learning)的启发,使用marker tokens来突出实体(key tokens)可以极大地提高了BERT的性能。MarkedBERT模型,使用marker tokens来突出Retrieve模块阶段得到的问题与每个文档匹配的实体,加入到fine-tuning阶段,以提升排序效果。 26 | 27 | ## 方法介绍 28 | 29 | ### 基础介绍 30 | 31 | 模型以问题Q为Segment A ,以段落P为Segment B构建BERT的输入序列;在微调阶段,使用[CLS]向量作为关联分类向量构建passage-level point-wise classification。 32 | 33 | ![](img/20200901083934.png) 34 | 35 | ### MarkedBERT 36 | 37 | MarkedBERT模型的核心在于,在问题Q和段落P完全匹配的token前后,加入特殊token进行mask标记,如图1所示。 38 | 39 | ![](img/20200901084025.png) 40 | 41 | (1)不标记在document中未出现的query的term。 42 | 43 | (2)如果某个term在query中重复出现,那么它将具有与第一次出现相同的标识符。 44 | 45 | (3)如果document中的term,与query的term标识符一致。 46 | 47 | ![](img/20200901084101.png) 48 | 49 | 50 | ## 参考资料 51 | 52 | 1. [SIGIR 2020之MarkedBERT模型:加入传统检索线索的Rerank模型](https://zhuanlan.zhihu.com/p/175981489) 53 | -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/2010.02194.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/2010.02194.pdf -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/20201027210757.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/20201027210757.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/20201027211251.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/20201027211251.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194221.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194221.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194442.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194442.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194618.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194618.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194833.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415194833.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415195007.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210415195007.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210417132422.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SelfTrainingImprovesPreTraining/img/微信截图_20210417132422.png -------------------------------------------------------------------------------- /bert_study/SelfTrainingImprovesPreTraining/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于自训练 + 预训练 = 更好的自然语言理解模型 】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 个人github:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 论文标题:Self-training Improves Pre-training for Natural Language Understanding 8 | > 9 | > 论文代码 SentAugment :https://github.com/facebookresearch/SentAugment 10 | > 11 | > 论文地址:https://arxiv.org/abs/2010.02194 12 | > 13 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 14 | > 15 | > 【注:手机阅读可能图片打不开!!!】 16 | 17 | ## 目录 18 | 19 | - [【关于自训练 + 预训练 = 更好的自然语言理解模型 】 那些的你不知道的事](#关于自训练--预训练--更好的自然语言理解模型--那些的你不知道的事) 20 | - [目录](#目录) 21 | - [一、摘要](#一摘要) 22 | - [二、前期知识](#二前期知识) 23 | - [2.1 预训练](#21-预训练) 24 | - [2.2 自训练](#22-自训练) 25 | - [2.3 区别](#23-区别) 26 | - [三、问题提出](#三问题提出) 27 | - [四、论文方法](#四论文方法) 28 | - [五、论文贡献](#五论文贡献) 29 | - [六、论文思路](#六论文思路) 30 | - [6.1 自训练处理流程](#61-自训练处理流程) 31 | - [6.2 SentAugment: data augmentation forsemi-supervised learning](#62-sentaugment-data-augmentation-forsemi-supervised-learning) 32 | - [6.2.1 Large-scale sentence bank【大型句子库 构建】](#621-large-scale-sentence-bank大型句子库-构建) 33 | - [6.2.2 Downstream task embeddings 【下游任务编码 构建】](#622-downstream-task-embeddings-下游任务编码-构建) 34 | - [6.2.3 Unsupervised data retrieval](#623-unsupervised-data-retrieval) 35 | - [6.3 Semi-supervised learning for naturallanguage understanding](#63--semi-supervised-learning-for-naturallanguage-understanding) 36 | - [七、实验结果分析](#七实验结果分析) 37 | - [7.1 自训练](#71-自训练) 38 | - [7.2 少样本学习与知识蒸馏](#72-少样本学习与知识蒸馏) 39 | - [7.3 Ablation study of data augmentation](#73-ablation-study-of-data-augmentation) 40 | - [7.4 Sentence embeddings (SASE) 句子编码的影响](#74-sentence-embeddings-sase-句子编码的影响) 41 | - [7.5 Examples of large-scale similarity search](#75-examples-of-large-scale-similarity-search) 42 | - [参考](#参考) 43 | 44 | 45 | ## 一、摘要 46 | 47 | Unsupervised pre-training has led to much recent progress in natural language understanding. In this paper, we study self-training as another way to leverage unlabeled data through semi-supervised learning. To obtain additional data for a specific task, we introduce SentAugment, a data augmentation method which computes task-specific query embeddings from labeled data to retrieve sentences from a bank of billions of unlabeled sentences crawled from the web. Unlike previous semi-supervised methods, our approach does not require in domain unlabeled data and is therefore more generally applicable. Experiments show that self-training is complementary tostrong RoBERTa baselines on a variety oftasks. Our augmentation approach leads to scalable and effective self-training with improvements of up to 2.6% on standard text classification benchmarks. Finally, we also show strong gains on knowledge-distillation and few-shot learning. 48 | 49 | 无监督的预训练导致自然语言理解方面的最新进展。 50 | 51 | 在本文中,我们将自训练作为通过半监督学习利用未标记数据的另一种方法。 52 | 53 | 为了获得针对特定任务的其他数据,我们引入了SentAugment,这是一种数据增强方法,可从标记的数据计算特定于任务的查询嵌入,以从网上爬行的数十亿个未标记的句子中检索句子。 54 | 55 | 与以前的半监督方法不同,我们的方法不需要域内未标记的数据,因此更通用。 56 | 57 | 实验表明,自训练是在各种任务上的强RoBERTa基线的补充。我们的扩充方法可实现可扩展且有效的自我训练,并在标准文本分类基准上提高了2.6%。最后,我们还显示出在知识提炼和少量学习方面的巨大收获。 58 | 59 | ## 二、前期知识 60 | 61 | ![](img/20201027210757.png) 62 | 63 | ### 2.1 预训练 64 | 65 | 预训练(Pre-training)从广义上来讲,是指先在较大规模的数据上对模型训练一波,然后再在具体的下游任务数据中微调。大多数情况下,预训练的含义都比较狭窄:在大规模无标注语料上,用自监督的方式训练模型。这里的自监督方法一般指的是语言模型。 66 | 67 | ### 2.2 自训练 68 | 69 | 自训练是说有一个Teacher模型Ft和一个Student模型Fs,首先在标注数据上训练Ft,然后用它对大规模无标注数据进行标注,把得到的结果当做伪标注数据去训练Fs。 70 | 71 | ### 2.3 区别 72 | 73 | 预训练和自训练都用到了大规模无标注的数据,只是二者的处理过程不同。而且,其中非常重要的一点是,预训练始终对针对一个模型进行操作,而自训练却用到了两个模型,前者是直接从无标注数据中学习,而后者是间接地从数据中学习。 74 | 75 | 76 | ## 三、问题提出 77 | 78 | - 问题一: do pre-training and self-training capture the same information, or are they complementary? 【预训练和自训练会捕获相同的信息,还是它们是互补的?】 79 | - 问题二: how can we obtain large amounts of unannotated data from specific domains?【如何从特定域中获取大量未注释的数据?】 80 | 81 | ## 四、论文方法 82 | 83 | - 问题二解决方法:提出 SentAugment 方法 从 web 上获取有用数据; 84 | - 问题一解决方法:使用标记的任务数据训练一个 teacher 模型,然后用它对检索到的未标注句子进行标注,并基于这个合成数据集训练最终的模型。 85 | 86 | ## 五、论文贡献 87 | 88 | - 结合自训练与预训练,比单纯的预训练取得了大幅度的效果提升; 89 | - 为了使伪标注数据更加契合下游的具体任务,提出了 SentAugment ,一种特定领域的数据抽取方法,减少通用语料造成的噪声干扰; 90 | - 在知识蒸馏和小样本学习任务上也取得了突出的结果,证明自训练+预训练的优越性。 91 | 92 | ## 六、论文思路 93 | 94 | ### 6.1 自训练处理流程 95 | 96 | 1. 将一个预训练模型(本文使用RoBERTa_Large)在标注数据上训练,作为 Teacher 模型 Ft; 97 | 2. 使用 Ft 从海量通用语料中提取相关领域的数据; 98 | 3. 用 Ft 对提取的数据作标注; 99 | 4. 用伪标注语料训练学生模型Fs。 100 | 101 | 其中的1,3,4步都是确定的,所以我们重点关注如何使用Ft从海量通用语料库D中抽取出领域相关的语料D'。 102 | 103 | ![](img/20201027211251.png) 104 | 105 | ### 6.2 SentAugment: data augmentation forsemi-supervised learning 106 | 107 | #### 6.2.1 Large-scale sentence bank【大型句子库 构建】 108 | 109 | - 数据来源:依赖于大规模的无监督语句语料库,这些语料库是从爬网的数据中得出的(Wenzeket等人,2019)。 110 | - 思路: 111 | 112 | 1. 对 语料库中的文档进行 分句; 113 | 2. 利用 句子编码器 将 句子 编码为 句向量; 114 | 3. 利用 句向量 检索与特定任务相关的句子库的子集,所用的 损失函数: 115 | 116 | ![](img/微信截图_20210417132422.png) 117 | 118 | > 注:其中 positive pairs(x,y) 是复述或平行句子(Wieting等人,2019a)和 $b_c$ are in-batch hard negatives (Wieting et al., 2016) 119 | 120 | #### 6.2.2 Downstream task embeddings 【下游任务编码 构建】 121 | 122 | - 动机:在 第 6.2.1 节 所构建的 句子编码,虽然能表示 通用语料库 D 中每个句子 s 的意义,但是无法 区别 这些句子 所属领域; 123 | - 针对该问题,论文提出了一种思路: 124 | 125 | 1. 对于每个下游任务,使用相同的伪随机模型构建代表该任务的嵌入; 126 | 2. 使用这些任务嵌入从句子存储库中检索相似的句子,即 计算句子编码和任务编码的余弦值 127 | 128 | - 余弦值 计算方法: 129 | - All-Average: 将训练 $f_T$ 所用的所有句子编码平均起来作为任务编码; 130 | - Label-Average: 将训练 $f_T$ 所用的每个类别的所有句子编码平均起来作为各个类别的任务编码; 131 | - Per-Sentence:将训练 $f_T$ 所用的每个句子都作为一个单独的任务编码。 132 | 133 | #### 6.2.3 Unsupervised data retrieval 134 | 135 | 1. 相关领域数据召回:在获取任务编码后,根据余弦值大小,从通用语料库中抽取相关的句子,这可以减少通用语料对下游特定任务的噪声干扰。对于每个类别,只抽取Top-K个句子,并且对提取的句子,还要满足 $f_T$ 能取得较高的置信度。 136 | 2. 伪标签数据集 $D' = {(x,y)}$ 构建:利用 $f_T$ 对每个句子 x 进行预测,得到其软标签或者one-hot硬标签; 137 | 138 | ### 6.3 Semi-supervised learning for naturallanguage understanding 139 | 140 | - 思路:利用 第 6.2.3 节 得到的 伪标签数据集 $D' = {(x,y)}$ 训练 $f_S$; 141 | - 训练方式: 142 | 143 | 1. 自训练(Self-Training):将另一个预训练的RoBERTa_Large作为 $f_S$,使用one-hot硬标签在 D’ 上训练; 144 | 2. 知识蒸馏(Knowledge-Distillation):将一个预训练的RoBERTa_Small作为 $f_S$,使用软标签在 D’ 上训练; 145 | 3. 少样本学习(Few-Shot):训练 $f_T$ 所使用的标注数据是少样本,伪标注语料的大小是标注数据的2~3个数量级,$f_S$ 是RoBERTa_Large,使用one-hot硬标签在 D‘+D 上训练。 146 | 147 | ## 七、实验结果分析 148 | 149 | ### 7.1 自训练 150 | 151 | ![](img/微信截图_20210415194221.png) 152 | 153 | > 结论:没有伪标注数据,单纯的预训练不能很好地实现领域知识迁移,还要借助标注数据 154 | 155 | ### 7.2 少样本学习与知识蒸馏 156 | 157 | ![](img/微信截图_20210415194442.png) 158 | 159 | > 结论:领域内自训练可以大幅提升少样本场景下的效果 160 | 161 | ### 7.3 Ablation study of data augmentation 162 | 163 | ![](img/微信截图_20210415194618.png) 164 | 165 | > 结论:对知识蒸馏来说,自训练带来的数据增广也是很重要的 166 | 167 | ### 7.4 Sentence embeddings (SASE) 句子编码的影响 168 | 169 | ![](img/微信截图_20210415194833.png) 170 | 171 | > 结论:复述与多语言掩码语言模型任务对于训练句子编码是很有帮助的 172 | 173 | ### 7.5 Examples of large-scale similarity search 174 | 175 | ![](img/微信截图_20210415195007.png) 176 | 177 | > 注:如果是用Per-Sentence,那么抽取的句子就基本上是询问的转述;如果是用Label-Average,抽取的句子就符合该类别。基于句子编码与任务编码的抽取方法有能力得到满足条件的句子。 178 | 179 | ## 参考 180 | 181 | 1. [香侬读 | 自训练 + 预训练 = 更好的自然语言理解模型](https://zhuanlan.zhihu.com/p/268770394) 182 | -------------------------------------------------------------------------------- /bert_study/SpanBERT/paper.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/SpanBERT/paper.pdf -------------------------------------------------------------------------------- /bert_study/SpanBERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 SpanBERT 】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 项目地址:https://github.com/km1994/nlp_paper_study 6 | > 7 | > NLP 面经地址:https://github.com/km1994/NLP-Interview-Notes 8 | > 9 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 10 | > 11 | > 论文:SpanBERT: Improving Pre-training by Representing and Predicting Spans 12 | > 13 | > 发表会议: 14 | > 15 | > 论文地址:https://arxiv.org/abs/1907.10529 16 | > 17 | > github:https://github.com/facebookresearch/SpanBERT 18 | 19 | ## 摘要 20 | 21 | - 动机:旨在更好地表示和预测文本的 span; 22 | - 论文方法->扩展了BERT: 23 | - (1)屏蔽连续的随机跨度,而不是随机标记; 24 | - (2)训练跨度边界表示来预测屏蔽跨度的整个内容,而不依赖其中的单个标记表示。 25 | - 实验结果: 26 | - SpanBERT始终优于BERT和我们更好调整的基线,在跨选择任务(如问题回答和共指消解)上有实质性的收益。特别是在训练数据和模型大小与BERT-large相同的情况下,我们的单一模型在1.1班和2.0班分别获得94.6%和88.7%的F1。我们还实现了OntoNotes共指消解任务(79.6\%F1)的最新发展,在TACRED关系抽取基准测试上表现出色,甚至在GLUE上也有所提高。 27 | 28 | 29 | 30 | ## 参考资料 31 | 32 | 1. [SpanBERT:提出基于分词的预训练模型,多项任务性能超越现有模型!](https://cloud.tencent.com/developer/article/1476168) 33 | 2. [解读SpanBERT:《Improving Pre-training by Representing and Predicting Spans》](https://blog.csdn.net/weixin_37947156/article/details/99210514) 34 | 3. [NLP中的预训练语言模型(二)—— Facebook的SpanBERT和RoBERTa](https://www.shuzhiduo.com/A/Gkz1MGQZzR/) 35 | 36 | -------------------------------------------------------------------------------- /bert_study/T1_bert/BERT Pre-training of Deep Bidirectional Transformers for Language Understanding.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/BERT Pre-training of Deep Bidirectional Transformers for Language Understanding.pdf -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/.gitignore: -------------------------------------------------------------------------------- 1 | # Initially taken from Github's Python gitignore file 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # celery beat schedule file 86 | celerybeat-schedule 87 | 88 | # SageMath parsed files 89 | *.sage.py 90 | 91 | # Environments 92 | .env 93 | .venv 94 | env/ 95 | venv/ 96 | ENV/ 97 | env.bak/ 98 | venv.bak/ 99 | 100 | # Spyder project settings 101 | .spyderproject 102 | .spyproject 103 | 104 | # Rope project settings 105 | .ropeproject 106 | 107 | # mkdocs documentation 108 | /site 109 | 110 | # mypy 111 | .mypy_cache/ 112 | .dmypy.json 113 | dmypy.json 114 | 115 | # Pyre type checker 116 | .pyre/ 117 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | BERT needs to maintain permanent compatibility with the pre-trained model files, 4 | so we do not plan to make any major changes to this library (other than what was 5 | promised in the README). However, we can accept small patches related to 6 | re-factoring and documentation. To submit contributes, there are just a few 7 | small guidelines you need to follow. 8 | 9 | ## Contributor License Agreement 10 | 11 | Contributions to this project must be accompanied by a Contributor License 12 | Agreement. You (or your employer) retain the copyright to your contribution; 13 | this simply gives us permission to use and redistribute your contributions as 14 | part of the project. Head over to to see 15 | your current agreements on file or to sign a new one. 16 | 17 | You generally only need to submit a CLA once, so if you've already submitted one 18 | (even if it was for a different project), you probably don't need to do it 19 | again. 20 | 21 | ## Code reviews 22 | 23 | All submissions, including submissions by project members, require review. We 24 | use GitHub pull requests for this purpose. Consult 25 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 26 | information on using pull requests. 27 | 28 | ## Community Guidelines 29 | 30 | This project follows 31 | [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). 32 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/modeling_test.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import collections 20 | import json 21 | import random 22 | import re 23 | 24 | import modeling 25 | import six 26 | import tensorflow as tf 27 | 28 | 29 | class BertModelTest(tf.test.TestCase): 30 | 31 | class BertModelTester(object): 32 | 33 | def __init__(self, 34 | parent, 35 | batch_size=13, 36 | seq_length=7, 37 | is_training=True, 38 | use_input_mask=True, 39 | use_token_type_ids=True, 40 | vocab_size=99, 41 | hidden_size=32, 42 | num_hidden_layers=5, 43 | num_attention_heads=4, 44 | intermediate_size=37, 45 | hidden_act="gelu", 46 | hidden_dropout_prob=0.1, 47 | attention_probs_dropout_prob=0.1, 48 | max_position_embeddings=512, 49 | type_vocab_size=16, 50 | initializer_range=0.02, 51 | scope=None): 52 | self.parent = parent 53 | self.batch_size = batch_size 54 | self.seq_length = seq_length 55 | self.is_training = is_training 56 | self.use_input_mask = use_input_mask 57 | self.use_token_type_ids = use_token_type_ids 58 | self.vocab_size = vocab_size 59 | self.hidden_size = hidden_size 60 | self.num_hidden_layers = num_hidden_layers 61 | self.num_attention_heads = num_attention_heads 62 | self.intermediate_size = intermediate_size 63 | self.hidden_act = hidden_act 64 | self.hidden_dropout_prob = hidden_dropout_prob 65 | self.attention_probs_dropout_prob = attention_probs_dropout_prob 66 | self.max_position_embeddings = max_position_embeddings 67 | self.type_vocab_size = type_vocab_size 68 | self.initializer_range = initializer_range 69 | self.scope = scope 70 | 71 | def create_model(self): 72 | input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length], 73 | self.vocab_size) 74 | 75 | input_mask = None 76 | if self.use_input_mask: 77 | input_mask = BertModelTest.ids_tensor( 78 | [self.batch_size, self.seq_length], vocab_size=2) 79 | 80 | token_type_ids = None 81 | if self.use_token_type_ids: 82 | token_type_ids = BertModelTest.ids_tensor( 83 | [self.batch_size, self.seq_length], self.type_vocab_size) 84 | 85 | config = modeling.BertConfig( 86 | vocab_size=self.vocab_size, 87 | hidden_size=self.hidden_size, 88 | num_hidden_layers=self.num_hidden_layers, 89 | num_attention_heads=self.num_attention_heads, 90 | intermediate_size=self.intermediate_size, 91 | hidden_act=self.hidden_act, 92 | hidden_dropout_prob=self.hidden_dropout_prob, 93 | attention_probs_dropout_prob=self.attention_probs_dropout_prob, 94 | max_position_embeddings=self.max_position_embeddings, 95 | type_vocab_size=self.type_vocab_size, 96 | initializer_range=self.initializer_range) 97 | 98 | model = modeling.BertModel( 99 | config=config, 100 | is_training=self.is_training, 101 | input_ids=input_ids, 102 | input_mask=input_mask, 103 | token_type_ids=token_type_ids, 104 | scope=self.scope) 105 | 106 | outputs = { 107 | "embedding_output": model.get_embedding_output(), 108 | "sequence_output": model.get_sequence_output(), 109 | "pooled_output": model.get_pooled_output(), 110 | "all_encoder_layers": model.get_all_encoder_layers(), 111 | } 112 | return outputs 113 | 114 | def check_output(self, result): 115 | self.parent.assertAllEqual( 116 | result["embedding_output"].shape, 117 | [self.batch_size, self.seq_length, self.hidden_size]) 118 | 119 | self.parent.assertAllEqual( 120 | result["sequence_output"].shape, 121 | [self.batch_size, self.seq_length, self.hidden_size]) 122 | 123 | self.parent.assertAllEqual(result["pooled_output"].shape, 124 | [self.batch_size, self.hidden_size]) 125 | 126 | def test_default(self): 127 | self.run_tester(BertModelTest.BertModelTester(self)) 128 | 129 | def test_config_to_json_string(self): 130 | config = modeling.BertConfig(vocab_size=99, hidden_size=37) 131 | obj = json.loads(config.to_json_string()) 132 | self.assertEqual(obj["vocab_size"], 99) 133 | self.assertEqual(obj["hidden_size"], 37) 134 | 135 | def run_tester(self, tester): 136 | with self.test_session() as sess: 137 | ops = tester.create_model() 138 | init_op = tf.group(tf.global_variables_initializer(), 139 | tf.local_variables_initializer()) 140 | sess.run(init_op) 141 | output_result = sess.run(ops) 142 | tester.check_output(output_result) 143 | 144 | self.assert_all_tensors_reachable(sess, [init_op, ops]) 145 | 146 | @classmethod 147 | def ids_tensor(cls, shape, vocab_size, rng=None, name=None): 148 | """Creates a random int32 tensor of the shape within the vocab size.""" 149 | if rng is None: 150 | rng = random.Random() 151 | 152 | total_dims = 1 153 | for dim in shape: 154 | total_dims *= dim 155 | 156 | values = [] 157 | for _ in range(total_dims): 158 | values.append(rng.randint(0, vocab_size - 1)) 159 | 160 | return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name) 161 | 162 | def assert_all_tensors_reachable(self, sess, outputs): 163 | """Checks that all the tensors in the graph are reachable from outputs.""" 164 | graph = sess.graph 165 | 166 | ignore_strings = [ 167 | "^.*/assert_less_equal/.*$", 168 | "^.*/dilation_rate$", 169 | "^.*/Tensordot/concat$", 170 | "^.*/Tensordot/concat/axis$", 171 | "^testing/.*$", 172 | ] 173 | 174 | ignore_regexes = [re.compile(x) for x in ignore_strings] 175 | 176 | unreachable = self.get_unreachable_ops(graph, outputs) 177 | filtered_unreachable = [] 178 | for x in unreachable: 179 | do_ignore = False 180 | for r in ignore_regexes: 181 | m = r.match(x.name) 182 | if m is not None: 183 | do_ignore = True 184 | if do_ignore: 185 | continue 186 | filtered_unreachable.append(x) 187 | unreachable = filtered_unreachable 188 | 189 | self.assertEqual( 190 | len(unreachable), 0, "The following ops are unreachable: %s" % 191 | (" ".join([x.name for x in unreachable]))) 192 | 193 | @classmethod 194 | def get_unreachable_ops(cls, graph, outputs): 195 | """Finds all of the tensors in graph that are unreachable from outputs.""" 196 | outputs = cls.flatten_recursive(outputs) 197 | output_to_op = collections.defaultdict(list) 198 | op_to_all = collections.defaultdict(list) 199 | assign_out_to_in = collections.defaultdict(list) 200 | 201 | for op in graph.get_operations(): 202 | for x in op.inputs: 203 | op_to_all[op.name].append(x.name) 204 | for y in op.outputs: 205 | output_to_op[y.name].append(op.name) 206 | op_to_all[op.name].append(y.name) 207 | if str(op.type) == "Assign": 208 | for y in op.outputs: 209 | for x in op.inputs: 210 | assign_out_to_in[y.name].append(x.name) 211 | 212 | assign_groups = collections.defaultdict(list) 213 | for out_name in assign_out_to_in.keys(): 214 | name_group = assign_out_to_in[out_name] 215 | for n1 in name_group: 216 | assign_groups[n1].append(out_name) 217 | for n2 in name_group: 218 | if n1 != n2: 219 | assign_groups[n1].append(n2) 220 | 221 | seen_tensors = {} 222 | stack = [x.name for x in outputs] 223 | while stack: 224 | name = stack.pop() 225 | if name in seen_tensors: 226 | continue 227 | seen_tensors[name] = True 228 | 229 | if name in output_to_op: 230 | for op_name in output_to_op[name]: 231 | if op_name in op_to_all: 232 | for input_name in op_to_all[op_name]: 233 | if input_name not in stack: 234 | stack.append(input_name) 235 | 236 | expanded_names = [] 237 | if name in assign_groups: 238 | for assign_name in assign_groups[name]: 239 | expanded_names.append(assign_name) 240 | 241 | for expanded_name in expanded_names: 242 | if expanded_name not in stack: 243 | stack.append(expanded_name) 244 | 245 | unreachable_ops = [] 246 | for op in graph.get_operations(): 247 | is_unreachable = False 248 | all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs] 249 | for name in all_names: 250 | if name not in seen_tensors: 251 | is_unreachable = True 252 | if is_unreachable: 253 | unreachable_ops.append(op) 254 | return unreachable_ops 255 | 256 | @classmethod 257 | def flatten_recursive(cls, item): 258 | """Flattens (potentially nested) a tuple/dictionary/list to a list.""" 259 | output = [] 260 | if isinstance(item, list): 261 | output.extend(item) 262 | elif isinstance(item, tuple): 263 | output.extend(list(item)) 264 | elif isinstance(item, dict): 265 | for (_, v) in six.iteritems(item): 266 | output.append(v) 267 | else: 268 | return [item] 269 | 270 | flat_output = [] 271 | for x in output: 272 | flat_output.extend(cls.flatten_recursive(x)) 273 | return flat_output 274 | 275 | 276 | if __name__ == "__main__": 277 | tf.test.main() 278 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/optimization.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Functions and classes related to optimization (weight updates).""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import re 22 | import tensorflow as tf 23 | 24 | 25 | def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu): 26 | """Creates an optimizer training op.""" 27 | global_step = tf.train.get_or_create_global_step() 28 | 29 | learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32) 30 | 31 | # Implements linear decay of the learning rate. 32 | learning_rate = tf.train.polynomial_decay( 33 | learning_rate, 34 | global_step, 35 | num_train_steps, 36 | end_learning_rate=0.0, 37 | power=1.0, 38 | cycle=False) 39 | 40 | # Implements linear warmup. I.e., if global_step < num_warmup_steps, the 41 | # learning rate will be `global_step/num_warmup_steps * init_lr`. 42 | if num_warmup_steps: 43 | global_steps_int = tf.cast(global_step, tf.int32) 44 | warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32) 45 | 46 | global_steps_float = tf.cast(global_steps_int, tf.float32) 47 | warmup_steps_float = tf.cast(warmup_steps_int, tf.float32) 48 | 49 | warmup_percent_done = global_steps_float / warmup_steps_float 50 | warmup_learning_rate = init_lr * warmup_percent_done 51 | 52 | is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32) 53 | learning_rate = ( 54 | (1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate) 55 | 56 | # It is recommended that you use this optimizer for fine tuning, since this 57 | # is how the model was trained (note that the Adam m/v variables are NOT 58 | # loaded from init_checkpoint.) 59 | optimizer = AdamWeightDecayOptimizer( 60 | learning_rate=learning_rate, 61 | weight_decay_rate=0.01, 62 | beta_1=0.9, 63 | beta_2=0.999, 64 | epsilon=1e-6, 65 | exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]) 66 | 67 | if use_tpu: 68 | optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) 69 | 70 | tvars = tf.trainable_variables() 71 | grads = tf.gradients(loss, tvars) 72 | 73 | # This is how the model was pre-trained. 74 | (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0) 75 | 76 | train_op = optimizer.apply_gradients( 77 | zip(grads, tvars), global_step=global_step) 78 | 79 | # Normally the global step update is done inside of `apply_gradients`. 80 | # However, `AdamWeightDecayOptimizer` doesn't do this. But if you use 81 | # a different optimizer, you should probably take this line out. 82 | new_global_step = global_step + 1 83 | train_op = tf.group(train_op, [global_step.assign(new_global_step)]) 84 | return train_op 85 | 86 | 87 | class AdamWeightDecayOptimizer(tf.train.Optimizer): 88 | """A basic Adam optimizer that includes "correct" L2 weight decay.""" 89 | 90 | def __init__(self, 91 | learning_rate, 92 | weight_decay_rate=0.0, 93 | beta_1=0.9, 94 | beta_2=0.999, 95 | epsilon=1e-6, 96 | exclude_from_weight_decay=None, 97 | name="AdamWeightDecayOptimizer"): 98 | """Constructs a AdamWeightDecayOptimizer.""" 99 | super(AdamWeightDecayOptimizer, self).__init__(False, name) 100 | 101 | self.learning_rate = learning_rate 102 | self.weight_decay_rate = weight_decay_rate 103 | self.beta_1 = beta_1 104 | self.beta_2 = beta_2 105 | self.epsilon = epsilon 106 | self.exclude_from_weight_decay = exclude_from_weight_decay 107 | 108 | def apply_gradients(self, grads_and_vars, global_step=None, name=None): 109 | """See base class.""" 110 | assignments = [] 111 | for (grad, param) in grads_and_vars: 112 | if grad is None or param is None: 113 | continue 114 | 115 | param_name = self._get_variable_name(param.name) 116 | 117 | m = tf.get_variable( 118 | name=param_name + "/adam_m", 119 | shape=param.shape.as_list(), 120 | dtype=tf.float32, 121 | trainable=False, 122 | initializer=tf.zeros_initializer()) 123 | v = tf.get_variable( 124 | name=param_name + "/adam_v", 125 | shape=param.shape.as_list(), 126 | dtype=tf.float32, 127 | trainable=False, 128 | initializer=tf.zeros_initializer()) 129 | 130 | # Standard Adam update. 131 | next_m = ( 132 | tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad)) 133 | next_v = ( 134 | tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2, 135 | tf.square(grad))) 136 | 137 | update = next_m / (tf.sqrt(next_v) + self.epsilon) 138 | 139 | # Just adding the square of the weights to the loss function is *not* 140 | # the correct way of using L2 regularization/weight decay with Adam, 141 | # since that will interact with the m and v parameters in strange ways. 142 | # 143 | # Instead we want ot decay the weights in a manner that doesn't interact 144 | # with the m/v parameters. This is equivalent to adding the square 145 | # of the weights to the loss with plain (non-momentum) SGD. 146 | if self._do_use_weight_decay(param_name): 147 | update += self.weight_decay_rate * param 148 | 149 | update_with_lr = self.learning_rate * update 150 | 151 | next_param = param - update_with_lr 152 | 153 | assignments.extend( 154 | [param.assign(next_param), 155 | m.assign(next_m), 156 | v.assign(next_v)]) 157 | return tf.group(*assignments, name=name) 158 | 159 | def _do_use_weight_decay(self, param_name): 160 | """Whether to use L2 weight decay for `param_name`.""" 161 | if not self.weight_decay_rate: 162 | return False 163 | if self.exclude_from_weight_decay: 164 | for r in self.exclude_from_weight_decay: 165 | if re.search(r, param_name) is not None: 166 | return False 167 | return True 168 | 169 | def _get_variable_name(self, param_name): 170 | """Get the variable name from the tensor name.""" 171 | m = re.match("^(.*):\\d+$", param_name) 172 | if m is not None: 173 | param_name = m.group(1) 174 | return param_name 175 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/optimization_test.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import optimization 20 | import tensorflow as tf 21 | 22 | 23 | class OptimizationTest(tf.test.TestCase): 24 | 25 | def test_adam(self): 26 | with self.test_session() as sess: 27 | w = tf.get_variable( 28 | "w", 29 | shape=[3], 30 | initializer=tf.constant_initializer([0.1, -0.2, -0.1])) 31 | x = tf.constant([0.4, 0.2, -0.5]) 32 | loss = tf.reduce_mean(tf.square(x - w)) 33 | tvars = tf.trainable_variables() 34 | grads = tf.gradients(loss, tvars) 35 | global_step = tf.train.get_or_create_global_step() 36 | optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2) 37 | train_op = optimizer.apply_gradients(zip(grads, tvars), global_step) 38 | init_op = tf.group(tf.global_variables_initializer(), 39 | tf.local_variables_initializer()) 40 | sess.run(init_op) 41 | for _ in range(100): 42 | sess.run(train_op) 43 | w_np = sess.run(w) 44 | self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2) 45 | 46 | 47 | if __name__ == "__main__": 48 | tf.test.main() 49 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow >= 1.11.0 # CPU Version of TensorFlow. 2 | # tensorflow-gpu >= 1.11.0 # GPU version of TensorFlow. 3 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/sample_text.txt: -------------------------------------------------------------------------------- 1 | This text is included to make sure Unicode is handled properly: 力加勝北区ᴵᴺᵀᵃছজটডণত 2 | Text should be one-sentence-per-line, with empty lines between documents. 3 | This sample text is public domain and was randomly selected from Project Guttenberg. 4 | 5 | The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors. 6 | Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity. 7 | Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them. 8 | "Cass" Beard had risen early that morning, but not with a view to discovery. 9 | A leak in his cabin roof,--quite consistent with his careless, improvident habits,--had roused him at 4 A. M., with a flooded "bunk" and wet blankets. 10 | The chips from his wood pile refused to kindle a fire to dry his bed-clothes, and he had recourse to a more provident neighbor's to supply the deficiency. 11 | This was nearly opposite. 12 | Mr. Cassius crossed the highway, and stopped suddenly. 13 | Something glittered in the nearest red pool before him. 14 | Gold, surely! 15 | But, wonderful to relate, not an irregular, shapeless fragment of crude ore, fresh from Nature's crucible, but a bit of jeweler's handicraft in the form of a plain gold ring. 16 | Looking at it more attentively, he saw that it bore the inscription, "May to Cass." 17 | Like most of his fellow gold-seekers, Cass was superstitious. 18 | 19 | The fountain of classic wisdom, Hypatia herself. 20 | As the ancient sage--the name is unimportant to a monk--pumped water nightly that he might study by day, so I, the guardian of cloaks and parasols, at the sacred doors of her lecture-room, imbibe celestial knowledge. 21 | From my youth I felt in me a soul above the matter-entangled herd. 22 | She revealed to me the glorious fact, that I am a spark of Divinity itself. 23 | A fallen star, I am, sir!' continued he, pensively, stroking his lean stomach--'a fallen star!--fallen, if the dignity of philosophy will allow of the simile, among the hogs of the lower world--indeed, even into the hog-bucket itself. Well, after all, I will show you the way to the Archbishop's. 24 | There is a philosophic pleasure in opening one's treasures to the modest young. 25 | Perhaps you will assist me by carrying this basket of fruit?' And the little man jumped up, put his basket on Philammon's head, and trotted off up a neighbouring street. 26 | Philammon followed, half contemptuous, half wondering at what this philosophy might be, which could feed the self-conceit of anything so abject as his ragged little apish guide; 27 | but the novel roar and whirl of the street, the perpetual stream of busy faces, the line of curricles, palanquins, laden asses, camels, elephants, which met and passed him, and squeezed him up steps and into doorways, as they threaded their way through the great Moon-gate into the ample street beyond, drove everything from his mind but wondering curiosity, and a vague, helpless dread of that great living wilderness, more terrible than any dead wilderness of sand which he had left behind. 28 | Already he longed for the repose, the silence of the Laura--for faces which knew him and smiled upon him; but it was too late to turn back now. 29 | His guide held on for more than a mile up the great main street, crossed in the centre of the city, at right angles, by one equally magnificent, at each end of which, miles away, appeared, dim and distant over the heads of the living stream of passengers, the yellow sand-hills of the desert; 30 | while at the end of the vista in front of them gleamed the blue harbour, through a network of countless masts. 31 | At last they reached the quay at the opposite end of the street; 32 | and there burst on Philammon's astonished eyes a vast semicircle of blue sea, ringed with palaces and towers. 33 | He stopped involuntarily; and his little guide stopped also, and looked askance at the young monk, to watch the effect which that grand panorama should produce on him. 34 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bert/tokenization_test.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import os 20 | import tempfile 21 | import tokenization 22 | import six 23 | import tensorflow as tf 24 | 25 | 26 | class TokenizationTest(tf.test.TestCase): 27 | 28 | def test_full_tokenizer(self): 29 | vocab_tokens = [ 30 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 31 | "##ing", "," 32 | ] 33 | with tempfile.NamedTemporaryFile(delete=False) as vocab_writer: 34 | if six.PY2: 35 | vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) 36 | else: 37 | vocab_writer.write("".join( 38 | [x + "\n" for x in vocab_tokens]).encode("utf-8")) 39 | 40 | vocab_file = vocab_writer.name 41 | 42 | tokenizer = tokenization.FullTokenizer(vocab_file) 43 | os.unlink(vocab_file) 44 | 45 | tokens = tokenizer.tokenize(u"UNwant\u00E9d,running") 46 | self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) 47 | 48 | self.assertAllEqual( 49 | tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9]) 50 | 51 | def test_chinese(self): 52 | tokenizer = tokenization.BasicTokenizer() 53 | 54 | self.assertAllEqual( 55 | tokenizer.tokenize(u"ah\u535A\u63A8zz"), 56 | [u"ah", u"\u535A", u"\u63A8", u"zz"]) 57 | 58 | def test_basic_tokenizer_lower(self): 59 | tokenizer = tokenization.BasicTokenizer(do_lower_case=True) 60 | 61 | self.assertAllEqual( 62 | tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "), 63 | ["hello", "!", "how", "are", "you", "?"]) 64 | self.assertAllEqual(tokenizer.tokenize(u"H\u00E9llo"), ["hello"]) 65 | 66 | def test_basic_tokenizer_no_lower(self): 67 | tokenizer = tokenization.BasicTokenizer(do_lower_case=False) 68 | 69 | self.assertAllEqual( 70 | tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "), 71 | ["HeLLo", "!", "how", "Are", "yoU", "?"]) 72 | 73 | def test_wordpiece_tokenizer(self): 74 | vocab_tokens = [ 75 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 76 | "##ing" 77 | ] 78 | 79 | vocab = {} 80 | for (i, token) in enumerate(vocab_tokens): 81 | vocab[token] = i 82 | tokenizer = tokenization.WordpieceTokenizer(vocab=vocab) 83 | 84 | self.assertAllEqual(tokenizer.tokenize(""), []) 85 | 86 | self.assertAllEqual( 87 | tokenizer.tokenize("unwanted running"), 88 | ["un", "##want", "##ed", "runn", "##ing"]) 89 | 90 | self.assertAllEqual( 91 | tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) 92 | 93 | def test_convert_tokens_to_ids(self): 94 | vocab_tokens = [ 95 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 96 | "##ing" 97 | ] 98 | 99 | vocab = {} 100 | for (i, token) in enumerate(vocab_tokens): 101 | vocab[token] = i 102 | 103 | self.assertAllEqual( 104 | tokenization.convert_tokens_to_ids( 105 | vocab, ["un", "##want", "##ed", "runn", "##ing"]), [7, 4, 5, 8, 9]) 106 | 107 | def test_is_whitespace(self): 108 | self.assertTrue(tokenization._is_whitespace(u" ")) 109 | self.assertTrue(tokenization._is_whitespace(u"\t")) 110 | self.assertTrue(tokenization._is_whitespace(u"\r")) 111 | self.assertTrue(tokenization._is_whitespace(u"\n")) 112 | self.assertTrue(tokenization._is_whitespace(u"\u00A0")) 113 | 114 | self.assertFalse(tokenization._is_whitespace(u"A")) 115 | self.assertFalse(tokenization._is_whitespace(u"-")) 116 | 117 | def test_is_control(self): 118 | self.assertTrue(tokenization._is_control(u"\u0005")) 119 | 120 | self.assertFalse(tokenization._is_control(u"A")) 121 | self.assertFalse(tokenization._is_control(u" ")) 122 | self.assertFalse(tokenization._is_control(u"\t")) 123 | self.assertFalse(tokenization._is_control(u"\r")) 124 | self.assertFalse(tokenization._is_control(u"\U0001F4A9")) 125 | 126 | def test_is_punctuation(self): 127 | self.assertTrue(tokenization._is_punctuation(u"-")) 128 | self.assertTrue(tokenization._is_punctuation(u"$")) 129 | self.assertTrue(tokenization._is_punctuation(u"`")) 130 | self.assertTrue(tokenization._is_punctuation(u".")) 131 | 132 | self.assertFalse(tokenization._is_punctuation(u"A")) 133 | self.assertFalse(tokenization._is_punctuation(u" ")) 134 | 135 | 136 | if __name__ == "__main__": 137 | tf.test.main() 138 | -------------------------------------------------------------------------------- /bert_study/T1_bert/bertCode.md: -------------------------------------------------------------------------------- 1 | # 【关于 Bert 源码解析 之 总览大局篇】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 论文链接:https://arxiv.org/pdf/1810.04805.pdf 6 | > 7 | > 本文链接:https://github.com/km1994/nlp_paper_study 8 | > 9 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 10 | > 11 | > 【注:手机阅读可能图片打不开!!!】 12 | 13 | ## 内容 14 | 15 | 16 | - [【关于 Bert 源码解析I 之 主体篇 】 那些的你不知道的事](bertCode1_modeling.md) 17 | - [【关于 Bert 源码解析I 之 主体篇 】 那些的你不知道的事](bertCode2_pretraining.md) 18 | - [【关于 Bert 源码解析I 之 主体篇 】 那些的你不知道的事](bertCode3_fineTune.md) 19 | - [【关于 Bert 源码解析I 之 主体篇 】 那些的你不知道的事](bertCode4_word2embedding.md) 20 | - [【关于 Bert 源码解析I 之 主体篇 】 那些的你不知道的事](bertCode5_similarity.md) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200528133755.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200528133755.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200624080740.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200624080740.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200624084515.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200624084515.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629083749.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629083749.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629084400.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629084400.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629085428.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629085428.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629085533.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629085533.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629085712.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629085712.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629085906.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629085906.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629092209.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629092209.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200629203527.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200629203527.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200630084746.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200630084746.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200701082543.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200701082543.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20200701091112.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20200701091112.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20201130205012.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20201130205012.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20201130205229.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20201130205229.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20201130205325.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20201130205325.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/20201130205357.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/20201130205357.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/v2-02f5f0a3a2bc5c8a0931e677df2a78a6_r.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/v2-02f5f0a3a2bc5c8a0931e677df2a78a6_r.jpg -------------------------------------------------------------------------------- /bert_study/T1_bert/img/zg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/zg.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/微信截图_20200625082324.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/微信截图_20200625082324.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/微信截图_20200625101800.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/微信截图_20200625101800.png -------------------------------------------------------------------------------- /bert_study/T1_bert/img/微信截图_20201128130050.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/img/微信截图_20201128130050.png -------------------------------------------------------------------------------- /bert_study/T1_bert/readme - 副本.md: -------------------------------------------------------------------------------- 1 | # 【关于Bert】 那些的你不知道的事 2 | 3 | > 作者:小莫 4 | > 5 | > 论文链接:https://arxiv.org/pdf/1810.04805.pdf 6 | > 7 | > 代码链接:https://github.com/google-research/bert 8 | > 9 | > 【注:手机阅读可能图片打不开!!!】 10 | 11 | ## 引言 12 | 13 | 本博客 主要 是本人在学习 Bert 时的**所遇、所思、所解**,通过以 **十五连弹** 的方式帮助大家更好的理解 该问题。 14 | 15 | ## 十五连弹 16 | 17 | 1. 【演变史】one-hot 是什么及所存在问题? 18 | 2. 【演变史】word2vec 是什么及所存在问题? 19 | 3. 【演变史】fastText 是什么及所存在问题? 20 | 4. 【演变史】elmo 是什么及所存在问题? 21 | 5. 【BERT】Bert 是什么? 22 | 6. 【BERT】Bert 三个关键点? 23 | 7. 【BERT】Bert 输入表征长啥样? 24 | 8. 【BERT】Bert 预训练任务? 25 | 9. 【BERT】Bert 预训练任务 Masked LM 怎么做? 26 | 10. 【BERT】Bert 预训练任务 Next Sentence Prediction 怎么做? 27 | 28 | 29 | 30 | ## 问题解答 31 | 32 | ### 【演变史】one-hot 是什么及所存在问题? 33 | 34 | - one-hot: 35 | - 介绍: 36 | - 用一个很长的向量来表示一个词,向量长度为词典的大小N,每个向量只有一个维度为1,其余维度全部为0,为1的位置表示该词语在词典的位置。 37 | - 特点: 38 | - 维度长:向量的维度为 **词典大小**; 39 | - 一一其零:每个向量**只有一个维度为1**,其余维度全部为0,**为1的位置表示该词语在词典的位置**; 40 | - 问题: 41 | - 维度灾难:容易受维数灾难的困扰,每个词语的维度就是语料库字典的长度; 42 | - 离散、稀疏问题:因为 one-Hot 中,句子向量,如果词出现则为1,没出现则为0,但是由于维度远大于句子长度,所以句子中的1远小于0的个数; 43 | - 维度鸿沟问题:词语的编码往往是随机的,导致不能很好地刻画词与词之间的相似性。 44 | 45 | ### 【演变史】wordvec 是什么及所存在问题? 46 | 47 | - 双剑客 48 | - CBOW vs Skip-gram 49 | - CBOW 50 | - 思想:用周围词预测中心词 51 | - ![](img/20200701091112.png) 52 | - Skip-gram 53 | - 思想:用中心词预测周围词 54 | - ![](img/20200629083749.png) 55 | - CBOW vs Skip-gram 哪一个好? 56 | - CBOW 可以理解为 一个老师教多个学生;(高等教育) 57 | - Skip-gram 可以理解为 一个学生被多个老师教;(补习班) 58 | - 那问题来了? 59 | - 最后 哪个学生 成绩 会更好? 60 | - 存在问题: 61 | - 多义词问题 62 | - 因为 word2vec 为静态方式,即训练好后,每个词表达固定; 63 | 64 | ### 【演变史】fastText 是什么及所存在问题? 65 | 66 | - 动机 67 | - word-level Model 68 | - 介绍: 69 | - 基于word单词作为基本单位的,这种方式虽然能够很好的对词库中每一个词进行向量表示 70 | - 问题: 71 | - OOV 问题 72 | - 问题描述:容易出现单词不存在于词汇库中的情况; 73 | - 解决方法:最佳语料规模,使系统能够获得更多的词汇量; 74 | - 误拼障碍 75 | - 问题描述:如果遇到了不正式的拼写, 系统很难进行处理; 76 | - 解决方法:矫正或加规则约束; 77 | - 做翻译问题时, 音译姓名比较难做到 78 | - Character-Level Model 79 | - 介绍: 80 | - 基于 Character 作为基本单位的,这种方式虽然能够很好的对字库中每一个 Char 进行向量表示 81 | - 优点: 82 | - 能够解决 Word-level 所存在的 OOV 问题; 83 | - 拼写类似的单词 具有类似的 embedding; 84 | - 问题: 85 | - Character-level 的输入句子变长; 86 | - 数据变得稀疏; 87 | - 对于远距离的依赖难以学到; 88 | - 训练速度降低; 89 | - 解决方法: 90 | - Lee 等 提出了利用多层 conv 和 pooling 和 highway layer 的方式来解决该问题,其结构如下所示: 91 | - 输入的字符首先需要经过 Character embedding 层,并被转化为 character embeddings 表示; 92 | - 采用 不同窗口大小的卷积核对输入字符的 character embeddings 表示进行卷积操作,论文中采用的窗口的大小分别为 3、4、5 ,也就是说学习 Character-level 的 3-gram、4-gram、5-gram; 93 | - 对不同卷积层的卷积结果进行 max-pooling 操作,即捕获其最显著特征生成 segment embedding; 94 | - segment embedding 经过 Highway Network (有些类似于Residual network,方便深层网络中信息的流通,不过加入了一些控制信息流量的gate); 95 | - 输出结果 再经过 单层 BiGRU,得到最终 的 encoder output; 96 | - 之后,decoder再利用Attention机制以及character level GRU进行decode 97 | - 通过这种方式不仅能够解决 Word-level 所存在的 OOV 问题,而且能够捕获 句子的 3-gram、4-gram、5-gram 信息,这个也是 后期 FastText 的想法雏形; 98 | 99 | ![](img/20200629203527.png) 100 | 101 | - 引言 102 | 在前面,我们已经介绍和比较了 word-level 和 character-level 的优缺点,并根据其特点,提出一种介于 word-level Model 和 Character-level 之间的 Model —— Subword Model。 103 | 104 | 那么,我们可不可以采取类似于上面的subword的思路来产生更好的word embedding呢? 105 | 106 | FAIR的FastText就是利用subword将word2vec扩充,有效的构建embedding。 107 | - 基本思想 108 | 109 | 将每个 word 表示成 bag of character n-gram 以及单词本身的集合,例如对于where这个单词和n=3的情况,它可以表示为 , ,其中"<",">"为代表单词开始与结束的特殊标记。 110 | 111 | 假设对于word $w$ ,其n-gram集合用 $G_w$ 表示,每个 n-gram 的矢量表示为![](img/zg.png),则每个单词可以表示成其所有n-gram的矢量和的形式,而center word $w$ 与context word $c$ 的分数就可表示成 112 | 113 | ![](img/20200528133755.png) 114 | 115 | 之后就可以按照经典的word2vec算法训练得到这些特征向量。 116 | 117 | 这种方式既保持了word2vec计算速度快的优点,又解决了遇到training data中没见过的oov word的表示问题,可谓一举两得。 118 | 119 | - 模型结构 120 | - 每个单词通过嵌入层可以得到词向量; 121 | - 然后将所有词向量平均可以得到文本的向量表达; 122 | - 在输入分类器,使用softmax计算各个类别的概率; 123 | - ![](img/20200629084400.png) 124 | - 核心方法介绍: 125 | - 词内的n-gram信息(subword n-gram information) 126 | - 动机: 127 | - 之前方法: 128 | - 以词汇表中的独立单词作为基本单元来进行训练学习的 129 | - 存在问题: 130 | - 低频词、罕见词:由于在语料中本身出现的次数就少,得不到足够的训练,效果不佳 131 | - 未登录词:如果出现了一些在词典中都没有出现过的词,或者带有某些拼写错误的词,传统模型更加无能为力 132 | - 解决方法: 133 | - s1. 将一个单词打散到字符级别; 134 | - s2. 利用字符级别的n-gram信息来捕捉字符间的顺序关系 135 | - 目的:以此丰富单词内部更细微的语义 136 | - 举例: 137 | - 对于一个单词“google”,为了表达单词前后边界,我们加入<>两个字符,即变形为“”; 138 | - 抽取所有的tri-gram信息:G = { }; 139 | - 通过这种方式:原始的一个单词google,就被一个字符级别的n-gram集合所表达; 140 | - 训练过程: 141 | - s1:每个n-gram都会对应训练一个向量; 142 | - s2:原来完整单词的词向量就由它对应的所有n-gram的向量求和得到; 143 | - s3:所有的单词向量以及字符级别的n-gram向量会同时相加求平均作为训练模型的输入; 144 | - 存在问题: 145 | - 问题 1: 146 | - 由于需要估计的参数多,模型可能会比较膨胀 147 | - 压缩模型的建议: 148 | - 采用hash-trick:由于n-gram原始的空间太大,可以用某种hash函数将其映射到固定大小的buckets中去,从而实现内存可控; 149 | - 采用quantize命令:对生成的模型进行参数量化和压缩; 150 | - 减小最终向量的维度。 151 | - 层次化Softmax回归(Hierarchical Softmax) 152 | - 动机: 153 | - 传统 softmax 154 | - 介绍: 155 | - 以隐藏层的输出h为输入,经过线性和指数变换后,再进行全局的归一化处理,找到概率最大的输出项; 156 | - 问题: 157 | - 当词汇数量V较大时(一般会到几十万量级),Softmax计算代价很大,是O(V)量级。 158 | - 思想: 159 | - 将一个全局多分类的问题,转化成为了若干个二元分类问题,从而将计算复杂度从O(V)降到O(logV); 160 | - 每个二元分类问题,由一个基本的逻辑回归单元来实现 161 | - 介绍: 162 | - ![](img/20200629085428.png) 163 | - 步骤: 164 | - 从根结点开始,每个中间结点(标记成灰色)都是一个逻辑回归单元,根据它的输出来选择下一步是向左走还是向右走; 165 | - 上图示例中实际上走了一条“左-左-右”的路线,从而找到单词w₂。而最终输出单词w₂的概率,等于中间若干逻辑回归单元输出概率的连乘积; 166 | - ![](img/20200629085533.png) 167 | - 问题: 168 | - 如何构造每个逻辑回归单元的输入 169 | - ![](img/20200629085712.png) 170 | - 特殊函数 ⟦x⟧ 171 | - 如果下一步需要向左走其函数值定义为1,向右则取-1。在训练时,我们知道最终输出叶子结点,并且从根结点到叶子结点的每一步的路径也是确定的。 172 | - 每个内部结点(逻辑回归单元)对应的一个向量 v' 173 | - 以在训练过程中学习和更新 174 | - h 是网络中隐藏层的输出 175 | - 如何建立这棵用于判断的树形结构? 176 | - 霍夫曼树的构造 177 | - 处理机制:将字符信息编码成为0/1二进制串 178 | - 结构介绍:给出现频繁的字符较短的编码,出现较少的字符以较长的编码,是最经济的方案 179 | - 构造步骤: 180 | - ![](img/20200629085906.png) 181 | 182 | ### 【演变史】elmo 是什么及所存在问题? 183 | 184 | - 动机 185 | - 多义词问题: 186 | - 因为 one-hot、word2vec、fastText 为静态方式,即训练好后,每个词表达固定; 187 | - 单向性: 188 | - 因为 one-hot、word2vec、fastText 都是 从左向右 学习,导致该方法 不能 同时考虑 两边信息; 189 | - 特点: 190 | - 基于特征融合 的 word emb 191 | - 思想: 192 | - 预训练时,使用语言模型学习一个单词的emb(**多义词无法解决**); 193 | - 使用时,单词间具有特定上下文,可根据上下文单词语义调整单词的emb表示(**可解决多义词问题**) 194 | - 理解:因为预训练过程中,emlo 中 的 lstm 能够学习到 每个词 对应的 上下文信息,并保存在网络中,在 fine-turning 时,下游任务 能够对 该 网络进行 fine-turning,使其 学习到新特征; 195 | 196 | ![](img/20200629092209.png) 197 | 198 | - 问题: 199 | - 1. 在做序列编码任务时,使用 LSTM; 200 | - 2. ELMo 采用双向拼接的融合特征,比Bert一体化融合特征方式弱; 201 | 202 | ### 【BERT】Bert 是什么? 203 | 204 | BERT(Bidirectional Encoder Representations from Transformers)是一种Transformer的双向编码器,旨在通过在左右上下文中共有的条件计算来预先训练来自无标号文本的深度双向表示。因此,经过预先训练的BERT模型只需一个额外的输出层就可以进行微调,从而为各种自然语言处理任务生成最新模型。 205 | 206 | 这个也是我们常说的 【预训练】+【微调】 207 | 208 | ### 【BERT】Bert 三个关键点? 209 | 210 | - 基于 transformer 结构 211 | - 大量语料预训练: 212 | - 介绍:在包含整个维基百科的无标签号文本的大语料库中(足足有25亿字!) 和图书语料库(有8亿字)中进行预训练; 213 | - 优点:大语料 能够 覆盖 更多 的 信息; 214 | - 双向模型: 215 | - BERT是一个“深度双向”的模型。双向意味着BERT在训练阶段从所选文本的左右上下文中汲取信息 216 | - 举例 217 | - ![](img/20200630084746.png) 218 | - > BERT同时捕获左右上下文 219 | - 问题: 220 | - 如果仅取左上下文或右上下文来预测单词“bank”的性质,那么在两个给定示例中,至少有一个会出错; 221 | - 解决方法: 222 | - 在做出预测之前同时考虑左上下文和右上下文 223 | 224 | ### 【BERT】Bert 输入表征长啥样? 225 | 226 | - input 组成: 227 | - Token embedding: 228 | - Segment embedding: 229 | - Position embedding: 230 | 231 | ![](img/20200701082543.png) 232 | 233 | - 特点: 234 | - 在30000个词上使用了WordPiece嵌入,把拆分的词片段(word pieces)用"##"标注; 235 | - eg:在图中"playing"-"play ##ing"; 236 | - 最大长度:使用了学习过的位置嵌入,支持序列长度达512的 Token; 237 | - 特殊分类嵌入([CLS]):位于句首,在最终的隐藏层中(也就是转换器的输出)对应的是分类任务中序列标识的**聚合表征**。非分类任务中这一标记将被忽略; 238 | - 区分句子对在 序列 中位置的方式: 239 | - s1:用特殊词块([SEP])将它们分开; 240 | - s2:给第一句的每一个标记添加一个学习到的句子 A 的嵌入,给第二句的每个标记添加一个学习到的句子 B 的嵌入; 241 | - 对于单句输入,我们只使用句子A嵌入 242 | 243 | ### 【BERT】Bert 预训练任务? 244 | 245 | - 预训练 包含 两个 Task: 246 | - Task 1:Masked LM 247 | - Task 2:Next Sentence Prediction 248 | 249 | ### 【BERT】Bert 预训练任务 Masked LM 怎么做? 250 | 251 | - 动机: 252 | - 双向模型 由于 可以分别 从左到右 和 从右到左 训练,使得 每个词 都能 通过多层 上下文 “看到自己”; 253 | - 方法:Masked LM 254 | - 做法: 255 | - s1:随机遮蔽输入词块的某些部分; 256 | - s2:仅预测那些被遮蔽词块; 257 | - s3:被遮盖的标记对应的最终的隐藏向量被当作softmax的关于该词的一个输出,和其他标准语言模型中相同 258 | - 问题: 259 | - 预训练和微调之间的不匹配: 260 | - 解释:在微调期间从未看到[MASK]词块 261 | - 解决方法: 262 | - 以一定概率用 [MASK] 词块替换“遮蔽”单词,论文采用 15% 的概率 随机选择 词块 263 | - 举例: 264 | - 句子:我的狗是毛茸茸的 265 | - 操作: 266 | - 80%的概率:用[MASK]词块替换单词,例如,我的狗是毛茸茸的!我的狗是[MASK]; 267 | - 10%的概率:用随机词替换遮蔽词,例如,我的狗是毛茸茸的!我的狗是苹果; 268 | - 10%的概率:保持单词不变,例如,我的狗是毛茸茸的!我的狗毛茸茸的。 269 | - 目的:是将该表征偏向于实际观察到的单词 270 | - 目的:模型需要学习每个输入词块的分布式语境表征 271 | - 收敛速度慢问题: 272 | - 原因:每 batch 中只预测了15%的词块,导致 收敛速度慢 273 | 274 | ### 【BERT】Bert 预训练任务 Next Sentence Prediction 怎么做? 275 | 276 | - 动机:很多重要的下游任务,例如问答(QA)和自然语言推理(NLI),都是基于对两个文本句子间关系的理解,而这种关系并非通过语言建模直接获得 277 | - 方法: 278 | - 预训练 一个 二值化 NSP 任务 学习 句子间关系; 279 | - 操作: 280 | - 选择句子A和B作为预训练样本:B有50%的可能是A的下一句,也有50%的可能是来自语料库的随机句子 281 | - 举例: 282 | - > 输入=[CLS]男子去[MASK]商店[SEP]他买了一加仑[MASK]牛奶[SEP] 283 | - > Label= IsNext 284 | - > 输入=[CLS]男人[面具]到商店[SEP]企鹅[面具]是飞行##少鸟[SEP] 285 | - > Label= NotNext 286 | 287 | ### 【BERT】如何 fine-turning? 288 | 289 | - 动机:获得输入序列的固定维度池化表征 290 | - 操作: 291 | - 对该输入第一个词块采取最终隐藏状态(例如,该变换器输出),通过对应于特殊[CLS]词嵌入来构造。我们将该向量表示为$C∈R^H$。 292 | - 微调期间添加的唯一新参数是分类层向量$W∈R^{KxH}$,其中K是分类器标签的数量。 293 | - 该标签概率$P∈R^K$用标准softmax函数,P=softmax(CWT)计算。BERT和W的所有参数都经过联动地微调,以最大化正确标签的对数概率 294 | 295 | 296 | ## 参考 297 | 298 | 1. [知识网络](https://shimo.im/mindmaps/hGxYWjcvvvwJWrGR) 299 | 2. [ELMO、BERT、ERNIE、GPT](https://blog.csdn.net/Forlogen/article/details/92011185) 300 | 3. [搞懂 NLP 中的词向量,看这一篇就足够](https://www.infoq.cn/article/PFvZxgGDm27453BbS24W) 301 | 4. [后BERT时代:15个预训练模型对比分析与关键点探索(附链接)](https://www.jiqizhixin.com/articles/2019-08-26-16) -------------------------------------------------------------------------------- /bert_study/T1_bert/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于Bert】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 论文链接:https://arxiv.org/pdf/1810.04805.pdf 6 | > 7 | > 代码链接:https://github.com/google-research/bert 8 | > 9 | > 【注:手机阅读可能图片打不开!!!】 10 | 11 | ## 引言 12 | 13 | 本博客 主要 是本人在学习 Bert 时的**所遇、所思、所解**,通过以 **十二连弹** 的方式帮助大家更好的理解 该问题。 14 | 15 | ## 十二连弹 16 | 17 | 1. 【演变史】one-hot 是什么及所存在问题? 18 | 2. 【演变史】word2vec 是什么及所存在问题? 19 | 3. 【演变史】fastText 是什么及所存在问题? 20 | 4. 【演变史】elmo 是什么及所存在问题? 21 | 5. 【BERT】Bert 是什么? 22 | 6. 【BERT】Bert 三个关键点? 23 | 7. 【BERT】Bert 输入表征长啥样? 24 | 8. 【BERT】Bert 预训练任务? 25 | 9. 【BERT】Bert 预训练任务 Masked LM 怎么做? 26 | 10. 【BERT】Bert 预训练任务 Next Sentence Prediction 怎么做? 27 | 11. 【BERT】如何 fine-turning? 28 | 12. 【对比】多义词问题及解决方法? 29 | 30 | 31 | 32 | ## 问题解答 33 | 34 | ### 【演变史】one-hot 是什么及所存在问题? 35 | 36 | - one-hot: 37 | - 介绍: 38 | - 用一个很长的向量来表示一个词,向量长度为词典的大小N,每个向量只有一个维度为1,其余维度全部为0,为1的位置表示该词语在词典的位置。 39 | - 特点: 40 | - 维度长:向量的维度为 **词典大小**; 41 | - 一一其零:每个向量**只有一个维度为1**,其余维度全部为0,**为1的位置表示该词语在词典的位置**; 42 | - 问题: 43 | - 维度灾难:容易受维数灾难的困扰,每个词语的维度就是语料库字典的长度; 44 | - 离散、稀疏问题:因为 one-Hot 中,句子向量,如果词出现则为1,没出现则为0,但是由于维度远大于句子长度,所以句子中的1远小于0的个数; 45 | - 维度鸿沟问题:词语的编码往往是随机的,导致不能很好地刻画词与词之间的相似性。 46 | 47 | 48 | 49 | 50 | 51 | ### 【演变史】wordvec 是什么及所存在问题? 52 | 53 | - 双剑客 54 | - CBOW vs Skip-gram 55 | - CBOW 56 | - 思想:用周围词预测中心词 57 | - ![](img/20200701091112.png) 58 | - Skip-gram 59 | - 思想:用中心词预测周围词 60 | - ![](img/20200629083749.png) 61 | - CBOW vs Skip-gram 哪一个好? 62 | - CBOW 可以理解为 一个老师教多个学生;(高等教育) 63 | - Skip-gram 可以理解为 一个学生被多个老师教;(补习班) 64 | - 那问题来了? 65 | - 最后 哪个学生 成绩 会更好? 66 | - 存在问题: 67 | - 多义词问题 68 | - 因为 word2vec 为静态方式,即训练好后,每个词表达固定; 69 | 70 | 71 | 72 | 73 | ### 【演变史】fastText 是什么及所存在问题? 74 | 75 | - 动机 76 | - word-level Model 77 | - 介绍: 78 | - 基于word单词作为基本单位的,这种方式虽然能够很好的对词库中每一个词进行向量表示 79 | - 问题: 80 | - OOV 问题 81 | - 问题描述:容易出现单词不存在于词汇库中的情况; 82 | - 解决方法:最佳语料规模,使系统能够获得更多的词汇量; 83 | - 误拼障碍 84 | - 问题描述:如果遇到了不正式的拼写, 系统很难进行处理; 85 | - 解决方法:矫正或加规则约束; 86 | - 做翻译问题时, 音译姓名比较难做到 87 | - Character-Level Model 88 | - 介绍: 89 | - 基于 Character 作为基本单位的,这种方式虽然能够很好的对字库中每一个 Char 进行向量表示 90 | - 优点: 91 | - 能够解决 Word-level 所存在的 OOV 问题; 92 | - 拼写类似的单词 具有类似的 embedding; 93 | - 问题: 94 | - Character-level 的输入句子变长; 95 | - 数据变得稀疏; 96 | - 对于远距离的依赖难以学到; 97 | - 训练速度降低; 98 | - 解决方法: 99 | - Lee 等 提出了利用多层 conv 和 pooling 和 highway layer 的方式来解决该问题,其结构如下所示: 100 | - 输入的字符首先需要经过 Character embedding 层,并被转化为 character embeddings 表示; 101 | - 采用 不同窗口大小的卷积核对输入字符的 character embeddings 表示进行卷积操作,论文中采用的窗口的大小分别为 3、4、5 ,也就是说学习 Character-level 的 3-gram、4-gram、5-gram; 102 | - 对不同卷积层的卷积结果进行 max-pooling 操作,即捕获其最显著特征生成 segment embedding; 103 | - segment embedding 经过 Highway Network (有些类似于Residual network,方便深层网络中信息的流通,不过加入了一些控制信息流量的gate); 104 | - 输出结果 再经过 单层 BiGRU,得到最终 的 encoder output; 105 | - 之后,decoder再利用Attention机制以及character level GRU进行decode 106 | - 通过这种方式不仅能够解决 Word-level 所存在的 OOV 问题,而且能够捕获 句子的 3-gram、4-gram、5-gram 信息,这个也是 后期 FastText 的想法雏形; 107 | 108 | ![](img/20200629203527.png) 109 | 110 | - 引言 111 | 在前面,我们已经介绍和比较了 word-level 和 character-level 的优缺点,并根据其特点,提出一种介于 word-level Model 和 Character-level 之间的 Model —— Subword Model。 112 | 113 | 那么,我们可不可以采取类似于上面的subword的思路来产生更好的word embedding呢? 114 | 115 | FAIR的FastText就是利用subword将word2vec扩充,有效的构建embedding。 116 | - 基本思想 117 | 118 | 将每个 word 表示成 bag of character n-gram 以及单词本身的集合,例如对于where这个单词和n=3的情况,它可以表示为 , ,其中"<",">"为代表单词开始与结束的特殊标记。 119 | 120 | 假设对于word $w$ ,其n-gram集合用 $G_w$ 表示,每个 n-gram 的矢量表示为![](img/zg.png),则每个单词可以表示成其所有n-gram的矢量和的形式,而center word $w$ 与context word $c$ 的分数就可表示成 121 | 122 | ![](img/20200528133755.png) 123 | 124 | 之后就可以按照经典的word2vec算法训练得到这些特征向量。 125 | 126 | 这种方式既保持了word2vec计算速度快的优点,又解决了遇到training data中没见过的oov word的表示问题,可谓一举两得。 127 | 128 | - 模型结构 129 | - 每个单词通过嵌入层可以得到词向量; 130 | - 然后将所有词向量平均可以得到文本的向量表达; 131 | - 在输入分类器,使用softmax计算各个类别的概率; 132 | - ![](img/20200629084400.png) 133 | - 核心方法介绍: 134 | - 词内的n-gram信息(subword n-gram information) 135 | - 动机: 136 | - 之前方法: 137 | - 以词汇表中的独立单词作为基本单元来进行训练学习的 138 | - 存在问题: 139 | - 低频词、罕见词:由于在语料中本身出现的次数就少,得不到足够的训练,效果不佳 140 | - 未登录词:如果出现了一些在词典中都没有出现过的词,或者带有某些拼写错误的词,传统模型更加无能为力 141 | - 解决方法: 142 | - s1. 将一个单词打散到字符级别; 143 | - s2. 利用字符级别的n-gram信息来捕捉字符间的顺序关系 144 | - 目的:以此丰富单词内部更细微的语义 145 | - 举例: 146 | - 对于一个单词“google”,为了表达单词前后边界,我们加入<>两个字符,即变形为“”; 147 | - 抽取所有的tri-gram信息:G = { }; 148 | - 通过这种方式:原始的一个单词google,就被一个字符级别的n-gram集合所表达; 149 | - 训练过程: 150 | - s1:每个n-gram都会对应训练一个向量; 151 | - s2:原来完整单词的词向量就由它对应的所有n-gram的向量求和得到; 152 | - s3:所有的单词向量以及字符级别的n-gram向量会同时相加求平均作为训练模型的输入; 153 | - 存在问题: 154 | - 问题 1: 155 | - 由于需要估计的参数多,模型可能会比较膨胀 156 | - 压缩模型的建议: 157 | - 采用hash-trick:由于n-gram原始的空间太大,可以用某种hash函数将其映射到固定大小的buckets中去,从而实现内存可控; 158 | - 采用quantize命令:对生成的模型进行参数量化和压缩; 159 | - 减小最终向量的维度。 160 | - 层次化Softmax回归(Hierarchical Softmax) 161 | - 动机: 162 | - 传统 softmax 163 | - 介绍: 164 | - 以隐藏层的输出h为输入,经过线性和指数变换后,再进行全局的归一化处理,找到概率最大的输出项; 165 | - 问题: 166 | - 当词汇数量V较大时(一般会到几十万量级),Softmax计算代价很大,是O(V)量级。 167 | - 思想: 168 | - 将一个全局多分类的问题,转化成为了若干个二元分类问题,从而将计算复杂度从O(V)降到O(logV); 169 | - 每个二元分类问题,由一个基本的逻辑回归单元来实现 170 | - 介绍: 171 | - ![](img/20200629085428.png) 172 | - 步骤: 173 | - 从根结点开始,每个中间结点(标记成灰色)都是一个逻辑回归单元,根据它的输出来选择下一步是向左走还是向右走; 174 | - 上图示例中实际上走了一条“左-左-右”的路线,从而找到单词w₂。而最终输出单词w₂的概率,等于中间若干逻辑回归单元输出概率的连乘积; 175 | - ![](img/20200629085533.png) 176 | - 问题: 177 | - 如何构造每个逻辑回归单元的输入 178 | - ![](img/20200629085712.png) 179 | - 特殊函数 ⟦x⟧ 180 | - 如果下一步需要向左走其函数值定义为1,向右则取-1。在训练时,我们知道最终输出叶子结点,并且从根结点到叶子结点的每一步的路径也是确定的。 181 | - 每个内部结点(逻辑回归单元)对应的一个向量 v' 182 | - 以在训练过程中学习和更新 183 | - h 是网络中隐藏层的输出 184 | - 如何建立这棵用于判断的树形结构? 185 | - 霍夫曼树的构造 186 | - 处理机制:将字符信息编码成为0/1二进制串 187 | - 结构介绍:给出现频繁的字符较短的编码,出现较少的字符以较长的编码,是最经济的方案 188 | - 构造步骤: 189 | - ![](img/20200629085906.png) 190 | 191 | 192 | 193 | 194 | ### 【演变史】elmo 是什么及所存在问题? 195 | 196 | - 动机 197 | - 多义词问题: 198 | - 因为 one-hot、word2vec、fastText 为静态方式,即训练好后,每个词表达固定; 199 | - 单向性: 200 | - 因为 one-hot、word2vec、fastText 都是 从左向右 学习,导致该方法 不能 同时考虑 两边信息; 201 | - 特点: 202 | - 基于特征融合 的 word emb 203 | - 思想: 204 | - 预训练时,使用语言模型学习一个单词的emb(**多义词无法解决**); 205 | - 使用时,单词间具有特定上下文,可根据上下文单词语义调整单词的emb表示(**可解决多义词问题**) 206 | - 理解:因为预训练过程中,emlo 中 的 lstm 能够学习到 每个词 对应的 上下文信息,并保存在网络中,在 fine-turning 时,下游任务 能够对 该 网络进行 fine-turning,使其 学习到新特征; 207 | 208 | ![](img/20200629092209.png) 209 | 210 | - 问题: 211 | - 1. 在做序列编码任务时,使用 LSTM; 212 | - 2. ELMo 采用双向拼接的融合特征,比Bert一体化融合特征方式弱; 213 | 214 | 215 | 216 | ### 【BERT】Bert 是什么? 217 | 218 | BERT(Bidirectional Encoder Representations from Transformers)是一种Transformer的双向编码器,旨在通过在左右上下文中共有的条件计算来预先训练来自无标号文本的深度双向表示。因此,经过预先训练的BERT模型只需一个额外的输出层就可以进行微调,从而为各种自然语言处理任务生成最新模型。 219 | 220 | 这个也是我们常说的 【预训练】+【微调】 221 | 222 | 223 | 224 | ### 【BERT】Bert 三个关键点? 225 | 226 | - 基于 transformer 结构 227 | - 大量语料预训练: 228 | - 介绍:在包含整个维基百科的无标签号文本的大语料库中(足足有25亿字!) 和图书语料库(有8亿字)中进行预训练; 229 | - 优点:大语料 能够 覆盖 更多 的 信息; 230 | - 双向模型: 231 | - BERT是一个“深度双向”的模型。双向意味着BERT在训练阶段从所选文本的左右上下文中汲取信息 232 | - 举例 233 | - ![](img/20200630084746.png) 234 | - > BERT同时捕获左右上下文 235 | - 问题: 236 | - 如果仅取左上下文或右上下文来预测单词“bank”的性质,那么在两个给定示例中,至少有一个会出错; 237 | - 解决方法: 238 | - 在做出预测之前同时考虑左上下文和右上下文 239 | 240 | 241 | 242 | 243 | ### 【BERT】Bert 输入输出表征长啥样? 244 | 245 | - input 组成: 246 | - Token embedding 字向量: BERT模型通过查询字向量表将文本中的每个字转换为一维向量,作为模型输入; 247 | - Segment embedding 文本向量: 该向量的取值在模型训练过程中自动学习,用于刻画文本的全局语义信息,并与单字/词的语义信息相融合; 248 | - Position embedding 位置向量:由于出现在文本不同位置的字/词所携带的语义信息存在差异(比如:“我爱你”和“你爱我”),因此,BERT模型对不同位置的字/词分别附加一个不同的向量以作区分 249 | - output 组成:输入各字对应的融合全文语义信息后的向量表示 250 | - 251 | ![](img/20200701082543.png) 252 | 253 | - 特点: 254 | - 在30000个词上使用了WordPiece嵌入,把拆分的词片段(word pieces)用"##"标注; 255 | - eg:在图中"playing"-"play ##ing"; 256 | - 最大长度:使用了学习过的位置嵌入,支持序列长度达512的 Token; 257 | - 特殊分类嵌入([CLS]):位于句首,在最终的隐藏层中(也就是转换器的输出)对应的是分类任务中序列标识的**聚合表征**。非分类任务中这一标记将被忽略; 258 | - 区分句子对在 序列 中位置的方式: 259 | - s1:用特殊词块([SEP])将它们分开; 260 | - s2:给第一句的每一个标记添加一个学习到的句子 A 的嵌入,给第二句的每个标记添加一个学习到的句子 B 的嵌入; 261 | - 对于单句输入,我们只使用句子A嵌入 262 | 263 | 264 | 265 | 266 | ### 【BERT】Bert 预训练任务? 267 | 268 | - 预训练 包含 两个 Task: 269 | - Task 1:Masked LM 270 | - Task 2:Next Sentence Prediction 271 | 272 | 273 | 274 | 275 | ### 【BERT】Bert 预训练任务 Masked LM 怎么做? 276 | 277 | - 动机: 278 | - 双向模型 由于 可以分别 从左到右 和 从右到左 训练,使得 每个词 都能 通过多层 上下文 “看到自己”; 279 | - 方法:Masked LM 280 | - 做法: 281 | - s1:随机遮蔽输入词块的某些部分; 282 | - s2:仅预测那些被遮蔽词块; 283 | - s3:被遮盖的标记对应的最终的隐藏向量被当作softmax的关于该词的一个输出,和其他标准语言模型中相同 284 | - 问题: 285 | - 预训练和微调之间的不匹配: 286 | - 解释:在微调期间从未看到[MASK]词块 287 | - 解决方法: 288 | - 以一定概率用 [MASK] 词块替换“遮蔽”单词,论文采用 15% 的概率 随机选择 词块 289 | - 举例: 290 | - 句子:我的狗是毛茸茸的 291 | - 操作: 292 | - 80%的概率:用[MASK]词块替换单词,例如,我的狗是毛茸茸的!我的狗是[MASK]; 293 | - 10%的概率:用随机词替换遮蔽词,例如,我的狗是毛茸茸的!我的狗是苹果; 294 | - 10%的概率:保持单词不变,例如,我的狗是毛茸茸的!我的狗毛茸茸的。 295 | - 目的:是将该表征偏向于实际观察到的单词 296 | - 目的:模型需要学习每个输入词块的分布式语境表征 297 | - 收敛速度慢问题: 298 | - 原因:每 batch 中只预测了15%的词块,导致 收敛速度慢 299 | 300 | 301 | 302 | 303 | ### 【BERT】Bert 预训练任务 Next Sentence Prediction 怎么做? 304 | 305 | - 动机:很多重要的下游任务,例如问答(QA)和自然语言推理(NLI),都是基于对两个文本句子间关系的理解,而这种关系并非通过语言建模直接获得 306 | - 方法: 307 | - 预训练 一个 二值化 NSP 任务 学习 句子间关系; 308 | - 操作: 309 | - 选择句子A和B作为预训练样本:B有50%的可能是A的下一句,也有50%的可能是来自语料库的随机句子 310 | - 举例: 311 | - > 输入=[CLS]男子去[MASK]商店[SEP]他买了一加仑[MASK]牛奶[SEP] 312 | - > Label= IsNext 313 | - > 输入=[CLS]男人[面具]到商店[SEP]企鹅[面具]是飞行##少鸟[SEP] 314 | - > Label= NotNext 315 | 316 | 317 | 318 | 319 | ### 【BERT】如何 fine-turning? 320 | 321 | - 动机:获得输入序列的固定维度池化表征 322 | - 操作: 323 | - 对该输入第一个词块采取最终隐藏状态(例如,该变换器输出),通过对应于特殊[CLS]词嵌入来构造。我们将该向量表示为$C∈R^H$。 324 | - 微调期间添加的唯一新参数是分类层向量$W∈R^{KxH}$,其中K是分类器标签的数量。 325 | - 该标签概率$P∈R^K$用标准softmax函数,P=softmax(CWT)计算。BERT和W的所有参数都经过联动地微调,以最大化正确标签的对数概率 326 | 327 | 328 | 329 | 330 | ### 【BERT】BERT的两个预训练任务对应的损失函数是什么(用公式形式展示)? 331 | 332 | - Bert 损失函数组成: 333 | - 第一部分是来自 Mask-LM 的单词级别分类任务; 334 | - 另一部分是句子级别的分类任务; 335 | - 优点:通过这两个任务的联合学习,可以使得 BERT 学习到的表征既有 token 级别信息,同时也包含了句子级别的语义信息。 336 | - 损失函数 337 | 338 | ![](img/20201130205012.png) 339 | 340 | > 注: 341 | > θ:BERT 中 Encoder 部分的参数; 342 | > θ1:是 Mask-LM 任务中在 Encoder 上所接的输出层中的参数; 343 | > θ2:是句子预测任务中在 Encoder 接上的分类器参数; 344 | 345 | - 在第一部分的损失函数中,如果被 mask 的词集合为 M,因为它是一个词典大小 |V| 上的多分类问题,所用的损失函数叫做负对数似然函数(且是最小化,等价于最大化对数似然函数),那么具体说来有: 346 | 347 | ![](img/20201130205229.png) 348 | 349 | - 在第一部分的损失函数中,在句子预测任务中,也是一个分类问题的损失函数: 350 | 351 | ![](img/20201130205325.png) 352 | 353 | - 两个任务联合学习的损失函数是: 354 | 355 | ![](img/20201130205357.png) 356 | 357 | 358 | 359 | 360 | 361 | ### 【对比】多义词问题及解决方法? 362 | 363 | - 问题:什么是多义词? 364 | - 一个单词在不同场景下意思不同 365 | - 举例: 366 | - 单词 Bank,有“银行”、“河岸”两个含义 367 | - 问题:word2vec 为什么解决不了多义词问题? 368 | - 由于 word2vec 采用静态方式, 369 | - 第一阶段:训练结束后,每个单词 只对应 一个固定的词向量; 370 | - 第二阶段:在使用时, 该词向量 不会 根据上下文场景 而变化 371 | - 因此 word2vec 解决不了 多义词 问题 372 | - 问题:为什么 elmo、GPT、Bert能够解决多义词问题?(以 elmo 为例) 373 | - 解决方式: 374 | - 因为 elmo、GPT、Bert 的词向量包含网络结构,简而言之就是,word2vec的词向量y=x,而bert的词向量是y=f(x) 375 | - 思路: 376 | - 预训练时,使用语言模型学习一个单词的emb(**多义词无法解决**); 377 | - 使用时,单词间具有特定上下文,可根据上下文单词语义调整单词的emb表示(**可解决多义词问题**) 378 | - 理解:因为预训练过程中,**emlo 中 的 lstm 能够学习到 每个词 对应的 上下文信息**,并保存在网络中,在 fine-turning 时,**下游任务 能够对 该 网络进行 fine-turning,使其 学习到新特征**; 379 | - 因此 elmo能够解决 多义词 问题(GPT、Bert 采用 的 是 transformer) 380 | 381 | 382 | 383 | ## 参考 384 | 385 | 1. [CS224n](http://web.stanford.edu/class/cs224n/index.html) 386 | 2. [关于BERT的若干问题整理记录](https://zhuanlan.zhihu.com/p/95594311) 387 | 388 | -------------------------------------------------------------------------------- /bert_study/T1_bert/readme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T1_bert/readme.png -------------------------------------------------------------------------------- /bert_study/T2020_GRAPH_BERT/2001.05140.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2020_GRAPH_BERT/2001.05140.pdf -------------------------------------------------------------------------------- /bert_study/T2020_GRAPH_BERT/img/model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2020_GRAPH_BERT/img/model.png -------------------------------------------------------------------------------- /bert_study/T2020_GRAPH_BERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 GRAPH-BERT】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 项目地址:https://github.com/km1994/nlp_paper_study/ 6 | > 7 | > 论文名称:GRAPH-BERT: Only Attention is Needed for Learning Graph Representations 8 | > 9 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 10 | > 11 | > 论文地址:https://arxiv.org/abs/2001.05140 12 | > 13 | > 论文代码:https://github.com/jwzhanggy/Graph-Bert 14 | 15 | ## 动机 16 | 17 | - 传统的GNN技术问题: 18 | - 模型做深会存在suspended animation和over smoothing的问题。 19 | - 由于 graph 中每个结点相互连接的性质,一般都是丢进去一个完整的graph给他训练而很难用batch去并行化。 20 | 21 | ## 论文方法 22 | 23 | 论文提出一种新的图神经网络模型GRAPH-BERT (Graph based BERT),该模型只依赖于注意力机制,不涉及任何的图卷积和聚合操作。Graph-Bert 将原始图采样为多个子图,并且只利用attention机制在子图上进行表征学习,而不考虑子图中的边信息。因此Graph-Bert可以解决上面提到的传统GNN具有的性能问题和效率问题。 24 | 25 | ## Graph-Bert Vs GNN 26 | 27 | 1. Graph-Bert没有用任何图卷积操作以及相应的聚合操作(因此可以避免over-smoothing)而完全采用attention mechanism 28 | 2. Graph-Bert的输入是由某个结点的context信息构成的linkless subgraph而非传统GNN所用的整图 29 | 3. 一个pre-trained好的Graph-Bert可以较好的通过fine-tune来适应不同的task 30 | 31 | ## Graph-Bert Model 32 | 33 | Grpah-Bert模型主要是包含了5个部分 34 | 35 | ### linkless subgraph batching 36 | 37 | 将原始图分解为无边子图集合,这一步属于预处理部分。具体来说,对于每个目标节点,根据节点之间的相似度分数选取前K个节点作为目标节点的上下文节点。 38 | 39 | ### node input embedding 40 | 41 | 节点输入特征的嵌入表示。本文考虑四种节点的特征:(1) raw feature vector embedding, (2) Weisfeiler-Lehman absolute role embedding, (3) intimacy based relative positional embedding, and (4) hop based relative distance embedding。这一步也是预处理。 42 | 43 | ### graph-transformer based encoder 44 | 45 | 基于图transformer的节点表征学习编码器,编码器的输出作为学习到的节点特征表示。 46 | 47 | ### graph-transformer based decoder 48 | 49 | 基于图transformer的解码器。主要考虑节点属性重建以及图结构恢复任务。 50 | 51 | ![](img/model.png) 52 | 53 | 54 | ## 参考 55 | 56 | 1. [Graph-Bert 阅读笔记](https://zhuanlan.zhihu.com/p/150367881) -------------------------------------------------------------------------------- /bert_study/T2_XLNet/XLNet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2_XLNet/XLNet.pdf -------------------------------------------------------------------------------- /bert_study/T2_XLNet/img/fun1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2_XLNet/img/fun1.png -------------------------------------------------------------------------------- /bert_study/T2_XLNet/img/fun2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2_XLNet/img/fun2.png -------------------------------------------------------------------------------- /bert_study/T2_XLNet/img/plm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2_XLNet/img/plm.png -------------------------------------------------------------------------------- /bert_study/T2_XLNet/img/two_attention.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T2_XLNet/img/two_attention.png -------------------------------------------------------------------------------- /bert_study/T2_XLNet/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 XLNet】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 个人github:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 【注:手机阅读可能图片打不开!!!】 8 | 9 | ## 目录 10 | 11 | - [【关于 XLNet】 那些的你不知道的事](#关于-xlnet-那些的你不知道的事) 12 | - [目录](#目录) 13 | - [摘要](#摘要) 14 | - [动机](#动机) 15 | - [论文思路](#论文思路) 16 | - [Model](#model) 17 | - [Permutation Language Modeling](#permutation-language-modeling) 18 | - [Two-Stream Self-Attention for Target-Aware Representations](#two-stream-self-attention-for-target-aware-representations) 19 | - [Transformer-XL](#transformer-xl) 20 | - [Pretraining and Implementation](#pretraining-and-implementation) 21 | - [Conclusion](#conclusion) 22 | - [Reference](#reference) 23 | 24 | ## 摘要 25 | 26 | 由于具有双向上下文建模的能力,像BERT这样基于自动去噪的预训练语言模型比基于自回归的预训练语言模型的性能更好。然而,依赖于使用带掩码损坏的输入,BERT忽略了掩码位置之间的依赖性,进而受到了预训练-微调不一致的影响。根据这些优点和缺点,我们提出了XLNet,一种广义自回归预训练方法,它(1)通过最大化输入序列的因式分解的所有排列的似然函数的期望来学习双向上下文,并且(2)由于其自回归方法,克服了BERT的局限性。此外,XLNet将最先进的自回归模型Transformer-XL的思想整合到预训练中。实验表明,XLNet在20个任务上常大幅度优于BERT的表现,并在18个任务中实现最先进的结果,包括问答、自然语言推理、情感分析和文档排名。 27 | 28 | 29 | ## 动机 30 | 31 | 文章从AR(autoregressive,自回归)和AE(autoencoding,自编码)的角度出发,解释论文动机。 32 | 33 | AR LM,即自回归语言模型。具体而言,给定一个序列,当前token时刻只知道前面的信息,而不知道后面的信息,即使分成正向和反向计算当前token时刻的概率分布,也是同样的原则,ELMo、GPT是属于这个范畴。对于一些自然语言理解任务而言,是给定上下文的,即使ELMo把两个的方向计算的信息concat,但也是独立计算,对上下文的编码是有缺陷的。 34 | 35 | AE LM,即自编码语言模型。BERT通过预测原始数据里MASK掉的token来预训练语言模型,预测[MASK]使用了上下文信息,弥补了AR LM的缺陷。但是[MASK]只在预训练的时候用到,finetune的时候是不用的,这使得pretrain/train不一致。并且,BERT假定每个[MASK]与其他[MASK]是相互独立的,不能计算序列、长期依赖的联合概率。即使BERT的NSP预训练任务一定程度上给了模型建模句间关系的能力,但是还是对长文本不敏感。 36 | 37 | ## 论文思路 38 | 39 | 本文结合AR LM和AE LM,在Transformer-XL的基础上提出generalized autoregressive method,XLNet。 40 | 41 | - 所有的分解序列作为一个集合,从中采样一个序列,XLNet按照AR LM的计算方式最大化有关序列所有可能的因式分解的排列的对数似然函数的期望。通常,当前token的上文包含left和right的tokens:比如原始序列为1-2-3-4,分解序列中采样一个为2-4-1-3,那么如果当前token为3,XLNet的方式就可以看到所有的信息,当然这也是理想情况。 42 | - 引入Transformer-XL的segment recurrence mechanism和relative encoding scheme。 43 | - 引入Masked Two-Stream Self-Attention**解决PLM出现的目标预测歧义**【the ambiguity in target prediction】问题。 44 | > 举个例子,比如分解序列中采样一个为2-4-6-1-3-5的序列,假设要预测[1]的token,按照经典的Transformer来计算next-token的概率分布,位置[1]token的概率就是通过[2,4,6]位置上的tokens来计算softmax,不会把[1]作为输入来计算的。但是如果以这种方式去预测next-token,这对[3,5]的预测就会产生影响,因为如果[1]的预测出现错误会把错误传给后面。对后面每一个token的预测,需要建立在之前token都已知的条件下。因此本文计算了两个self-attention计算方式,一个mask当前词,attention值记为$g$;一个已知当前词,attention值记为$h$。最后假设self-attention一共有$M$层,用第$M$层、$t$时刻的$g_t$,去预测词$x_t$。 45 | 46 | ## Model 47 | 48 | ### Permutation Language Modeling 49 | 50 | 首先代码会根据输入序列的长度采样一个排列,然后用Transformer中attention mask的方式实现排列,如果原始序列长度为T,那么理论上一共有T的阶乘种情况。PLM的目标函数就是所有排列情况(论文里设定:统共T种)的期望最大: 51 | 52 | $$ 53 | \max _{\theta} \quad \mathbb{E}_{\mathbf{Z} \sim \mathcal{Z}_{T}}\left[\sum_{t=1}^{T} \log p_{\theta}\left(x_{z_{t}} | \mathbf{x}_{\mathbf{z} 注:假设要预测t=3的词,按照不同的排列顺序,h_3的上文都不一样,用attention-mask的方式得到t=3的上文。 61 | 62 | ### Two-Stream Self-Attention for Target-Aware Representations 63 | 64 | 上面是构造输入,这里就是自回归地得到每一时刻的概率分布,示意图如下: 65 | 66 | ![](img/two_attention.png) 67 | 68 | 动机部分已经介绍过为什么要计算两个self-attention。 69 | 70 | (a)代表context stream self-attention,以[1,t]时刻的词作为K、V,t时刻的词作为Q计算当前词的信息,把排列之后的原始序列信息用h记忆起来。 71 | 72 | (b)代表query stream self-attention,mask掉当前词,以[1,t-1]时刻的词作为K、V,t时刻的词作为Q预测当前词,得到概率分布。 73 | 74 | (c)代表通过多层的masked two-stream attention,最后用t时刻的$g_t$来预测x_t。 75 | 76 | 计算公式如下: 77 | 78 | $$ 79 | \begin{array}{l}{g_{z_{t}}^{(m)} \leftarrow \text { Attention }\left(\mathbf{Q}=g_{z_{t}}^{(m-1)}, \mathbf{K} \mathbf{V}=\mathbf{h}_{\mathbf{z} 作者:杨夕 4 | > 5 | > 个人github:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 【注:手机阅读可能图片打不开!!!】 8 | 9 | ## 目录 10 | 11 | - [【关于 RoBERTa 】那些的你不知道的事](#关于-roberta-那些的你不知道的事) 12 | - [目录](#目录) 13 | - [摘要](#摘要) 14 | - [动机](#动机) 15 | - [所做工作概述](#所做工作概述) 16 | - [贡献](#贡献) 17 | - [实现方式](#实现方式) 18 | - [结论](#结论) 19 | - [参考文献](#参考文献) 20 | 21 | ## 摘要 22 | 23 | Language model pretraining has led to significant performance gains but careful comparison between different approaches is challenging. Training is computationally expensive, often done on private datasets of different sizes, and, as we will show, hyperparameter choices have significant impact on the final results. We present a replication study of BERT pretraining (Devlin et al., 2019) that carefully measures the impact of many key hyperparameters and training data size. We find that BERT was significantly undertrained, and can match or exceed the performance of every model published after it. Our best model achieves state-of-the-art results on GLUE, RACE and SQuAD. These results highlight the importance of previously overlooked design choices, and raise questions about the source of recently reported improvements. We release our models and code. 24 | 25 | 语言模型的预训练已导致显着的性能提升,但是不同方法之间的仔细比较是具有挑战性的。 训练在计算上很昂贵,通常是在不同大小的私人数据集上进行的,而且正如我们将显示的那样,超参数的选择对最终结果有重大影响。 我们提出了BERT预训练的重复研究(Devlin等人,2019),该研究仔细衡量了许多关键超参数和训练数据量的影响。 我们发现BERT的训练不足,并且可以匹配或超过其发布的每个模型的性能。 我们最好的模型在GLUE,RACE和SQuAD上获得了最先进的结果。 这些结果突出了以前被忽略的设计选择的重要性,并引起了人们对最近报告的改进来源的质疑。 我们发布我们的模型和代码。 26 | 27 | 28 | ## 动机 29 | 30 | - Bert 序列模型的问题 31 | > 确定方法的哪些方面贡献最大可能是具有挑战性的; 32 | > 33 | > 训练在计算上是昂贵的的,限制了可能完成的调整量 34 | 35 | 36 | ## 所做工作概述 37 | 38 | We present a replication study of BERT pretraining (Devlin et al., 2019), which includes a careful evaluation of the effects of hyperparmeter tuning and training set size. We find that BERT was significantly undertrained and propose an improved recipe for training BERT models, which we call RoBERTa, that can match or exceed the performance of all of the post-BERT methods. Our modifications are simple, they include: (1) training the model longer, with bigger batches, over more data; (2) removing the next sentence prediction objective; (3) training on longer sequences; and (4) dynamically changing the masking pattern applied to the training data. We also collect a large new dataset (CC-NEWS) of comparable size to other privately used datasets, to better control for training set size effects. 39 | 40 | 我们提出了BERT预训练的复制研究(Devlin等人,2019),其中包括对超参数调整和训练集大小的影响的仔细评估。 我们发现BERT的训练不足,并提出了一种改进的方法来训练BERT模型(我们称为RoBERTa),该模型可以匹配或超过所有后BERT方法的性能。 我们的修改很简单,其中包括: 41 | 42 | - 更大的模型参数量(论文提供的训练时间来看,模型使用 1024 块 V100 GPU 训练了 1 天的时间) 43 | - 更大bacth size。RoBERTa 在训练过程中使用了更大的bacth size。尝试过从 256 到 8000 不等的bacth size。 44 | - 更多的训练数据(包括:CC-NEWS 等在内的 160GB 纯文本。而最初的BERT使用16GB BookCorpus数据集和英语维基百科进行训练) 45 | 另外,RoBERTa在训练方法上有以下改进: 46 | 47 | - 去掉下一句预测(NSP)任务 48 | - 动态掩码。BERT 依赖随机掩码和预测 token。原版的 BERT 实现在数据预处理期间执行一次掩码,得到一个静态掩码。 而 RoBERTa 使用了动态掩码:每次向模型输入一个序列时都会生成新的掩码模式。这样,在大量数据不断输入的过程中,模型会逐渐适应不同的掩码策略,学习不同的语言表征。 49 | - 文本编码。Byte-Pair Encoding(BPE)是字符级和词级别表征的混合,支持处理自然语言语料库中的众多常见词汇。原版的 BERT 实现使用字符级别的 BPE 词汇,大小为 30K,是在利用启发式分词规则对输入进行预处理之后学得的。Facebook 研究者没有采用这种方式,而是考虑用更大的 byte 级别 BPE 词汇表来训练 BERT,这一词汇表包含 50K 的 subword 单元,且没有对输入作任何额外的预处理或分词。 50 | 51 | 52 | ## 贡献 53 | 54 | In summary, the contributions of this paper are: (1) We present a set of important BERT design choices and training strategies and introduce alternatives that lead to better downstream task performance; (2) We use a novel dataset, CCNEWS, and confirm that using more data for pretraining further improves performance on downstream tasks; (3) Our training improvements show that masked language model pretraining, under the right design choices, is competitive with all other recently published methods. We release our model, pretraining and fine-tuning code implemented in PyTorch (Paszke et al., 2017). 55 | 56 | 总而言之,本文的贡献是:(1)我们提出了一组重要的BERT设计选择和训练策略,并介绍了可以改善下游任务性能的替代方法; (2)我们使用新的数据集CCNEWS,并确认使用更多数据进行预训练可进一步提高下游任务的性能; (3)我们的训练改进表明,在正确的设计选择下,屏蔽语言模型预训练与所有其他最近发布的方法相比具有竞争力。 我们发布了在PyTorch中实现的模型,预训练和微调代码(Paszke et al。,2017)。 57 | 58 | 59 | ## 实现方式 60 | 61 | We reimplement BERT in FAIRSEQ (Ott et al., 2019). We primarily follow the original BERT optimization hyperparameters, given in Section 2, except for the peak learning rate and number of warmup steps, which are tuned separately for each setting. We additionally found training to be very sensitive to the Adam epsilon term, and in some cases we obtained better performance or improved stability after tuning it. Similarly, we found setting β2 = 0.98 to improve stability when training with large batch sizes. We pretrain with sequences of at most T = 512 tokens. Unlike Devlin et al. (2019), we do not randomly inject short sequences, and we do not train with a reduced sequence length for the first 90% of updates. We train only with full-length sequences. We train with mixed precision floating point arithmetic on DGX-1 machines, each with 8 × 32GB Nvidia V100 GPUs interconnected by In- finiband (Micikevicius et al., 2018). 62 | 63 | 我们在FAIRSEQ中重新实现BERT(Ott等,2019)。 我们主要遵循第2节中给出的原始BERT优化超参数,除了峰值学习速率和预热步骤数(针对每个设置分别调整)之外。 我们还发现训练对 Adam epsilon term 非常敏感,并且在某些情况下,对其进行调整后可以获得更好的性能或更高的稳定性。 64 | 65 | 同样,我们发现设置β2= 0.98可以提高大批量训练时的稳定性。 我们使用最多T = 512个令牌的序列进行预训练。 与Devlin等人不同。 (2019),我们不会随机注入短序列,并且对于前90%的更新,我们不会以缩短的序列长度进行训练。 我们只训练全长序列。 我们在DGX-1机器上使用混合精度浮点算术进行训练,每台机器都配有由Infiniband互连的8×32GB Nvidia V100 GPU(Micikevicius等,2018)。 66 | 67 | 68 | ## 结论 69 | 70 | We carefully evaluate a number of design decisions when pretraining BERT models. We find that performance can be substantially improved by training the model longer, with bigger batches over more data; removing the next sentence prediction objective; training on longer sequences; and dynamically changing the masking pattern applied to the training data. Our improved pretraining procedure, which we call RoBERTa, achieves state-of-the-art results on GLUE, RACE and SQuAD, without multi-task finetuning for GLUE or additional data for SQuAD. These results illustrate the importance of these previously overlooked design decisions and suggest that BERT’s pretraining objective remains competitive with recently proposed alternatives. We additionally use a novel dataset, CC-NEWS, and release our models and code for pretraining and finetuning at: https://github.com/pytorch/fairseq. 71 | 72 | 在预训练BERT模型时,我们会仔细评估许多设计决策。 我们发现,通过对模型进行较长时间的训练(使用更多批次的数据处理更多数据),可以显着提高性能。 删除下一个句子预测目标; 训练更长的序列; 并动态更改应用于训练数据的掩蔽模式。 我们改进的预训练程序(称为RoBERTa)可在GLUE,RACE和SQuAD上获得最新的结果,而无需为GLUE进行多任务微调或为SQuAD进行其他数据调整。 这些结果说明了这些先前被忽略的设计决策的重要性,并表明BERT的预训练目标与最近提出的替代方案相比仍然具有竞争力。 我们还使用一个新颖的数据集CC-NEWS,并在以下网址发布我们的模型和代码以进行预训练和微调:https://github.com/pytorch/fairseq。 73 | 74 | 75 | ## 参考文献 76 | 77 | 1. [文献阅读笔记:RoBERTa:A Robustly Optimized BERT Pretraining Approach](https://blog.csdn.net/ljp1919/article/details/100666563) -------------------------------------------------------------------------------- /bert_study/T4_RoBERTa/RoBERTa.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T4_RoBERTa/RoBERTa.pdf -------------------------------------------------------------------------------- /bert_study/T5_ALBERT/ALBERT A Lite BERT for Self supervised Learning of Language Representations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T5_ALBERT/ALBERT A Lite BERT for Self supervised Learning of Language Representations.pdf -------------------------------------------------------------------------------- /bert_study/T5_ALBERT/img/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T5_ALBERT/img/1.png -------------------------------------------------------------------------------- /bert_study/T5_ALBERT/img/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T5_ALBERT/img/2.png -------------------------------------------------------------------------------- /bert_study/T5_ALBERT/img/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T5_ALBERT/img/3.png -------------------------------------------------------------------------------- /bert_study/T5_ALBERT/img/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/T5_ALBERT/img/4.png -------------------------------------------------------------------------------- /bert_study/T5_ALBERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 Albert】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 个人github:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 论文:A lite BERT for self-supervised learning of language representations 8 | > 9 | > 【注:手机阅读可能图片打不开!!!】 10 | 11 | ## 摘要 12 | 13 | Increasing model size when pretraining natural language representations often results in improved performance on downstream tasks. However, at some point further model increases become harder due to GPU/TPU memory limitations, longer training times, and unexpected model degradation. 14 | 15 | To address these problems, we present two parameter-reduction techniques to lower memory consumption and increase the training speed of BERT (Devlin et al., 2019). 16 | 17 | Comprehensive empirical evidence shows that our proposed methods lead to models that scale much better compared to the original BERT. We also use a self-supervised loss that focuses on modeling inter-sentence coherence, and show it consistently helps downstream tasks with multi-sentence inputs. 18 | 19 | As a result, our best model establishes new state-of-the-art results on the GLUE, RACE, and SQuAD benchmarks while having fewer parameters compared to BERT-large. 20 | 21 | 预训练自然语言表征时,增加模型大小一般是可以提升模型在下游任务中的性能。但是这种纯粹依赖模型尺寸进而期望大力出奇迹的想法在未来会越发困难。进一步增加模型大小将带来以下困难: 22 | 23 | > (1)GPU/TPU内存不足 24 | > 25 | > (2)训练时间会更长 26 | > 27 | > (3)模型退化。 28 | 29 | 30 | 所以,为了解决上述这些问题,本文提出通过两种参数精简技术来降低内存消耗,并加快BERT的训练速度。 31 | 32 | 此外,本文还引入一个自监督损失(self-supervised loss),用于对句子连贯性(inter-sentence coherence)建模,并证明该损失函数能够提升多句子作为输入的下游任务的性能。本文所提出的模型ALBERT在 GLUE、RACE 和 SQuAD 这3个基准上都取得了新的SOTA结果,且参数量还少于 BERT-large。 33 | 34 | ## 动机 35 | 36 | 过往的研究者们在诸多NLP任务上的实验已经表明,模型规模在取得SOTA结果上至关重要。在应用场景中通常是预训练一个大规模的模型,再对其进行蒸馏萃取出一个更小的模型。考虑模型大小的重要性,我们不禁要问:“拥有更好的NLP模型是否能够和拥有更大的模型一样容易?” 37 | 38 | 上述问题首要解决的便是 39 | 1. 内存受限。当下的各种SOTA模型动辄数亿甚至数十亿个参数,倘若要扩大模型规模,这个内存问题是无法回避的。 40 | 2. 训练速度上的限制。由于通信开销与模型中参数的数量成正比,在分布式训练中训练速度将成为一大瓶颈。简单地增加隐含层单元数,只会适得其反,从而降低性能。Table 1和Fig 1中可以看出将BERT-large 的隐藏层单元数增加一倍, 该模型(BERT-xlarge)在 RACE 基准测试上的准确率显著降低。 41 | 42 | ![](img/1.png) 43 | 44 | 45 | ## 所做工作概述 46 | 47 | 为解决上述问题,已有先贤们做了一些研究,比如模型并行化、智能内存管理等。这些解决方案只解决了内存受限问题,而没有考虑模型通信开销过大和模型退化问题。为此,本文提出A Lite BERT(ALBERT)模型以解决上述三个问题。 该模型的参数量远远少于传统的 BERT 架构。 48 | 49 | ALBERT 引入2种参数精简技术,克服了扩展预训练模型面临的主要障碍。 50 | 51 | 第一种技术是**对嵌入参数进行因式分解(factorized embedding parameterization)**。将一个大的词汇嵌入矩阵分解为两个小矩阵,从而将隐藏层的大小与词汇嵌入的大小分离开来。这种分离便于后续隐藏层单元数量的增加,怎么说呢?就是增加隐藏层单元数量,并不显著增加词汇嵌入的参数量。 52 | 53 | 第二种技术是**跨层参数共享**。这一技术可以避免参数量随着网络深度的增加而增加。 54 | 55 | 这两种技术都显著降低了 BERT 的参数量,同时不显著损害其性能, 从而提升了参数效率。ALBERT 的配置类似于 BERT-large,但参数量仅为后者的 1/18,训练速度却是后者的 1.7 倍。 这些参数精简技术还可以充当某种形式的正则化,可以使训练更加稳定,且有利于泛化。 56 | 57 | 为了进一步提升 ALBERT 的性能, 本文还引入了一个**自监督损失函数,用于句子顺序预测(SOP,sentence-order prediction)**。SOP 主要聚焦于句间连贯,用于解决原版 BERT中下一句预测(NSP)损失的低效问题。因为确实已有研究(Yang et al., 2019; Liu et al., 2019)表明NSP是可以去掉的。 58 | 59 | 基于上述的这3个设计,ALBERT 能够扩展为更大的版本,在参数量仍然小于 BERT-large的同时,性能可以显著提升。本文在GLUE、SQuAD 和 RACE 这3个自然语言理解基准测试上都刷新了记录:在 RACE 上的准确率为 89.4%,在 GLUE 上的得分为 89.4,在 SQuAD 2.0 上的 F1 得分为 92.2。 60 | 61 | ![](img/2.png) 62 | 63 | ## 相关研究 64 | 65 | ### 扩大模型表征 66 | 67 | 68 | 69 | 70 | ## 实现方式 71 | 72 | 自然语言的表征学习其重要程度不言而喻,目前的趋势已从前两年预训练词向量如标准的Word2Vec抑或是基于上下文语境的ELMo转变为整个网络的预训练+下游任务微。调。一般上来说,模型更大能够提升性能,比如Devlin et al. (2019)的工作就表明采用更多的隐含层单元数、更多的隐含层和更多的attention head能够提升性能。但是,凡事都有其适用范围。Devlin在隐含层单元数设置为1024后,就没有继续增加了。本文继续进一步,发现当隐含层单元数增加为2048个后,模型性能是退化的。所以,扩大自然语言的表征学习模型,并不能简单地增加模型尺寸了事。 73 | 74 | 另外,面对有限的计算资源,特别是GPU/TPU的内存受限,大规模模型的训练会显得很艰难。之前研究者们的方案有以下几种:(1)Chen et al. (2016) 提出的gradient checkpointing,以降低内存消耗,从而使得内存的占用是次线性的,其代价是需要一个额外的forward pass。(2)Gomez et al. (2017)提出从下一层重构每一层的激活,如此便无需存储中间激活。这两种方法是以牺牲速度为代价换取内存占用的降低。反观本文的方法,通过参数精简技术降低内存占用的同时还加速了训练速度,着实令人惊喜,有木有。 75 | 76 | ### 跨层参数共享 77 | 78 | 跨层参数共享在之前的Transformer架构中就有,但是Transformer只注重训练用于标准encoder-decoder的任务,而非预训练+下游任务微调的设置。与本文的观察所不同的是,Dehghani et al. (2018)发现跨层参数共享(Universal Transformer,UT)在语言建模和主谓一致方面能够取得比标准Transformer更好的结果。近来, Bai et al. (2019)提出的Deep Equilibrium Model (DQE)表明DQE能够在某一层取得输入嵌入与输出嵌入保持一致的平衡点。 79 | 80 | ### 句子次序目标 81 | 82 | 为了学习句子之间的连贯性,ALBERT引入了一个预测两个连续句子次序的目标函数。针对篇章中句子的连贯和衔接,此前就有学者在预训练中采用类似操作,比如基于Skip thought (Kiros et al., 2015)和FastSent (Hill et al., 2016)是通过对句子进行encoding进而预测句子周边词汇,从而学习句子嵌入。Gan et al., 2017虽然也是学习句子嵌入,但是使用的是预测后续的句子,而非仅仅其周边单词。[Jernite et al., 2017; Nie et al., 2019]所采用的目标则是预测显性话语标记语(explicit discourse markers,即话语末尾标记语)。本文所提出的损失函数是面向文本段落segments,而非句子。BERT中采用的一个损失函数是预测两个segments是否来自相同文档,更确切地说是,其正样本是下一个句子,而负样本是随机的其他文档句子。相比于上述的这些方法,本文的句子次序预测更具挑战性,于下游任务更有益。 83 | 84 | ## 主要内容 85 | 86 | ### 模型架构的选择 87 | 88 | ALBERT 架构的主干网络与 BERT 相似,即使用 Transformer 编码器和 GELU 非线性激活函数。为便于论述,本文做如下约定:词嵌入大小为 E、编码器层数为L、隐藏层大小为 H。与 Devlin 等人的研究一样,本文将 前馈网络/滤波器 大小设置为4H,将注意力头的数量设置为H/64。 89 | 90 | 本文ALBERT框架与BERT相比有以下3点不同: 91 | 92 | 嵌入向量参数化的因式分解 93 | 在BERT 及后续的 XLNet 和 RoBERTa 中,WordPiece 词嵌入大小E和隐藏层大小H是相等的,即$E \equiv H$。这在建模和实际使用中,看起来可能并不是最优的。 94 | 95 | (1)从建模的角度来说,WordPiece 词嵌入的目标是学习上下文无关的表示,而隐藏层嵌入的目标是学习上下文相关的表示。[Liu et al.,2019]通过上下文长度相关的实验表明,BERT的表征能力很大一部分来自于使用上下文以在学习过程提供上下文相关的表征信息。因此,将 WordPiece 词嵌入大小E 从隐藏层大小 H 分离出来,可以更高效地利用总体的模型参数, 其中H远远大于E。 96 | 97 | (2)从实践的角度,自然语言处理使用的词典大小V一般非常庞大,如果E恒等于HHH,即$E \equiv H$,那么增加 H 将直接增大词典嵌入矩阵的大小$(V \times E)$。这会导致模型参数剧增,而模型训练过程中大部分参数的更新是很稀疏的。 98 | 99 | 因此,本文所提出的ALBERT对词嵌入参数进行了因式分解,将其分解为两个小矩阵。**本文不再将 one-hot 向量直接映射到大小为H 的隐藏空间,而是先将它们映射到一个低维词嵌入空间E,然后再映射到隐藏空间。通过这种分解,可以将词嵌入参数从 $O(V \times H)$ 降低到 $O(V \times E+E\times H)$。**这在H 远远大于E的时候,参数量减少得非常明显。 100 | 101 | ### 跨层参数共享 102 | 103 | 此外,ALBERT中还使用了一种跨层参数共享机制来进一步提升参数效率。其实目前有很多方式来共享参数,比如只共享前馈网络不同层之间的参数,或者只共享注意力机制的参数,而 **ALBERT 采用的是所有层共享所有参数**。 104 | 105 | 在之前也有学者提出过类似机制,比如[Dehghani et al. (2018)]的[(Universal Transformer, UT)](https://zhuanlan.zhihu.com/p/44655133)和Bai et al. (2019)和Deep Equilibrium Models(DQE)。虽然上述方案都有一定提升效果,但在度量过程发现词嵌入的 L2 距离和余弦相似性是震荡而不是收敛。如下图 2 展示了每一层输入与输出嵌入矩阵间的 L2 距离与余弦相似性。 106 | 107 | ![](img/4.png) 108 | 109 | ![](img/3.png) 110 | 111 | ### 句间连贯性损失 112 | 113 | 除了语言建模损失(masked language modeling,MLM)外,BERT 还使用了额外的下一句预测损失(NSP)。NSP损失本是为了提升下游任务的性能,但是后来很多研究 (Yang et al., 2019; Liu et al., 114 | 2019)发现这种机制并不是很高效,因此决定去除它。 115 | 116 | 据此我们猜测,NSP低效的原因,主要是它的难度太小。因为下一句预测将主题预测和连贯性预测结合到单个任务中,然而主题预测比连贯性预测简单得多,同时NSP与MLM损失函数学到的内容是有重合的。 117 | 118 | 由于句间建模在语言理解中非常重要,因此本文提出一种基于语言连贯性的损失函数。在ALBERT中本文使用了一个句子次序预测(SOP)损失函数,它会避免预测主题,而只关注建模句子之间的连贯性。**SOP正样本获取方法与BERT相同,而负样本仅仅是将正样本的两个segments次序对换**。实验结果表明SOP能够在合理范围内解决NSP任务。在使用了该损失函数后,ALBERT能显著提升下游多句子编码任务的性能。 119 | 120 | ## 总结 121 | 122 | 本文的贡献主要在3个方面: 123 | 124 | (1)对嵌入矩阵分解,解除词嵌入和隐含层大小的关系,便于隐含层大小的扩展而不剧增模型参数 125 | 126 | (2)跨层参数共享,虽然一定程度上微微降低性能,但是可以大大地降低模型参数,收益很高 127 | 128 | (3)放弃NSP,引入SOP,更为有力地学习句子间的连贯性 129 | 130 | 131 | ## 参考文献 132 | 133 | 1. [文献阅读笔记-ALBERT : A lite BERT for self-supervised learning of language representations](https://blog.csdn.net/ljp1919/article/details/101680220) 134 | 2. [【NLP】ALBERT粗读](https://zhuanlan.zhihu.com/p/84273154) -------------------------------------------------------------------------------- /bert_study/TinyBERT/1909.10351.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/1909.10351.pdf -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927190511.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927190511.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927190613.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927190613.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927191001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927191001.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927191946.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927191946.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927194101.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927194101.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927194629.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927194629.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927194737.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927194737.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927194815.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927194815.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927194927.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927194927.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927195206.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927195206.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927195319.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927195319.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/img/20200927195725.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/TinyBERT/img/20200927195725.png -------------------------------------------------------------------------------- /bert_study/TinyBERT/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 TinyBert】 那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 项目地址:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 个人介绍:大佬们好,我叫杨夕,该项目主要是本人在研读顶会论文和复现经典论文过程中,所见、所思、所想、所闻,可能存在一些理解错误,希望大佬们多多指正。 8 | > 9 | > 论文题目:TinyBERT: Distilling BERT for Natural Language Understanding 10 | > 11 | > 论文地址:chrome-extension://ikhdkkncnoglghljlkmcimlnlhkeamad/pdf-viewer/web/viewer.html?file=https%3A%2F%2Farxiv.org%2Fpdf%2F1909.10351.pdf 12 | 13 | ## 目录 14 | 15 | 16 | 17 | ## 摘要 18 | 19 | - 介绍:预训练语言模型如BERT等已经极大地提高了多项自然处理任务的性能; 20 | - 问题:预训练语言模型通常具需要很大计算资源,所以其很难在有限的资源设备上运行。 21 | - 动机:为了加速推理、减小模型的尺寸而同时保留精度; 22 | - 方法:首先提出了一个新颖的迁移蒸馏方法,它是一种基于迁移方法的知识蒸馏思路。利用整个新颖的KD方法,大量的知识编码在一个大的“老师”BERT可以很好地被迁移到一个小的“学生”TinyBERT模型那里。我们引入一个新的两阶段学习TinyBERT学习框架,在预训练阶段和任务明确任务学习阶段都采用迁移蒸馏方式,整个框架可以保证TinyBERT能够捕捉到BERT中通用域和明确域的知识。 23 | - 优点:性能能够超过基线BERT的96%,容量小7.5倍,推理速度快9.4倍。同时,TinyBERT要比基线DistillBERT也明显更优,只有其28%的参数,31%的推理时间 24 | 25 | ## 动机 26 | 27 | - Bert 系列模型 成本增长 的 计算量; 28 | - 模型不断增长的算力和内存要求可能阻止被广泛使用 29 | 30 | ## 前期知识 31 | 32 | ### Multi-Head Attention (MHA) 介绍 33 | 34 | ![](img/20200927190511.png) 35 | 36 | ### Position-wise Feed-Forward Network (FFN) 介绍 37 | 38 | ![](img/20200927190613.png) 39 | 40 | ### 知识蒸馏【Knowledge Distillation(KD)】 41 | 42 | - 介绍:一种模型压缩常见方法,指的是在teacher-student框架中,将复杂、学习能力强的网络(teacher)学到的特征表示“知识”蒸馏出来,传递给参数量小、学习能力弱的网络(student)。teacher网络中学习到的特征表示可作为监督信息,训练student网络以模仿teacher网络的行为; 43 | - 知识蒸馏的误差函数: 44 | 45 | ![](img/20200927191001.png) 46 | 47 | > 注:
48 | > x:网络输入;
49 | > L(·):衡量在输入x xx下,teacher网络和student的网络的差异性;
50 | > X:训练集;
51 | > $f^T$:teacher网络的行为函数,可以通俗理解成网络中特征表示;
52 | > $f^S$:student网络的行为函数,可以通俗理解成网络中特征表示;
53 | 54 | - 关键问题: 55 | - 如何定义网络的差异性loss? 56 | - 如何选取网络的行为函数? 57 | 58 | ## 基于transformer的知识蒸馏模型压缩 59 | 60 | - tinybert的创新点:学习了teacher Bert中更多的层数的特征表示; 61 | - 特征表示: 62 | - 词向量层的输出; 63 | - Transformer layer的输出以及注意力矩阵; 64 | - 预测层输出(仅在微调阶段使用); 65 | 66 | ![](img/20200927191946.png) 67 | 68 | - bert知识蒸馏的过程 69 | - 左图:整体概括了知识蒸馏的过程 70 | - 左边:Teacher BERT; 71 | - 右边:Student TinyBERT 72 | - 目标:将Teacher BERT学习到的知识迁移到TinyBERT中 73 | - 右图:描述了知识迁移的细节; 74 | - 在训练过程中选用Teacher BERT中每一层transformer layer的attention矩阵和输出作为监督信息 75 | 76 | - 举例 77 | - 假设: Teacher BERT 有M层,TinyBERT有N层(N Student BERT 词向量层: 0 = g(0) 80 | - Teacher BERT 预测输出层- > Student BERT 预测输出层: N+1=g(M + 1) 81 | - Teacher BERT 预测对应层- > Student BERT 预测对应层: n = g(m) 82 | 83 | - 目标:将Teacher BERT学习到的特征表示作为TinyBERT的监督信息,从而训练TinyBERT 84 | - 损失函数: 85 | 86 | ![](img/20200927194101.png) 87 | 88 | > 注:
89 | > $L_{layer}$:当前层衡量Teacher BERT络和TinyBERT的差异性的loss函数;
90 | > $λ_m$:超参数,代表当前层的重要程度;
91 | 92 | ### Transformer层: 93 | 94 | #### attention矩阵 95 | 96 | - 操作: attention矩阵作为知识蒸馏过程中teacher网络的监督信息。 97 | - 原因: 文献 证明了attention举证中包含了语法和共指信息,通过将attention矩阵作为teacher网络中的监督信息,可以将这些信息迁移到student网络。采用的是均方误差函数,h 是atteniton的头数,每层共h 个注意力矩阵A ; 98 | 99 | ![](img/20200927194629.png) 100 | 101 | #### Transformer层输出: 102 | 103 | ![](img/20200927194737.png) 104 | 105 | #### 词向量层: 106 | 107 | ![](img/20200927194815.png) 108 | 109 | #### 预测输出层: 110 | 111 | ![](img/20200927194927.png) 112 | 113 | #### 整体: 114 | 115 | ![](img/20200927195206.png) 116 | 117 | ## Pre-training和Fine-tuning两个阶段知识蒸馏 118 | 119 | ![](img/20200927195319.png) 120 | 121 | - General distillation (Pre-training阶段):使用大规模无监督的数据, 帮助student网络TinyBERT学习到尚未微调的teacher BERT中的知识,有利于提高TinyBERT的泛化能力。此时,由于词向量维度的减小,隐层神经元的减少,以及网络层数的减少,tinybert的表现远不如teacher bert。(注意:在Pre-training阶段,蒸馏的特征表示未使用预测层输出) 122 | - task-specific distillation(Fine-tuning阶段):使用具体任务的数据,帮助TinyBERT学习到更多任务相关的具体知识。值得注意的是,在Fine-tuning阶段,论文采用了**数据增强**的策略,从后面的实验中可以看出,数据增强起到了很重要的作用。 123 | - 数据扩充的过程如下: 124 | - 首先对特定任务的数据中每一条文本使用bert自带的方式进行bpe分词,bpe分词之后是完整单词(single-piece word),用[MASK]符号代替; 125 | - 然后使用bert进行预测并选择其对应的候选词N个;如果bpe分词之后不是完整单词,则使用Glove词向量以及余弦相似度来选择对应的N个候选词; 126 | - 最后以概率 $p_{t}$ 选择是否替换这个单词,从而产生更多的文本数据。 127 | 128 | ![](img/20200927195725.png) 129 | 130 | ## 参考 131 | 132 | 1. [TINYBERT: DISTILLING BERT FOR NATURAL LANGUAGE UNDERSTANDING](https://blog.csdn.net/ltochange/article/details/103115311) 133 | 134 | -------------------------------------------------------------------------------- /bert_study/bert_trick/UNK_process/img/微信截图_20220917161347.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/bert_trick/UNK_process/img/微信截图_20220917161347.png -------------------------------------------------------------------------------- /bert_study/bert_trick/UNK_process/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 Bert 未登录词处理】 那些你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > 介绍:研读顶会论文,复现论文相关代码 6 | > 7 | > NLP 百面百搭 地址:https://github.com/km1994/NLP-Interview-Notes 8 | > 9 | > **[手机版NLP百面百搭](https://mp.weixin.qq.com/s?__biz=MzAxMTU5Njg4NQ==&mid=100005719&idx=3&sn=5d8e62993e5ecd4582703684c0d12e44&chksm=1bbff26d2cc87b7bf2504a8a4cafc60919d722b6e9acbcee81a626924d80f53a49301df9bd97&scene=18#wechat_redirect)** 10 | > 11 | > 推荐系统 百面百搭 地址:https://github.com/km1994/RES-Interview-Notes 12 | > 13 | > **[手机版推荐系统百面百搭](https://mp.weixin.qq.com/s/b_KBT6rUw09cLGRHV_EUtw)** 14 | > 15 | > 搜索引擎 百面百搭 地址:https://github.com/km1994/search-engine-Interview-Notes 【编写ing】 16 | > 17 | > NLP论文学习笔记:https://github.com/km1994/nlp_paper_study 18 | > 19 | > 推荐系统论文学习笔记:https://github.com/km1994/RS_paper_study 20 | > 21 | > GCN 论文学习笔记:https://github.com/km1994/GCN_study 22 | > 23 | > **推广搜 军火库**:https://github.com/km1994/recommendation_advertisement_search 24 | ![](other_study/resource/pic/微信截图_20210301212242.png) 25 | 26 | > 手机版笔记,可以关注公众号 **【关于NLP那些你不知道的事】** 获取,并加入 【NLP && 推荐学习群】一起学习!!! 27 | 28 | > 注:github 网页版 看起来不舒服,可以看 **[手机版NLP论文学习笔记](https://mp.weixin.qq.com/s?__biz=MzAxMTU5Njg4NQ==&mid=100005719&idx=1&sn=14d34d70a7e7cbf9700f804cca5be2d0&chksm=1bbff26d2cc87b7b9d2ed12c8d280cd737e270cd82c8850f7ca2ee44ec8883873ff5e9904e7e&scene=18#wechat_redirect)** 29 | 30 | ## 一、动机 31 | 32 | - 中文预训练BERT 对于 英文单词覆盖不全问题。由于 中文预训练BERT 主要针对中文,所以词表中英文单词比较少,但是一般英文单词如果简单的直接使用tokenize函数,往往在一些序列预测问题上存在一些对齐问题,或者很多不存在的单词或符号没办法处理而直接使用 unk 替换了,某些英文单词或符号失去了单词的预训练效果; 33 | - 专业领域(如医疗、金融)用词或中文偏僻词问题。NLP经常会用到预训练的语言模型,小到word2vector,大到bert。现在bert之类的基本都用char级别来训练,然而由于 Bert 等预训练模型都是采用开放域的语料进行预训练,所以对词汇覆盖的更多是日常用词,专业用词则覆盖不了,这时候该怎么处理? 34 | 35 | ```s 36 | ... 37 | print(tokenizer.tokenize('骨骺')) 38 | >>> 39 | ['骨', '[UNK]'] 40 | ``` 41 | 42 | - 英文预训练BERT(bert-base-uncased 和 bert-base-cased)词语被自动拆成词根词缀问题。 英文预训练BERT 以词为单位。社会生活中总是会有新词产生,而且在专业领域(如医疗、金融)有一些不常用的词语是 英文预训练BERT 没有涵盖到的,可能词语会被自动拆成词根词缀; 43 | 44 | ```s 45 | ... 46 | print(tokenizer.tokenize('COVID')) 47 | >>> 48 | ['co', '##vi', '##d'] 49 | ``` 50 | 51 | ## 二、处理方法 52 | 53 | ### 2.1 直接在 BERT 词表 vocab.txt 中替换 [unused] 54 | 55 | 1. 找到pytorch版本的 bert-base-cased 的文件夹中的vocab.txt文件; 56 | 2. 最前面的100行都是[unused]([PAD]除外),直接用需要添加的词替换进去; 57 | 58 | > 注:这里我们 加入 骺 和 COVID 两个新词 59 | 60 | ![](img/微信截图_20220917161347.png) 61 | 62 | 3. 查询 运行 之前实例,效果如下: 63 | 64 | ```s 65 | ... 66 | print(tokenizer.tokenize('骨骺')) 67 | >>> 68 | ['骨', '骺'] 69 | ``` 70 | 71 | ```s 72 | ... 73 | print(tokenizer.tokenize('COVID')) 74 | >>> 75 | ['covid'] 76 | ``` 77 | 78 | ### 2.2 通过重构词汇矩阵来增加新词 79 | 80 | 1. 如果 觉得 修改 vocab.txt文件 会干扰到 其他项目,那么通过重构BERT初始权重矩阵的方式将他们加入词表; 81 | 82 | ```s 83 | new_tokens = ['COVID', '骨骺'] 84 | num_added_toks = tokenizer.add_tokens(new_tokens) 85 | print(tokenizer.tokenize('骨骺')) 86 | print(tokenizer.tokenize('COVID')) 87 | >>> 88 | ['骨骺'] 89 | ['covid'] 90 | ``` 91 | 92 | > 注:num_added_toks返回一个数,表示加入的新词数量,在这里是2 93 | 94 | 2. resize_token_embeddings输入的参数是tokenizer的新长度 95 | 96 | ```s 97 | model.resize_token_embeddings(len(tokenizer)) 98 | ``` 99 | 100 | 3. 添加后的词汇,通过model.resize_token_embeddings方法,随机初始化了一个权重。 101 | 102 | ```s 103 | tokenizer.save_pretrained("Pretrained_LMs/bert-base-cased") 104 | ``` 105 | 106 | ### 2.3 添加特殊占位符号 add_special_tokens 107 | 108 | 1. 动机 109 | 110 | 前面两个是往 词典中 添加未登录词,那么如何往分词器tokenizer中添加新的特殊占位符呢? 111 | 112 | 2. 方法介绍 113 | 114 | add_special_tokens : 往分词器tokenizer中添加新的特殊占位符 115 | 116 | ```s 117 | tokenizer.add_special_tokens({'additional_special_tokens':[""]}) 118 | ``` 119 | 120 | > 注:往additional_special_tokens这一类tokens中添加特殊占位符 121 | 122 | 3. 测试 123 | 124 | ```s 125 | ... 126 | text = " I love ! " 127 | # 对于一个句子,首尾分别加[CLS]和[SEP]。 128 | text = "[CLS] " + text + " [SEP]" 129 | # 然后进行分词 130 | print("普通 分词效果:") 131 | tokenized_text1 = tokenizer.tokenize(text) 132 | print(tokenized_text1) 133 | indexed_tokens1 = tokenizer.convert_tokens_to_ids(tokenized_text1) 134 | # 分词结束后获取BERT模型需要的tensor 135 | segments_ids1 = [1] * len(tokenized_text1) 136 | tokens_tensor1 = torch.tensor([indexed_tokens1]) # 将list转为tensor 137 | segments_tensors1 = torch.tensor([segments_ids1]) 138 | # 获取所有词向量的embedding 139 | word_vectors1 = bertmodel(tokens_tensor1, segments_tensors1)[0] 140 | # 获取句子的embedding 141 | sentenc_vector1 = bertmodel(tokens_tensor1, segments_tensors1)[1] 142 | tokenizer.add_special_tokens({'additional_special_tokens':[""]}) 143 | print("添加特殊占位符 后 的分词效果:") 144 | print(tokenizer.additional_special_tokens) # 查看此类特殊token有哪些 145 | print(tokenizer.additional_special_tokens_ids) # 查看其id 146 | tokenized_text1 = tokenizer.tokenize(text) 147 | print(tokenized_text1) 148 | >>> 149 | 普通 分词效果: 150 | ['[CLS]', 'i', 'love', '<', 'e', '>', '!', '[SEP]'] 151 | 152 | 添加特殊占位符 后 的分词效果: 153 | [''] 154 | [21128] 155 | ['[CLS]', 'i', 'love', '', '!', '[SEP]'] 156 | ``` 157 | 158 | ## 三、方法对比 159 | 160 | - 方法一: 161 | - 优点:如果存在大量领域内专业词汇,而且已经整理成词表,可以利用该方法批量添加; 162 | - 缺点:因为 方法1 存在 未登录词数量限制(eg:cased模型只有99个空位,uncased模型有999个空位),所以当 未登录词 太多时,将不适用; 163 | - 方法二: 164 | - 优点:不存在 方法1 的 未登录词数量限制 问题; 165 | - 方法三: 166 | - 优点:对于一些 占位符(eg:),方法一和方法二可能都无法生效,因为 <, e, >和 均存在于 vocab.txt,但前三者的优先级高于 ,而 add_special_tokens会起效,却会使得词汇表大小增大,从而需另外调整模型size。但是,如果同时在词汇表vocab.txt中替换[unused],同时 add_special_tokens,则新增词会起效,同时词汇表大小不变。 167 | 168 | 169 | ## 参考 170 | 171 | 1. [NLP | How to add a domain-specific vocabulary (new tokens) to a subword tokenizer already trained like BERT WordPiece | by Pierre Guillou | Medium](https://medium.com/@pierre_guillou/nlp-how-to-add-a-domain-specific-vocabulary-new-tokens-to-a-subword-tokenizer-already-trained-33ab15613a41) 172 | 2. [如何向BERT词汇表中添加token,新增特殊占位符](https://blog.csdn.net/icestorm_rain/article/details/108540053) 173 | 3. [在BERT模型中添加自己的词汇(pytorch版)](https://zhuanlan.zhihu.com/p/391814780) -------------------------------------------------------------------------------- /bert_study/bert_trick/UNK_process/ukn_test.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 4, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "model_path = \"F:/document/datasets/nlpData/pretrain/bert/chinese_wwm_ext_pytorch\" #自己的bert模型路径" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# 添加新词" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 5, 22 | "metadata": {}, 23 | "outputs": [ 24 | { 25 | "name": "stderr", 26 | "output_type": "stream", 27 | "text": [ 28 | "Some weights of the model checkpoint at F:/document/datasets/nlpData/pretrain/bert/chinese_wwm_ext_pytorch were not used when initializing BertForMaskedLM: ['cls.seq_relationship.bias', 'cls.seq_relationship.weight']\n", 29 | "- This IS expected if you are initializing BertForMaskedLM from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", 30 | "- This IS NOT expected if you are initializing BertForMaskedLM from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n" 31 | ] 32 | } 33 | ], 34 | "source": [ 35 | "from transformers import BertForMaskedLM, BertTokenizer\n", 36 | "tokenizer = BertTokenizer.from_pretrained(model_path, use_fast=True)\n", 37 | "model = BertForMaskedLM.from_pretrained(model_path)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 2, 43 | "metadata": {}, 44 | "outputs": [ 45 | { 46 | "name": "stdout", 47 | "output_type": "stream", 48 | "text": [ 49 | "['骨', '[UNK]']\n" 50 | ] 51 | } 52 | ], 53 | "source": [ 54 | "print(tokenizer.tokenize('骨骺'))" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 3, 60 | "metadata": {}, 61 | "outputs": [ 62 | { 63 | "name": "stdout", 64 | "output_type": "stream", 65 | "text": [ 66 | "['an', '##ew', '##word']\n" 67 | ] 68 | } 69 | ], 70 | "source": [ 71 | "print(tokenizer.tokenize('anewword'))" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 4, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "new_tokens = ['COVID', '骨骺']\n", 81 | "num_added_toks = tokenizer.add_tokens(new_tokens)" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 5, 87 | "metadata": {}, 88 | "outputs": [ 89 | { 90 | "name": "stdout", 91 | "output_type": "stream", 92 | "text": [ 93 | "['骨骺']\n", 94 | "['covid']\n" 95 | ] 96 | } 97 | ], 98 | "source": [ 99 | "print(tokenizer.tokenize('骨骺'))\n", 100 | "print(tokenizer.tokenize('COVID'))" 101 | ] 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "metadata": {}, 106 | "source": [ 107 | "# 添加 新占位符" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 10, 113 | "metadata": {}, 114 | "outputs": [ 115 | { 116 | "name": "stderr", 117 | "output_type": "stream", 118 | "text": [ 119 | "Some weights of the model checkpoint at F:/document/datasets/nlpData/pretrain/bert/chinese_wwm_ext_pytorch were not used when initializing BertModel: ['cls.seq_relationship.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.decoder.weight', 'cls.seq_relationship.weight', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.dense.bias']\n", 120 | "- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", 121 | "- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n" 122 | ] 123 | } 124 | ], 125 | "source": [ 126 | "# 导入模型和分词器\n", 127 | "from transformers import BertTokenizer,BertModel\n", 128 | "import torch\n", 129 | "tokenizer = BertTokenizer.from_pretrained(model_path, use_fast=True)\n", 130 | "bertmodel = BertModel.from_pretrained(model_path)" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": 11, 136 | "metadata": {}, 137 | "outputs": [ 138 | { 139 | "name": "stdout", 140 | "output_type": "stream", 141 | "text": [ 142 | "普通 分词效果:\n", 143 | "['[CLS]', 'i', 'love', '<', 'e', '>', '!', '[SEP]']\n", 144 | "添加特殊占位符 后 的分词效果:\n", 145 | "['']\n", 146 | "[21128]\n", 147 | "['[CLS]', 'i', 'love', '', '!', '[SEP]']\n" 148 | ] 149 | } 150 | ], 151 | "source": [ 152 | "text = \" I love ! \"\n", 153 | "# 对于一个句子,首尾分别加[CLS]和[SEP]。\n", 154 | "text = \"[CLS] \" + text + \" [SEP]\"\n", 155 | "# 然后进行分词\n", 156 | "print(\"普通 分词效果:\")\n", 157 | "tokenized_text1 = tokenizer.tokenize(text)\n", 158 | "print(tokenized_text1)\n", 159 | "indexed_tokens1 = tokenizer.convert_tokens_to_ids(tokenized_text1)\n", 160 | "# 分词结束后获取BERT模型需要的tensor\n", 161 | "segments_ids1 = [1] * len(tokenized_text1)\n", 162 | "tokens_tensor1 = torch.tensor([indexed_tokens1]) # 将list转为tensor\n", 163 | "segments_tensors1 = torch.tensor([segments_ids1])\n", 164 | "# 获取所有词向量的embedding\n", 165 | "word_vectors1 = bertmodel(tokens_tensor1, segments_tensors1)[0]\n", 166 | "# 获取句子的embedding\n", 167 | "sentenc_vector1 = bertmodel(tokens_tensor1, segments_tensors1)[1]\n", 168 | "tokenizer.add_special_tokens({'additional_special_tokens':[\"\"]})\n", 169 | "print(\"添加特殊占位符 后 的分词效果:\")\n", 170 | "print(tokenizer.additional_special_tokens) # 查看此类特殊token有哪些\n", 171 | "print(tokenizer.additional_special_tokens_ids) # 查看其id\n", 172 | "tokenized_text1 = tokenizer.tokenize(text)\n", 173 | "print(tokenized_text1)" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [] 182 | } 183 | ], 184 | "metadata": { 185 | "kernelspec": { 186 | "display_name": "Python 3", 187 | "language": "python", 188 | "name": "python3" 189 | }, 190 | "language_info": { 191 | "codemirror_mode": { 192 | "name": "ipython", 193 | "version": 3 194 | }, 195 | "file_extension": ".py", 196 | "mimetype": "text/x-python", 197 | "name": "python", 198 | "nbconvert_exporter": "python", 199 | "pygments_lexer": "ipython3", 200 | "version": "3.7.0" 201 | }, 202 | "toc": { 203 | "base_numbering": 1, 204 | "nav_menu": {}, 205 | "number_sections": true, 206 | "sideBar": true, 207 | "skip_h1_title": false, 208 | "title_cell": "Table of Contents", 209 | "title_sidebar": "Contents", 210 | "toc_cell": false, 211 | "toc_position": {}, 212 | "toc_section_display": true, 213 | "toc_window_display": false 214 | } 215 | }, 216 | "nbformat": 4, 217 | "nbformat_minor": 2 218 | } 219 | -------------------------------------------------------------------------------- /bert_study/distilbert/img/20200801191212.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/distilbert/img/20200801191212.png -------------------------------------------------------------------------------- /bert_study/distilbert/img/20200801191434.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/distilbert/img/20200801191434.png -------------------------------------------------------------------------------- /bert_study/distilbert/readme.md: -------------------------------------------------------------------------------- 1 | # 【关于 DistilBERT】 那些的你不知道的事 2 | 3 | > 作者:杨夕 4 | > 5 | > github:https://github.com/km1994/nlp_paper_study 6 | > 7 | > 论文:DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter 8 | > 9 | > paper:http://arxiv.org/abs/1910.01108 10 | 11 | # 摘要 12 | 13 | 随着自大型预训练模型执行的转移学习在自然语言处理(NLP)中愈发普遍,在实时与/或受限的计算训练中或推理预算下,操作这些大型模型仍然很有挑战性。 14 | 15 | 在本文中,我们提出了一种名为DistilBERT的方法,预训练较小的通用语言表征模型,在将其用于较大任务(如较大的对应对象)时再对其进行微调。尽管之前的大多工作都在研究使用蒸馏来构建特定的任务模型,但是在预训练阶段,我们使用了知识蒸馏,证明了将BERT模型的大小减少40%,同时保留其97%的语言理解能力,并且增速60%是可行的。 16 | 17 | ## 动机 18 | 19 | - Bert 系列模型 成本增长 的 计算量; 20 | - 模型不断增长的算力和内存要求可能阻止被广泛使用 21 | 22 | ## 核心思想 23 | 24 | 通过知识蒸馏(在 logits,hidden_states 上计算学生与教师的 loss)训练一个小(主要是层数)模型实现和大模型类似的效果。 25 | 26 | ## 模型蒸馏思路 27 | 28 | ### 思路介绍 29 | 30 | 知识蒸馏 [Bucila 等,2006; Hinton 等,2015] 是一种压缩技术,训练一个紧凑型模型(学生),以再现较大模型(教师)或模型集合的行为。 31 | 32 | ### 损失函数 33 | 34 | ![](img/20200801191212.png) 35 | 36 | > $t_i$ 老师的概率估计 37 | > $s_i$ 学生的概率估计 38 | 39 | - 使用了 softmax-temperature: 40 | 41 | ![](img/20200801191434.png) 42 | 43 | > T 控制输出分布的平滑程度,推理时设置为 1 变为标准的 Softmax; 44 | > $z_i$ 表示类别 i 的分数。 45 | 46 | 最终的损失函数是 Lce 和 masked language modeling loss Lmlm 的线性组合,另外作者发现添加余弦嵌入损失(Lcos)有利于使学生和教师隐藏状态向量的方向一致。 47 | 48 | ### 学生架构 49 | 50 | - 具有和老师一般的体系结构; 51 | - 移除了 Token type embedding 和 pooler; 52 | - 层数减少为 1/2:作者调查发现改变隐层维度对计算效率的影响比其他因素的变化要小(比如层数)。 53 | 54 | 从老师的两层中选择一层来初始化学生。蒸馏应用了Liu et al. [2019] 提出的 BERT 模型训练最佳实践。语料和 Bert 使用的一致。 55 | 56 | 57 | ## 参考 58 | 59 | 1. [DistilBERT 论文+代码笔记](https://yam.gift/2020/04/27/Paper/2020-04-27-DistilBERT/) 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /bert_study/img/20201015170627.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/20201015170627.png -------------------------------------------------------------------------------- /bert_study/img/20201026153603.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/20201026153603.png -------------------------------------------------------------------------------- /bert_study/img/20201026153725.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/20201026153725.png -------------------------------------------------------------------------------- /bert_study/img/20201026154010.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/20201026154010.png -------------------------------------------------------------------------------- /bert_study/img/20201026154623.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/20201026154623.png -------------------------------------------------------------------------------- /bert_study/img/20230321223629.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/20230321223629.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910210322.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910210322.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910210729.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910210729.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910210907.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910210907.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910211607.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910211607.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910212046.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910212046.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910212205.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910212205.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910212307.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910212307.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910213336.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910213336.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910213420.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910213420.png -------------------------------------------------------------------------------- /bert_study/img/微信截图_20210910213837.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/img/微信截图_20210910213837.png -------------------------------------------------------------------------------- /bert_study/readme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/readme.png -------------------------------------------------------------------------------- /bert_study/基于知识增强的语言表示模型.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/km1994/nlp_paper_study_bert/136b1f595ebf6ca78aff64b46a631119c13b0cdb/bert_study/基于知识增强的语言表示模型.pdf --------------------------------------------------------------------------------