-
Notifications
You must be signed in to change notification settings - Fork 0
/
pred_mod_4.py
274 lines (200 loc) · 11.1 KB
/
pred_mod_4.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
# predict.py for a 4-way split of the doc along with merging
import argparse
import jsonlines
import torch
from tqdm import tqdm
from coref.coref_model2 import CorefModel
from coref.tokenizer_customization import *
from coref import bert, conll, utils
# usage : python pred_mod_4.py roberta data_4_splits_jsonlines/english_train_head.jsonlines output.jsonlines
# output.jsonlines [output path] redundant right now
# pred.conll and gold.conll files written in the data/conll_logs dir, model wts loaded from data/
# the unsplitted doc .jsonlines should be in the data/ dir
def build_cluster_emb(doc1, doc2, clusters, offset):
# offset is 0 for doc1, doc2
# offset is len*word1 + lenword2
words_emb1 = doc1["words_emb"]
words_emb2 = doc2["words_emb"]
word_emb = torch.cat((words_emb1, words_emb2), 0)
# task : see the wordsemb1 type
cluster_emb = []
for cluster in clusters:
cluster_i = []
for span in cluster:
span_embedding = None
start, end = span
start -= offset
end -= offset
for i in range(start, end):
if(span_embedding == None):
span_embedding = word_emb[i]
else:
span_embedding += word_emb[i]
span_embedding /= (end - start)
cluster_i.append(span_embedding)
cluster_i = torch.stack(cluster_i)
cluster_i = torch.mean(cluster_i, dim=0)
cluster_emb.append(cluster_i)
return cluster_emb
def build_doc(doc: dict, model: CorefModel) -> dict:
filter_func = TOKENIZER_FILTERS.get(model.config.bert_model,
lambda _: True)
token_map = TOKENIZER_MAPS.get(model.config.bert_model, {})
word2subword = []
subwords = []
word_id = []
for i, word in enumerate(doc["cased_words"]):
tokenized_word = (token_map[word]
if word in token_map
else model.tokenizer.tokenize(word))
tokenized_word = list(filter(filter_func, tokenized_word))
word2subword.append((len(subwords), len(subwords) + len(tokenized_word)))
subwords.extend(tokenized_word)
word_id.extend([i] * len(tokenized_word))
doc["word2subword"] = word2subword
doc["subwords"] = subwords
doc["word_id"] = word_id
doc["head2span"] = []
if "speaker" not in doc:
doc["speaker"] = ["_" for _ in doc["cased_words"]]
doc["word_clusters"] = []
doc["span_clusters"] = []
doc['cluster_emb'] = []
doc["span_clusters_res"] = []
doc["words_emb"] = []
return doc
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument("experiment")
argparser.add_argument("input_file")
argparser.add_argument("output_file")
argparser.add_argument("--config-file", default="config.toml")
argparser.add_argument("--batch-size", type=int,
help="Adjust to override the config value if you're"
" experiencing out-of-memory issues")
argparser.add_argument("--weights",
help="Path to file with weights to load."
" If not supplied, in the latest"
" weights of the experiment will be loaded;"
" if there aren't any, an error is raised.")
args = argparser.parse_args()
model = CorefModel(args.config_file, args.experiment)
if args.batch_size:
model.config.a_scoring_batch_size = args.batch_size
model.load_weights(path=args.weights, map_location="cpu",
ignore={"bert_optimizer", "general_optimizer",
"bert_scheduler", "general_scheduler"})
model.training = False
with jsonlines.open(args.input_file, mode="r") as input_data:
docs = [build_doc(doc, model) for doc in input_data]
# First run
with torch.no_grad():
for doc in tqdm(docs, unit="docs"):
result, word_emb = model.run(doc)
print(doc['document_id'])
doc["words_emb"] = word_emb
# assert len(doc['cased_words']) == len(word_emb)
doc["span_clusters_res"] = result.span_clusters # predicted span clusters
doc["word_clusters"] = result.word_clusters
clusters = doc["span_clusters_res"]
for cluster in clusters:
# you have to set a offset
cluster_i = []
for span in cluster:
span_embedding = None
start, end = span
for i in range(start, end):
if(span_embedding == None):
span_embedding = word_emb[i]
else:
span_embedding += word_emb[i]
span_embedding /= (end - start)
cluster_i.append(span_embedding)
cluster_i = torch.stack(cluster_i)
cluster_i = torch.mean(cluster_i, dim=0)
doc['cluster_emb'].append(cluster_i)
for key in ("word2subword", "subwords", "word_id", "head2span"):
del doc[key]
with torch.no_grad():
docs_new = {} #mapping for doc name to span clusters obtained after merging
for doc1, doc2, doc3, doc4 in zip(docs[::4], docs[1::4], docs[2::4], docs[3::4]):
span_clusters_mapping1 = {} # for doc 1 and 2
span_clusters_mapping2 = {} # for doc 3 and 4
cluster_emb1 = doc1['cluster_emb']
clusters1 = doc1['span_clusters_res']
cluster_emb2 = doc2['cluster_emb']
clusters2 = doc2['span_clusters_res']
cluster_emb3 = doc3['cluster_emb']
clusters3 = doc3['span_clusters_res']
cluster_emb4 = doc4['cluster_emb']
clusters4 = doc4['span_clusters_res']
offset1 = 0
offset2 = len(doc1['cased_words'])
offset3 = offset2 + len(doc2['cased_words'])
offset4 = offset3 + len(doc3['cased_words'])
clusters2 = [[(start + offset2, end + offset2) for start, end in tuple_list] for tuple_list in clusters2]
clusters3 = [[(start + offset3, end + offset3) for start, end in tuple_list] for tuple_list in clusters3]
clusters4 = [[(start + offset4, end + offset4) for start, end in tuple_list] for tuple_list in clusters4]
# ---------------------------------BLOCK1-------------------------------------
cluster_emb_merged1 = torch.stack(cluster_emb1 + cluster_emb2)
cluster_emb_merged1 = cluster_emb_merged1.to('cuda')
for i, cluster in enumerate(clusters1 + clusters2):
span_clusters_mapping1[i] = cluster #List[Tuple[int, int]]
res1 = model.run2(cluster_emb_merged1)
combined_span_clusters1 = [] # list of clusters in the combined doc 1 and 2
for second_lvl_clusters in res1.word_clusters:
combined_span_clusters_i = []
for x in second_lvl_clusters:
combined_span_clusters_i += span_clusters_mapping1[x]
combined_span_clusters1.append(sorted(combined_span_clusters_i))
# ---------------------------------BLOCK2-------------------------------------
cluster_emb_merged2 = torch.stack(cluster_emb3 + cluster_emb4)
cluster_emb_merged2 = cluster_emb_merged2.to('cuda')
for i, cluster in enumerate(clusters3 + clusters4):
span_clusters_mapping2[i] = cluster #List[Tuple[int, int]]
res2 = model.run2(cluster_emb_merged2)
combined_span_clusters2 = [] # list of clusters in the combined doc 3 and 4, with the word indices acc to the full doc
for second_lvl_clusters in res2.word_clusters:
combined_span_clusters_i = []
for x in second_lvl_clusters:
combined_span_clusters_i += span_clusters_mapping2[x]
combined_span_clusters2.append(sorted(combined_span_clusters_i))
# ------------- RUN 2 -----------------------------------------------------------
# create cluster embeddings
# to create this --- you need 2 docs now because the spans might be in 2 diff docs
# or another way could be to average out the cluster embs that were merged to create the emb of the new cluster
combined_clusters_emb1 = build_cluster_emb(doc1, doc2, combined_span_clusters1, 0)
combined_clusters_emb2 = build_cluster_emb(doc3, doc4, combined_span_clusters2, offset3)
span_clusters_mapping = {}
cluster_emb_merged = torch.stack(combined_clusters_emb1 + combined_clusters_emb2)
cluster_emb_merged = cluster_emb_merged.to('cuda')
for i, cluster in enumerate(combined_span_clusters1 + combined_span_clusters2):
span_clusters_mapping[i] = cluster #List[Tuple[int, int]]
res = model.run2(cluster_emb_merged)
# print(res.word_clusters)
combined_span_clusters = []
#mapping the indexes to the actual clusters of spans
for second_lvl_clusters in res.word_clusters:
combined_span_clusters_i = []
for x in second_lvl_clusters:
combined_span_clusters_i += span_clusters_mapping[x]
combined_span_clusters.append(sorted(combined_span_clusters_i))
# print("final res", combined_span_clusters)
doc_id = doc1["document_id"][:-2]
docs_new[doc_id] = combined_span_clusters
# # with jsonlines.open(args.output_file, mode="w") as output_data:
# # output_data.write_all(docs_new)
data_split = 'test'
docs = model._get_docs(model.config.__dict__[f"{data_split}_data"]) # from the head.jsonlines, because they contain 'span_clusters' not the other .jsonlines which contains the 'clusters'
# span clusters are formed after you run the convert_to_heads.py -- which are : clusters - some deleted clusters
with conll.open_(model.config, model.epochs_trained, data_split) \
as (gold_f, pred_f):
pbar = tqdm(docs, unit="docs", ncols=0)
for doc in pbar:
doc_id = doc['document_id']
pred_span_clusters = docs_new[doc_id]
conll.write_conll(doc, doc["span_clusters"], gold_f)
# remove singletons using ./coref-toolkit mod --strip-singletons data/conll_logs/roberta_test_e30.gold.conll > data/conll_logs/roberta_test_e30_x.gold.conll
# then rename it back
conll.write_conll(doc, pred_span_clusters, pred_f) # will be written in data/conll_logs/ dir
# to eval : python calculate_conll.py roberta test 30[no of epochs]