-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLORE.py
1912 lines (1587 loc) · 67.1 KB
/
LORE.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import csv
import sys
import json
import math
import time
import heapq
import pickle
import random
import struct
import asyncio
import difflib
import logging
import argparse
import datetime
import traceback
from collections import defaultdict
import numpy as np
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(message)s",
datefmt="%Y/%m/%d %H:%M:%S",
level=logging.INFO,
)
csv.register_dialect(
"csv", delimiter=",", quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True,
escapechar=None, lineterminator="\n", skipinitialspace=False,
)
"""
Config
"""
class Config:
def __init__(self):
self.task = ""
# LLM-ORE
self.literature_entity_file = ""
self.literature_content_file = ""
self.ore_extraction_file = ""
self.ore_prompt_file = ""
self.ore_knowledge_graph_file = ""
self.ore_server = ""
self.ore_model = ""
self.ore_concurrent_requests = 0
self.ore_requests_per_minute = 0
self.ore_tokens_per_minute = 0
self.ore_generations_per_prompt = 3
self.ore_max_title_tokens = 200
self.ore_max_article_tokens = 2500
self.ore_max_completion_tokens = 200
self.ore_max_prompt_runs = 10
self.ore_sort_knowledge_graph = True
self.ore_max_relation_similarity = 0.9
# LLM-EMB
self.emb_meta_file = ""
self.emb_bytes_file = ""
self.emb_file = ""
self.emb_model = ""
self.emb_dimension = 0
self.emb_max_text_tokens = 8191
self.emb_requests_per_minute = 0
self.emb_tokens_per_minute = 0
self.emb_max_prompt_runs = 10
# ML-Ranker
self.ranker_entity_feature_file = ""
self.ranker_entity_label_file = ""
self.ranker_D_split_file = ""
self.ranker_entity_score_file = ""
self.ranker_model_file = ""
self.ranker_lgb_data_sample_strategy = "goss"
self.ranker_lgb_num_leaves = 12
self.ranker_lgb_max_depth = 4
# Key-Semantics
self.semantics_lemma_file = ""
self.semantics_candidate_file = ""
self.semantics_file = ""
self.semantics_taxonomy_path = ""
self.semantics_knowledge_graph_file = ""
self.semantics_min_DGs = 100
self.semantics_min_gold_DG_relations = 0.5
self.semantics_samples_per_lemma = 10
return
def load(self, config_file):
with open(config_file, "r", encoding="utf8") as f:
parameter_to_value = json.load(f)
for parameter, value in parameter_to_value.items():
setattr(self, parameter, value)
logger.info(f"[config.{parameter}] {value}")
return
config = Config()
"""
LLM-ORE
"""
class DeepInfraTaskDatum:
def __init__(
self, prompt_id,
d, g, p, title, article,
d_name, g_name, d_alias_list, g_alias_list,
template,
):
self.runs = 0
self.prompt_id = prompt_id
self.d = d
self.g = g
self.p = p
self.title = title
self.article = article
self.d_name = d_name
self.g_name = g_name
self.d_alias_list = d_alias_list
self.g_alias_list = g_alias_list
self.text_in = template.replace(
"yoloTITLEyolo", self.title,
).replace(
"yoloTEXTyolo", self.article,
).replace(
"yoloGENEyolo", self.g_name,
).replace(
"yoloDISEASEyolo", self.d_name,
)
self.text_out_list = []
self.request_start_time = 0
self.request_end_time = 0
self.log_string = (
f"[#{self.prompt_id}]"
f" [D:{self.d}]"
f" [G:{self.g}]"
f" [P:{self.p}]"
f" [HEAD:{self.g_name}]"
f" [TAIL:{self.d_name}]"
)
return
def get_json_obj(self):
request_start_time = datetime.datetime.fromtimestamp(self.request_start_time).isoformat()
request_end_time = datetime.datetime.fromtimestamp(self.request_end_time).isoformat()
json_obj = {
"prompt_id": self.prompt_id,
"D_id": self.d, "G_id": self.g, "P_id": self.p,
"D_name": self.d_name, "G_name": self.g_name,
}
if self.d_alias_list:
json_obj["D_alias_list"] = self.d_alias_list
if self.g_alias_list:
json_obj["G_alias_list"] = self.g_alias_list
json_obj["text_out_list"] = self.text_out_list
json_obj["request_start_time"] = request_start_time
json_obj["request_end_time"] = request_end_time
return json_obj
class OpenAITaskDatum:
def __init__(
self, prompt_id,
d, g, p, title, article,
d_name, g_name, d_alias_list, g_alias_list,
template, tokenizer,
):
self.runs = 0
self.prompt_id = prompt_id
self.d = d
self.g = g
self.p = p
self.title = title
self.article = article
self.d_name = d_name
self.g_name = g_name
self.d_alias_list = d_alias_list
self.g_alias_list = g_alias_list
self.text_in = template.replace(
"yoloTITLEyolo", self.title,
).replace(
"yoloTEXTyolo", self.article,
).replace(
"yoloGENEyolo", self.g_name,
).replace(
"yoloDISEASEyolo", self.d_name,
)
self.in_tokens = len(tokenizer.encode(self.text_in))
self.text_out_list = []
self.request_start_time = 0
self.request_end_time = 0
self.log_string = (
f"[#{self.prompt_id}]"
f" [D:{self.d}]"
f" [G:{self.g}]"
f" [P:{self.p}]"
f" [HEAD:{self.g_name}]"
f" [TAIL:{self.d_name}]"
)
return
def get_json_obj(self):
request_start_time = datetime.datetime.fromtimestamp(self.request_start_time).isoformat()
request_end_time = datetime.datetime.fromtimestamp(self.request_end_time).isoformat()
json_obj = {
"prompt_id": self.prompt_id,
"D_id": self.d, "G_id": self.g, "P_id": self.p,
"D_name": self.d_name, "G_name": self.g_name,
}
if self.d_alias_list:
json_obj["D_alias_list"] = self.d_alias_list
if self.g_alias_list:
json_obj["G_alias_list"] = self.g_alias_list
json_obj["in_tokens"] = self.in_tokens
json_obj["text_out_list"] = self.text_out_list
json_obj["request_start_time"] = request_start_time
json_obj["request_end_time"] = request_end_time
return json_obj
async def ore_request(client, task_datum):
task_datum.runs += 1
task_datum.request_start_time = time.time()
completion = await client.chat.completions.create(
model=config.ore_model,
n=config.ore_generations_per_prompt,
messages=[
{"role": "user", "content": task_datum.text_in},
],
max_completion_tokens=config.ore_max_completion_tokens,
)
task_datum.request_end_time = time.time()
task_datum.text_out_list = [
choice.message.content
for choice in completion.choices
]
return task_datum
async def run_ore_extraction_deepinfra():
from openai import AsyncOpenAI
# set up client
logger.info("setting up ORE client...")
api_key = input("please input ORE server API key: ")
logger.info("received server API key")
client = AsyncOpenAI(
api_key=api_key,
base_url=config.ore_server, # for Deep Infra: "https://api.deepinfra.com/v1/openai"
)
# set up task management
requests_quota = config.ore_concurrent_requests
task_to_datum = {}
done_task_datum_queue = []
done_task_datum_queue_next_id = 0
# read prompt template
with open(config.ore_prompt_file, "r", encoding="utf8") as f:
template = f.read()
# read completed data
completed_prompt_id_set = set()
if os.path.exists(config.ore_extraction_file):
logger.info("reading completed data...")
with open(config.ore_extraction_file, "r", encoding="utf8") as f:
for line in f:
datum = json.loads(line)
completed_prompt_id_set.add(datum["prompt_id"])
completed_prompts = len(completed_prompt_id_set)
logger.info(f"read {completed_prompts:,} completed_prompts")
# read article data
logger.info("reading article data...")
p_to_title_article = {}
with open(config.literature_content_file, "r", encoding="utf8") as f:
for line in f:
datum = json.loads(line)
p = datum["P_id"]
title = datum["title"]
article = datum["article"]
p_to_title_article[p] = (title, article)
articles = len(p_to_title_article)
logger.info(f"read {articles:,} articles")
# run extraction by calling server
logger.info("running extraction...")
with open(config.literature_entity_file, "r", encoding="utf8") as fr, \
open(config.ore_extraction_file, "a", encoding="utf8") as fw:
for li, line in enumerate(fr):
prompt_id = li + 1
if prompt_id in completed_prompt_id_set:
logger.info(f"skip: [#{prompt_id}]")
continue
# create task datum
datum = json.loads(line)
d = datum["D_id"]
g = datum["G_id"]
p = datum["P_id"]
d_name = datum["D_name"]
g_name = datum["G_name"]
d_alias_list = datum.get("D_alias_list", [])
g_alias_list = datum.get("G_alias_list", [])
title, article = p_to_title_article[p]
# skip papers with super long titles, which are the proceedings
if len(title) > config.ore_max_title_tokens * 4:
logger.info(f"title too long, skip: [#{prompt_id}]")
continue
# limit article size
article = article[:config.ore_max_article_tokens * 4]
# create prompt
init_task_datum = DeepInfraTaskDatum(
prompt_id,
d, g, p, title, article,
d_name, g_name, d_alias_list, g_alias_list,
template,
)
logger.info(f"init: {init_task_datum.log_string}")
# wait until quota is enough
while requests_quota < 1:
# let tasks run
await asyncio.sleep(0.001)
# process completed tasks
new_task_to_datum = {}
for running_task, running_task_datum in task_to_datum.items():
if running_task.done():
successful = False
try:
_running_task_datum = running_task.result()
successful = True
logger.info(f"done: {running_task_datum.log_string}")
except:
if running_task_datum.runs < config.ore_max_prompt_runs:
running_task = asyncio.create_task(
ore_request(
client, running_task_datum,
)
)
new_task_to_datum[running_task] = running_task_datum
logger.info(f"re-run #{running_task_datum.runs}: {running_task_datum.log_string}")
await asyncio.sleep(0.0001)
continue
else:
running_task_datum.request_end_time = time.time()
logger.info(f"error: {running_task_datum.log_string}")
# save results
if successful:
json.dump(running_task_datum.get_json_obj(), fw)
fw.write("\n")
fw.flush()
heapq.heappush(
done_task_datum_queue,
(
running_task_datum.request_end_time,
done_task_datum_queue_next_id,
running_task_datum,
),
)
done_task_datum_queue_next_id += 1
else:
new_task_to_datum[running_task] = running_task_datum
task_to_datum = new_task_to_datum
# process quota: reclaim quota from tasks
while done_task_datum_queue:
heapq.heappop(done_task_datum_queue)
requests_quota += 1
# deduct quota
requests_quota -= 1
# create a task and wait long enough so that request has been sent to server
init_task = asyncio.create_task(
ore_request(client, init_task_datum)
)
task_to_datum[init_task] = init_task_datum
logger.info(f"run: {init_task_datum.log_string}")
await asyncio.sleep(0.0001)
# wait until all done
while task_to_datum:
done_task_set, pending_task_set = await asyncio.wait(task_to_datum, return_when=asyncio.FIRST_COMPLETED)
new_task_to_datum = {
pending_task: task_to_datum[pending_task]
for pending_task in pending_task_set
}
for done_task in done_task_set:
done_task_datum = task_to_datum[done_task]
try:
_done_task_datum = done_task.result()
logger.info(f"done: {done_task_datum.log_string}")
except:
if done_task_datum.runs < config.ore_max_prompt_runs:
done_task = asyncio.create_task(
ore_request(client, done_task_datum)
)
new_task_to_datum[done_task] = done_task_datum
logger.info(f"re-run #{done_task_datum.runs}: {done_task_datum.log_string}")
await asyncio.sleep(0.0001)
else:
done_task_datum.request_end_time = time.time()
logger.info(f"error: {done_task_datum.log_string}")
continue
# save results
json.dump(done_task_datum.get_json_obj(), fw)
fw.write("\n")
fw.flush()
task_to_datum = new_task_to_datum
logger.info("done")
return
def get_truncated_text(text, tokenizer, max_tokens):
tokens = len(tokenizer.encode(text))
while tokens > max_tokens:
cutoff_index = math.floor(len(text) * max_tokens / tokens) - 1
if cutoff_index < 1:
break
text = text[:cutoff_index]
tokens = len(tokenizer.encode(text))
return text, tokens
async def run_ore_extraction_openai():
from openai import AsyncOpenAI
import tiktoken
# set up client
logger.info("setting up ORE client...")
api_key = input("please input ORE server API key: ")
logger.info("received server API key")
client = AsyncOpenAI(
api_key=api_key,
)
tokenizer = tiktoken.encoding_for_model(config.ore_model)
# set up task management
rpm_quota = config.ore_requests_per_minute
tpm_quota = config.ore_tokens_per_minute
task_to_datum = {}
done_task_datum_queue = []
done_task_datum_queue_next_id = 0
# read prompt template
with open(config.ore_prompt_file, "r", encoding="utf8") as f:
template = f.read()
# read completed data
completed_prompt_id_set = set()
if os.path.exists(config.ore_extraction_file):
logger.info("reading completed data...")
with open(config.ore_extraction_file, "r", encoding="utf8") as f:
for line in f:
datum = json.loads(line)
completed_prompt_id_set.add(datum["prompt_id"])
completed_prompts = len(completed_prompt_id_set)
logger.info(f"read {completed_prompts:,} completed_prompts")
# read article data
logger.info("reading article data...")
p_to_title_article = {}
with open(config.literature_content_file, "r", encoding="utf8") as f:
for line in f:
datum = json.loads(line)
p = datum["P_id"]
title = datum["title"]
article = datum["article"]
p_to_title_article[p] = (title, article)
articles = len(p_to_title_article)
logger.info(f"read {articles:,} articles")
# run extraction by calling server
logger.info("running extraction...")
with open(config.literature_entity_file, "r", encoding="utf8") as fr, \
open(config.ore_extraction_file, "a", encoding="utf8") as fw:
for li, line in enumerate(fr):
prompt_id = li + 1
if prompt_id in completed_prompt_id_set:
logger.info(f"skip: [#{prompt_id}]")
continue
# create task datum
datum = json.loads(line)
d = datum["D_id"]
g = datum["G_id"]
p = datum["P_id"]
d_name = datum["D_name"]
g_name = datum["G_name"]
d_alias_list = datum.get("D_alias_list", [])
g_alias_list = datum.get("G_alias_list", [])
title, article = p_to_title_article[p]
# skip papers with super long titles, which are the proceedings
title_tokens = len(tokenizer.encode(title))
if title_tokens > config.ore_max_title_tokens * 4:
logger.info(f"title too long, skip: [#{prompt_id}]")
continue
# limit article size
article, _article_tokens = get_truncated_text(article, tokenizer, config.ore_max_article_tokens)
# create prompt
init_task_datum = OpenAITaskDatum(
prompt_id,
d, g, p, title, article,
d_name, g_name, d_alias_list, g_alias_list,
template, tokenizer,
)
logger.info(f"init: {init_task_datum.log_string}")
# wait until quota is enough
while rpm_quota < 1 or tpm_quota < init_task_datum.in_tokens:
# let tasks run
await asyncio.sleep(0.001)
# process completed tasks
new_task_to_datum = {}
for running_task, running_task_datum in task_to_datum.items():
if running_task.done():
successful = False
try:
_running_task_datum = running_task.result()
successful = True
logger.info(f"done: {running_task_datum.log_string}")
except:
if running_task_datum.runs < config.ore_max_prompt_runs:
running_task = asyncio.create_task(
ore_request(
client, running_task_datum,
)
)
new_task_to_datum[running_task] = running_task_datum
logger.info(f"re-run #{running_task_datum.runs}: {running_task_datum.log_string}")
await asyncio.sleep(0.0001)
continue
else:
running_task_datum.request_end_time = time.time()
logger.info(f"error: {running_task_datum.log_string}")
# save results
if successful:
json.dump(running_task_datum.get_json_obj(), fw)
fw.write("\n")
fw.flush()
heapq.heappush(
done_task_datum_queue,
(
running_task_datum.request_end_time,
done_task_datum_queue_next_id,
running_task_datum,
),
)
done_task_datum_queue_next_id += 1
else:
new_task_to_datum[running_task] = running_task_datum
task_to_datum = new_task_to_datum
# process quota: reclaim quota from tasks
while done_task_datum_queue:
request_end_time, _done_task_datum_queue_id, done_task_datum = done_task_datum_queue[0]
if request_end_time >= time.time() - 60:
break
heapq.heappop(done_task_datum_queue)
rpm_quota += 1
tpm_quota += done_task_datum.in_tokens
# deduct quota
rpm_quota -= 1
tpm_quota -= init_task_datum.in_tokens
# create a task and wait long enough so that request has been sent to server
init_task = asyncio.create_task(
ore_request(client, init_task_datum)
)
task_to_datum[init_task] = init_task_datum
logger.info(f"run: {init_task_datum.log_string}")
await asyncio.sleep(0.0001)
# wait until all done
while task_to_datum:
done_task_set, pending_task_set = await asyncio.wait(task_to_datum, return_when=asyncio.FIRST_COMPLETED)
new_task_to_datum = {
pending_task: task_to_datum[pending_task]
for pending_task in pending_task_set
}
for done_task in done_task_set:
done_task_datum = task_to_datum[done_task]
try:
_done_task_datum = done_task.result()
logger.info(f"done: {done_task_datum.log_string}")
except:
if done_task_datum.runs < config.ore_max_prompt_runs:
done_task = asyncio.create_task(
ore_request(client, done_task_datum)
)
new_task_to_datum[done_task] = done_task_datum
logger.info(f"re-run #{done_task_datum.runs}: {done_task_datum.log_string}")
await asyncio.sleep(0.0001)
else:
done_task_datum.request_end_time = time.time()
logger.info(f"error: {done_task_datum.log_string}")
continue
# save results
json.dump(done_task_datum.get_json_obj(), fw)
fw.write("\n")
fw.flush()
task_to_datum = new_task_to_datum
logger.info("done")
return
def run_ore_extraction():
# check config
global config
assert os.path.exists(config.literature_entity_file)
assert os.path.exists(config.literature_content_file)
if config.ore_prompt_file:
assert os.path.exists(config.ore_prompt_file)
else:
config.ore_prompt_file = "examples/LLM-ORE_prompt.txt"
logger.info(f"<ore_prompt_file> is not specified. Will use {config.ore_prompt_file}.")
if config.ore_server:
# deepinfra
if not config.ore_model:
config.ore_model = "meta-llama/Meta-Llama-3.1-8B-Instruct"
logger.info(f"<ore_model> is not specified. Will use {config.ore_model}.")
if config.ore_concurrent_requests <= 0:
config.ore_concurrent_requests = 200
logger.info(f"<ore_concurrent_requests> is not specified. Will use {config.ore_concurrent_requests}.")
logger.info("check https://deepinfra.com/docs/advanced/rate-limits for more info")
asyncio.run(run_ore_extraction_deepinfra())
else:
# openai
logger.info("<ore_server> is not specified. Will use OpenAI server.")
if not config.ore_model:
config.ore_model = "gpt-4o-mini"
logger.info(f"<ore_model> is not specified. Will use {config.ore_model}.")
if config.ore_requests_per_minute <= 0:
config.ore_requests_per_minute = 3 # gpt-4o-mini: [free tier: 3], [tier 5: 30,000]
logger.info(
f"<ore_requests_per_minute> is not specified. Will use {config.ore_requests_per_minute} (free tier)."
)
logger.info("check https://platform.openai.com/docs/guides/rate-limits for more info")
if config.ore_tokens_per_minute <= 0:
config.ore_tokens_per_minute = 40000 # gpt-4o-mini: [free tier: 40,000], [tier 5: 150,000,000]
logger.info(
f"<ore_tokens_per_minute> is not specified. Will use {config.ore_tokens_per_minute}. (free tier)"
)
logger.info("check https://platform.openai.com/docs/guides/rate-limits for more info")
asyncio.run(run_ore_extraction_openai())
return
def run_ore_knowledge_graph():
assert os.path.exists(config.ore_extraction_file)
header = ["D_id", "G_id", "P_id", "relation"]
relation_pattern = re.compile(r'^- "([^"]+)", "([^"]+)", "([^"]+)"$')
if config.ore_sort_knowledge_graph:
logger.info("<ore_sort_knowledge_graph> is True, will store all relations in memory")
else:
logger.info("<ore_sort_knowledge_graph> is False, relations will not be sorted")
fw = open(config.ore_knowledge_graph_file, "w", encoding="utf8", newline="")
writer = csv.writer(fw, dialect="csv")
writer.writerow(header)
knowledge_graph = []
all_relations = 0
all_d_dict = {}
all_g_dict = {}
all_dg_dict = {}
all_p_dict = {}
logger.info("building knowledge graph...")
with open(config.ore_extraction_file, "r", encoding="utf8") as fr:
# each line corresponds to a prompt
for line in fr:
datum = json.loads(line)
d = datum["D_id"]
g = datum["G_id"]
p = datum["P_id"]
d_name = datum["D_name"]
g_name = datum["G_name"]
d_alias_list = datum.get("D_alias_list", [])
g_alias_list = datum.get("G_alias_list", [])
text_out_list = datum["text_out_list"]
accepted_relation_to_matcher = {}
# each text_out corresponds to an LLM generation
for text_out in text_out_list:
relation_dict = {}
# each text_out_line corresponds to a relation
for text_out_line in text_out.split("\n"):
text_out_line = text_out_line.strip()
if not text_out_line.startswith("- "):
break
match = relation_pattern.fullmatch(text_out_line)
if match:
head, predicate, tail = match.group(1), match.group(2), match.group(3)
# check g in head
for alias in [g_name] + g_alias_list:
if alias in head:
break
else:
continue
# check d in tail
for alias in [d_name] + d_alias_list:
if alias in tail:
break
else:
continue
relation = f"{head} {predicate} {tail}"
relation_dict[relation] = True
if not accepted_relation_to_matcher:
# this is the first successful generation
accepted_relation_to_matcher = {
relation: difflib.SequenceMatcher(b=relation, autojunk=False)
for relation in relation_dict
}
else:
# add non-redundant relations from other successful generations
for candidate_relation in relation_dict:
for accepted_relation, matcher in accepted_relation_to_matcher.items():
if candidate_relation == accepted_relation:
break
matcher.set_seq1(candidate_relation)
if matcher.ratio() > config.ore_max_relation_similarity:
break
else:
accepted_relation_to_matcher[candidate_relation] = (
difflib.SequenceMatcher(b=candidate_relation, autojunk=False)
)
if config.ore_sort_knowledge_graph:
for relation in accepted_relation_to_matcher:
knowledge_graph.append([d, g, p, relation])
else:
for relation in accepted_relation_to_matcher:
writer.writerow([d, g, p, relation])
all_relations += 1
if accepted_relation_to_matcher:
all_d_dict[d] = True
all_g_dict[g] = True
all_dg_dict[(d, g)] = True
all_p_dict[p] = True
if config.ore_sort_knowledge_graph:
all_relations = len(knowledge_graph)
ds = len(all_d_dict)
gs = len(all_g_dict)
dgs = len(all_dg_dict)
ps = len(all_p_dict)
logger.info(
f"built knowledge graph:"
f" {ds:,} Ds; {gs:,} Gs; {dgs:,} DGs; {ps:,} Ps (articles); {all_relations:,} relations"
)
if config.ore_sort_knowledge_graph:
logger.info("sorting knowledge graph...")
knowledge_graph = sorted(knowledge_graph)
with open(config.ore_knowledge_graph_file, "w", encoding="utf8", newline="") as fw:
writer = csv.writer(fw, dialect="csv")
writer.writerow(header)
for row in knowledge_graph:
writer.writerow(row)
logger.info("done")
return
def run_ore():
run_ore_extraction()
run_ore_knowledge_graph()
return
"""
LLM-EMB
"""
def extract_dg_text():
import tiktoken
# collect text for each DGP
logger.info("reading knowledge graph...")
dg_p_text = defaultdict(lambda: defaultdict(lambda: []))
dgp_dict = {}
with open(config.ore_knowledge_graph_file, "r", encoding="utf8", newline="") as f:
reader = csv.reader(f, dialect="csv")
header = next(reader)
assert header == ["D_id", "G_id", "P_id", "relation"]
for d, g, p, relation in reader:
dg_p_text[(d, g)][p].append(f"{relation}.")
dgp_dict[(d, g, p)] = True
dg_p_text = {
dg: {
p: " ".join(text)
for p, text in p_to_text.items()
}
for dg, p_to_text in dg_p_text.items()
}
dgs = len(dg_p_text)
dgps = len(dgp_dict)
del dgp_dict
logger.info(f"read {dgs:,} DGs; {dgps:,} DGPs")
# collect text list for each DG
logger.info("creating text list for each DG...")
tokenizer = tiktoken.encoding_for_model(config.emb_model)
dg_to_text_tokens_list = {}
texts = 0
for dg, p_to_text in dg_p_text.items():
block_text_tokens_list = []
block_text = []
block_tokens = 0
for p, p_text in p_to_text.items():
p_tokens = len(tokenizer.encode(p_text))
assert p_tokens <= config.emb_max_text_tokens
if block_text:
if block_tokens + 1 + p_tokens > config.emb_max_text_tokens:
block_text = " ".join(block_text)
block_tokens = len(tokenizer.encode(block_text))
assert block_tokens <= config.emb_max_text_tokens
block_text_tokens_list.append((block_text, block_tokens))
texts += 1
block_text = [p_text]
block_tokens = p_tokens
else:
block_text.append(p_text)
block_tokens += 1 + p_tokens
else:
block_text = [p_text]
block_tokens = p_tokens
if block_text:
block_text = " ".join(block_text)
block_tokens = len(tokenizer.encode(block_text))
assert block_tokens <= config.emb_max_text_tokens
block_text_tokens_list.append((block_text, block_tokens))
texts += 1
dg_to_text_tokens_list[dg] = block_text_tokens_list
logger.info(f"created {texts:,} texts")
return dg_to_text_tokens_list
class EmbTaskDatum:
def __init__(self, prompt_id, d, g, text, tokens):
self.prompt_id = prompt_id
self.d = d
self.g = g
self.text = text
self.tokens = tokens
self.embedding = None
self.runs = 0
self.request_start_time = 0
self.request_end_time = 0
self.log_string = f"[#{self.prompt_id}] tokens={self.tokens:,} text[:100]={self.text[:100]}"
return
def get_json_obj(self):
request_start_time = datetime.datetime.fromtimestamp(self.request_start_time).isoformat()
request_end_time = datetime.datetime.fromtimestamp(self.request_end_time).isoformat()
json_obj = {
"prompt_id": self.prompt_id,
"D_id": self.d, "G_id": self.g, "tokens": self.tokens,
"runs": self.runs, "request_start_time": request_start_time, "request_end_time": request_end_time,
}
return json_obj
async def emb_request(async_client, task_datum):
task_datum.runs += 1
task_datum.request_start_time = time.time()
completion = await async_client.embeddings.create(
input=[task_datum.text],
model=config.emb_model,
dimensions=config.emb_dimension,
)
task_datum.request_end_time = time.time()
task_datum.embedding = completion.data[0].embedding
return task_datum
async def run_emb_extraction():
from openai import AsyncOpenAI
# check config
assert os.path.exists(config.ore_knowledge_graph_file)
if not config.emb_model:
config.emb_model = "text-embedding-3-large"
logger.info(f"<ore_model> is not specified. Will use {config.emb_model}.")
if config.emb_requests_per_minute <= 0:
config.emb_requests_per_minute = 100 # text-embedding-3-large: [free tier: 100], [tier 5: 30,000]
logger.info(
f"<emb_requests_per_minute> is not specified. Will use {config.emb_requests_per_minute}. (free tier)"
)
logger.info("check https://platform.openai.com/docs/guides/rate-limits for more info")
if config.emb_tokens_per_minute <= 0:
config.emb_tokens_per_minute = 10000 # text-embedding-3-large: [free tier: 10,000], [tier 5: 10,000,000]
logger.info(
f"<emb_tokens_per_minute> is not specified. Will use {config.emb_tokens_per_minute} (free tier)."
)
logger.info("check https://platform.openai.com/docs/guides/rate-limits for more info")
# set up client
logger.info("setting up ORE client...")
api_key = input("please input EMB server API key: ")
logger.info("received server API key")
async_client = AsyncOpenAI(api_key=api_key)
# set up task management
rpm_quota = config.emb_requests_per_minute
tpm_quota = config.emb_tokens_per_minute
task_to_datum = {}
done_task_datum_queue = []
done_task_datum_queue_next_id = 0
# read knowledge graph
dg_to_text_tokens_list = extract_dg_text()