Deep Learning Foundations / Module 8 of 8
15-min lesson · final module

Natural Language Processing with BERT

BERT · Tokenization · Segmenting Text · Text Masking · Question and Answering

BERT

Everything so far has looked at pixels. BERT looks at words — and reads them bidirectionally: it considers the words both before and after a given word to understand it, rather than only reading left to right. It was pre-trained on a huge amount of text the same way VGG16 was pre-trained on images — general language understanding, ready to be reused.

Tokenization

Models can't read raw text — tokenization breaks it into pieces from a fixed vocabulary BERT understands. Special tokens get added automatically: [CLS] marks the start, [SEP] marks the end.

from transformers import BertTokenizer

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
tokens = tokenizer.tokenize("Deep learning models can understand language.")
print(tokens)
→ ['deep', 'learning', 'models', 'can', 'understand', 'language', '.']

Segmenting Text

Some tasks (like question answering, below) need two pieces of text at once — a question and a passage, say. token_type_ids mark which sentence each token belongs to: 0 for the first, 1 for the second.

encoded = tokenizer("Izza built Distilligent.", "She had never coded before.", return_tensors='pt')
print(encoded['token_type_ids'])
→ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]

Text Masking

BERT's original training task, and still the clearest way to see what it learned: hide a word with [MASK], ask the model to guess it. Getting this right at scale, across billions of sentences, is how it built its understanding of language in the first place.

from transformers import BertForMaskedLM
import torch

model = BertForMaskedLM.from_pretrained('bert-base-uncased')
inputs = tokenizer("Paris is the capital of [MASK].", return_tensors='pt')
mask_position = (inputs['input_ids'] == tokenizer.mask_token_id).nonzero(as_tuple=True)[1]

with torch.no_grad():
    outputs = model(**inputs)
predicted_id = outputs.logits[0, mask_position].argmax(dim=-1).item()
print(tokenizer.decode([predicted_id]))
→ france

Question and Answering

A version of BERT fine-tuned specifically for Q&A takes a question and a context passage together (using segmenting, from above), and predicts where the answer starts and ends inside that passage — it extracts the answer, it doesn't generate one from memory:

from transformers import BertForQuestionAnswering

qa_model = BertForQuestionAnswering.from_pretrained(
    'bert-large-uncased-whole-word-masking-finetuned-squad'
)
context = "Distilligent was founded by Izza Masud, who had no coding background when she started."
question = "Who founded Distilligent?"

inputs = tokenizer(question, context, return_tensors='pt')
outputs = qa_model(**inputs)
start = outputs.start_logits.argmax()
end = outputs.end_logits.argmax()
answer = tokenizer.decode(inputs['input_ids'][0][start:end+1])
print(answer)
→ izza masud
It never "knew" who founded Distilligent. It read the sentence you gave it, and pointed.

Vocabulary

BERT
A bidirectional language model, pretrained on huge amounts of text to understand language generally.
Bidirectional
Reading context from both before and after a word, not just left to right.
Tokenization
Breaking text into pieces from a fixed vocabulary the model understands.
[CLS] / [SEP]
Special tokens marking the start of input, and the end of a segment.
token_type_ids
Marks which of two combined texts each token came from.
Masked language modeling
BERT's original training task — predicting hidden [MASK] words.
Extractive Q&A
Finding and pulling out an existing answer span from a given passage, not generating new text.

15-min quiz

Course Complete · 8 of 8

The person who put this course together had no code at all, once — and built a working AI system anyway. If she could, you can too. Go try something.