Sean MacAvaney commited on
Commit
fbf5042
1 Parent(s): f76be94

initial commit

Browse files
Files changed (4) hide show
  1. README.md +85 -6
  2. app.py +239 -0
  3. packages.txt +5 -0
  4. requirements.txt +3 -0
README.md CHANGED
@@ -1,12 +1,91 @@
1
  ---
2
- title: Pyterrier Splade
3
- emoji: 🌍
4
- colorFrom: indigo
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 3.8
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: PyTerrier SPLADE
3
+ emoji: 🐕
4
+ colorFrom: green
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 3.7
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+ <style>
13
+ .transformer {
14
+ display: inline-block;
15
+ background: #8facdb;
16
+ position: relative;
17
+ height: 60px;
18
+ line-height: 60px;
19
+ padding: 0 24px;
20
+ margin: 0 18px;
21
+ color: #333;
22
+ cursor: help;
23
+ }
24
+ .transformer::before {
25
+ content: "";
26
+ position: absolute;
27
+ bottom: 0;
28
+ top: 0;
29
+ left: -15px;
30
+ border-top: 30px solid #8facdb;
31
+ border-bottom: 30px solid #8facdb;
32
+ border-left: 15px solid transparent;
33
+ }
34
+ .transformer::after {
35
+ content: "";
36
+ position: absolute;
37
+ bottom: 0;
38
+ top: 0;
39
+ right: -15px;
40
+ border-top: 30px solid transparent;
41
+ border-bottom: 30px solid transparent;
42
+ border-left: 15px solid #8facdb;
43
+ }
44
+ .transformer.boring {
45
+ background: #ddd;
46
+ }
47
+ .transformer.boring::before {
48
+ border-top-color: #ddd;
49
+ border-bottom-color: #ddd;
50
+ }
51
+ .transformer.boring::after {
52
+ border-left-color: #ddd;
53
+ }
54
+ .df {
55
+ width: 24px;
56
+ line-height: 24px;
57
+ text-align: center;
58
+ border: 3px double #888;
59
+ background-color: #eee;
60
+ color: #333;
61
+ border-radius: 4px;
62
+ display: inline-block;
63
+ box-sizing: content-box;
64
+ cursor: help;
65
+ margin: 0 -25px;
66
+ opacity: 0.5;
67
+ z-index: 1;
68
+ position: relative;
69
+ }
70
+ .df:hover {
71
+ opacity: 1;
72
+ }
73
+ .pipeline {
74
+ text-align: center;
75
+ }
76
+ </style>
77
+
78
+ This is a demonstration of [PyTerrier's SPLADE package](https://github.com/cmacdonald/pyt_splade). The SPLADE model encodes queries and documents
79
+ into sparse representations, which can then be used for indexing and retrieval.
80
+
81
+ ### Query Encoding
82
+
83
+ Let's start by exploring SPLADE's query encoder. The query encoder is a `Q→Q` (query rewriting, query-to-query) transformer, and can be used in pipelines accordingly.
84
+ It maps a query string into [MatchOp](https://terrier-core.readthedocs.io/en/latest/querylanguage.html#matching-op-query-language) query with terms from the
85
+ query re-weighted and weighted expansion terms added.
86
+
87
+ <div class="pipeline">
88
+ <div class="df" title="Query Frame">Q</div>
89
+ <div class="transformer" title="SPLADE Query Transformer">SPLADE</div>
90
+ <div class="df" title="Query Frame">Q</div>
91
+ </div>
app.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import json
3
+ import base64
4
+ import pandas as pd
5
+ import gradio as gr
6
+ import pyterrier as pt
7
+ pt.init()
8
+ import pyt_splade
9
+ factory = pyt_splade.SpladeFactory()
10
+ pipe_queries = factory.query()
11
+ pipe_docs = factory.indexing()
12
+
13
+ COLAB_NAME = 'pyterrier_splade.ipynb'
14
+ COLAB_INSTALL = '''
15
+ !pip install -q git+https://github.com/naver/splade
16
+ !pip install -q git+https://github.com/cmacdonald/pyt_splade@misc
17
+ '''.strip()
18
+
19
+ def df2code(df):
20
+ rows = []
21
+ for row in df.itertuples(index=False):
22
+ rows.append(f' {dict(row._asdict())},')
23
+ rows = '\n'.join(rows)
24
+ return f'''pd.DataFrame([
25
+ {rows}
26
+ ])'''
27
+
28
+ def code2colab(code):
29
+ enc_code = base64.b64encode((COLAB_INSTALL + '\n\n' + code.strip()).encode()).decode()
30
+ dec = base64.b64decode(enc_code)
31
+ url = f'https://colaburl.macavaney.us/?py64={enc_code}&name={COLAB_NAME}'
32
+ return f'<div style="text-align: center; margin-bottom: -16px;"><a href="{url}" rel="nofollow" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" style="margin: 0; display: inline-block;" /></a></div>'
33
+
34
+ def code2md(code):
35
+ return f'''
36
+ {code2colab(code)}
37
+
38
+ ```python
39
+ {code.strip()}
40
+ ```
41
+ '''
42
+
43
+ def generate_vis(df, mode='Document'):
44
+ if len(df) == 0:
45
+ return ''
46
+ result = []
47
+ if mode == 'Document':
48
+ max_score = max(max(t.values()) for t in df['toks'])
49
+ for row in df.itertuples(index=False):
50
+ if mode == 'Query':
51
+ tok_scores = {m.group(2): float(m.group(1)) for m in re.finditer(r'combine:0=([0-9.]+)\(([^)]+)\)', row.query)}
52
+ max_score = max(tok_scores.values())
53
+ orig_tokens = factory.tokenizer.tokenize(row.query_0)
54
+ id = row.qid
55
+ else:
56
+ tok_scores = row.toks
57
+ orig_tokens = factory.tokenizer.tokenize(row.text)
58
+ id = row.docno
59
+ def toks2span(toks):
60
+ return '<kbd> </kbd>'.join(f'<kbd style="background-color: rgba(66, 135, 245, {tok_scores.get(t, 0)/max_score});">{t}</kbd>' for t in toks)
61
+ orig_tokens_set = set(orig_tokens)
62
+ exp_tokens = [t for t, v in sorted(tok_scores.items(), key=lambda x: (-x[1], x[0])) if t not in orig_tokens_set]
63
+ result.append(f'''
64
+ <div style="font-size: 1.2em;">{mode}: <strong>{id}</strong></div>
65
+ <div style="margin: 4px 0 16px; padding: 4px; border: 1px solid black;">
66
+ <div>
67
+ {toks2span(orig_tokens)}
68
+ </div>
69
+ <div><strong>Expansion Tokens:</strong> {toks2span(exp_tokens)}</div>
70
+ </div>
71
+ ''')
72
+ return '\n'.join(result)
73
+
74
+ def predict_query(input):
75
+ code = f'''import pandas as pd
76
+ import pyterrier as pt ; pt.init()
77
+ import pyt_splade
78
+
79
+ factory = pyt_splade.SpladeFactory()
80
+
81
+ query_pipeline = factory.query()
82
+
83
+ query_pipeline({df2code(input)})
84
+ '''
85
+ res = pipe_queries(input)
86
+ vis = generate_vis(res, mode='Query')
87
+ return (res, code2md(code), vis)
88
+
89
+ def predict_doc(input):
90
+ code = f'''import pandas as pd
91
+ import pyterrier as pt ; pt.init()
92
+ import pyt_splade
93
+
94
+ factory = pyt_splade.SpladeFactory()
95
+
96
+ doc_pipeline = factory.indexing()
97
+
98
+ doc_pipeline({df2code(input)})
99
+ '''
100
+ res = pipe_docs(input)
101
+ vis = generate_vis(res, mode='Document')
102
+ res['toks'] = [json.dumps({k: round(v, 4) for k, v in t.items()}) for t in res['toks']]
103
+ return (res, code2md(code), vis)
104
+
105
+ with gr.Blocks(css="table.font-mono td, table.font-mono th { white-space: pre-line; font-size: 11px; line-height: 16px; } table.font-mono td input { width: 95%; } th .cursor-pointer {display: none;} th .min-h-\[2\.3rem\] {min-height: inherit;}") as demo:
106
+ gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>🐕 PyTerrier: SPLADE</h1>")
107
+ gr.Markdown(open('README.md', 'rt').read().split('\n---\n')[-1])
108
+
109
+ example_inp = pd.DataFrame([
110
+ {'qid': '1112389', 'query': 'what is the county for grand rapids, mn'},
111
+ ])
112
+ example_out = predict_query(example_inp)
113
+ inputs, outputs = [], []
114
+ with gr.Row().style(equal_height=False):
115
+ with gr.Column(scale=1):
116
+ with gr.Tab('Pipeline Input'):
117
+ inputs.append(gr.Dataframe(
118
+ headers=["qid", "query"],
119
+ datatype=["str", "str"],
120
+ col_count=(2, "fixed"),
121
+ row_count=1,
122
+ wrap=True,
123
+ value=example_inp,
124
+ ))
125
+ submit_btn = gr.Button("Submit", variant="primary")
126
+ with gr.Column(scale=2):
127
+ with gr.Tab('Pipeline Output'):
128
+ outputs.append(gr.Dataframe(
129
+ headers=["qid", "query", "docno", "score", "rank", "text"],
130
+ datatype=["str", "str", "str", "number", "number", "str"],
131
+ col_count=6,
132
+ row_count=1,
133
+ wrap=True,
134
+ value=example_out[0],
135
+ ))
136
+ with gr.Tab('Code'):
137
+ outputs.append(gr.Markdown(value=example_out[1]))
138
+ with gr.Tab('Visualisation'):
139
+ outputs.append(gr.HTML(value=example_out[2]))
140
+ submit_btn.click(predict_query, inputs, outputs, api_name="predict_query", scroll_to_output=True)
141
+
142
+ gr.Markdown('''
143
+ ### Document Encoding
144
+
145
+ The document encoder works similarly to the query encoder: it is a `D→D` (document rewriting, doc-to-doc) transformer, and can be used in pipelines accordingly.
146
+ It maps a document's text into a dictionary with terms from the document re-weighted and weighted expansion terms added.
147
+
148
+ <div class="pipeline">
149
+ <div class="df" title="Document Frame">D</div>
150
+ <div class="transformer" title="SPLADE Indexing Transformer">SPLADE</div>
151
+ <div class="df" title="Document Frame">D</div>
152
+ </div>
153
+
154
+ ''')
155
+
156
+ example_inp = pd.DataFrame([
157
+ {'docno': '0', 'text': 'The presence of communication amid scientific minds was equally important to the success of the Manhattan Project as scientific intellect was. The only cloud hanging over the impressive achievement of the atomic researchers and engineers is what their success truly meant; hundreds of thousands of innocent lives obliterated.'},
158
+ ])
159
+ example_out = predict_doc(example_inp)
160
+ inputs, outputs = [], []
161
+ with gr.Row().style(equal_height=False):
162
+ with gr.Column(scale=1):
163
+ with gr.Tab("Pipeline Input"):
164
+ inputs.append(gr.Dataframe(
165
+ headers=["docno", "text"],
166
+ datatype=["str", "str"],
167
+ col_count=(2, "fixed"),
168
+ row_count=1,
169
+ wrap=True,
170
+ value=example_inp,
171
+ ))
172
+ submit_btn = gr.Button("Submit", variant="primary")
173
+ with gr.Column(scale=2):
174
+ with gr.Tab("Pipeline Output"):
175
+ outputs.append(gr.Dataframe(
176
+ headers=["qid", "query", "docno", "score", "rank", "text"],
177
+ datatype=["str", "str", "str", "number", "number", "str"],
178
+ col_count=6,
179
+ row_count=1,
180
+ wrap=True,
181
+ value=example_out[0],
182
+ ))
183
+ with gr.Tab('Code'):
184
+ outputs.append(gr.Markdown(value=example_out[1]))
185
+ with gr.Tab('Visualisation'):
186
+ outputs.append(gr.HTML(value=example_out[2]))
187
+ submit_btn.click(predict_doc, inputs, outputs, api_name="predict_doc", scroll_to_output=True)
188
+
189
+ gr.Markdown('''
190
+ ### Putting it all together
191
+
192
+ When you use the document encoder in an indexing pipeline, the rewritting document contents are indexed:
193
+
194
+ <div class="pipeline">
195
+ <div class="df" title="Document Frame">D</div>
196
+ <div class="transformer" title="SPLADE Indexing Transformer">SPLADE</div>
197
+ <div class="df" title="Document Frame">D</div>
198
+ <div class="transformer boring" title="Indexer">Indexer</div>
199
+ </div>
200
+
201
+ ```python
202
+ import pyterrer as pt
203
+ pt.init(version='snapshot')
204
+ import pyt_splade
205
+
206
+ dataset = pt.get_dataset('irds:msmarco-passage')
207
+ factory = pyt_splade.SpladeFactory()
208
+
209
+ indexer = pt.IterDictIndexer('./msmarco_psg', pretokenized=True)
210
+
211
+ indxer_pipe = factory.indexing() >> indexer
212
+ indxer_pipe.index(dataset.get_corpus_iter())
213
+ ```
214
+
215
+ Once you built an index, you can build a retrieval pipeline that first encodes the query,
216
+ and then performs retrieval:
217
+
218
+ <div class="pipeline">
219
+ <div class="df" title="Query Frame">Q</div>
220
+ <div class="transformer" title="SPLADE Query Transformer">SPLADE</div>
221
+ <div class="df" title="Query Frame">Q</div>
222
+ <div class="transformer boring" title="Term Frequency Transformer">TF Retriever</div>
223
+ <div class="df" title="Result Frame">R</div>
224
+ </div>
225
+
226
+ ```python
227
+ splade_retr = factory.query() >> pt.BatchRetrieve('./msmarco_psg', wmodel='Tf')
228
+ ```
229
+
230
+ ### References & Credits
231
+
232
+ This package uses [Naver's SPLADE repository](https://github.com/naver/splade).
233
+
234
+ - Thibault Formal, Benjamin Piwowarski, Stéphane Clinchant. [SPLADE: Sparse Lexical and Expansion Model for First Stage Ranking](https://arxiv.org/abs/2107.05720). SIGIR 2021.
235
+ - Craig Macdonald, Nicola Tonellotto, Sean MacAvaney, Iadh Ounis. [PyTerrier: Declarative Experimentation in Python from BM25 to Dense Retrieval](https://dl.acm.org/doi/abs/10.1145/3459637.3482013). CIKM 2021.
236
+ ''')
237
+
238
+
239
+ demo.launch(share=False)
packages.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ openjdk-11-jdk
2
+ openjdk-11-jre-headless
3
+ openjdk-11-jre
4
+ openjdk-11-jre-headless
5
+ debianutils
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ python-terrier
2
+ git+https://github.com/naver/splade
3
+ git+https://github.com/cmacdonald/pyt_splade@misc