Hey GPT, I'm learning about the Hugging Face transformers library, and was wondering..…
- User
Hey GPT, I'm learning about the Hugging Face transformers library, and was wondering.. what are those "heads" they are talking about? For example, you pass a text to the tokenizer, or can pass multiple at once as an array/dictionary - but with the "QuestionAnswering" one, the tokenizer takes two text inputs for one query (in the tutorial dubbed "question" and "text", but it is the same tokenizer. How does this work? Is the "head" some kind of mechanism in this case, directing two inputs to the same model in sequence to get the expected result? Thanks.
From Hugging Face:
OPTForSequenceClassification: "The OPT Model transformer with a sequence classification head on top (linear layer)."
OPTForQuestionAnswering: "The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute span start logits and span end logits)."
- Assistant
In the Hugging Face transformers library, "heads" usually refer to specialized layers added on top of the base transformer models to perform specific tasks, such as sequence classification or question-answering. Essentially, these heads are added to the pre-trained transformer models to fine-tune them for different downstream tasks.
In the case of the tokenizer, when you provide two input texts (like "question" and "text" in the QuestionAnswering model), the tokenizer concatenates those texts with a special separator token in between (usually
[SEP]or similar, depending on the model architecture). This concatenated sequence of tokens is then fed to the base transformer model.The "head" is not a mechanism for directing two inputs; rather, it operates on the final hidden states of the model. The main role of the head is to take the output of the pre-trained transformer model and process it for the specific task.
For example, in the sequence classification task, the head is a linear layer that processes the output to produce classification logits; while in the extractive question-answering task, the head is composed of linear layers to compute span start logits and span end logits.
- User
So, is providing two texts different from a dictionary of length two?
"text a", "text b" vs ["text a", "text b"]? Then I'd understand the tokenizer part at least. Because then, for a batch of 2 QA prompts, the input would need to look like ["text a sep token textb", "text c sep token text d"].
I still don't understand the heads - is it like a modular thing, or does it just mean the model is a bit different from base, because it was finetuned and so the layers are a bit different from the base model?
- Assistant
Apologies for the confusion. Let me clarify the two points:
- Providing two texts: The transformer tokenizer accepts different input types depending on how the input needs to be processed. In the case of question-answering, the format of the input to the tokenizer is different from simply providing an array or List of texts. Here's an example using the BERT tokenizer:
from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") question = "What is the capital of Germany?" context = "Berlin is the capital of Germany." # For question-answering, you can input the question and context to the tokenizer like this: input_tokens = tokenizer(question, context, return_tensors="pt") # This will concatenate "question" and "context" using a separator token. - User
Ah okay, I guess QuestionAnswering "models" (models + QA head) have been trained to expect a question and an answer seperated by that special token then?
And also, I guess what confuses me about the heads is that I normally thought of language models as being a general text predictor (LLaMA for example), and every specialized version being a finetune (Alpaca for example, in the case of making LLaMA take instructions). Is heads just a different way of saying that or is it another thing altogether?
- Assistant
Yes, you're correct that the question-answering models (base models + QA head) are trained to expect a question and context (not an answer) separated by a special token. These models are fine-tuned using the question-context pairs in datasets like SQuAD, which contain questions along with context paragraphs from where the answer spans can be extracted.
Regarding your second question, the term "head" is not synonymous with "finetune". Heads are additional layers added on top of the base transformer models for specific tasks, whereas fine-tuning is the process of updating the weights of the model (including both the base model and the head) by training on a specific task like classification or question answering.
Transformers like LLaMA are general-purpose language models. To make them perform specific tasks, you can either fine-tune them directly by adjusting their weights or add specialized heads that process the transformer's output for the desired task, followed by fine-tuning.
So, when you add a head, it is part of the overall fine-tuning process, but it doesn't encompass the entire process. Adding a head means attaching a specialized module to perform a specific task, and then you fine-tune the complete model (base model + head) on the task-specific data.
- User
Ahhh, okay, so adding a head is expanding on the general-purpose model's architecture?
And another question - when you talk about extracting spans: I've read these start_logits end_logits in the following snippet:
inputs = tokenizer(question, text, return_tensors="pt")
with torch.no_grad(): outputs = model(**inputs)
answer_start_index = outputs.start_logits.argmax() answer_end_index = outputs.end_logits.argmax()
I've heard these exist in PyTorch as well as TensorFlow, what do they mean and do? How does it work? Is this specific model variant (QA head added) trained to give out start and end of a sequence like "pointers"?
- Assistant
Yes, adding a head expands on the general-purpose model's architecture to handle a specific task. The head processes the output from the base transformer to produce predictions suitable for that task.
Now, let's talk about extracting spans using
start_logitsandend_logits. When fine-tuned for the question-answering task, the QA head module is designed to output two sets of logits:start_logitsandend_logits. The logits represent the probability of each token in the input sequence being the start or end position of the answer. - User
Thank you so very, very much!
- Assistant
You're welcome! I'm glad I could help. If you have any more questions or need further clarification, feel free to ask. Good luck with your learning and using Hugging Face Transformers!
- User
Okay, so, this is from Hugging Face's website:
from transformers import AutoTokenizer, OPTForQuestionAnswering import torch
torch.manual_seed(4)
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
note: we are loading a OPTForQuestionAnswering from the hub here,
so the head will be randomly initialized, hence the predictions will be random
model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m")
question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
inputs = tokenizer(question, text, return_tensors="pt")
with torch.no_grad(): outputs = model(**inputs)
answer_start_index = outputs.start_logits.argmax() answer_end_index = outputs.end_logits.argmax() answer_offset = len(tokenizer(question)[0])
predict_answer_tokens = inputs.input_ids[ 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1 ]
predicted = tokenizer.decode(predict_answer_tokens)
predicted ' a nice puppet'
At this line "answer_offset = len(tokenizer(question)[0])" I get the following error: "Exception has occurred: KeyError 'Indexing with integers (to access backend Encoding for a given batch index) is not available when using Python based tokenizers'"
- Assistant
Apologies for the confusion caused by the example code. It appears to be outdated, and some of the syntax may not be compatible with the current version of the Hugging Face Transformers library.
Regarding your error, instead of using the
[0]operator to access the tokenizer output forquestion, you can use the following line to obtain the properanswer_offset.Replace this line:
- User
Thank you very much, it works! Can you maybe also explain to me what happens to the special tokens? Why does the range at the end give me the correct answer and is not offset weirdly? Does it have something to do with the "0" at the start and the "+ 1" at the end in this line?:
inputs.input_ids[ 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1 ]
- Assistant
Certainly! When the two input strings (in this case, the question and the text) are tokenized, the tokenizer adds special tokens, like the separator token (usually
[SEP]) and, depending on the model architecture, other special tokens such as . These tokens help the model understand the inputs and their structure better.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.