Hugging Face 发布 BERT 模型入门详解
Hugging Face 博客发布了一篇关于 BERT 模型的入门级技术解读文章。该文章回顾了 BERT 作为双向编码器表示在自然语言处理中的核心机制与应用场景,旨在帮助开发者理解这一经典架构的基础原理。
报道正文
本文目录30 个章节
BERT 101 🤗 深入解析最先进(SOTA)的 NLP 模型
发布于 2022 年 3 月 2 日 在 GitHub 上更新 点赞 12
什么是 BERT?
BERT,全称为 Bidirectional Encoder Representations from Transformers(基于 Transformer 的双向编码器表示),是一种用于自然语言处理(NLP)的机器学习(ML)模型。它由 Google AI Language 的研究人员于 2018 年开发,是解决 11+ 种最常见语言任务(如情感分析和命名实体识别)的“瑞士军刀”式解决方案。
历史上,计算机一直难以真正“理解”语言。诚然,计算机可以收集、存储和读取文本输入,但它们缺乏基本的语言语境。
于是,自然语言处理(NLP)应运而生:这是人工智能的一个领域,旨在让计算机能够阅读、分析、解释文本和口语并从中提取含义。这一实践结合了语言学、统计学和机器学习,以辅助计算机“理解”人类语言。
传统的 NLP 任务通常由为每个特定任务单独创建的独立模型来解决。直到——BERT 的出现!
BERT 彻底改变了 NLP 领域,它不仅解决了 11+ 种最常见的 NLP 任务,而且性能优于之前的模型,使其成为 NLP 领域的多面手。
在本指南中,你将了解 BERT 是什么、它为何与众不同,以及如何开始使用 BERT:
- BERT 用于什么?
- BERT 是如何工作的?
- BERT 模型大小与架构
- BERT 在常见语言任务上的表现
- 深度学习的环境影响
- BERT 的开源力量
- 如何开始使用 BERT
- BERT 常见问题解答 (FAQs)
- 结论
让我们开始吧!🚀
1. BERT 用于什么?
BERT 可以应用于多种语言任务:
- 判断电影评论的正面或负面程度。(情感分析)
- 帮助聊天机器人回答你的问题。(问答)
- 在撰写电子邮件时预测文本内容(如 Gmail)。(文本预测)
- 仅凭几句输入即可撰写关于任何主题的文章。(文本生成)
- 快速总结冗长的法律合同。(摘要)
- 根据上下文区分具有多重含义的词(例如 ‘bank’)。(多义词消歧)
此外还有更多语言/NLP 任务,且每项任务背后都有更详细的说明。
趣味知识: 你几乎每天都在与 NLP(很可能也包括 BERT)互动!
NLP 技术支撑着 Google 翻译、语音助手(Alexa、Siri 等)、聊天机器人、Google 搜索、语音控制的 GPS 以及其他众多应用。
1.1 BERT 示例
自 2020 年 11 月以来,BERT 帮助 Google 为几乎所有搜索更好地呈现(英文)结果。
以下是一个示例,展示了 BERT 如何帮助 Google 更好地理解特定搜索查询:
在引入 BERT 之前,Google 会展示有关配药的信息。
在引入 BERT 之后,Google 理解了“for someone”指的是为他人取药,因此搜索结果现在能够针对这一意图提供答案。
2. BERT 是如何工作的?
BERT 通过利用以下要素来工作:
2.1 海量训练数据
一个包含 33 亿单词的庞大数据集促成了 BERT 的持续成功。
BERT 专门在维基百科(约 25 亿单词)和 Google BooksCorpus(约 8 亿单词)上进行训练。这些大型信息数据集不仅赋予了 BERT 对英语语言的深刻理解,也使其具备了丰富的世界知识!🚀
在如此大规模的数据集上进行训练需要很长时间。得益于新颖的 Transformer 架构以及 TPU(Tensor Processing Units,谷歌专为大型机器学习模型定制的电路)的使用,BERT 的训练得以实现并加速——64 个 TPU 历时 4 天完成了 BERT 的训练。
注: 为了在计算资源较小的环境(如手机和个人电脑)中使用 BERT,市场对小型化 BERT 模型的需求正在增长。2020 年 3 月发布了 23 个小型化 BERT 模型。DistilBERT 提供了 BERT 的轻量级版本;运行速度提升 60%,同时保持了 BERT 95% 以上的性能。
2.2 什么是掩码语言模型?
MLM 通过遮蔽(隐藏)句子中的一个词,并强制 BERT 利用被遮盖词两侧的词进行双向预测,从而实现/强化了从文本中进行双向学习。这在以前从未有过!
趣味知识: 我们人类天生就在做这件事!
掩码语言模型示例:
想象一下,你的朋友在冰川国家公园露营时给你打电话,信号开始断断续续。电话挂断前你听到的最后一句话是:
朋友:“天哪!我正在钓鱼,一条巨大的鳟鱼刚刚 [空白] 了我的鱼线!”
你能猜出朋友说了什么吗??
你能够自然地通过考虑缺失词前后的词语作为上下文线索(再加上你对钓鱼原理的历史知识),来预测缺失的词。你猜到朋友说的是“broke”(弄断/扯断)了吗?这也是我们的预测结果,但即便是我们人类,在某些情况下也容易出错。
注: 这就是为什么你经常会看到语言模型的性能分数与“人类表现”进行比较的原因。是的,像 BERT 这样的新模型可以比人类更准确!🤯
你在上面填补 [空白] 词时所采用的双向方法,类似于 BERT 达到最先进(state-of-the-art)准确率的方式。在训练过程中,随机隐藏 15% 的分词(tokenized words),BERT 的任务是正确预测这些被隐藏的词。因此,这直接教会了模型关于英语语言(以及我们使用的词汇)的知识。是不是很巧妙?
尝试使用 BERT 的掩码预测功能:
托管推理 API Fill-Mask 示例 掩码标记:[MASK] 该模型可按需加载到 Inference API 上。
趣味知识: 掩码技术已经存在很长时间了 - 1953 年关于完形填空程序(或‘Masking’)的论文。
2.3 什么是下一句预测?
NSP (Next Sentence Prediction) is used to help BERT learn about relationships between sentences by predicting if a given sentence follows the previous sentence or not.
Next Sentence Prediction Example:
- Paul went shopping. He bought a new shirt. (correct sentence pair)
- Ramona made coffee. Vanilla ice cream cones for sale. (incorrect sentence pair)
In training, 50% correct sentence pairs are mixed in with 50% random sentence pairs to help BERT increase next sentence prediction accuracy.
Fun Fact: BERT is trained on both MLM (50%) and NSP (50%) at the same time.
2.4 Transformers
The Transformer architecture makes it possible to parallelize ML training extremely efficiently. Massive parallelization thus makes it feasible to train BERT on large amounts of data in a relatively short period of time.
Transformers use an attention mechanism to observe relationships between words. A concept originally proposed in the popular 2017 Attention Is All You Need paper sparked the use of Transformers in NLP models all around the world.
Since their introduction in 2017, Transformers have rapidly become the state-of-the-art approach to tackle tasks in many domains such as natural language processing, speech recognition, and computer vision. In short, if you’re doing deep learning, then you need Transformers!
Lewis Tunstall, Hugging Face ML Engineer & Author of Natural Language Processing with Transformers)
Timeline of popular Transformer model releases:
2.4.1 How do Transformers work?
Transformers work by leveraging attention, a powerful deep-learning algorithm, first seen in computer vision models.
—Not all that different from how we humans process information through attention. We are incredibly good at forgetting/ignoring mundane daily inputs that don’t pose a threat or require a response from us. For example, can you remember everything you saw and heard coming home last Tuesday? Of course not! Our brain’s memory is limited and valuable. Our recall is aided by our ability to forget trivial inputs.
[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]
Similarly, Machine Learning models need to learn how to pay attention only to the things that matter and not waste computational resources processing irrelevant information. Transformers create differential weights signaling which words in a sentence are the most critical to further process.
A transformer does this by successively processing an input through a stack of transformer layers, usually called the encoder. If necessary, another stack of transformer layers - the decoder - can be used to predict a target output. —BERT however, doesn’t use a decoder. Transformers are uniquely suited for unsupervised learning because they can efficiently process millions of data points.
Fun Fact: Google has been using your reCAPTCHA selections to label training data since 2011. The entire Google Books archive and 13 million articles from the New York Times catalog have been transcribed/digitized via people entering reCAPTCHA text. Now, reCAPTCHA is asking us to label Google Street View images, vehicles, stoplights, airplanes, etc. Would be neat if Google made us aware of our participation in this effort (as the training data likely has future commercial intent) but I digress..
To learn more about Transformers check out our Hugging Face Transformers Course.
3. BERT model size & architecture
Let’s break down the architecture for the two original BERT models:
ML Architecture Glossary:
| ML Architecture Parts | Definition |
|---|---|
| Parameters: | Number of learnable variables/values available for the model. |
| Transformer Layers: | Number of Transformer blocks. A transformer block transforms a sequence of word representations to a sequence of contextualized words (numbered representations). |
| Hidden Size: | Layers of mathematical functions, located between the input and output, that assign weights (to words) to produce a desired result. |
| Attention Heads: | The size of a Transformer block. |
| Processing: | Type of processing unit used to train the model. |
| Length of Training: | Time it took to train the model. |
Here’s how many of the above ML architecture parts BERTbase and BERTlarge has:
| Transformer Layers | Hidden Size | Attention Heads | Parameters | Processing | Length of Training | |
|---|---|---|---|---|---|---|
| BERTbase | 12 | 768 | 12 | 110M | 4 TPUs | 4 days |
| BERTlarge | 24 | 1024 | 16 | 340M | 16 TPUs | 4 days |
Let’s take a look at how BERTlarge’s additional layers, attention heads, and parameters have increased its performance across NLP tasks.
4. BERT's performance on common language tasks
BERT has successfully achieved state-of-the-art accuracy on 11 common NLP tasks, outperforming previous top NLP models, and is the first to outperform humans! But, how are these achievements measured?
NLP Evaluation Methods:
4.1 SQuAD v1.1 & v2.0
SQuAD (Stanford Question Answering Dataset) is a reading comprehension dataset of around 108k questions that can be answered via a corresponding paragraph of Wikipedia text. BERT’s performance on this evaluation method was a big achievement beating previous state-of-the-art models and human-level performance:
4.2 SWAG
SWAG (Situations With Adversarial Generations) is an interesting evaluation in that it detects a model’s ability to infer commonsense! It does this through a large-scale dataset of 113k multiple choice questions about common sense situations. These questions are transcribed from a video scene/situation and SWAG provides the model with four possible outcomes in the next scene. The model then does its’ best at predicting the correct answer.
BERT out outperformed top previous top models including human-level performance:
4.3 GLUE Benchmark
GLUE (General Language Understanding Evaluation) benchmark is a group of resources for training, measuring, and analyzing language models comparatively to one another. These resources consist of nine “difficult” tasks designed to test an NLP model’s understanding. Here’s a summary of each of those tasks:
While some of these tasks may seem irrelevant and banal, it’s important to note that these evaluation methods are incredibly powerful in indicating which models are best suited for your next NLP application.
Attaining performance of this caliber isn’t without consequences. Next up, let’s learn about Machine Learning's impact on the environment.
5. Environmental impact of deep learning
Large Machine Learning models require massive amounts of data which is expensive in both time and compute resources.
These models also have an environmental impact:
Machine Learning’s environmental impact is one of the many reasons we believe in democratizing the world of Machine Learning through open source! Sharing large pre-trained language models is essential in reducing the overall compute cost and carbon footprint of our community-driven efforts.
6. The open source power of BERT
Unlike other large learning models like GPT-3, BERT’s source code is publicly accessible (view BERT’s code on Github) allowing BERT to be more widely used all around the world. This is a game-changer!
Developers are now able to get a state-of-the-art model like BERT up and running quickly without spending large amounts of time and money. 🤯
Developers can instead focus their efforts on fine-tuning BERT to customize the model’s performance to their unique tasks.
It’s important to note that thousands of open-source and free, pre-trained BERT models are currently available for specific use cases if you don’t want to fine-tune BERT.
BERT models pre-trained for specific tasks:
- Twitter sentiment analysis
- Analysis of Japanese text
- Emotion categorizer (English - anger, fear, joy, etc.)
- Clinical Notes analysis
- Speech to text translation
- Toxic comment detection?
You can also find hundreds of pre-trained, open-source Transformer models available on the Hugging Face Hub.
7. How to get started using BERT
We've created this notebook so you can try BERT through this easy tutorial in Google Colab. Open the notebook or add the following code to your own. Pro Tip: Use (Shift + Click) to run a code cell.
Note: Hugging Face's pipeline class makes it incredibly easy to pull in open source ML models like transformers with just a single line of code.
7.1 Install Transformers
First, let's install Transformers via the following code:
!pip install transformers7.2 Try out BERT
Feel free to swap out the sentence below for one of your own. However, leave [MASK] in somewhere to allow BERT to predict the missing word
from transformers import pipeline
unmasker = pipeline('fill-mask', model='bert-base-uncased')
unmasker("Artificial Intelligence [MASK] take over the world.")When you run the above code you should see an output like this:
[{'score': 0.3182411789894104,
'sequence': 'artificial intelligence can take over the world.',
'token': 2064,
'token_str': 'can'},
{'score': 0.18299679458141327,
'sequence': 'artificial intelligence will take over the world.',
'token': 2097,
'token_str': 'will'},
{'score': 0.05600147321820259,
'sequence': 'artificial intelligence to take over the world.',
'token': 2000,
'token_str': 'to'},
{'score': 0.04519503191113472,
'sequence': 'artificial intelligences take over the world.',
'token': 2015,
'token_str': '##s'},
{'score': 0.045153118669986725,
'sequence': 'artificial intelligence would take over the world.',
'token': 2052,
'token_str': 'would'}]Kind of frightening right? 🙃
7.3 Be aware of model bias
Let's see what jobs BERT suggests for a "man":
unmasker("The man worked as a [MASK].")When you run the above code you should see an output that looks something like:
[{'score': 0.09747546911239624,
'sequence': 'the man worked as a carpenter.',
'token': 10533,
'token_str': 'carpenter'},
{'score': 0.052383411675691605,
'sequence': 'the man worked as a waiter.',
'token': 15610,
'token_str': 'waiter'},
{'score': 0.04962698742747307,
'sequence': 'the man worked as a barber.',
'token': 13362,
'token_str': 'barber'},
{'score': 0.037886083126068115,
'sequence': 'the man worked as a mechanic.',
'token': 15893,
'token_str': 'mechanic'},
{'score': 0.037680838257074356,
'sequence': 'the man worked as a salesman.',
'token': 18968,
'token_str': 'salesman'}]BERT predicted the man's job to be a Carpenter, Waiter, Barber, Mechanic, or Salesman
Now let's see what jobs BERT suggesst for "woman"
unmasker("The woman worked as a [MASK].")You should see an output that looks something like:
[{'score': 0.21981535851955414,
'sequence': 'the woman worked as a nurse.',
'token': 6821,
'token_str': 'nurse'},
{'score': 0.1597413569688797,
'sequence': 'the woman worked as a waitress.',
'token': 13877,
'token_str': 'waitress'},
{'score': 0.11547300964593887,
'sequence': 'the woman worked as a maid.',
'token': 10850,
'token_str': 'maid'},
{'score': 0.03796879202127457,
'sequence': 'the woman worked as a prostitute.',
'token': 19215,
'token_str': 'prostitute'},
{'score': 0.030423851683735847,
'sequence': 'the woman worked as a cook.',
'token': 5660,
'token_str': 'cook'}]BERT predicted the woman's job to be a Nurse, Waitress, Maid, Prostitute, or Cook displaying a clear gender bias in professional roles.
7.4 Some other BERT Notebooks you might enjoy:
A Visual Notebook to BERT for the First Time
+Don't forget to checkout the Hugging Face Transformers Course to learn more 🎉
8. BERT FAQs
Can BERT be used with PyTorch?
Yes! Our experts at Hugging Face have open-sourced the PyTorch transformers repository on GitHub.
Pro Tip: Lewis Tunstall, Leandro von Werra, and Thomas Wolf also wrote a book to help people build language applications with Hugging Face called, ‘Natural Language Processing with Transformers’.
Can BERT be used with Tensorflow?
Yes
How long does it take to pre-train BERT?
The 2 original BERT models were trained on 4(BERTbase) and 16(BERTlarge) Cloud TPUs for 4 days.
How long does it take to fine-tune BERT?
For common NLP tasks discussed above, BERT takes between 1-25mins on a single Cloud TPU or between 1-130mins on a single GPU.
What makes BERT different?
BERT was one of the first models in NLP that was trained in a two-step way:
- BERT was trained on massive amounts of unlabeled data (no human annotation) in an unsupervised fashion.
- BERT was then trained on small amounts of human-annotated data starting from the previous pre-trained model resulting in state-of-the-art performance.
9. Conclusion
BERT is a highly complex and advanced language model that helps people automate language understanding. Its ability to accomplish state-of-the-art performance is supported by training on massive amounts of data and leveraging Transformers architecture to revolutionize the field of NLP.
Thanks to BERT’s open-source library, and the incredible AI community’s efforts to continue to improve and share new BERT models, the future of untouched NLP milestones looks bright.
What will you create with BERT?
Learn how to fine-tune BERT for your particular use case 🤗