FiD Model
rankify.generator.models.fid_model
BaseRAGModel
Bases: ABC
Base RAG Model for Retrieval-Augmented Generation (RAG).
This is an abstract base class for implementing LLM endpoints in rankify. It defines the interface for generating responses and optional embedding generation.
Methods:
| Name | Description |
|---|---|
generate |
str, **kwargs) -> str: Abstract method to generate a response based on the given prompt. |
embed |
str, **kwargs) -> List[float]: Optional method to generate embeddings for the given text. |
Notes
- This class serves as a blueprint for RAG models like
OpenAIModelandHuggingFaceModel. - The
embedmethod is optional and can be implemented if needed. - This class needs to be extended to include new LLM endpoints in Rankify.
Source code in rankify/generator/models/base_rag_model.py
generate(prompt, **kwargs)
abstractmethod
embed(text, **kwargs)
Optional: Generate embeddings for the given text.
Dataset
Bases: Dataset
Source code in rankify/utils/generator/FiD/data.py
Collator
Bases: object
Source code in rankify/utils/generator/FiD/data.py
FiDT5
Bases: T5ForConditionalGeneration
Source code in rankify/utils/generator/FiD/model.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
wrap_encoder(use_checkpoint=False)
Wrap T5 encoder to obtain a Fusion-in-Decoder model.
unwrap_encoder()
Unwrap Fusion-in-Decoder encoder, useful to load T5 weights.
Source code in rankify/utils/generator/FiD/model.py
set_checkpoint(use_checkpoint)
Enable or disable checkpointing in the encoder. See https://pytorch.org/docs/stable/checkpoint.html
reset_score_storage()
Reset score storage, only used when cross-attention scores are saved to train a retriever.
get_crossattention_scores(context_mask)
Cross-attention scores are aggregated to obtain a single scalar per passage. This scalar can be seen as a similarity score between the question and the input passage. It is obtained by averaging the cross-attention scores obtained on the first decoded token over heads, layers, and tokens of the input passage.
More details in Distilling Knowledge from Reader to Retriever: https://arxiv.org/abs/2012.04584.
Source code in rankify/utils/generator/FiD/model.py
overwrite_forward_crossattention()
Replace cross-attention forward function, only used to save cross-attention scores.
Source code in rankify/utils/generator/FiD/model.py
ModelDownloader
Utility class for downloading and extracting model files.
Source code in rankify/utils/generator/download.py
download_and_extract(url, output_dir)
staticmethod
Downloads and extracts a model from a given URL.
Source code in rankify/utils/generator/download.py
Document
Represents a document consisting of a question, answers, and contexts.
Attributes:
| Name | Type | Description |
|---|---|---|
question |
Question
|
The question associated with the document. |
answers |
Answer
|
The answers to the question. |
contexts |
list[Context]
|
A list of related contexts. |
reorder_contexts |
list[Context] or None
|
A reordered list of contexts based on relevance. |
Source code in rankify/dataset/dataset.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | |
__init__(question, answers, contexts=None, id=None)
Initializes a Document instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
Question
|
The question associated with the document. |
required |
answers
|
Answer
|
The answers to the question. |
required |
contexts
|
list[Context]
|
A list of contexts related to the question. |
None
|
Example
q = Question("What is the capital of France?")
a = Answer(["Paris"])
c1 = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
c2 = Context(score=0.5, has_answer=False, id=2, title="Berlin", text="Berlin is the capital of Germany.")
d = Document(question=q, answers=a, contexts=[c1, c2])
print(d)
Source code in rankify/dataset/dataset.py
from_dict(data, n_docs=100)
classmethod
Creates a Document instance from a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
A dictionary containing the question, answers, and contexts. |
required |
n_docs
|
int
|
The number of contexts to include. Defaults to 100. |
100
|
Returns:
| Name | Type | Description |
|---|---|---|
Document |
Document
|
A new Document instance. |
Example
data = {
"question": "What is the capital of France?",
"answers": ["Paris"],
"ctxs": [
{"score": 0.9, "has_answer": True, "id": 1, "title": "Paris", "text": "The capital of France is Paris."},
{"score": 0.5, "has_answer": False, "id": 2, "title": "Berlin", "text": "Berlin is the capital of Germany."}
]
}
d = Document.from_dict(data)
print(d.question)
Source code in rankify/dataset/dataset.py
to_dict()
Converts the document into a dictionary representation.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Optional[object]]
|
A dictionary containing the question, answers, and contexts. |
Source code in rankify/dataset/dataset.py
__str__()
Returns a string representation of the Document instance.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted document information. |
Source code in rankify/dataset/dataset.py
FiDModel
Bases: BaseRAGModel
FiD (Fusion-in-Decoder) Generator for Open-Domain Question Answering.
Fusion-in-Decoder (FiD) is a retrieval-augmented generation (RAG) model that
aggregates information from multiple retrieved passages to generate context-aware answers.
Inside Rankifys architecture, this model is an exception, it subclasses BaseRAGModel but also includes the logic
of the FiD RAG method, since this RAG technique relies on the full transformer architecture.
Attributes:
| Name | Type | Description |
|---|---|---|
device |
str
|
Device used for inference ( |
model_path |
str
|
Path to the downloaded and extracted model. |
tokenizer |
T5Tokenizer
|
T5 tokenizer for text encoding. |
model |
FiDT5
|
Pretrained FiD model for text generation. |
max_length |
int
|
Maximum length of the generated output (default: 50 tokens). |
References
- Izacard & Grave Leveraging Passage Retrieval with Generative Models for Open-Domain QA
Paper
See Also
BaseRAGModel: Parent class for FiDModel.RAG-based QA Models: FiD falls under retrieval-augmented generation.
Example
from rankify.dataset.dataset import Document, Question, Answer, Context
from rankify.generator.generator import Generator
# Define question and answer
question = Question("What is the capital of France?")
answers = Answer([""])
contexts = [
Context(id=1, title="France", text="The capital of France is Paris.", score=0.9),
Context(id=2, title="Germany", text="Berlin is the capital of Germany.", score=0.5)
]
# Construct document
doc = Document(question=question, answers=answers, contexts=contexts)
# Initialize Generator (e.g., Meta Llama)
generator = Generator(method="fid", model_name='nq_reader_base', backend="fid")
# Generate answer
generated_answers = generator.generate([doc])
print(generated_answers) # Output: ["Paris"]
Notes
- FiD combines multiple passages to generate better responses.
- It integrates seamlessly with the
Generatorclass. - Uses retrieval-augmented generation (RAG) techniques for QA.
Source code in rankify/generator/models/fid_model.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
__init__(method='fid', model_name='nq_reader_base', **kwargs)
Initializes the FiDModel for retrieval-augmented generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
The generator type (default: |
'fid'
|
model_name
|
str
|
The specific FiD model to use (e.g., |
'nq_reader_base'
|
max_length
|
int
|
Maximum length of generated answers (default: 50). |
required |
device
|
str
|
Device for inference ( |
required |
**kwargs
|
Additional parameters for model configuration. |
{}
|
Sets up device, downloads and loads the model and tokenizer, and configures generation parameters.
Example
Source code in rankify/generator/models/fid_model.py
generate(documents)
Generates answers for a list of documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
List[Document]
|
A list of documents with queries and retrieved contexts. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: A list of generated answers. |