distilbert base uncased

提供商distilbert
分类fill-mask
许可证apache-2.0
下载量2.6K
星标0

简介

DistilBERT 是 BERT 的轻量化精简版,通过知识蒸馏技术在保留大部分自然语言理解能力的同时,大幅降低了模型体积和推理延迟。它采用了 uncased 版本,这意味着不区分大小写,更适合处理通用文本。对于开发者而言,它在性能和速度之间取得了极佳平衡,非常适合部署在资源受限的边缘端或需要高吞吐量的实时生产环境。如果你觉得原版 BERT 太慢且内存占用过高,但又需要处理掩码预测(Fill-Mask)或作为下游任务的预训练底座,DistilBERT 是一个极低门槛且高效的替代方案。

核心亮点

  • 轻量化设计,推理速度比 BERT 快 60%
  • 内存占用低,适合端侧部署与实时应用
  • 保留了 BERT 绝大部分的语义理解能力
  • Apache-2.0 协议,商业化集成无压力

使用方法

安装依赖
# 安装 Hugging Face transformers
pip install transformers torch
SDK 使用
# 使用 transformers 加载模型
from transformers import AutoModel, AutoTokenizer

model = AutoModel.from_pretrained("distilbert/distilbert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")

Hugging Face 下载

我们推荐使用命令行或者 Hugging Face Hub SDK 来进行模型的下载。

操作指引:在下载前,请先通过如下命令安装 huggingface_hub:

操作指引
pip install -U huggingface_hub

命令行下载

下载完整模型库

下载完整模型库
huggingface-cli download distilbert/distilbert-base-uncased

下载单个文件到指定本地文件夹(以下载 config.json 到当前路径下 ./dir 目录为例)

下载单个文件到指定本地文件夹(以下载 config.json 到当前路径下 ./dir 目录为例)
huggingface-cli download distilbert/distilbert-base-uncased config.json --local-dir ./dir

更多命令行下载选项,可参见官方文档

SDK 下载

SDK 下载
# 模型下载
from huggingface_hub import snapshot_download
model_dir = snapshot_download('distilbert/distilbert-base-uncased')

Git 下载

请确保 lfs 已经被正确安装

Git 下载
git lfs install
git clone https://huggingface.co/distilbert/distilbert-base-uncased

如果您希望跳过 lfs 大文件下载,可以使用如下命令

跳过 LFS
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/distilbert/distilbert-base-uncased

模型文件托管在 Hugging Face Hub,使用 HF CLI / SDK / Git 直接下载,不经过本站。

PyTorch / Transformers 使用

安装 Transformers

安装 Transformers
pip install -U transformers torch

模型加载和推理

模型加载和推理
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained('distilbert/distilbert-base-uncased')
tokenizer = AutoTokenizer.from_pretrained('distilbert/distilbert-base-uncased')

模型下载

我们推荐使用命令行或者 ModelScope SDK 来进行模型的下载。

操作指引:在下载前,请先通过如下命令安装 ModelScope:

操作指引
pip install modelscope

命令行下载

下载完整模型库

下载完整模型库
modelscope download --model distilbert/distilbert-base-uncased

下载单个文件到指定本地文件夹(以下载 README.md 到当前路径下 dir 目录为例)

下载单个文件到指定本地文件夹(以下载 README.md 到当前路径下 dir 目录为例)
modelscope download --model distilbert/distilbert-base-uncased README.md --local_dir ./dir

更多更丰富的命令行下载选项,可参见具体文档

SDK 下载

SDK 下载
# 模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('distilbert/distilbert-base-uncased')

Git 下载

请确保 lfs 已经被正确安装

Git 下载
git lfs install
git clone https://www.modelscope.cn/distilbert/distilbert-base-uncased.git

如果您希望跳过 lfs 大文件下载,可以使用如下命令

跳过 LFS
GIT_LFS_SKIP_SMUDGE=1 git clone https://www.modelscope.cn/distilbert/distilbert-base-uncased.git

ModelScope 模型页直接下载模型文件;无需将模型文件放在本站服务器。

Notebook 快速开发

下载并安装 ModelScope library

下载并安装 ModelScope library
pip install "modelscope[audio,cv,nlp,multi-modal,science]" -f https://modelscope.oss-cn-beijing.aliyuncs.com/releases/repo.html

模型加载和推理

模型加载和推理
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

p = pipeline('text-generation', 'distilbert/distilbert-base-uncased')

完整文档

来源: HuggingFace

---
language: en
tags:

  • exbert

license: apache-2.0
datasets:
  • bookcorpus

  • wikipedia

---

DistilBERT base model (uncased)

This model is a distilled version of the BERT base model. It was
introduced in this paper. The code for the distillation process can be found
here. This model is uncased: it does
not make a difference between english and English.

Model description

DistilBERT is a transformers model, smaller and faster than BERT, which was pretrained on the same corpus in a
self-supervised fashion, using the BERT base model as a teacher. This means it was pretrained on the raw texts only,
with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic
process to generate inputs and labels from those texts using the BERT base model. More precisely, it was pretrained
with three objectives:

  • Distillation loss: the model was trained to return the same probabilities as the BERT base model.
  • Masked language modeling (MLM): this is part of the original training loss of the BERT base model. When taking a
sentence, the model randomly masks 15% of the words in the input then run the entire masked sentence through the model and has to predict the masked words. This is different from traditional recurrent neural networks (RNNs) that usually see the words one after the other, or from autoregressive models like GPT which internally mask the future tokens. It allows the model to learn a bidirectional representation of the sentence.
  • Cosine embedding loss: the model was also trained to generate hidden states as close as possible as the BERT base
model.

This way, the model learns the same inner representation of the English language than its teacher model, while being
faster for inference or downstream tasks.

Intended uses & limitations

You can use the raw model for either masked language modeling or next sentence prediction, but it's mostly intended to
be fine-tuned on a downstream task. See the model hub to look for
fine-tuned versions on a task that interests you.

Note that this model is primarily aimed at being fine-tuned on tasks that use the whole sentence (potentially masked)
to make decisions, such as sequence classification, token classification or question answering. For tasks such as text
generation you should look at model like GPT2.

How to use

You can use this model directly with a pipeline for masked language modeling:

python
>>> from transformers import pipeline
>>> unmasker = pipeline('fill-mask', model='distilbert-base-uncased')
>>> unmasker("Hello I'm a [MASK] model.")

[{'sequence': "[CLS] hello i'm a role model. [SEP]",
'score': 0.05292855575680733,
'token': 2535,
'token_str': 'role'},
{'sequence': "[CLS] hello i'm a fashion model. [SEP]",
'score': 0.03968575969338417,
'token': 4827,
'token_str': 'fashion'},
{'sequence': "[CLS] hello i'm a business model. [SEP]",
'score': 0.034743521362543106,
'token': 2449,
'token_str': 'business'},
{'sequence': "[CLS] hello i'm a model model. [SEP]",
'score': 0.03462274372577667,
'token': 2944,
'token_str': 'model'},
{'sequence': "[CLS] hello i'm a modeling model. [SEP]",
'score': 0.018145186826586723,
'token': 11643,
'token_str': 'modeling'}]

Here is how to use this model to get the features of a given text in PyTorch:

python
from transformers import DistilBertTokenizer, DistilBertModel
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = DistilBertModel.from_pretrained("distilbert-base-uncased")
text = "Replace me by any text you'd like."
encoded_input = tokenizer(text, return_tensors='pt')
output = model(**encoded_input)

and in TensorFlow:

python
from transformers import DistilBertTokenizer, TFDistilBertModel
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
text = "Replace me by any text you'd like."
encoded_input = tokenizer(text, return_tensors='tf')
output = model(encoded_input)

Limitations and bias

Even if the training data used for this model could be characterized as fairly neutral, this model can have biased
predictions. It also inherits some of
the bias of its teacher model.

python
>>> from transformers import pipeline
>>> unmasker = pipeline('fill-mask', model='distilbert-base-uncased')
>>> unmasker("The White man worked as a [MASK].")

[{'sequence': '[CLS] the white man worked as a blacksmith. [SEP]',
'score': 0.1235365942120552,
'token': 20987,
'token_str': 'blacksmith'},
{'sequence': '[CLS] the white man worked as a carpenter. [SEP]',
'score': 0.10142576694488525,
'token': 10533,
'token_str': 'carpenter'},
{'sequence': '[CLS] the white man worked as a farmer. [SEP]',
'score': 0.04985016956925392,
'token': 7500,
'token_str': 'farmer'},
{'sequence': '[CLS] the white man worked as a miner. [SEP]',
'score': 0.03932540491223335,
'token': 18594,
'token_str': 'miner'},
{'sequence': '[CLS] the white man worked as a butcher. [SEP]',
'score': 0.03351764753460884,
'token': 14998,
'token_str': 'butcher'}]

>>> unmasker("The Black woman worked as a [MASK].")

[{'sequence': '[CLS] the black woman worked as a waitress. [SEP]',
'score': 0.13283951580524445,
'token': 13877,
'token_str': 'waitress'},
{'sequence': '[CLS] the black woman worked as a nurse. [SEP]',
'score': 0.12586183845996857,
'token': 6821,
'token_str': 'nurse'},
{'sequence': '[CLS] the black woman worked as a maid. [SEP]',
'score': 0.11708822101354599,
'token': 10850,
'token_str': 'maid'},
{'sequence': '[CLS] the black woman worked as a prostitute. [SEP]',
'score': 0.11499975621700287,
'token': 19215,
'token_str': 'prostitute'},
{'sequence': '[CLS] the black woman worked as a housekeeper. [SEP]',
'score': 0.04722772538661957,
'token': 22583,
'token_str': 'housekeeper'}]

This bias will also affect all fine-tuned versions of this model.

Training data

DistilBERT pretrained on the same data as BERT, which is BookCorpus, a dataset
consisting of 11,038 unpublished books and English Wikipedia
(excluding lists, tables and headers).

Training procedure

Preprocessing

The texts are lowercased and tokenized using WordPiece and a vocabulary size of 30,000. The inputs of the model are
then of the form:

code
[CLS] Sentence A [SEP] Sentence B [SEP]

With probability 0.5, sentence A and sentence B correspond to two consecutive sentences in the original corpus and in
the other cases, it's another random sentence in the corpus. Note that what is considered a sentence here is a
consecutive span of text usually longer than a single sentence. The only constrain is that the result with the two
"sentences" has a combined length of less than 512 tokens.

The details of the masking procedure for each sentence are the following:

  • 15% of the tokens are masked.

  • In 80% of the cases, the masked tokens are replaced by [MASK].

  • In 10% of the cases, the masked tokens are replaced by a random token (different) from the one they replace.

  • In the 10% remaining cases, the masked tokens are left as is.

Pretraining

The model was trained on 8 16 GB V100 for 90 hours. See the
training code for all hyperparameters
details.

Evaluation results

When fine-tuned on downstream tasks, this model achieves the following results:

Glue test results:

| Task | MNLI | QQP | QNLI | SST-2 | CoLA | STS-B | MRPC | RTE |
|:----:|:----:|:----:|:---