Sub topic 7
Your first answer with the pipeline
This chapter runs a pretrained extractive question-answering model through the Hugging Face pipeline helper and reads its output closely. It assumes you know basic Python, have a general idea of what a pretrained language model is, and understand tokenization at a high level. You don't need to know how the model works inside. Later chapters open the pipeline up and rebuild it by hand.
What the pipeline does for you
Extractive question answering takes two strings, a question and a context, and returns a span of the context that answers the question. The model never writes new text. It points at a piece of the passage you gave it.
The question-answering pipeline wraps the whole procedure in one call:
- It tokenizes the question and the context together as one pair.
- It runs the encoder and the span head, which produce one start score and one end score per token.
- It picks the best valid span and maps token positions back to character positions in your original string.
- It returns the answer text, a score, and the character offsets.
Running your first query
Install the libraries first. The pipeline needs transformers and a backend such as PyTorch.
pip install transformers torchThen run the example below. The first call downloads the model weights, about a few hundred megabytes, and caches them locally.
from transformers import pipeline
qa = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
context = (
"The Amazon River in South America is the largest river by discharge volume of water in the world. "
"Its drainage basin covers about seven million square kilometres."
)
result = qa(question="What does the Amazon basin cover?", context=context)
print(result) # a dict with the keys 'score', 'start', 'end' and 'answer'The model, distilbert-base-cased-distilled-squad, is a smaller DistilBERT student model distilled from a BERT model fine-tuned on SQuAD. It is "cased", so it distinguishes Amazon from amazon. The printed dictionary should look like this, though the exact numbers may differ slightly between library versions:
{'score': 0.5, 'start': 98, 'end': 138, 'answer': 'about seven million square kilometres'}Treat the numbers above as a shape, not a promise. The answer should be the phrase about seven million square kilometres, possibly without the word "about".
Reading the result
Each key in the dictionary has a precise meaning.
| Key | Type | Meaning |
|---|---|---|
| `answer` | string | The text of the chosen span, copied from the context |
| `start` | int | Character index in the context where the answer begins |
| `end` | int | Character index just after the last answer character (exclusive) |
| `score` | float | The model's probability for this span, between 0 and 1 |
The offsets are character positions in your original context string. They are not token positions. You can check this with a slice:
print(context[result["start"]:result["end"]])
print(context[result["start"]:result["end"]] == result["answer"]) # TrueThis property is what makes extractive QA useful for products. You can highlight the answer inside the source document, and the user can see where the claim came from.
What the score means
The score is a probability computed from the start and end scores, normalized over the candidate spans the pipeline considered. It is a ranking signal and is only loosely a calibrated confidence. A score of 0.9 does not mean the answer is right 90 percent of the time. Treat it as follows:
- Use it to compare candidate answers for the same question.
- Use it to choose a threshold, for example "show the answer only if the score is above 0.3", and tune that threshold on your own labeled data.
- Do not compare scores across different models or domains and expect them to mean the same thing.
Getting several candidates with top_k
By default the pipeline returns a single dictionary. Pass top_k to get a list of the best distinct spans, sorted from best to worst:
from transformers import pipeline
qa = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
context = (
"The Amazon River in South America is the largest river by discharge volume of water in the world. "
"Its drainage basin covers about seven million square kilometres."
)
answers = qa(question="What is the largest river by discharge?", context=context, top_k=3)
for a in answers:
print(round(a["score"], 3), a["start"], a["end"], repr(a["answer"]))Two behaviors are worth knowing:
- With
top_k=1(the default) you get a dictionary. Withtop_kgreater than 1 you get a list of dictionaries. Code that handles both cases must check the type. - The lower-ranked candidates are often overlapping or nested variants of the first, such as the same phrase with and without a leading word. They are not always independent alternative answers.
Asking several questions
Many questions about one passage are the common case: one document, a form with several fields to fill. Loop over the questions and reuse the same qa object, so the model loads only once.
from transformers import pipeline
qa = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
context = (
"The Amazon River in South America is the largest river by discharge volume of water in the world. "
"Its drainage basin covers about seven million square kilometres."
)
questions = [
"Where is the Amazon River?",
"How large is the drainage basin?",
"What is the Amazon the largest river by?",
]
for q in questions:
r = qa(question=q, context=context)
print(f"{q} -> {r['answer']!r} (score {r['score']:.2f})")The loop runs each question separately. On a GPU you can speed this up by passing device=0 to pipeline(...) and by sending many inputs at once with the pipeline's batch_size argument. For a short script on a CPU, the loop is fine.
Parameters that change behavior
The pipeline exposes several arguments that map directly onto the steps you will implement by hand later. You can pass them in the call.
| Argument | Default | Effect |
|---|---|---|
| `top_k` | 1 | Number of answers to return |
| `max_answer_len` | 15 | Maximum length of an answer in tokens. Longer spans are never considered |
| `max_seq_len` | 384 | Maximum tokens in one window, question included |
| `doc_stride` | 128 | Overlap in tokens between consecutive windows of a long context |
| `max_question_len` | 64 | Questions longer than this many tokens are truncated |
| `handle_impossible_answer` | False | Allow the pipeline to return an empty answer when the null score wins |
The max_answer_len default is the most common source of surprise. If your answers are long, such as a full sentence or a list of items, the pipeline cuts them short or picks a shorter span that fits the limit. Raise it when you expect long answers:
result = qa(
question="What does the Amazon basin cover?",
context=context,
max_answer_len=40,
)
print(result["answer"])Long contexts happen automatically
If the context plus question exceeds max_seq_len tokens, the pipeline splits the context into overlapping windows. Each window contains the whole question and a piece of the context, overlapping the previous one by roughly doc_stride tokens. The pipeline scores every window and returns the best span across all of them. You don't write any code for this. The behavior is still worth knowing about, because answers that fall across a window boundary can be missed if you set doc_stride too small, and processing time grows with the number of windows. A later chapter shows the splitting step directly.
Common mistakes
- Swapping the arguments. Passing the long text as
questionand the short text ascontextruns without an error and produces a meaningless answer. Always use the keyword arguments. - Expecting reasoning or synthesis. The model copies a span. A question like "How many rivers are mentioned?" needs counting, and the pipeline will return some span such as a number that happens to appear in the text.
- Using the wrong model type. A model fine-tuned for text classification or generation cannot be loaded into this pipeline without a QA head. Pick a checkpoint trained for question answering.
- Reading
endas inclusive.endis exclusive, like a Python slice bound. Usecontext[start:end]. - Ignoring casing and language. A cased English model is the wrong choice for a Spanish contract. Choose a checkpoint trained on your language and domain.
- Assuming a null answer is available. With a SQuAD v1 checkpoint,
handle_impossible_answer=Truedoes not give you a reliable abstain signal, because the model was never trained to predict "no answer". For that you need a SQuAD v2 style checkpoint, such asdeepset/roberta-base-squad2.
Checking your understanding
Exercise
You run the pipeline and get {'score': 0.71, 'start': 98, 'end': 135, 'answer': 'about seven million square kilometres'}. (a) Which expression recovers the answer from the context string? (b) You ask a different question whose true answer is a 25-word sentence, and the pipeline returns only a fragment of it. Which argument do you change first, and why?
Show answer
(a) context[98:135]. The offsets are character positions in the original context, and end is exclusive, so a normal Python slice returns the answer. (b) Raise maxanswerlen. Its default of 15 tokens means the pipeline never considers a span longer than that, so a 25-word answer is cut or replaced by a shorter span. A sentence of 25 words needs well over 15 tokens, so set maxanswerlen to a larger value such as 50 or 60.
Exercise
Why should you not treat the pipeline's score as the probability that the answer is correct, and what is a sound way to use it?
Show answer
The score is a normalized model output for ranking spans within one query. It is not calibrated against real accuracy, and a SQuAD v1 model gives a span with some score even when the passage has no answer. A sound use is to choose a threshold by measuring accuracy at different score cutoffs on labeled examples from your own domain, and to compare candidates for the same question only.