-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmodel_fns.py
1755 lines (1620 loc) · 66.3 KB
/
model_fns.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
# Lint as: python3
"""Collection of model functions implementing different multihop variants."""
from language.labs.drkit import model_fns as model_utils
from language.labs.drkit import search_utils
import tensorflow.compat.v1 as tf
from bert import modeling
from tensorflow.contrib import layers as contrib_layers
DEFAULT_VALUE = -10000.
def follow_mention(batch_entities,
relation_st_qry,
relation_en_qry,
entity_word_ids,
entity_word_masks,
ent2ment_ind,
ent2ment_val,
ment2ent_map,
word_emb_table,
word_weights,
mips_search_fn,
tf_db,
hidden_size,
mips_config,
qa_config,
is_training,
ensure_index=None):
"""Sparse implementation of the relation follow operation.
Args:
batch_entities: [batch_size, num_entities] SparseTensor of incoming entities
and their scores.
relation_st_qry: [batch_size, dim] Tensor representating start query vectors
for dense retrieval.
relation_en_qry: [batch_size, dim] Tensor representating end query vectors
for dense retrieval.
entity_word_ids: [num_entities, max_entity_len] Tensor holding word ids of
each entity.
entity_word_masks: [num_entities, max_entity_len] Tensor with masks into
word ids above.
ent2ment_ind: [num_entities, num_mentions] RaggedTensor mapping entities to
mention indices which co-occur with them.
ent2ment_val: [num_entities, num_mentions] RaggedTensor mapping entities to
mention scores which co-occur with them.
ment2ent_map: [num_mentions] Tensor mapping mentions to their entities.
word_emb_table: [vocab_size, dim] Tensor of word embedddings. (?)
word_weights: [vocab_size, 1] Tensor of word weights. (?)
mips_search_fn: Function which accepts a dense query vector and returns the
top-k indices closest to it (from the tf_db).
tf_db: [num_mentions, 2 * dim] Tensor of mention representations.
hidden_size: Scalar dimension of word embeddings.
mips_config: MIPSConfig object.
qa_config: QAConfig object.
is_training: Boolean.
ensure_index: [batch_size] Tensor of mention ids. Only needed if
`is_training` is True. (? each example only one ensure entity?)
Returns:
ret_mentions_ids: [batch_size, k] Tensor of retrieved mention ids.
ret_mentions_scs: [batch_size, k] Tensor of retrieved mention scores.
ret_entities_ids: [batch_size, k] Tensor of retrieved entities ids.
"""
if qa_config.entity_score_threshold is not None:
# Remove the entities which have scores lower than the threshold.
mask = tf.greater(batch_entities.values, qa_config.entity_score_threshold)
batch_entities = tf.sparse.retain(batch_entities, mask)
batch_size = batch_entities.dense_shape[0] # number of the batches
batch_ind = batch_entities.indices[:, 0] # the list of the batch ids
entity_ind = batch_entities.indices[:, 1] # the list of the entity ids
entity_scs = batch_entities.values # the list of the scores of each entity
# Obtain BOW embeddings for the given set of entities.
# [NNZ, dim] NNZ (number of non-zero entries) = len(entity_ind)
batch_entity_emb = model_utils.entity_emb(entity_ind, entity_word_ids,
entity_word_masks, word_emb_table,
word_weights)
batch_entity_emb = batch_entity_emb * tf.expand_dims(entity_scs, axis=1)
# [batch_size, dim]
uniq_batch_ind, uniq_idx = tf.unique(batch_ind)
agg_emb = tf.unsorted_segment_sum(batch_entity_emb, uniq_idx,
tf.shape(uniq_batch_ind)[0])
batch_bow_emb = tf.scatter_nd(
tf.expand_dims(uniq_batch_ind, 1), agg_emb,
tf.stack([batch_size, hidden_size], axis=0))
batch_bow_emb.set_shape([None, hidden_size])
if qa_config.projection_dim is not None:
with tf.variable_scope("projection"):
batch_bow_emb = contrib_layers.fully_connected(
batch_bow_emb,
qa_config.projection_dim,
activation_fn=tf.nn.tanh,
reuse=tf.AUTO_REUSE,
scope="bow_projection")
# Each instance in a batch has onely one vector as embedding.
# Ragged sparse search.
# (num_batch x num_entities) * (num_entities x num_mentions)
# [batch_size x num_mentions] sparse
sp_mention_vec = model_utils.sparse_ragged_mul(
batch_entities,
ent2ment_ind,
ent2ment_val,
batch_size,
mips_config.num_mentions,
qa_config.sparse_reduce_fn, # max or sum
threshold=qa_config.entity_score_threshold,
fix_values_to_one=qa_config.fix_sparse_to_one)
if is_training and qa_config.ensure_answer_sparse:
ensure_indices = tf.stack([tf.range(batch_size), ensure_index], axis=-1)
sp_ensure_vec = tf.SparseTensor(
tf.cast(ensure_indices, tf.int64),
tf.ones([batch_size]),
dense_shape=[batch_size, mips_config.num_mentions])
sp_mention_vec = tf.sparse.add(sp_mention_vec, sp_ensure_vec)
sp_mention_vec = tf.SparseTensor(
indices=sp_mention_vec.indices,
values=tf.minimum(1., sp_mention_vec.values),
dense_shape=sp_mention_vec.dense_shape)
# Dense scam search.
# [batch_size, 2 * dim]
# Constuct query embeddings (dual encoder: [subject; relation]).
scam_qrys = tf.concat(
[batch_bow_emb + relation_st_qry, batch_bow_emb + relation_en_qry],
axis=1)
with tf.device("/cpu:0"):
# [batch_size, num_neighbors]
_, ret_mention_ids = mips_search_fn(scam_qrys)
if is_training and qa_config.ensure_answer_dense:
ret_mention_ids = model_utils.ensure_values_in_mat(
ret_mention_ids, ensure_index, tf.int32)
# [batch_size, num_neighbors, 2 * dim]
ret_mention_emb = tf.gather(tf_db, ret_mention_ids)
if qa_config.l2_normalize_db:
ret_mention_emb = tf.nn.l2_normalize(ret_mention_emb, axis=2)
# [batch_size, 1, num_neighbors]
ret_mention_scs = tf.matmul(
tf.expand_dims(scam_qrys, 1), ret_mention_emb, transpose_b=True)
# [batch_size, num_neighbors]
ret_mention_scs = tf.squeeze(ret_mention_scs, 1)
# [batch_size, num_mentions] sparse
dense_mention_vec = model_utils.convert_search_to_vector(
ret_mention_scs, ret_mention_ids, tf.cast(batch_size, tf.int32),
mips_config.num_neighbors, mips_config.num_mentions)
# Combine sparse and dense search.
if (is_training and qa_config.train_with_sparse) or (
(not is_training) and qa_config.predict_with_sparse):
# [batch_size, num_mentions] sparse
if qa_config.sparse_strategy == "dense_first":
ret_mention_vec = model_utils.sp_sp_matmul(dense_mention_vec,
sp_mention_vec)
elif qa_config.sparse_strategy == "sparse_first":
with tf.device("/cpu:0"):
ret_mention_vec = model_utils.rescore_sparse(sp_mention_vec, tf_db,
scam_qrys)
else:
raise ValueError("Unrecognized sparse_strategy %s" %
qa_config.sparse_strategy)
else:
# [batch_size, num_mentions] sparse
ret_mention_vec = dense_mention_vec
# Get entity scores and ids.
# [batch_size, num_entities] sparse
entity_indices = tf.cast(
tf.gather(ment2ent_map, ret_mention_vec.indices[:, 1]), tf.int64)
ret_entity_vec = tf.SparseTensor(
indices=tf.concat(
[ret_mention_vec.indices[:, 0:1],
tf.expand_dims(entity_indices, 1)],
axis=1),
values=ret_mention_vec.values,
dense_shape=[batch_size, qa_config.num_entities])
### Start of debugging w/ tf.Print ###
is_printing = True
if is_printing:
tmp_vals = ret_entity_vec.values
tmp_vals = tf.Print(
input_=tmp_vals,
data=[tf.shape(batch_entities.indices)[0], batch_entities.indices],
message="batch_entities.indices",
first_n=10,
summarize=25)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[tf.shape(ret_entity_vec.indices)[0], ret_entity_vec.indices],
message="ret_entity_vec.indices",
first_n=10,
summarize=25)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(ret_entity_vec.values),
ret_entity_vec.values,
],
message="ret_entity_vec.values",
first_n=10,
summarize=25)
ret_entity_vec = tf.SparseTensor(
indices=ret_entity_vec.indices,
values=tmp_vals,
dense_shape=ret_entity_vec.dense_shape)
### End of debugging w/ tf.Print ###
return ret_entity_vec, ret_mention_vec, dense_mention_vec, sp_mention_vec
def maxscale_spare_tensor(sp_tensor):
"""Scales the sparse tensor with its maximum per row."""
sp_tensor_maxmiums = tf.sparse.reduce_max(sp_tensor, 1) # batch_size
gather_sp_tensor_maxmiums = tf.gather(sp_tensor_maxmiums,
sp_tensor.indices[:, 0:1])
gather_sp_tensor_maxmiums = tf.reshape(gather_sp_tensor_maxmiums,
tf.shape(sp_tensor.values))
scaled_val = sp_tensor.values / gather_sp_tensor_maxmiums
scaled_sp_tensor = tf.SparseTensor(sp_tensor.indices, scaled_val,
sp_tensor.dense_shape)
return scaled_sp_tensor
def scam_projection_layer(context_qry_emb, project_dim, is_training, qa_config, suffix=""):
"""MLP layer for translating the concat of previous-fact and qry."""
dropout = qa_config.dropout if is_training else 0.0
context_qry_emb_drop = contrib_layers.dropout(context_qry_emb, 1-dropout)
with tf.variable_scope("qry/hop" + suffix, reuse=tf.AUTO_REUSE):
translated_scam_qry = contrib_layers.fully_connected(
context_qry_emb_drop,
project_dim,
activation_fn=tf.nn.tanh,
reuse=tf.AUTO_REUSE,
scope="scam_qry_translation")
return translated_scam_qry
def follow_fact(
batch_facts,
hopwise_qry_seq_emb,
word_emb_table,
word_weights,
fact2fact_ind,
fact2fact_val,
fact2ent_ind,
fact2ent_val,
fact_mips_search_fn,
tf_fact_db,
fact_mips_config,
qa_config,
is_training,
hop_id=0,
is_printing=True,
):
"""Sparse implementation of the relation follow operation.
Args:
batch_facts: [batch_size, num_facts] SparseTensor of incoming facts and
their scores.
relation_st_qry: [batch_size, dim] Tensor representating start query vectors
for dense retrieval.
relation_en_qry: [batch_size, dim] Tensor representating end query vectors
for dense retrieval.
fact2fact_ind: [num_facts, num_facts] RaggedTensor mapping facts to entity
indices which co-occur with them.
fact2fact_val: [num_facts, num_facts] RaggedTensor mapping facts to entity
scores which co-occur with them.
fact2ent_ind: [num_facts, num_entities] RaggedTensor mapping facts to entity
indices which co-occur with them.
fact2ent_val: [num_facts, num_entities] RaggedTensor mapping facts to entity
scores which co-occur with them.
fact_mips_search_fn: Function which accepts a dense query vector and returns
the top-k indices closest to it (from the tf_fact_db).
tf_fact_db: [num_facts, 2 * dim] Tensor of fact representations.
fact_mips_config: MIPS Config object.
qa_config: QAConfig object.
is_training: Boolean.
hop_id: int, the current hop id.
is_printing: if print results for debugging.
Returns:
ret_entities: [batch_size, num_entities] Tensor of retrieved entities.
ret_facts: [batch_size, num_facts] Tensor of retrieved facts.
dense_fact_vec: [batch_size, num_facts] Tensor of retrieved facts (dense).
sp_fact_vec: [batch_size, num_facts] Tensor of retrieved facts (sparse).
"""
num_facts = fact_mips_config.num_facts
batch_size = batch_facts.dense_shape[0] # number of examples in a batch
example_ind = batch_facts.indices[:, 0] # the list of the example ids
fact_ind = batch_facts.indices[:, 1] # the list of the fact ids
fact_scs = batch_facts.values # the list of the scores of each fact
uniq_original_example_ind, uniq_local_example_idx = tf.unique(example_ind)
# uniq_original_example_ind: local to original example id
# uniq_local_example_idx: a list of local example id
# tf.shape(uniq_original_example_ind)[0] = num_examples
# if qa_config.fact_score_threshold is not None:
# # Remove the facts which have scores lower than the threshold.
# mask = tf.greater(batch_facts.values, qa_config.fact_score_threshold)
# batch_facts = tf.sparse.retain(batch_facts, mask)
# Sparse: Ragged sparse search from the current facts to the next facts.
# (num_batch x num_facts) X (num_facts x num_facts)
# [batch_size x num_facts] sparse
if hop_id > 0:
sp_fact_vec = model_utils.sparse_ragged_mul(
batch_facts,
fact2fact_ind,
fact2fact_val,
batch_size,
num_facts,
"max", # Note: check this.
threshold=None,
fix_values_to_one=True)
# Start Self Follow
if qa_config.self_follow_threshold > 0:
high_mask = tf.greater(batch_facts.values, qa_config.self_follow_threshold)
high_batch_facts = tf.sparse.retain(batch_facts, high_mask)
sp_fact_vec = tf.SparseTensor(
indices=tf.concat([sp_fact_vec.indices, high_batch_facts.indices], axis=0),
values=tf.concat([sp_fact_vec.values, high_batch_facts.values], axis=0),
dense_shape=[batch_size, fact_mips_config.num_facts]) # Update to next hop.
# Remove duplicate facts
sp_fact_vec = tf.sparse.reorder(sp_fact_vec)
uniq_fact_ids, uniq_fact_scs = model_utils.aggregate_sparse_indices(
sp_fact_vec.indices, sp_fact_vec.values, sp_fact_vec.dense_shape,
"max")
sp_fact_vec = tf.SparseTensor(uniq_fact_ids, uniq_fact_scs, sp_fact_vec.dense_shape)
# End Self Follow
# TODO: find a better way for this.
mask = tf.greater(sp_fact_vec.values, qa_config.fact_score_threshold)
sp_fact_vec = tf.sparse.retain(sp_fact_vec, mask)
else:
# For the first hop, then we use the init fact itself.
# Because the sparse retieval is already done from the question.
sp_fact_vec = batch_facts
# Note: Remove the previous hop's facts
# Note: Limit the number of fact followers.
# Dense: Aggregate the facts in each batch as a single fact embedding vector.
fact_embs = tf.gather(tf_fact_db, fact_ind) # len(fact_ind) X 2dim
# Note: check, does mean make sense?
# sum if it was softmaxed
# mean..
# del fact_scs # Not used for now.
fact_embs = fact_embs * tf.expand_dims(fact_scs, axis=1) #batch_fact.values
### Start of debugging w/ tf.Print ###
if is_printing:
fact_embs = tf.Print(
input_=fact_embs,
data=[tf.shape(batch_facts.indices)[0], batch_facts.indices],
message="\n\n###\nbatch_facts.indices and total #facts at hop %d \n" %
hop_id,
first_n=10,
summarize=50)
fact_embs = tf.Print(
input_=fact_embs,
data=[
batch_facts.values,
],
message="batch_facts.values at hop %d \n" % hop_id,
first_n=10,
summarize=25)
fact_embs = tf.Print(
input_=fact_embs,
data=[tf.shape(sp_fact_vec.indices)[0], sp_fact_vec.indices],
message="\n Sparse Fact Results @ hop %d \n" % hop_id +
" sp_fact_vec.indices at hop %d \n" % hop_id,
first_n=10,
summarize=50)
fact_embs = tf.Print(
input_=fact_embs,
data=[
sp_fact_vec.values,
],
message="sp_fact_vec.values at hop %d \n" % hop_id,
first_n=10,
summarize=25)
### End of debugging w/ tf.Print ###
# agg_emb = tf.math.unsorted_segment_mean(
agg_emb = tf.math.unsorted_segment_sum( # Soft Max fact scores
fact_embs, uniq_local_example_idx,
tf.shape(uniq_original_example_ind)[0])
batch_fact_emb = tf.scatter_nd(
tf.expand_dims(uniq_original_example_ind, 1), agg_emb,
tf.stack([batch_size, 2 * qa_config.projection_dim], axis=0))
# Each instance in a batch has onely one vector as the overall fact emb.
batch_fact_emb.set_shape([None, 2 * qa_config.projection_dim])
# Note: Normalize the embeddings if they are not from SoftMax.
# batch_fact_emb = tf.nn.l2_normalize(batch_fact_emb, axis=1)
# Dense scam search.
# [batch_size, 2 * dim]
# Note: reform query embeddings.
# scam_qrys = batch_fact_emb + tf.concat([relation_st_qry, relation_en_qry], axis=1)
# scam_qrys = batch_fact_emb
# scam_qrys = tf.concat([relation_st_qry, relation_en_qry], axis=1)
# scam_qrys = batch_fact_emb + hopwise_qry_seq_emb
# scam_qrys = hopwise_qry_seq_emb # TODO: check this later.
if hop_id > 0:
contextual_qry_emb = tf.concat([hopwise_qry_seq_emb, batch_fact_emb], axis=1)
scam_qrys = scam_projection_layer(contextual_qry_emb, 2 * qa_config.projection_dim, is_training, qa_config, str(hop_id))
else:
contextual_qry_emb = tf.concat([hopwise_qry_seq_emb, batch_fact_emb], axis=1)
scam_qrys = scam_projection_layer(contextual_qry_emb, 2 * qa_config.projection_dim, is_training, qa_config, str(hop_id))
# zero_batch_fact_emb = tf.zeros_like(batch_fact_emb, dtype=tf.float32)
# scam_qrys = scam_projection_layer(hopwise_qry_seq_emb, 2 * qa_config.projection_dim, is_training, qa_config, str(hop_id))
with tf.device("/cpu:0"):
# [batch_size, num_neighbors]
_, ret_fact_ids = fact_mips_search_fn(scam_qrys)
# [batch_size, num_neighbors, 2 * dim]
ret_fact_emb = tf.gather(tf_fact_db, ret_fact_ids)
if qa_config.l2_normalize_db:
ret_fact_emb = tf.nn.l2_normalize(ret_fact_emb, axis=2)
# [batch_size, 1, num_neighbors]
# The score of a fact is its innder product with qry.
ret_fact_scs = tf.matmul(
tf.expand_dims(scam_qrys, 1), ret_fact_emb, transpose_b=True)
# [batch_size, num_neighbors]
ret_fact_scs = tf.squeeze(ret_fact_scs, 1)
# [batch_size, num_facts] sparse
dense_fact_vec = model_utils.convert_search_to_vector(
ret_fact_scs, ret_fact_ids, tf.cast(batch_size, tf.int32),
fact_mips_config.num_neighbors, fact_mips_config.num_facts)
# Combine sparse and dense search.
if (is_training and qa_config.train_with_sparse) or (
(not is_training) and qa_config.predict_with_sparse):
# [batch_size, num_mentions] sparse
if qa_config.sparse_strategy == "dense_first":
ret_fact_vec = model_utils.sp_sp_matmul(dense_fact_vec, sp_fact_vec)
elif qa_config.sparse_strategy == "sparse_first":
with tf.device("/cpu:0"):
ret_fact_vec = model_utils.rescore_sparse(sp_fact_vec, tf_fact_db,
scam_qrys)
else:
raise ValueError("Unrecognized sparse_strategy %s" %
qa_config.sparse_strategy)
else:
# [batch_size, num_facts] sparse
ret_fact_vec = dense_fact_vec
# # Scaling facts with SoftMax.
ret_fact_vec = tf.sparse.reorder(ret_fact_vec)
scaled_facts = tf.SparseTensor(
indices=ret_fact_vec.indices,
values=ret_fact_vec.values/2, # TODO: add softmax temperature
dense_shape=ret_fact_vec.dense_shape)
ret_fact_vec_sf = tf.sparse.softmax(scaled_facts)
# Remove the facts which have scores lower than the threshold.
mask = tf.greater(ret_fact_vec_sf.values, qa_config.fact_score_threshold)
# TODO: use hp threshold
ret_fact_vec_sf_fitered = tf.sparse.retain(ret_fact_vec_sf, mask)
# Note: add a soft way to score (all) the entities based on the facts.
# Note: maybe use the pre-computed (tf-idf) similarity score here. e2e
# Retrieve entities before Fact-SoftMaxing
if is_training:
infer_agg_method = qa_config.entity_score_aggregation_fn
ret_entities_nosc = model_utils.sparse_ragged_mul(
scaled_facts, # Use the non-filtered scores of the retrieved facts.
fact2ent_ind,
fact2ent_val,
batch_size,
qa_config.num_entities,
infer_agg_method,
threshold=None,
fix_values_to_one=False) # TODO: check if to use True here.
if infer_agg_method == "sum":
clipped_values = tf.clip_by_value(ret_entities_nosc.values, clip_value_min=-100, clip_value_max=100) + 100.001
ret_entities = tf.SparseTensor(
indices=ret_entities_nosc.indices,
# values=tf.math.log(tf.math.sqrt(50.001+clipped_values)), # when it's sum
values=tf.math.sqrt(clipped_values)/7, # when it's sum
# values=tf.math.log(clipped_values+100), # when it's sum
# values=ret_entities_nosc.values, # when it's max/mean
dense_shape=ret_entities_nosc.dense_shape)
else:
ret_entities = ret_entities_nosc
else:
# Inference with another method
infer_agg_method = qa_config.entity_score_aggregation_fn # TODO: use a hp later.
ret_entities_nosc = model_utils.sparse_ragged_mul(
scaled_facts, # Use the non-filtered scores of the retrieved facts.
# sp_fact_vec, # TODO: only for debug. disable dense re-ranking
fact2ent_ind,
fact2ent_val,
batch_size,
qa_config.num_entities,
infer_agg_method, # TODO: use a hp later.
threshold=None,
fix_values_to_one=False) # TODO: check if to use True here.
if infer_agg_method == "sum":
clipped_values = tf.clip_by_value(ret_entities_nosc.values, clip_value_min=-100, clip_value_max=100) + 100.001
ret_entities = tf.SparseTensor(
indices=ret_entities_nosc.indices,
# values=tf.math.log(tf.math.sqrt(50.001+clipped_values)), # when it's sum
values=tf.math.sqrt(clipped_values)/7, # when it's sum
# values=tf.math.log(clipped_values+100), # when it's sum
# values=ret_entities_nosc.values, # when it's max/mean
dense_shape=ret_entities_nosc.dense_shape)
else:
ret_entities = ret_entities_nosc
### Start of debugging w/ tf.Print ###
if is_printing:
tmp_vals = ret_entities.values
tmp_vals = tf.Print(
input_=tmp_vals,
data=[tf.shape(batch_fact_emb), batch_fact_emb],
message="\n\n- batch_fact_emb at hop %d \n" % hop_id,
first_n=10,
summarize=100)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[tf.shape(scam_qrys), scam_qrys],
message="\n\n- scam_qrys at hop %d \n" % hop_id,
first_n=10,
summarize=100)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[tf.shape(ret_fact_vec.indices), ret_fact_vec.indices],
message="\n\n-rescored- ret_fact_vec.indices at hop %d \n" % hop_id,
first_n=10,
summarize=51)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
ret_fact_vec.values,
],
message="-rescored- ret_fact_vec.values at hop %d \n" % hop_id,
first_n=10,
summarize=25)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
ret_fact_vec_sf.values,
],
message="ret_fact_vec_sf.values at hop %d \n" % hop_id,
first_n=10,
summarize=25)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(ret_fact_vec_sf_fitered.indices),
tf.shape(ret_fact_vec_sf_fitered.values),
ret_fact_vec_sf_fitered.values,
],
message="ret_fact_vec_sf_fitered.values at hop %d \n" % hop_id,
first_n=10,
summarize=25)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[tf.shape(ret_entities.indices)[0], ret_entities.indices],
message="ret_entities.indices at hop %d \n" % hop_id,
first_n=10,
summarize=25)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(ret_entities.values),
ret_entities.values,
],
message="ret_entities.values at hop %d \n" % hop_id,
first_n=10,
summarize=25)
ret_entities = tf.SparseTensor(
indices=ret_entities.indices,
values=tmp_vals,
dense_shape=ret_entities.dense_shape)
### End of debugging w/ tf.Print ###
return ret_entities, ret_fact_vec_sf_fitered, None, None
def hopwise_qry_encoder(qry_seq_emb,
qry_input_ids,
qry_input_mask,
is_training,
bert_config,
qa_config,
suffix="",
project=True,
project_dim=None):
"""Embed query into vectors for dense retrieval for a hop."""
dropout = qa_config.dropout if is_training else 0.0
if project and not project_dim:
project_dim = qa_config.projection_dim
attention_mask = modeling.create_attention_mask_from_input_mask(
qry_input_ids, qry_input_mask)
# hop-wise question encoder
with tf.variable_scope("qry/hop" + suffix, reuse=tf.AUTO_REUSE):
hopwise_qry_seq_emb = modeling.transformer_model(
input_tensor=qry_seq_emb,
attention_mask=attention_mask,
hidden_size=bert_config.hidden_size,
num_hidden_layers=1,
num_attention_heads=bert_config.num_attention_heads,
intermediate_size=bert_config.intermediate_size,
intermediate_act_fn=modeling.get_activation(bert_config.hidden_act),
hidden_dropout_prob=dropout,
attention_probs_dropout_prob=dropout,
initializer_range=bert_config.initializer_range,
do_return_all_layers=False)
hopwise_qry_seq_emb = tf.squeeze(hopwise_qry_seq_emb[:, 0:1, :], axis=1)
if project and project_dim is not None:
with tf.variable_scope("projection"):
hopwise_qry_seq_emb = contrib_layers.fully_connected(
hopwise_qry_seq_emb,
project_dim,
activation_fn=tf.nn.tanh,
reuse=tf.AUTO_REUSE,
scope="qry_projection")
return hopwise_qry_seq_emb
def multi_hop_fact(qry_input_ids,
qry_input_mask,
qry_entity_ids,
init_fact_ids,
init_fact_scores,
entity_ids,
entity_mask,
ent2fact_ind,
ent2fact_val,
fact2ent_ind,
fact2ent_val,
fact2fact_ind,
fact2fact_val,
is_training,
use_one_hot_embeddings,
bert_config,
qa_config,
fact_mips_config,
num_hops,
exclude_set=None,
is_printing=True,
sup_fact_index_list=None,
):
"""Multi-hops of propagation from input to output facts.
Args:
qry_input_ids:
qry_input_mask:
qry_entity_ids:
entity_ids: (entity_word_ids) [num_entities, max_entity_len] Tensor holding
word ids of each entity.
entity_mask: (entity_word_masks) [num_entities, max_entity_len] Tensor with
masks into word ids above.
ent2fact_ind:
ent2fact_val:
fact2ent_ind:
fact2ent_val:
fact2fact_ind:
fact2fact_val:
is_training:
use_one_hot_embeddings:
bert_config:
qa_config:
fact_mips_config:
num_hops:
exclude_set:
is_printing:
sup_fact_index_list:
Returns:
layer_entities:
layer_facts:
layer_dense:
layer_sp:
batch_entities_nosc:
qry_seq_emb:
"""
del exclude_set # Not used for now.
# for embedding of concepts
with tf.variable_scope("qry/bow"):
# Note: trainable word weights over the BERT vocab for encoding concepts
word_weights = tf.get_variable(
"word_weights", [bert_config.vocab_size, 1],
dtype=tf.float32,
initializer=tf.ones_initializer()) # Inited as all ones.
# MIPS search for facts. Build fact feature Database
with tf.device("/cpu:0"):
tf_fact_db, fact_mips_search_fn = search_utils.create_mips_searcher(
fact_mips_config.ckpt_var_name,
# [fact_mips_config.num_facts, fact_mips_config.emb_size],
fact_mips_config.ckpt_path,
fact_mips_config.num_neighbors,
local_var_name="scam_init_barrier_fact")
qry_seq_emb, word_emb_table, qry_hidden_size = model_utils.shared_qry_encoder_v2(
qry_input_ids, qry_input_mask, is_training, use_one_hot_embeddings,
bert_config, qa_config)
batch_size = tf.shape(qry_input_ids)[0]
# Get question entities w/o scores.
batch_qry_entities = tf.SparseTensor(
indices=tf.concat([
qry_entity_ids.indices[:, 0:1],
tf.cast(tf.expand_dims(qry_entity_ids.values, 1), tf.int64)
],
axis=1),
values=tf.ones_like(qry_entity_ids.values, dtype=tf.float32),
dense_shape=[batch_size, qa_config.num_entities])
def get_init_facts():
"""Prepares initial facts. (new: from pre-computed init facts & scores)."""
init_facts = tf.SparseTensor(
indices=tf.concat([
init_fact_ids.indices[:, 0:1],
tf.cast(tf.expand_dims(init_fact_ids.values, 1), tf.int64)
],
axis=1),
# values=tf.ones_like(init_fact_ids.values, dtype=tf.float32),
values=init_fact_scores.values,
dense_shape=[batch_size, fact_mips_config.num_facts])
init_facts = tf.sparse.reorder(init_facts)
scaled_facts = tf.SparseTensor(
indices=init_facts.indices,
values=init_facts.values / 30,
# TODO: add softmax temperature
dense_shape=init_facts.dense_shape)
final_initial_facts = tf.sparse.softmax(scaled_facts)
if is_printing:
tmp_vals = final_initial_facts.values
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(init_facts.indices),
init_facts.indices,
],
message="-" * 100 + "\n\n## Initial Facts (at hop 0):\n"
"shape(initial_facts), initial_facts.indices,",
first_n=10,
summarize=52)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(init_facts.indices),
init_facts.values,
],
message="-" * 100 + "\n\n## Initial Facts (at hop 0):\n"
"shape(initial_facts), initial_facts.values,",
first_n=10,
summarize=52)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(final_initial_facts.indices),
final_initial_facts.indices,
],
message="-" * 100 + "\n\n## Initial Facts (at hop 0) SoftMax-ed:\n"
"shape(final_initial_facts), final_initial_facts.indices,",
first_n=10,
summarize=52)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(final_initial_facts.indices),
final_initial_facts.values,
],
message="-" * 100 + "\n\n## Initial Facts (at hop 0) SoftMax-ed:\n"
"shape(final_initial_facts), final_initial_facts.values,",
first_n=10,
summarize=52)
if is_training:
sup_fact_2hop_index = sup_fact_index_list[1]
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(sup_fact_2hop_index.indices),
sup_fact_2hop_index.indices,
],
message="-" * 100 + "\n\n## sup_fact_2hop_index:\n"
"shape(sup_fact_2hop_index), sup_fact_2hop_index.indices,",
first_n=10,
summarize=52)
tmp_vals = tf.Print(
input_=tmp_vals,
data=[
tf.shape(sup_fact_2hop_index.values),
sup_fact_2hop_index.values,
],
message="-" * 100 + "\n\n#shape(sup_fact_2hop_index.values), sup_fact_2hop_index.values,",
first_n=10,
summarize=52)
final_initial_facts = tf.SparseTensor(final_initial_facts.indices, tmp_vals,
final_initial_facts.dense_shape)
return init_facts, final_initial_facts
initial_facts, final_initial_facts = get_init_facts()
layer_facts, layer_entities = [], []
layer_dense, layer_sp = [], []
batch_facts = final_initial_facts
for hop in range(num_hops):
with tf.name_scope("hop_%d" % hop):
# The question start/end embeddings for each hop.
# qry_start_emb, qry_end_emb = model_utils.layer_qry_encoder(
# qry_seq_emb,
# qry_input_ids,
# qry_input_mask,
# is_training,
# bert_config,
# qa_config,
# suffix="_%d" % hop,
# project_dim=qa_config.projection_dim) # project=True
# hopwise_qry_seq_emb = tf.concat([qry_start_emb, qry_end_emb], axis=1)
# Option 2: The hop-wise additional layer.
# hopwise_qry_seq_emb = hopwise_qry_encoder(qry_seq_emb,
# qry_input_ids,
# qry_input_mask,
# is_training,
# bert_config,
# qa_config,
# suffix="_%d" % hop,
# project_dim=qa_config.projection_dim,
# project=False)
# Option 3: just use the original [CLS] token vector.
hopwise_qry_seq_emb = tf.squeeze(qry_seq_emb[:, 0:1, :], axis=1)
ret_entities, ret_facts, _, _ = follow_fact(
batch_facts, hopwise_qry_seq_emb, word_emb_table, word_weights,
fact2fact_ind, fact2fact_val, fact2ent_ind, fact2ent_val,
fact_mips_search_fn, tf_fact_db, fact_mips_config, qa_config,
is_training, hop, is_printing)
if is_training and hop == 1: # after the first hop, we need to add the 2nd-sup facts for computing the loss
# TODO: print the num of intersections here?
# sup_fact_2hop_index = sup_fact_index_list[1]
# ret_facts = tf.SparseTensor(
# indices=tf.concat([ret_facts.indices, sup_fact_2hop_index.indices], axis=0),
# values=tf.concat([ret_facts.values, sup_fact_2hop_index.values], axis=0),
# dense_shape=[batch_size, fact_mips_config.num_facts]) # Update to next hop.
# Do we need to make them unique?
# How do we set the softmax scores for the newly added facts?
# Actually, we have made sure that the f2f will include the truth facts.
# It is just because that we haven't
batch_facts = ret_facts
else:
batch_facts = ret_facts # Update to next hop.
# Update results.
layer_facts.append(ret_facts)
layer_entities.append(ret_entities)
tf.logging.info("len layer_facts: %d", len(layer_facts))
tf.logging.info("len layer_entities: %d", len(layer_entities))
return (layer_entities, layer_facts, layer_dense, layer_sp,
batch_qry_entities, final_initial_facts, qry_seq_emb)
def multi_hop_mention(qry_input_ids,
qry_input_mask,
qry_entity_ids,
entity_ids,
entity_mask,
ent2ment_ind,
ent2ment_val,
ment2ent_map,
is_training,
use_one_hot_embeddings,
bert_config,
qa_config,
mips_config,
num_hops,
exclude_set=None,
bridge_mentions=None,
answer_mentions=None): # answer mentions?
"""Multi-hops of propagation from input to output entities.
Args:
qry_input_ids:
qry_input_mask:
qry_entity_ids:
entity_ids: (entity_word_ids) [num_entities, max_entity_len] Tensor holding
word ids of each entity.
entity_mask: (entity_word_masks) [num_entities, max_entity_len] Tensor with
masks into word ids above.
ent2ment_ind:
ent2ment_val:
ment2ent_map:
is_training:
use_one_hot_embeddings:
bert_config:
qa_config:
mips_config:
num_hops:
exclude_set:
bridge_mentions:
answer_mentions:
Returns:
layer_entities:
layer_mentions:
layer_dense:
layer_sp:
batch_entities_nosc:
qry_seq_emb:
"""
# for question BOW embedding
with tf.variable_scope("qry/bow"):
# Note: trainable word weights over the BERT vocab for query
word_weights = tf.get_variable(
"word_weights", [bert_config.vocab_size, 1],
dtype=tf.float32,
initializer=tf.ones_initializer())
# Note: we can use the [CLS] token here?
qry_seq_emb, word_emb_table, qry_hidden_size = model_utils.shared_qry_encoder_v2(
qry_input_ids, qry_input_mask, is_training, use_one_hot_embeddings,
bert_config, qa_config)
batch_size = tf.shape(qry_input_ids)[0]
# Multiple entities per question. We need to re-score.
with tf.name_scope("entity_linking"):
batch_entity_emb = model_utils.entity_emb(
tf.cast(qry_entity_ids.values, tf.int64), entity_ids, entity_mask,
word_emb_table, word_weights) # question entity embeddings.
# Embed query into start and end vectors for dense retrieval for a hop.
qry_el_emb, _ = model_utils.layer_qry_encoder( # question embeddings
qry_seq_emb,
qry_input_ids,
qry_input_mask,
is_training,
bert_config,
qa_config,
suffix="_el",
project=False)
batch_qry_el_emb = tf.gather(qry_el_emb, qry_entity_ids.indices[:, 0])
batch_entity_el_scs = tf.reduce_sum(batch_qry_el_emb * batch_entity_emb, -1)
batch_entities_nosc = tf.SparseTensor(
# Note: double check this.
indices=tf.concat([
qry_entity_ids.indices[:, 0:1],
tf.cast(tf.expand_dims(qry_entity_ids.values, 1), tf.int64)
],
axis=1),
values=batch_entity_el_scs,
dense_shape=[batch_size, qa_config.num_entities])
batch_entities = tf.sparse.softmax(tf.sparse.reorder(batch_entities_nosc))
ensure_mentions = bridge_mentions # Note: check "supporoting facts"
with tf.device("/cpu:0"):
# MIPS search for mentions. Mention Feature Database
tf_db, mips_search_fn = search_utils.create_mips_searcher(
mips_config.ckpt_var_name,
# [mips_config.num_mentions, mips_config.emb_size],
mips_config.ckpt_path,
mips_config.num_neighbors,
local_var_name="scam_init_barrier")
layer_mentions, layer_entities = [], []
layer_dense, layer_sp = [], []
for hop in range(num_hops):
with tf.name_scope("hop_%d" % hop):
# Note: the question start/end embeddings for each hop?
qry_start_emb, qry_end_emb = model_utils.layer_qry_encoder(
qry_seq_emb,
qry_input_ids,
qry_input_mask,
is_training,
bert_config,
qa_config,
suffix="_%d" % hop) # project=True
(ret_entities, ret_mentions,
dense_mention_vec, sp_mention_vec) = follow_mention(
batch_entities, qry_start_emb, qry_end_emb, entity_ids, entity_mask,
ent2ment_ind, ent2ment_val, ment2ent_map, word_emb_table,
word_weights, mips_search_fn, tf_db, bert_config.hidden_size,
mips_config, qa_config, is_training, ensure_mentions)
# Note: check this. Shouldn't for wrong choices.
if exclude_set:
# batch_ind = tf.expand_dims(tf.range(batch_size), 1)
exclude_indices = tf.concat([
tf.cast(exclude_set.indices[:, 0:1], tf.int64),
tf.cast(tf.expand_dims(exclude_set.values, 1), tf.int64)