Create a Question and Answer NLP Model with BERT
BERT (Bidirectional Encoder Representations from Transformers) is a pre-trained language model developed by Google. Because it is trained bidirectionally — conditioning on both left and right context simultaneously — it captures richer semantic meaning than previous unidirectional models. HuggingFace provides fine-tuned BERT checkpoints for specific tasks, including extractive question answering on the SQuAD dataset.
This post shows how to use one of those checkpoints to build a working Q&A system in Python with no model training required.
Installation
pip install transformers torch
Step 1: Download and Save the Model Locally
BERT models are large. Downloading them on every run is slow. Save them locally once and load from disk afterward.
# model.py
from transformers import BertForQuestionAnswering, BertTokenizer
MODEL_NAME = 'bert-large-uncased-whole-word-masking-finetuned-squad'
model = BertForQuestionAnswering.from_pretrained(MODEL_NAME)
tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
model.save_pretrained('./bert-qa-model')
tokenizer.save_pretrained('./bert-qa-model')
print('Model saved.')
Run this once: python model.py
Step 2: Load and Run Inference
import torch
from transformers import BertForQuestionAnswering, BertTokenizer
model = BertForQuestionAnswering.from_pretrained('./bert-qa-model')
tokenizer = BertTokenizer.from_pretrained('./bert-qa-model')
def answer_question(question, context):
inputs = tokenizer.encode_plus(
question,
context,
add_special_tokens=True,
return_tensors='pt'
)
input_ids = inputs['input_ids'].tolist()[0]
token_type_ids = inputs['token_type_ids']
with torch.no_grad():
outputs = model(**inputs)
answer_start = torch.argmax(outputs.start_logits)
answer_end = torch.argmax(outputs.end_logits) + 1
tokens = tokenizer.convert_ids_to_tokens(input_ids)
answer_tokens = tokens[answer_start:answer_end]
answer = tokenizer.convert_tokens_to_string(answer_tokens)
return answer
Step 3: Try It
context = """
The Amazon rainforest covers most of the Amazon basin of South America.
This basin encompasses 7,000,000 km2, of which 5,500,000 km2 are covered
by the rainforest. It is the world's largest rainforest.
"""
question = "What is the size of the Amazon basin?"
print(answer_question(question, context))
Output: 7,000,000 km2
How It Works
The model receives the question and context concatenated together. Token type embeddings tell BERT which tokens belong to the question and which belong to the context. BERT then outputs logits for each token representing how likely it is to be the start or end of the answer span. The final answer is the sequence of tokens between the highest-scoring start and end positions.
The ## prefixes on subword tokens are removed by convert_tokens_to_string, which handles the WordPiece tokenization artefacts automatically.
Limitations
- BERT has a 512 token limit. For long documents, you need to chunk the context and run multiple inferences.
- This model is extractive — it returns a span from the context, not a generated answer. It cannot synthesise information from multiple passages.
- Quality depends on the context containing the answer. If it does not, the model will still return a span, which will be incorrect.
Conclusion
HuggingFace's pre-trained BERT checkpoint makes it straightforward to build an extractive Q&A system without training a model from scratch. For domain-specific use cases, fine-tuning on your own data will improve accuracy significantly — but for general-purpose question answering over well-formed text, the out-of-the-box checkpoint performs well.