flashrag-dev 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. flashrag/__init__.py +0 -0
  2. flashrag/config/__init__.py +2 -0
  3. flashrag/config/config.py +219 -0
  4. flashrag/dataset/__init__.py +2 -0
  5. flashrag/dataset/dataset.py +160 -0
  6. flashrag/dataset/utils.py +60 -0
  7. flashrag/evaluator/__init__.py +2 -0
  8. flashrag/evaluator/_bleu.py +209 -0
  9. flashrag/evaluator/evaluator.py +82 -0
  10. flashrag/evaluator/metrics.py +508 -0
  11. flashrag/evaluator/utils.py +19 -0
  12. flashrag/generator/__init__.py +2 -0
  13. flashrag/generator/fid.py +247 -0
  14. flashrag/generator/generator.py +623 -0
  15. flashrag/generator/openai_generator.py +96 -0
  16. flashrag/generator/stop_word_criteria.py +105 -0
  17. flashrag/judger/__init__.py +1 -0
  18. flashrag/judger/judger.py +184 -0
  19. flashrag/pipeline/__init__.py +3 -0
  20. flashrag/pipeline/active_pipeline.py +980 -0
  21. flashrag/pipeline/branching_pipeline.py +250 -0
  22. flashrag/pipeline/pipeline.py +248 -0
  23. flashrag/pipeline/replug_utils.py +249 -0
  24. flashrag/prompt/__init__.py +1 -0
  25. flashrag/prompt/base_prompt.py +165 -0
  26. flashrag/prompt/selfask_examplars.py +108 -0
  27. flashrag/prompt/trace_examplars.py +4015 -0
  28. flashrag/refiner/__init__.py +2 -0
  29. flashrag/refiner/kg_refiner.py +612 -0
  30. flashrag/refiner/llmlingua_compressor.py +2360 -0
  31. flashrag/refiner/refiner.py +252 -0
  32. flashrag/refiner/selective_context_compressor.py +294 -0
  33. flashrag/retriever/__init__.py +3 -0
  34. flashrag/retriever/__main__.py +4 -0
  35. flashrag/retriever/encoder.py +120 -0
  36. flashrag/retriever/index_builder.py +334 -0
  37. flashrag/retriever/reranker.py +145 -0
  38. flashrag/retriever/retriever.py +346 -0
  39. flashrag/retriever/utils.py +49 -0
  40. flashrag/utils/__init__.py +2 -0
  41. flashrag/utils/constants.py +51 -0
  42. flashrag/utils/pred_parse.py +25 -0
  43. flashrag/utils/utils.py +135 -0
  44. flashrag_dev-0.1.1.dist-info/LICENSE +21 -0
  45. flashrag_dev-0.1.1.dist-info/METADATA +616 -0
  46. flashrag_dev-0.1.1.dist-info/RECORD +48 -0
  47. flashrag_dev-0.1.1.dist-info/WHEEL +5 -0
  48. flashrag_dev-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,247 @@
1
+ # Source: FiD official repo: https://github.com/facebookresearch/FiD
2
+ # This software is released under Creative Commons public licenses.
3
+
4
+ import types
5
+ import torch
6
+ import transformers
7
+ import torch.nn.functional as F
8
+ from torch import nn
9
+
10
+
11
+ class FiDT5(transformers.T5ForConditionalGeneration):
12
+ def __init__(self, config):
13
+ super().__init__(config)
14
+ self.wrap_encoder()
15
+
16
+ def forward_(self, **kwargs):
17
+ if "input_ids" in kwargs:
18
+ kwargs["input_ids"] = kwargs["input_ids"].view(kwargs["input_ids"].size(0), -1)
19
+ if "attention_mask" in kwargs:
20
+ kwargs["attention_mask"] = kwargs["attention_mask"].view(kwargs["attention_mask"].size(0), -1)
21
+
22
+ return super(FiDT5, self).forward(**kwargs)
23
+
24
+ # We need to resize as B x (N * L) instead of (B * N) x L here
25
+ # because the T5 forward method uses the input tensors to infer
26
+ # dimensions used in the decoder.
27
+ # EncoderWrapper resizes the inputs as (B * N) x L.
28
+ def forward(self, input_ids=None, attention_mask=None, **kwargs):
29
+ if input_ids != None:
30
+ # inputs might have already be resized in the generate method
31
+ if input_ids.dim() == 3:
32
+ self.encoder.n_passages = input_ids.size(1)
33
+ input_ids = input_ids.view(input_ids.size(0), -1)
34
+ if attention_mask != None:
35
+ attention_mask = attention_mask.view(attention_mask.size(0), -1)
36
+ return super().forward(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
37
+
38
+ # We need to resize the inputs here, as the generate method expect 2D tensors
39
+ def generate(self, input_ids, attention_mask, max_length):
40
+ self.encoder.n_passages = input_ids.size(1)
41
+ return super().generate(
42
+ input_ids=input_ids.view(input_ids.size(0), -1),
43
+ attention_mask=attention_mask.view(attention_mask.size(0), -1),
44
+ max_length=max_length,
45
+ )
46
+
47
+ def wrap_encoder(self, use_checkpoint=False):
48
+ """
49
+ Wrap T5 encoder to obtain a Fusion-in-Decoder model.
50
+ """
51
+ self.encoder = EncoderWrapper(self.encoder, use_checkpoint=use_checkpoint)
52
+
53
+ def unwrap_encoder(self):
54
+ """
55
+ Unwrap Fusion-in-Decoder encoder, useful to load T5 weights.
56
+ """
57
+ self.encoder = self.encoder.encoder
58
+ block = []
59
+ for mod in self.encoder.block:
60
+ block.append(mod.module)
61
+ block = nn.ModuleList(block)
62
+ self.encoder.block = block
63
+
64
+ def load_t5(self, state_dict):
65
+ self.unwrap_encoder()
66
+ self.load_state_dict(state_dict)
67
+ self.wrap_encoder()
68
+
69
+ def set_checkpoint(self, use_checkpoint):
70
+ """
71
+ Enable or disable checkpointing in the encoder.
72
+ See https://pytorch.org/docs/stable/checkpoint.html
73
+ """
74
+ for mod in self.encoder.encoder.block:
75
+ mod.use_checkpoint = use_checkpoint
76
+
77
+ def reset_score_storage(self):
78
+ """
79
+ Reset score storage, only used when cross-attention scores are saved
80
+ to train a retriever.
81
+ """
82
+ for mod in self.decoder.block:
83
+ mod.layer[1].EncDecAttention.score_storage = None
84
+
85
+ def get_crossattention_scores(self, context_mask):
86
+ """
87
+ Cross-attention scores are aggregated to obtain a single scalar per
88
+ passage. This scalar can be seen as a similarity score between the
89
+ question and the input passage. It is obtained by averaging the
90
+ cross-attention scores obtained on the first decoded token over heads,
91
+ layers, and tokens of the input passage.
92
+
93
+ More details in Distilling Knowledge from Reader to Retriever:
94
+ https://arxiv.org/abs/2012.04584.
95
+ """
96
+ scores = []
97
+ n_passages = context_mask.size(1)
98
+ for mod in self.decoder.block:
99
+ scores.append(mod.layer[1].EncDecAttention.score_storage)
100
+ scores = torch.cat(scores, dim=2)
101
+ bsz, n_heads, n_layers, _ = scores.size()
102
+ # batch_size, n_head, n_layers, n_passages, text_maxlength
103
+ scores = scores.view(bsz, n_heads, n_layers, n_passages, -1)
104
+ scores = scores.masked_fill(~context_mask[:, None, None], 0.0)
105
+ scores = scores.sum(dim=[1, 2, 4])
106
+ ntokens = context_mask.sum(dim=[2]) * n_layers * n_heads
107
+ scores = scores / ntokens
108
+ return scores
109
+
110
+ def overwrite_forward_crossattention(self):
111
+ """
112
+ Replace cross-attention forward function, only used to save
113
+ cross-attention scores.
114
+ """
115
+ for mod in self.decoder.block:
116
+ attn = mod.layer[1].EncDecAttention
117
+ attn.forward = types.MethodType(cross_attention_forward, attn)
118
+
119
+
120
+ class EncoderWrapper(torch.nn.Module):
121
+ """
122
+ Encoder Wrapper for T5 Wrapper to obtain a Fusion-in-Decoder model.
123
+ """
124
+
125
+ def __init__(self, encoder, use_checkpoint=False):
126
+ super().__init__()
127
+
128
+ self.encoder = encoder
129
+ apply_checkpoint_wrapper(self.encoder, use_checkpoint)
130
+
131
+ def forward(
132
+ self,
133
+ input_ids=None,
134
+ attention_mask=None,
135
+ **kwargs,
136
+ ):
137
+ # total_length = n_passages * passage_length
138
+ bsz, total_length = input_ids.shape
139
+ passage_length = total_length // self.n_passages
140
+ input_ids = input_ids.view(bsz * self.n_passages, passage_length)
141
+ attention_mask = attention_mask.view(bsz * self.n_passages, passage_length)
142
+ outputs = self.encoder(input_ids, attention_mask, **kwargs)
143
+ outputs = (outputs[0].view(bsz, self.n_passages * passage_length, -1),) + outputs[1:]
144
+ return outputs
145
+
146
+
147
+ class CheckpointWrapper(torch.nn.Module):
148
+ """
149
+ Wrapper replacing None outputs by empty tensors, which allows the use of
150
+ checkpointing.
151
+ """
152
+
153
+ def __init__(self, module, use_checkpoint=False):
154
+ super().__init__()
155
+ self.module = module
156
+ self.use_checkpoint = use_checkpoint
157
+
158
+ def forward(self, hidden_states, attention_mask, position_bias, **kwargs):
159
+ if self.use_checkpoint and self.training:
160
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
161
+
162
+ def custom_forward(*inputs):
163
+ output = self.module(*inputs, **kwargs)
164
+ empty = torch.tensor([], dtype=torch.float, device=output[0].device, requires_grad=True)
165
+ output = tuple(x if x is not None else empty for x in output)
166
+ return output
167
+
168
+ output = torch.utils.checkpoint.checkpoint(custom_forward, hidden_states, attention_mask, position_bias)
169
+ output = tuple(x if x.size() != 0 else None for x in output)
170
+ else:
171
+ output = self.module(hidden_states, attention_mask, position_bias, **kwargs)
172
+ return output
173
+
174
+
175
+ def apply_checkpoint_wrapper(t5stack, use_checkpoint):
176
+ """
177
+ Wrap each block of the encoder to enable checkpointing.
178
+ """
179
+ block = []
180
+ for mod in t5stack.block:
181
+ wrapped_mod = CheckpointWrapper(mod, use_checkpoint)
182
+ block.append(wrapped_mod)
183
+ block = nn.ModuleList(block)
184
+ t5stack.block = block
185
+
186
+
187
+ def cross_attention_forward(
188
+ self,
189
+ input,
190
+ mask=None,
191
+ kv=None,
192
+ position_bias=None,
193
+ past_key_value_state=None,
194
+ head_mask=None,
195
+ query_length=None,
196
+ use_cache=False,
197
+ output_attentions=False,
198
+ ):
199
+ """
200
+ This only works for computing cross attention over the input
201
+ """
202
+ assert kv != None
203
+ assert head_mask == None
204
+ assert position_bias != None or self.has_relative_attention_bias
205
+
206
+ bsz, qlen, dim = input.size()
207
+ n_heads, d_heads = self.n_heads, self.d_kv
208
+ klen = kv.size(1)
209
+
210
+ q = self.q(input).view(bsz, -1, n_heads, d_heads).transpose(1, 2)
211
+ if past_key_value_state == None:
212
+ k = self.k(kv).view(bsz, -1, n_heads, d_heads).transpose(1, 2)
213
+ v = self.v(kv).view(bsz, -1, n_heads, d_heads).transpose(1, 2)
214
+ else:
215
+ k, v = past_key_value_state
216
+
217
+ scores = torch.einsum("bnqd,bnkd->bnqk", q, k)
218
+
219
+ if mask is not None:
220
+ scores += mask
221
+
222
+ if position_bias is None:
223
+ position_bias = self.compute_bias(qlen, klen)
224
+ scores += position_bias
225
+
226
+ if self.score_storage is None:
227
+ self.score_storage = scores
228
+
229
+ attn = F.softmax(scores.float(), dim=-1).type_as(scores)
230
+ attn = F.dropout(attn, p=self.dropout, training=self.training)
231
+
232
+ output = torch.matmul(attn, v)
233
+ output = output.transpose(1, 2).contiguous().view(bsz, -1, self.inner_dim)
234
+ output = self.o(output)
235
+
236
+ if use_cache:
237
+ output = (output,) + ((k, v),)
238
+ else:
239
+ output = (output,) + (None,)
240
+
241
+ if output_attentions:
242
+ output = output + (attn,)
243
+
244
+ if self.has_relative_attention_bias:
245
+ output = output + (position_bias,)
246
+
247
+ return output