liujch1998 commited on
Commit
d8d9fba
β€’
1 Parent(s): f2d5dd5

Copy files from dev

Browse files
Files changed (3) hide show
  1. README.md +6 -5
  2. app.py +243 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Infini Gram
3
- emoji: 🐒
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 4.16.0
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: infini-gram
3
+ emoji: πŸ“–
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 4.15.0
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import os
4
+ import requests
5
+
6
+ CORPUS_BY_DESC = {
7
+ 'RedPajama (LLaMA tokenizer)': 'rpj_v3_c4_llama2',
8
+ 'Pile-val (GPT-2 tokenizer)': 'pile_v3_val',
9
+ }
10
+ CORPUS_DESCS = list(CORPUS_BY_DESC.keys())
11
+ QUERY_TYPE_BY_DESC = {
12
+ '1. Count an n-gram': 'count',
13
+ '2. Compute the probability of the last token in an n-gram': 'compute_prob',
14
+ '3. Compute the next-token distribution of an (n-1)-gram': 'get_next_token_distribution_approx',
15
+ '4. Compute the ∞-gram probability of the last token': 'compute_infgram_prob',
16
+ '5. Compute the ∞-gram next-token distribution': 'get_infgram_next_token_distribution_approx',
17
+ '6. Searching for document containing n-gram(s)': 'get_a_random_document_from_cnf_query_fast_approx',
18
+ # '7. Analyze an (AI-generated) document using ∞-gram': 'analyze_document',
19
+ }
20
+ QUERY_DESC_BY_TYPE = {v: k for k, v in QUERY_TYPE_BY_DESC.items()}
21
+ QUERY_DESCS = list(QUERY_TYPE_BY_DESC.keys())
22
+
23
+ MAX_QUERY_CHARS = 1000
24
+ MAX_INPUT_DOC_TOKENS = 1000
25
+ MAX_OUTPUT_DOC_TOKENS = 5000 # must be an even number!
26
+ MAX_CNT_FOR_NTD = 1000
27
+ MAX_CLAUSE_FREQ = 10000
28
+ MAX_CLAUSE_FREQ_FAST = 1000000
29
+ MAX_CLAUSE_FREQ_FAST_APPROX_PER_SHARD = 50000
30
+ MAX_DIFF_TOKENS = 100
31
+ MAX_DIFF_BYTES = 2 * MAX_DIFF_TOKENS
32
+ MAX_CLAUSES_IN_CNF = 4
33
+ MAX_TERMS_IN_DISJ_CLAUSE = 4
34
+
35
+ API_IPADDR = os.environ.get('API_IPADDR', None)
36
+ default_concurrency_limit = os.environ.get('default_concurrency_limit', 10)
37
+ max_size = os.environ.get('max_size', 100)
38
+ max_threads = os.environ.get('max_threads', 40)
39
+ debug = os.environ.get('debug', False)
40
+
41
+ def process(corpus_desc, query_desc, query):
42
+ corpus = CORPUS_BY_DESC[corpus_desc]
43
+ query_type = QUERY_TYPE_BY_DESC[query_desc]
44
+ print(json.dumps({'corpus': corpus, 'query_type': query_type, 'query': query}))
45
+ data = {
46
+ 'corpus': corpus,
47
+ 'query_type': query_type,
48
+ 'query': query,
49
+ }
50
+ if API_IPADDR is None:
51
+ raise ValueError(f'API_IPADDR envvar is not set!')
52
+ response = requests.post(f'http://{API_IPADDR}:5000/', json=data)
53
+ if response.status_code == 200:
54
+ result = response.json()
55
+ else:
56
+ raise ValueError(f'Invalid response: {response.status_code}')
57
+ # print(result)
58
+ return result
59
+
60
+ with gr.Blocks() as demo:
61
+ with gr.Column():
62
+ gr.HTML(
63
+ '''<h1 text-align="center">Infini-gram: An Engine for n-gram / ∞-gram Language Models with Trillion-Token Corpora</h1>
64
+
65
+ <p style='font-size: 16px;'>This is an engine that processes n-gram / ∞-gram queries on a text corpus. Please first select the corpus and the type of query, then enter your query and submit.</p>
66
+ '''
67
+ )
68
+ with gr.Row():
69
+ with gr.Column(scale=1):
70
+ corpus_desc = gr.Radio(choices=CORPUS_DESCS, label='Corpus', value=CORPUS_DESCS[0])
71
+ with gr.Column(scale=4):
72
+ query_desc = gr.Radio(
73
+ choices=QUERY_DESCS, label='Query Type', value=QUERY_DESCS[0],
74
+ )
75
+
76
+ with gr.Row(visible=True) as row_1:
77
+ with gr.Column():
78
+ gr.HTML('<h2>1. Count an n-gram</h2>')
79
+ gr.HTML('<p style="font-size: 16px;">This counts the number of times an n-gram appears in the corpus. If you submit an empty input, it will return the total number of tokens in the corpus.</p>')
80
+ gr.HTML('<p style="font-size: 16px;">Example query: <b>natural language processing</b> (the output is Cnt(natural language processing))</p>')
81
+ with gr.Row():
82
+ with gr.Column(scale=1):
83
+ count_input = gr.Textbox(placeholder='Enter a string (an n-gram) here', label='Query', interactive=True)
84
+ with gr.Row():
85
+ count_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
86
+ count_submit = gr.Button(value='Submit', variant='primary', visible=True)
87
+ count_output_tokens = gr.Textbox(label='Tokenized', lines=2, interactive=False)
88
+ with gr.Column(scale=1):
89
+ count_output = gr.Label(label='Count', num_top_classes=0)
90
+
91
+ with gr.Row(visible=False) as row_2:
92
+ with gr.Column():
93
+ gr.HTML('<h2>2. Compute the probability of the last token in an n-gram</h2>')
94
+ gr.HTML('<p style="font-size: 16px;">This computes the n-gram probability of the last token conditioned on the previous tokens (i.e. (n-1)-gram)).</p>')
95
+ gr.HTML('<p style="font-size: 16px;">Example query: <b>natural language processing</b> (the output is P(processing | natural language), by counting the appearance of the 3-gram "natural language processing" and the 2-gram "natural language", and take the division between the two)</p>')
96
+ gr.HTML('<p style="font-size: 16px;">Note: The (n-1)-gram needs to exist in the corpus. If the (n-1)-gram is not found in the corpus, an error message will appear.</p>')
97
+ with gr.Row():
98
+ with gr.Column(scale=1):
99
+ ngram_input = gr.Textbox(placeholder='Enter a string (an n-gram) here', label='Query', interactive=True)
100
+ with gr.Row():
101
+ ngram_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
102
+ ngram_submit = gr.Button(value='Submit', variant='primary', visible=True)
103
+ ngram_output_tokens = gr.Textbox(label='Tokenized', lines=2, interactive=False)
104
+ with gr.Column(scale=1):
105
+ ngram_output = gr.Label(label='Probability', num_top_classes=0)
106
+
107
+ with gr.Row(visible=False) as row_3:
108
+ with gr.Column():
109
+ gr.HTML('<h2>3. Compute the next-token distribution of an (n-1)-gram</h2>')
110
+ gr.HTML('<p style="font-size: 16px;">This is an extension of the Query 2: It interprets your input as the (n-1)-gram and gives you the full next-token distribution.</p>')
111
+ gr.HTML('<p style="font-size: 16px;">Example query: <b>natural language</b> (the output is P(* | natural language), for the top-10 tokens *)</p>')
112
+ gr.HTML(f'<p style="font-size: 16px;">Note: The (n-1)-gram needs to exist in the corpus. If the (n-1)-gram is not found in the corpus, an error message will appear. If the (n-1)-gram appears more than {MAX_CNT_FOR_NTD} times in the corpus, the result will be approximate.</p>')
113
+ with gr.Row():
114
+ with gr.Column(scale=1):
115
+ a_ntd_input = gr.Textbox(placeholder='Enter a string (an (n-1)-gram) here', label='Query', interactive=True)
116
+ with gr.Row():
117
+ a_ntd_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
118
+ a_ntd_submit = gr.Button(value='Submit', variant='primary', visible=True)
119
+ a_ntd_output_tokens = gr.Textbox(label='Tokenized', lines=2, interactive=False)
120
+ with gr.Column(scale=1):
121
+ a_ntd_output = gr.Label(label='Distribution', num_top_classes=10)
122
+
123
+ with gr.Row(visible=False) as row_4:
124
+ with gr.Column():
125
+ gr.HTML('<h2>4. Compute the ∞-gram probability of the last token</h2>')
126
+ gr.HTML('<p style="font-size: 16px;">This computes the ∞-gram probability of the last token conditioned on the previous tokens. Compared to Query 2 (which uses your entire input for n-gram modeling), here we take the longest suffix that we can find in the corpus.</p>')
127
+ gr.HTML('<p style="font-size: 16px;">Example query: <b>I love natural language processing</b> (the output is P(processing | natural language), because "natural language" appears in the corpus but "love natural language" doesn\'t; in this case the effective n = 3)</p>')
128
+ gr.HTML('<p style="font-size: 16px;">Note: It may be possible that the effective n = 1, in which case it reduces to the uni-gram probability of the last token.</p>')
129
+ with gr.Row():
130
+ with gr.Column(scale=1):
131
+ infgram_input = gr.Textbox(placeholder='Enter a string here', label='Query', interactive=True)
132
+ with gr.Row():
133
+ infgram_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
134
+ infgram_submit = gr.Button(value='Submit', variant='primary', visible=True)
135
+ infgram_output_tokens = gr.Textbox(label='Tokenized', lines=2, interactive=False)
136
+ infgram_longest_suffix = gr.Textbox(label='Longest Found Suffix', interactive=False)
137
+ with gr.Column(scale=1):
138
+ infgram_output = gr.Label(label='Probability', num_top_classes=0)
139
+
140
+ with gr.Row(visible=False) as row_5:
141
+ with gr.Column():
142
+ gr.HTML('<h2>5. Compute the ∞-gram next-token distribution</h2>')
143
+ gr.HTML('<p style="font-size: 16px;">This is similar to Query 3, but with ∞-gram instead of n-gram.</p>')
144
+ gr.HTML('<p style="font-size: 16px;">Example query: <b>I love natural language</b> (the output is P(* | natural language), for the top-10 tokens *)</p>')
145
+ with gr.Row():
146
+ with gr.Column(scale=1):
147
+ a_infntd_input = gr.Textbox(placeholder='Enter a string here', label='Query', interactive=True)
148
+ with gr.Row():
149
+ a_infntd_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
150
+ a_infntd_submit = gr.Button(value='Submit', variant='primary', visible=True)
151
+ a_infntd_output_tokens = gr.Textbox(label='Tokenized', lines=2, interactive=False)
152
+ a_infntd_longest_suffix = gr.Textbox(label='Longest Found Suffix', interactive=False)
153
+ with gr.Column(scale=1):
154
+ a_infntd_output = gr.Label(label='Distribution', num_top_classes=10)
155
+
156
+ with gr.Row(visible=False) as row_6:
157
+ with gr.Column():
158
+ gr.HTML(f'''<h2>6. Searching for document containing n-gram(s)</h2>
159
+ <p style="font-size: 16px;">This displays a random document in the corpus that satisfies your query. You can simply enter an n-gram, in which case the document displayed would contain your n-gram. You can also connect multiple n-gram terms with the AND/OR operators, in the <a href="https://en.wikipedia.org/wiki/Conjunctive_normal_form">CNF format</a>, in which case the displayed document contains n-grams such that it satisfies this logical constraint.</p>
160
+ <p style="font-size: 16px;">Example queries:</p>
161
+ <ul style="font-size: 16px;">
162
+ <li><b>natural language processing</b> (the displayed document would contain "natural language processing")</li>
163
+ <li><b>natural language processing AND deep learning</b> (the displayed document would contain both "natural language processing" and "deep learning")</li>
164
+ <li><b>natural language processing OR artificial intelligence AND deep learning OR machine learning</b> (the displayed document would contain at least one of "natural language processing" / "artificial intelligence", and also at least one of "deep learning" / "machine learning")</li>
165
+ </ul>
166
+ <p style="font-size: 16px;">If you want another random document, simply hit the Submit button again :)</p>
167
+ <p style="font-size: 16px;">A few notes:</p>
168
+ <ul style="font-size: 16px;">
169
+ <li>When you write a query in CNF, note that <b>OR has higher precedence than AND</b> (which is contrary to conventions in boolean algebra).</li>
170
+ <li>If the document is too long, it will be truncated to {MAX_OUTPUT_DOC_TOKENS} tokens.</li>
171
+ <li>We can only include documents where all terms (or clauses) are separated by no more than {MAX_DIFF_TOKENS} tokens.</li>
172
+ <li>If you query for two or more clauses, and a clause has more than {MAX_CLAUSE_FREQ_FAST_APPROX_PER_SHARD} matches (per shard), we will search within a random subset of all documents containing that clause.</li>
173
+ <li>The number of found documents may contain duplicates (e.g., if a document contains your query term twice, it may be counted twice).</li>
174
+ </ul>
175
+ ''')
176
+ with gr.Row():
177
+ with gr.Column(scale=1):
178
+ a_ard_cnf_input = gr.Textbox(placeholder='Enter a query here', label='Query', interactive=True)
179
+ with gr.Row():
180
+ a_ard_cnf_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
181
+ a_ard_cnf_submit = gr.Button(value='Submit', variant='primary', visible=True)
182
+ a_ard_cnf_output_tokens = gr.Textbox(label='Tokenized', lines=2, interactive=False)
183
+ with gr.Column(scale=1):
184
+ a_ard_cnf_output_message = gr.Label(label='Message', num_top_classes=0)
185
+ a_ard_cnf_output = gr.HighlightedText(label='Document', show_legend=False, color_map={"-": "red", "0": "green", "1": "cyan", "2": "blue", "3": "magenta"})
186
+
187
+ with gr.Row(visible=False) as row_7:
188
+ with gr.Column():
189
+ gr.HTML('<h2>7. Analyze an (AI-generated) document using ∞-gram</h2>')
190
+ gr.HTML('<p style="font-size: 16px;">This analyzes the document you entered using the ∞-gram. Each token is highlighted where (1) the color represents its ∞-gram probability (red is 0.0, blue is 1.0), and (2) the alpha represents the effective n (higher alpha means higher n).</p>')
191
+ gr.HTML('<p style="font-size: 16px;">If you hover over a token, the tokens preceding it are each highlighted where (1) the color represents the n-gram probability of your selected token, with the n-gram starting from that highlighted token (red is 0.0, blue is 1.0), and (2) the alpha represents the count of the (n-1)-gram starting from that highlighted token (and up to but excluding your selected token) (higher alpha means higher count).</p>')
192
+ with gr.Row():
193
+ with gr.Column(scale=1):
194
+ doc_analysis_input = gr.Textbox(placeholder='Enter a document here', label='Query', interactive=True, lines=10)
195
+ with gr.Row():
196
+ doc_analysis_clear = gr.ClearButton(value='Clear', variant='secondary', visible=True)
197
+ doc_analysis_submit = gr.Button(value='Submit', variant='primary', visible=True)
198
+ with gr.Column(scale=1):
199
+ doc_analysis_output = gr.HTML(value='', label='Analysis')
200
+
201
+ count_clear.add([count_input, count_output, count_output_tokens])
202
+ ngram_clear.add([ngram_input, ngram_output, ngram_output_tokens])
203
+ a_ntd_clear.add([a_ntd_input, a_ntd_output, a_ntd_output_tokens])
204
+ infgram_clear.add([infgram_input, infgram_output, infgram_output_tokens])
205
+ a_infntd_clear.add([a_infntd_input, a_infntd_output, a_infntd_output_tokens, a_infntd_longest_suffix])
206
+ a_ard_cnf_clear.add([a_ard_cnf_input, a_ard_cnf_output, a_ard_cnf_output_tokens, a_ard_cnf_output_message])
207
+ doc_analysis_clear.add([doc_analysis_input, doc_analysis_output])
208
+
209
+ count_submit.click(process, inputs=[corpus_desc, query_desc, count_input], outputs=[count_output, count_output_tokens])
210
+ ngram_submit.click(process, inputs=[corpus_desc, query_desc, ngram_input], outputs=[ngram_output, ngram_output_tokens])
211
+ a_ntd_submit.click(process, inputs=[corpus_desc, query_desc, a_ntd_input], outputs=[a_ntd_output, a_ntd_output_tokens])
212
+ infgram_submit.click(process, inputs=[corpus_desc, query_desc, infgram_input], outputs=[infgram_output, infgram_output_tokens, infgram_longest_suffix])
213
+ a_infntd_submit.click(process, inputs=[corpus_desc, query_desc, a_infntd_input], outputs=[a_infntd_output, a_infntd_output_tokens, a_infntd_longest_suffix])
214
+ a_ard_cnf_submit.click(process, inputs=[corpus_desc, query_desc, a_ard_cnf_input], outputs=[a_ard_cnf_output, a_ard_cnf_output_tokens, a_ard_cnf_output_message])
215
+ doc_analysis_submit.click(process, inputs=[corpus_desc, query_desc, doc_analysis_input], outputs=[doc_analysis_output])
216
+
217
+ def update_query_desc(selection):
218
+ return {
219
+ row_1: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['count'])),
220
+ row_2: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['compute_prob'])),
221
+ row_3: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['get_next_token_distribution_approx'])),
222
+ row_4: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['compute_infgram_prob'])),
223
+ row_5: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['get_infgram_next_token_distribution_approx'])),
224
+ row_6: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['get_a_random_document_from_cnf_query_fast_approx'])),
225
+ # row_7: gr.Row(visible=(selection == QUERY_DESC_BY_TYPE['analyze_document'])),
226
+ }
227
+ query_desc.change(fn=update_query_desc, inputs=query_desc, outputs=[
228
+ row_1,
229
+ row_2,
230
+ row_3,
231
+ row_4,
232
+ row_5,
233
+ row_6,
234
+ # row_7,
235
+ ])
236
+
237
+ demo.queue(
238
+ default_concurrency_limit=default_concurrency_limit,
239
+ max_size=max_size,
240
+ ).launch(
241
+ max_threads=max_threads,
242
+ debug=debug,
243
+ )
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch==1.13.1
2
+ transformers==4.31.0
3
+ tokenizers==0.13.3
4
+ sentencepiece==0.1.96
5
+ huggingface_hub==0.14.1
6
+ requests