-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathembedder.py
354 lines (299 loc) · 12.7 KB
/
embedder.py
1
2
3
4
5
6
7
8
9
10
11
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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import re
import html
import asyncio
import datetime
import collections
from tqdm import tqdm
from collections import defaultdict
from InstructorEmbedding import INSTRUCTOR
from utils import log, log_with_mem
DOCUMENT_INSTRUCTION = "Represent the forum discussion on a topic:"
QUERY_INSTRUCTION = (
"Represent the question for retrieving supporting forum discussions: "
)
MAX_CACHE_SIZE = 100000
class Embedder:
def __init__(self):
self.model = INSTRUCTOR("hkunlp/instructor-large")
self.model.max_seq_length = DocumentEmbedder.TOKEN_LIMIT
self.request_queue = asyncio.PriorityQueue()
self._stop_event = asyncio.Event()
self.processing_task = asyncio.create_task(self._process_requests())
self.cache = collections.OrderedDict()
self.cache_hits = 0
async def encode(self, texts, high_priority=False, document=False):
# Normalize
texts = [" ".join(text.lower().split()) for text in texts]
# Check cache for single texts of instruction type query
if len(texts) == 1 and not document and texts[0] in self.cache:
self.cache_hits += 1
self.cache.move_to_end(texts[0])
return self.cache[texts[0]]
text_pairs = []
for text in texts:
if document:
text_pairs.append([DOCUMENT_INSTRUCTION, text])
else:
text_pairs.append([QUERY_INSTRUCTION, text])
result_queue = asyncio.Queue()
priority = 0 if high_priority else 1
await self.request_queue.put((priority, (text_pairs, result_queue)))
return await result_queue.get()
async def _process_requests(self):
while not self._stop_event.is_set():
_, (text_pairs, result_queue) = await self.request_queue.get()
if text_pairs is not None:
embeddings = self.model.encode(text_pairs)
# Store in cache if appropriate
if len(embeddings) == 1 and text_pairs[0][0] == QUERY_INSTRUCTION:
cache_key = text_pairs[0][1]
self.cache[cache_key] = embeddings
self.cache.move_to_end(cache_key)
if len(self.cache) > MAX_CACHE_SIZE:
self.cache.popitem(last=False)
await result_queue.put(embeddings)
async def shutdown(self):
self._stop_event.set()
self.processing_task.cancel()
try:
await self.processing_task
except asyncio.CancelledError:
pass
class DocumentEmbedder:
CHARACTER_LIMIT = 4096
TOKEN_LIMIT = 1024
BATCH_SIZE = 16
MIN_SCORE = 20
MIN_DESCENDANTS = 3
def __init__(self, db_conn, embed_conn, encoder):
self.db_conn = db_conn
self.embed_conn = embed_conn
self.encoder = encoder
# Create the embeddings table if it doesn't exist
self.embed_conn.execute(
"""
CREATE TABLE IF NOT EXISTS embeddings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
story INTEGER,
part_index INTEGER,
embedding BLOB,
UNIQUE (story, part_index)
)
"""
)
async def process_stories(self, story_ids):
progress = tqdm(desc="parts processed", disable=True)
doc_progress = tqdm(desc="documents processed", disable=True)
processed = []
cursor = self.db_conn.cursor()
for story_id in story_ids:
constraint = f"FROM items WHERE type = 'story' AND id = {story_id}"
cursor.execute(f"SELECT score, descendants {constraint}")
result = cursor.fetchone()
if not result:
continue
score = 0 if not result[0] else result[0]
descendants = 0 if not result[1] else result[1]
if score < self.MIN_SCORE or descendants < self.MIN_DESCENDANTS:
continue
await self.process_stories_with_constraint(
constraint, progress, doc_progress, batch_size=1
)
processed.append(story_id)
progress.close()
doc_progress.close()
return processed
async def process_catchup_stories(self, offset=0):
# Fetch all interesting stories
interesting = (
f"AND score >= {self.MIN_SCORE} AND descendants >= {self.MIN_DESCENDANTS}"
)
constraint = f"FROM items WHERE type = 'story' {interesting}"
# Fetch the last processed story
last_processed_story = self.fetch_last_processed_story()
# Return the difference between the two lists
missing = self.find_missing(constraint)
if len(missing) > 0:
log(
f"Found {len(missing)} missing stories, resetting last_processed_story ({last_processed_story})"
)
last_processed_story = min(min(missing), last_processed_story)
if last_processed_story:
log(f"Found last processed story: {last_processed_story}")
if offset != 0:
cursor = self.db_conn.cursor()
cursor.execute(
"""SELECT id FROM (
SELECT id FROM items WHERE id < ? AND type='story' ORDER BY id DESC
) AS subquery LIMIT 1 OFFSET ?;""",
(last_processed_story, offset - 1),
)
last_processed_story = cursor.fetchone()[0]
cursor.close()
log(f"Resuming from story {last_processed_story} (after offset: {offset})")
constraint += f" AND id > {last_processed_story}"
cursor = self.db_conn.cursor()
cursor.execute(f"SELECT COUNT(*) {constraint}")
total_stories = cursor.fetchone()[0]
cursor.close()
log(f"Found total eligible discussions: {total_stories}")
progress = tqdm(desc="parts processed")
doc_progress = tqdm(desc="documents processed", total=total_stories)
await self.process_stories_with_constraint(constraint, progress, doc_progress)
progress.close()
doc_progress.close()
async def process_stories_with_constraint(
self, constraint, progress, doc_progress, batch_size=BATCH_SIZE
):
story_iter = self.story_generator(constraint)
story_batch = []
for story, comments in story_iter:
document_parts = self.create_documents(story, comments)
for part_index, document_part in enumerate(document_parts):
story_batch.append((story["id"], part_index, document_part))
if len(story_batch) == batch_size:
await self.process_batch(story_batch)
progress.update(len(story_batch))
story_batch = []
doc_progress.update()
# Process the remaining stories in the batch
if story_batch:
await self.process_batch(story_batch)
async def process_batch(self, story_batch):
embeddings_batch = await self.encoder.encode(
[part for _, _, part in story_batch], document=True
)
insert_data = [
(story_id, part_index, embeddings.tobytes())
for (story_id, part_index, _), embeddings in zip(
story_batch, embeddings_batch
)
]
cursor = self.embed_conn.cursor()
cursor.executemany(
"""
INSERT OR REPLACE INTO embeddings (story, part_index, embedding)
VALUES (?, ?, ?)
""",
insert_data,
)
self.embed_conn.commit()
cursor.close()
def find_missing(self, constraint):
# Fetch list of ids from conn (items) table
items_cursor = self.db_conn.cursor()
items_cursor.execute(f"SELECT COUNT(*) {constraint}")
items_count = items_cursor.fetchone()[0]
log_with_mem(f"Found {items_count} interesting stories from items")
embeddings_cursor = self.embed_conn.cursor()
embeddings_cursor.execute("SELECT COUNT(DISTINCT story) FROM embeddings")
embeddings_count = embeddings_cursor.fetchone()[0]
log_with_mem(f"Found {embeddings_count} stories with embeddings")
# If no difference, just return
if items_count <= embeddings_count:
items_cursor.close()
embeddings_cursor.close()
return set()
# Find difference
log_with_mem("Finding missing stories")
items = set()
items_cursor.execute(f"SELECT id {constraint}")
for item in items_cursor.fetchall():
items.add(item[0])
item = items_cursor.fetchone()
items_cursor.close()
embeddings = set()
embeddings_cursor.execute("SELECT DISTINCT story FROM embeddings")
for embedding in embeddings_cursor.fetchall():
embeddings.add(embedding[0])
embeddings_cursor.close()
return items - embeddings
def format_date(self, unix_timestamp):
dt = datetime.datetime.fromtimestamp(unix_timestamp)
return dt.strftime("%Y-%m-%d")
def story_generator(self, constraint):
cursor = self.db_conn.cursor()
cursor.execute(f"SELECT id, title, text, parent {constraint}")
row = cursor.fetchone()
while row:
story = dict(row)
comments = self.fetch_comment_data(story["id"])
yield story, comments
row = cursor.fetchone()
cursor.close()
def filter_comments(self, comments):
# Filter out comments containing "[dead]" or "[flagged]"
filtered_comments = [
comment
for comment in comments
if "[dead]" not in comment["text"] and "[flagged]" not in comment["text"]
]
return filtered_comments
def fetch_comments(self, parent_id):
cursor = self.db_conn.cursor()
cursor.execute(
"""
SELECT id, title, text, parent
FROM items
WHERE type = 'comment' AND parent = ? AND text IS NOT NULL
""",
(parent_id,),
)
return cursor.fetchall()
def fetch_comment_data(self, story_id):
top_level_comments = self.fetch_comments(story_id)
all_comments = []
def fetch_descendants(parent_comment):
child_comments = self.fetch_comments(parent_comment["id"])
for child_comment in child_comments:
all_comments.append(child_comment)
fetch_descendants(child_comment)
for top_level_comment in top_level_comments:
all_comments.append(top_level_comment)
fetch_descendants(top_level_comment)
return self.filter_comments(all_comments)
def clean_text(self, text):
if text is None:
return ""
text = re.sub("<[^>]*>", "", text)
text = re.sub("\r\n", "\n", text)
text = html.unescape(text)
return text
def story_header(self, story):
if story["title"] is None or story["title"] == "":
if story["text"] is None or story["text"] == "":
return None
header = f'Topic: {self.clean_text(story["title"])}\n'
# submitted by {clean_text(story["by"])} on {format_date(story["time"])}\n
if story["text"]:
header += f'{self.clean_text(story["text"])}\n'
return header + "Discussion:\n"
def create_documents(self, story, comments):
document_parts = []
# Prepare a dictionary for comments, indexed by their parent ID
comments_by_parent = defaultdict(list)
for comment in comments:
comments_by_parent[comment["parent"]].append(comment)
current_document = self.story_header(story)
if current_document is None:
return []
# Iterate through top-level comments and their children
stack = [(0, comment) for comment in comments_by_parent[story["id"]]]
while stack:
level, comment = stack.pop()
# If adding the comment exceeds the character limit, start a new document
if len(current_document) + len(comment["text"]) > self.CHARACTER_LIMIT:
document_parts.append(current_document)
current_document = self.story_header(story)
current_document += "\t" * level + f'{self.clean_text(comment["text"])}\n'
# Add child comments to the stack
for child_comment in comments_by_parent[comment["id"]]:
stack.append((level + 1, child_comment))
document_parts.append(current_document)
return document_parts
def fetch_last_processed_story(self):
cursor = self.embed_conn.cursor()
cursor.execute("SELECT MAX(story) FROM embeddings")
result = cursor.fetchone()
cursor.close()
return result[0] if result else None