This repository has been archived by the owner on Sep 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfft_tree_constrained_inference.py
1708 lines (1316 loc) · 66 KB
/
fft_tree_constrained_inference.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
# Copyright 2016 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Inference routine for k-cardinality- and tree-constrained graphical models.
WARNING: This code is very experimental and if you choose to use it, you should
be very sure that's what you want.
This implements a tree-knapsack marginal inference and sampling algorithm
based on the "major extension" model of Tarlow et al.,
"Fast Exact Inference for Recursive Cardinality Models"
http://www.cs.toronto.edu/~dtarlow/tszaf-fast_cardinality.pdf
This supports inference over a set of binary token variables, each associated
to a token span. The spans are arranged hierarchically in a tree with the
constraint that each span can only be active if its parent span is also active.
Additionally, all token variables are subject to a k-cardinality constraint.
"""
from __future__ import absolute_import
# this will break a lot of stuff with tf.pad, etc. if uncommented
# from __future__ import division
from __future__ import print_function
import math
import numpy as np
import tensorflow as tf
import data
import discourse_tree as d_t
import fft_tree_indep_inference as ffttii
import model_base
import shared_util as su
# use 16bit ints instead of 32bit for now because of numerical issues
tf_int8 = tf.int8
tf_int16 = tf.int32
tf_int32 = tf.int32
np_int8 = np.int8
np_int16 = np.int32
np_int32 = np.int32
tf_real = tf.float32
def padded_gather_nd(params, indices, r, idx_rank):
"""Version of gather_nd that supports gradients and blank indices.
Works like gather_nd, but if an index is given as -1, a 0 will be inserted
in that spot in the output tensor.
Args:
params: tensor from which to gather (see gather_nd).
indices: tensor of indices (see gather_nd).
r: rank of params
idx_rank: rank of indices
Returns:
result: tensor shaped like indices containing things gathered from params
"""
# treats -1 indices as always gathering zeros
# pad 0 onto beginning of final dim of params
broadcasted_shift = tf.reshape(
tf.one_hot(
[r - 1], r, dtype=tf.int32), [1] * (idx_rank - 1) + [r])
shifted_idx = indices + broadcasted_shift
# unused indices might contain garbage, just 0 this out
shifted_idx = tf.maximum(0, shifted_idx)
padded_params = tf.pad(params, [[0, 0]] * (r - 1) + [[1, 0]])
# no gather_nd for now because gradient doesn't work
# return tf.gather_nd(padded_params,shifted_idx)
# HACK: work around lack of gradient for gather_nd
# params has shape of rank r
# indices has shape of rank idx_rank
params_shape = [d.value for d in padded_params.get_shape()]
idx_shape = [d.value for d in shifted_idx.get_shape()]
flat_params_x_size = 1
for dim in params_shape:
flat_params_x_size *= dim
flat_idx_x_size = 1
for dim in idx_shape[:-1]:
flat_idx_x_size *= dim
index_strides = tf.concat(
0, [tf.cumprod(
params_shape[1:], reverse=True), [1]])
index_strides = tf.reshape(index_strides, [1] * (idx_rank - 1) + [-1])
flat_idx = tf.reduce_sum(shifted_idx * index_strides, idx_rank - 1)
flat_idx = tf.reshape(flat_idx, [flat_idx_x_size])
flat_params = tf.reshape(padded_params, [flat_params_x_size])
result = tf.gather(flat_params, flat_idx)
result = tf.reshape(result, idx_shape[:-1])
return result
def to_int8(t):
if isinstance(t, list):
return [tf.cast(tt, tf_int8) for tt in t]
return tf.cast(t, tf_int8)
def to_int16(t):
if isinstance(t, list):
return [tf.cast(tt, tf_int16) for tt in t]
return tf.cast(t, tf_int16)
def to_int32(t):
if isinstance(t, list):
return [tf.cast(tt, tf_int32) for tt in t]
return tf.cast(t, tf_int32)
class TreeConstrainedInferencer(object):
"""Graph to perform tree-constrained inference."""
def do_tree_inference(self, hps, tree_inference_inputs, word_logits):
"""Perform tree-constrained inference on token inputs.
Args:
hps: bag of hyperparameters.
tree_inference_inputs: a TreeInferenceInputs graph containing placeholders
for the various tensors describing a batch of differently shaped trees,
and the graph edges and nodes involved in message-passing inference.
word_logits: batch of scores for each word token.
Returns:
tok_marg: batch of node-marginals for each binary token indicator.
tok_samples: batch of samples for each binary token indicator.
log_z: batch of log-partition function values for each graphical model.
"""
word_logits_padded = tf.pad(word_logits, tf.pack(
[[0, 0],
[0, hps.num_art_steps - tree_inference_inputs.article_max_len]]))
word_logits_padded.set_shape([hps.batch_size, hps.num_art_steps])
logit_mask = su.create_log_mask(
tf.maximum(1, tree_inference_inputs.article_len), hps.num_art_steps)
masked_word_logits = word_logits_padded + logit_mask
# get "integrated logits" to compute fast span sums
integrated_logits = tf.pad(tf.cumsum(
masked_word_logits, axis=1), [[0, 0], [1, 0]])
span_start_idx = tree_inference_inputs.span_start_idx
span_end_idx = tree_inference_inputs.span_end_idx
# expand dim since we are gathering only 1 thing
span_integrated_scores_start = padded_gather_nd(
integrated_logits, tf.expand_dims(span_start_idx, 2), 2, 4)
span_integrated_scores_end = padded_gather_nd(
integrated_logits, tf.expand_dims(span_end_idx, 2), 2, 4)
span_scores = span_integrated_scores_end - span_integrated_scores_start
span_scores = tf.reshape(span_scores, [hps.batch_size, hps.max_num_spans])
span_marg, span_samples, log_z = self.do_span_inference(
hps, tree_inference_inputs, span_scores)
# grab the span margs and samples out into the token margs and samples
# expand dim since we are gathering only 1 thing
span_idx_for_tok_marg = tf.expand_dims(
tree_inference_inputs.span_idx_for_tok_marg, 2)
span_idx_for_tok_samples = replicate_samples_2(span_idx_for_tok_marg,
hps.num_samples)
span_idx_for_tok_samples = add_leading_idx_2(span_idx_for_tok_samples)
span_idx_for_tok_marg = add_leading_idx_1(span_idx_for_tok_marg)
tok_marg = padded_gather_nd(span_marg, span_idx_for_tok_marg, 2, 4)
tok_samples = padded_gather_nd(span_samples, span_idx_for_tok_samples, 3, 5)
return tok_marg, tok_samples, log_z
def do_span_inference(self, hps, tree_inference_inputs, span_scores):
"""Perform tree-constrained inference on span inputs.
Args:
hps: bag of hyperparameters.
tree_inference_inputs: a TreeInferenceInputs graph containing placeholders
for the various tensors describing a batch of differently shaped trees,
and the graph edges and nodes involved in message-passing inference.
span_scores: batch of scores for each span of tokens in the parse.
Returns:
span_marg: batch of node-marginals for each binary span indicator.
span_samples: batch of samples for each binary span indicator.
log_z: batch of log-partition function values for each graphical model.
"""
# start from the bottom
init_span_beliefs = tf.exp(span_scores)
max_depth = len(hps.tree_widths_at_level)
# add extra indices for gather_nd-ing and tile out samples
span_off_to_node_msg = tree_inference_inputs.span_off_to_node_msg
span_on_to_node_msg = tree_inference_inputs.span_on_to_node_msg
span_belief_to_node_idx = add_all_leading_idx_1(
to_int32(tree_inference_inputs.span_belief_to_node_idx))
nodes_up_to_sum_tree_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.nodes_up_to_sum_tree_idx))
nodes_up_to_sum_tree_log_z_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.nodes_up_to_sum_tree_log_z_idx))
sum_tree_msg_start_depths = to_int32(
tree_inference_inputs.sum_tree_msg_start_depths)
sum_tree_msg_end_depths = to_int32(
tree_inference_inputs.sum_tree_msg_end_depths)
sum_tree_up_to_parent_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.sum_tree_up_to_parent_idx))
sum_tree_up_to_parent_log_z_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.sum_tree_up_to_parent_log_z_idx))
sum_tree_down_to_nodes_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.sum_tree_down_to_nodes_idx))
node_to_span_off_belief_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.node_to_span_off_belief_idx))
node_to_span_on_belief_range_idx = to_int32(
tree_inference_inputs.node_to_span_on_belief_range_idx)
node_to_span_on_belief_start_idx = []
node_to_span_on_belief_end_idx = []
for nsbrgi in node_to_span_on_belief_range_idx:
starts, ends = tf.split(3, 2, nsbrgi)
node_to_span_on_belief_start_idx.append(starts)
node_to_span_on_belief_end_idx.append(ends)
node_to_span_on_belief_start_idx = add_all_leading_idx_2(
node_to_span_on_belief_start_idx)
node_to_span_on_belief_end_idx = add_all_leading_idx_2(
node_to_span_on_belief_end_idx)
parent_on_down_to_sum_tree_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.parent_on_down_to_sum_tree_idx))
parent_off_down_to_sum_tree_idx = add_all_leading_idx_2(
to_int32(tree_inference_inputs.parent_off_down_to_sum_tree_idx))
global_sum_tree_msg_start_depths = to_int32(
tree_inference_inputs.global_sum_tree_msg_start_depths)
global_sum_tree_msg_end_depths = to_int32(
tree_inference_inputs.global_sum_tree_msg_end_depths)
node_up_to_global_idx = add_leading_idx_1(
to_int32(tree_inference_inputs.node_up_to_global_idx))
node_up_to_global_log_z_idx = add_leading_idx_1(
to_int32(tree_inference_inputs.node_up_to_global_log_z_idx))
global_down_to_node_idx = add_leading_idx_1(
to_int32(tree_inference_inputs.global_down_to_node_idx))
span_off_belief_to_span_off_marginal_idx = add_leading_idx_1(
to_int32(
tree_inference_inputs.span_off_belief_to_span_off_marginal_idx))
node_sample_to_span_off_belief_sample_idx = add_all_leading_idx_3(
replicate_all_samples_3(
to_int32(tree_inference_inputs.node_to_span_off_belief_idx),
hps.num_samples))
parent_on_sample_down_to_sum_tree_idx = add_all_leading_idx_3(
replicate_all_samples_3(
to_int32(tree_inference_inputs.parent_on_down_to_sum_tree_idx),
hps.num_samples))
parent_off_sample_down_to_sum_tree_idx = add_all_leading_idx_3(
replicate_all_samples_3(
to_int32(tree_inference_inputs.parent_off_down_to_sum_tree_idx),
hps.num_samples))
sum_tree_sample_down_to_nodes_idx = add_all_leading_idx_3(
replicate_all_samples_3(
to_int32(tree_inference_inputs.sum_tree_down_to_nodes_idx),
hps.num_samples))
global_down_to_node_sample_idx = add_leading_idx_2(
replicate_samples_2(
to_int32(tree_inference_inputs.global_down_to_node_idx),
hps.num_samples))
span_sample_off_belief_to_span_sample_off_marginal_idx = add_leading_idx_2(
replicate_samples_2(
to_int32(
tree_inference_inputs.span_off_belief_to_span_off_marginal_idx),
hps.num_samples))
# Handle base case of forward inference pass
init_node_beliefs = (
span_off_to_node_msg[0] + span_on_to_node_msg[0] * padded_gather_nd(
init_span_beliefs, span_belief_to_node_idx[0], 2, 4))
cur_node_out_up_msg = init_node_beliefs
cur_node_out_log_zs = tf.to_float(tf.zeros_like(cur_node_out_up_msg))
sum_tree_layers = []
parent_constraint_layers = []
for d in xrange(1, max_depth):
# Sum up siblings at current level
cur_fft_tree_width = hps.fft_tree_widths_at_level[max_depth - d - 1]
cur_sum_tree_msg_start_depths = sum_tree_msg_start_depths[d - 1]
cur_sum_tree_msg_end_depths = sum_tree_msg_end_depths[d - 1]
cur_sum_tree_layer = SiblingSumTreeLayer(
hps.batch_size,
hps.max_num_sentences,
hps.num_samples,
cur_fft_tree_width,
cur_sum_tree_msg_start_depths,
cur_sum_tree_msg_end_depths,
layer_depth=str(d),
message_damp_lambda=hps.fft_tree_msg_damp_lambdas[max_depth - d - 1])
cur_sum_tree_inc_up_msg = padded_gather_nd(
cur_node_out_up_msg, nodes_up_to_sum_tree_idx[d - 1], 3, 4)
cur_sum_tree_inc_log_zs = padded_gather_nd(
cur_node_out_log_zs, nodes_up_to_sum_tree_log_z_idx[d - 1], 3, 4)
# pylint: disable=line-too-long
sum_tree_out_up_msg, sum_tree_out_log_zs = cur_sum_tree_layer.compute_up_msg(
cur_sum_tree_inc_up_msg, cur_sum_tree_inc_log_zs)
# pylint: enable=line-too-long
sum_tree_layers.append(cur_sum_tree_layer)
# Apply parent constraints at current level
cur_parent_constraint_layer = ParentConstraintLayer(
init_span_beliefs, layer_depth=str(d))
parent_constraint_layers.append(cur_parent_constraint_layer)
# pylint: disable=line-too-long
cur_node_out_up_msg, cur_node_out_log_zs = cur_parent_constraint_layer.compute_up_msg(
sum_tree_out_up_msg, sum_tree_up_to_parent_idx[d - 1],
sum_tree_up_to_parent_log_z_idx[d - 1], span_belief_to_node_idx[d],
span_off_to_node_msg[d], span_on_to_node_msg[d], sum_tree_out_log_zs)
# pylint: enable=line-too-long
# Sentence-level forward pass done
# now we have the upward messages for each sentence
up_msg_by_sentence = cur_node_out_up_msg
up_log_zs_by_sentence = cur_node_out_log_zs
# Sum up the running log z across sentences and give an extra dim for
# the global "sentence"
# Since sum-trees expect a "sentence" dimension
global_up_sum_tree_inc_log_zs = padded_gather_nd(
up_log_zs_by_sentence, node_up_to_global_log_z_idx, 3, 3)
global_up_sum_tree_inc_msg = padded_gather_nd(up_msg_by_sentence,
node_up_to_global_idx, 3, 3)
if not hps.single_sentence_concat:
global_sum_tree_layer = SiblingSumTreeLayer(
hps.batch_size,
1,
hps.num_samples,
hps.global_fft_tree_width,
global_sum_tree_msg_start_depths,
global_sum_tree_msg_end_depths,
layer_depth="global")
# pylint: disable=line-too-long
global_sum_tree_out_up_msg, global_sum_tree_out_up_log_zs = global_sum_tree_layer.compute_up_msg(
global_up_sum_tree_inc_msg, global_up_sum_tree_inc_log_zs)
# pylint: enable=line-too-long
global_sum_tree_out_up_msg = tf.reshape(global_sum_tree_out_up_msg,
[hps.batch_size, -1])
running_log_zs = tf.reshape(global_sum_tree_out_up_log_zs,
[hps.batch_size, -1])
else:
running_log_zs = tf.reshape(global_up_sum_tree_inc_log_zs,
[hps.batch_size, -1])
global_sum_tree_out_up_msg = global_up_sum_tree_inc_msg
running_log_z = tf.reshape(running_log_zs, [hps.batch_size, -1])
running_log_z = tf.reshape(
tf.slice(running_log_z, [0, 0], [hps.batch_size, 1]),
[hps.batch_size, 1])
with tf.name_scope("k_beliefs"):
# TODO(lvilnis@) insert different type of cardinality potential here!
# this might not encourage long enough summaries.
if hps.single_sentence_concat:
k_pot_msg = su.create_mask(tree_inference_inputs.abstract_len + 1,
hps.global_fft_tree_width)
k_pot_msg -= su.create_mask(tree_inference_inputs.abstract_len * 0 + 1,
hps.global_fft_tree_width)
else:
k_pot_msg = su.create_mask(tree_inference_inputs.abstract_len,
hps.global_fft_tree_width)
k_belief, _, log_k_z = su.normalize_and_log(k_pot_msg *
global_sum_tree_out_up_msg)
running_log_z += log_k_z
running_log_z = tf.reshape(running_log_z, [hps.batch_size])
# with cardinality beliefs, start downward message passing
with tf.name_scope("k_samples"):
rep_k_b = su.repeat(hps.num_samples, k_belief)
rep_k_b = tf.reshape(rep_k_b, [hps.num_samples, hps.batch_size, -1])
rep_k_b = tf.transpose(rep_k_b, [1, 0, 2])
rep_k_b = tf.reshape(rep_k_b, [hps.batch_size * hps.num_samples, -1])
k_samples, _ = su.sample_categorical(tf.log(rep_k_b))
k_samples = tf.reshape(k_samples, [hps.batch_size, hps.num_samples, -1])
# compute the global samples and global downward messages
self.k_samples = k_samples
if not hps.single_sentence_concat:
k_pot_msg = tf.reshape(k_pot_msg, [hps.batch_size, 1, -1])
k_samples = tf.reshape(k_samples,
[hps.batch_size, 1, hps.num_samples, -1])
global_sum_tree_down_msgs, _ = global_sum_tree_layer.compute_down_msg(
k_pot_msg)
global_sum_tree_down_samples = global_sum_tree_layer.compute_down_samples(
k_samples)
global_sum_tree_down_msgs = tf.reshape(global_sum_tree_down_msgs,
[hps.batch_size, -1])
global_sum_tree_down_samples = tf.reshape(
global_sum_tree_down_samples, [hps.batch_size, hps.num_samples, -1])
else:
global_sum_tree_down_msgs = k_pot_msg
global_sum_tree_down_samples = k_samples
# now we gather down to per-sentence messages and samples
cur_node_inc_down_msg = padded_gather_nd(global_sum_tree_down_msgs,
global_down_to_node_idx, 2, 4)
cur_node_inc_down_samples = padded_gather_nd(global_sum_tree_down_samples,
global_down_to_node_sample_idx,
3, 5)
# This is stored as [batch,sample,sentence,node] so we need to transpose
cur_node_inc_down_samples = tf.transpose(cur_node_inc_down_samples,
[0, 2, 1, 3])
# stores [batch,sentence,width] span_off_marginals for each depth
all_span_off_marginals = []
# stores [batch,sentence,sample,width] span_off_samples for each depth
all_span_off_samples = []
for d in reversed(xrange(1, max_depth)):
cur_parent_constraint_layer = parent_constraint_layers[d - 1]
cur_sum_tree_layer = sum_tree_layers[d - 1]
# pylint: disable=line-too-long
cur_span_off_marginals, sum_tree_out_down_msg = cur_parent_constraint_layer.compute_down_msg(
cur_node_inc_down_msg, node_to_span_off_belief_idx[max_depth - d - 1],
node_to_span_on_belief_start_idx[max_depth - d - 1],
node_to_span_on_belief_end_idx[max_depth - d - 1],
parent_on_down_to_sum_tree_idx[max_depth - d - 1],
parent_off_down_to_sum_tree_idx[max_depth - d - 1])
cur_span_off_samples, sum_tree_out_down_samples = cur_parent_constraint_layer.compute_down_samples(
cur_node_inc_down_samples,
node_sample_to_span_off_belief_sample_idx[max_depth - d - 1],
parent_on_sample_down_to_sum_tree_idx[max_depth - d - 1],
parent_off_sample_down_to_sum_tree_idx[max_depth - d - 1])
# pylint: enable=line-too-long
all_span_off_marginals.append(cur_span_off_marginals)
all_span_off_samples.append(cur_span_off_samples)
cur_sum_tree_inc_down_msg, _ = cur_sum_tree_layer.compute_down_msg(
sum_tree_out_down_msg)
cur_sum_tree_inc_down_samples = cur_sum_tree_layer.compute_down_samples(
sum_tree_out_down_samples)
cur_node_inc_down_msg = padded_gather_nd(
cur_sum_tree_inc_down_msg, sum_tree_down_to_nodes_idx[max_depth - d],
3, 4)
cur_node_inc_down_samples = padded_gather_nd(
cur_sum_tree_inc_down_samples,
sum_tree_sample_down_to_nodes_idx[max_depth - d], 4, 5)
# Handle the base case for the final part of sampling
bottom_span_off_samples = padded_gather_nd(
cur_node_inc_down_samples,
node_sample_to_span_off_belief_sample_idx[-1], 4, 5)
all_span_off_samples.append(bottom_span_off_samples)
# Handle the base case for the final part of message passing
bottom_node_beliefs = cur_node_inc_down_msg * init_node_beliefs
bottom_span_off_beliefs = padded_gather_nd(bottom_node_beliefs,
node_to_span_off_belief_idx[-1],
3, 4)
bottom_span_off_marginals = bottom_span_off_beliefs
# Get "integrated" beliefs for easy sums over spans
integrated_bottom_beliefs = tf.cumsum(bottom_node_beliefs, 2)
span_on_start_cumulative_belief = padded_gather_nd(
integrated_bottom_beliefs, node_to_span_on_belief_start_idx[-1], 3, 4)
span_on_end_cumulative_belief = padded_gather_nd(
integrated_bottom_beliefs, node_to_span_on_belief_end_idx[-1], 3, 4)
bottom_span_on_beliefs = (
span_on_end_cumulative_belief - span_on_start_cumulative_belief)
bottom_span_belief_normalizer = (
bottom_span_on_beliefs + bottom_span_off_beliefs)
bottom_span_off_marginals = su.safe_divide(bottom_span_off_beliefs,
bottom_span_belief_normalizer)
all_span_off_marginals.append(bottom_span_off_marginals)
# Gather back out to the (batch,span_id) format
tree_marg_tensor = tf.concat(
2, [tf.expand_dims(ss, 2) for ss in all_span_off_marginals])
# switch off -> on
span_marginals = 1.0 - padded_gather_nd(
tree_marg_tensor, span_off_belief_to_span_off_marginal_idx, 4, 3)
tree_sample_tensor = tf.concat(
3, [tf.expand_dims(ss, 3) for ss in all_span_off_samples])
# We have [batch,sample,sent,depth,width] indices
# in the gather indices
# but tree_sample_tensor is [batch,sent,sample,depth,width]
# so we have to transpose
tree_sample_tensor = tf.transpose(tree_sample_tensor, [0, 2, 1, 3, 4])
# switch off -> on
span_samples = 1.0 - padded_gather_nd(
tree_sample_tensor,
span_sample_off_belief_to_span_sample_off_marginal_idx, 5, 4)
return span_marginals, span_samples, running_log_z
class TreeConstrainedExtractor(model_base.Extractor):
"""Implementation of Extractor interface using tree-constrained inference."""
def __init__(self, tree_inference_inputs, summarizer_features, hps):
self.hps = hps
article_max_len = tree_inference_inputs.article_max_len
batch_size = hps.batch_size
num_samples = hps.num_samples
self.word_logits = word_logits = tf.reshape(
self.get_extractor_logits(hps, tree_inference_inputs,
summarizer_features),
[hps.batch_size, hps.num_art_steps])
tree_inferencer = TreeConstrainedInferencer()
tok_marg, tok_samples, log_z = tree_inferencer.do_tree_inference(
hps, tree_inference_inputs, word_logits)
self.log_z = log_z
sliced_tok_marg = tf.slice(
tf.reshape(tok_marg, [hps.batch_size, hps.num_art_steps]), [0, 0],
[batch_size, article_max_len])
sliced_tok_marg *= tree_inference_inputs.article_sliced_mask
sliced_tok_samples = tf.slice(
tf.reshape(tok_samples,
[hps.batch_size, num_samples, hps.num_art_steps]), [0, 0, 0],
[batch_size, num_samples, article_max_len])
sliced_tok_samples *= tf.reshape(tree_inference_inputs.article_sliced_mask,
[batch_size, 1, -1])
log_prob_gold_words = tf.reduce_sum(
tf.to_float(tree_inference_inputs.sliced_extract_label) *
tf.reshape(word_logits, [batch_size, -1]), 1)
log_prob_gold_words -= log_z
self.gold_log_likelihood = log_prob_gold_words
log_prob_active_words = tf.reduce_sum(
tf.to_float(sliced_tok_samples) * tf.reshape(word_logits,
[batch_size, 1, -1]), 2)
log_prob_active_words -= tf.reshape(log_z, [batch_size, 1])
self.sample_log_likelihood = log_prob_active_words
self.marginals = sliced_tok_marg
self.map_prediction = sliced_tok_marg
self.samples = sliced_tok_samples
def get_extractor_logits(self, hps, tree_inference_inputs,
summarizer_features):
del hps, tree_inference_inputs # don't need these for simple extractor
return summarizer_features.word_logits
class ParentConstraintLayer(object):
"""Layer of batch junction tree expressing parent->child constraints.
Contains routines for message passing and sampling with this constraint.
Attributes:
init_span_beliefs: scores for spans on this level of tree.
layer_depth: string describing layer for logging.
"""
def __init__(self, init_span_beliefs, layer_depth=""):
self.init_span_beliefs = init_span_beliefs
self.layer_depth = layer_depth
def compute_down_samples(self, inc_node_samples,
node_sample_to_span_off_belief_sample_idx,
parent_on_sample_down_to_sum_tree_idx,
parent_off_sample_down_to_sum_tree_idx):
"""Compute downward samples for this layer of the tree.
Args:
inc_node_samples: incoming samples from parents.
node_sample_to_span_off_belief_sample_idx: map from sampled nodes at this
layer to corresponding span-off variables.
parent_on_sample_down_to_sum_tree_idx: map from sample of parent-on
variable to child variable.
parent_off_sample_down_to_sum_tree_idx: map from sample of parent-off
variable to child variable.
Returns:
span_off_samples: tensor of samples for span-off variables at this level.
off_samples: tensor of samples for outgoing child variables.
"""
span_off_samples = padded_gather_nd(
inc_node_samples, node_sample_to_span_off_belief_sample_idx, 4, 5)
out_samples = padded_gather_nd(inc_node_samples,
parent_on_sample_down_to_sum_tree_idx, 4, 5)
out_samples += padded_gather_nd(inc_node_samples,
parent_off_sample_down_to_sum_tree_idx, 4,
5)
return span_off_samples, out_samples
def compute_down_msg(self, inc_node_msg, node_to_span_off_belief_idx,
node_to_span_on_start_belief_idx,
node_to_span_on_end_belief_idx,
parent_on_down_to_sum_tree_idx,
parent_off_down_to_sum_tree_idx):
"""Compute downward BP messages for this layer of the tree.
Args:
inc_node_msg: incoming messages from parent variables.
node_to_span_off_belief_idx: map from node marginals at this layer to
corresponding span-off marginals.
node_to_span_on_start_belief_idx: map marking start of each span marginal.
node_to_span_on_end_belief_idx: map marking end of each span marginal.
parent_on_down_to_sum_tree_idx: map from marginal of parent-on
variable down to child variable.
parent_off_down_to_sum_tree_idx: map from marginal of parent-off
variable down to child variable.
Returns:
span_off_marginals:
out_msg:
"""
node_marginals = self.up_node_msg * inc_node_msg
span_off_beliefs = padded_gather_nd(node_marginals,
node_to_span_off_belief_idx, 3, 4)
cumulative_node_beliefs = tf.cumsum(node_marginals, 2)
span_on_start_cumulative_belief = padded_gather_nd(
cumulative_node_beliefs, node_to_span_on_start_belief_idx, 3, 4)
span_on_end_cumulative_belief = padded_gather_nd(
cumulative_node_beliefs, node_to_span_on_end_belief_idx, 3, 4)
span_on_beliefs = (
span_on_end_cumulative_belief - span_on_start_cumulative_belief)
span_belief_normalizer = span_on_beliefs + span_off_beliefs
span_off_marginals = su.safe_divide(span_off_beliefs,
span_belief_normalizer)
out_msg = padded_gather_nd(inc_node_msg, parent_on_down_to_sum_tree_idx, 3,
4)
out_msg += padded_gather_nd(inc_node_msg, parent_off_down_to_sum_tree_idx,
3, 4)
return span_off_marginals, out_msg
def compute_up_msg(self, inc_msg, sum_tree_up_to_parent_idx,
sum_tree_up_to_parent_log_z_idx, span_belief_to_node_idx,
span_off_to_node_msg, span_on_to_node_msg, running_log_zs):
"""Compute upward BP messages for this layer of the tree.
Args:
inc_msg: incoming messages from child sum tree graph.
sum_tree_up_to_parent_idx: map from incoming sum tree messages to
constraint messages.
sum_tree_up_to_parent_log_z_idx: map from elementwise child logz to
elementwise parent logz.
span_belief_to_node_idx: map from span on potential to all children.
span_off_to_node_msg: map from span-off potential to node message.
span_on_to_node_msg: map from span-on potential to child-off message.
running_log_zs: running elementwise log-normalizers for messages.
Returns:
message: outgoing message bathc to parents.
log_zs: outgoing elementwise log-normalizers for messages.
"""
# First clamp parent span variable to "ON"
# so map inc messages to their right-shifted counts
# and multiply by on-belief
# then add in the off-belief which is 1.0 for both
log_zs = padded_gather_nd(running_log_zs, sum_tree_up_to_parent_log_z_idx,
3, 4)
message = padded_gather_nd(inc_msg, sum_tree_up_to_parent_idx, 3, 4)
# renormalize node on and off messages with the running logZ
zs = tf.exp(log_zs)
span_on_to_node_msg /= zs
span_off_to_node_msg /= zs
# get the span_on for when we have no children
message = tf.maximum(message, span_on_to_node_msg)
span_belief_multipliers = padded_gather_nd(self.init_span_beliefs,
span_belief_to_node_idx, 2, 4)
message *= span_belief_multipliers
message += span_off_to_node_msg
self.up_node_msg = message
return message, log_zs
class SiblingSumTreeLayer(object):
"""Layer of batch junction tree that sums up sibling nodes.
Contains routines for message passing and sampling these counts.
Attributes:
layer_depth: string describing layer for logging.
k_constraints: If the z-potentials have a hard cutoff for some k-sparsity,
we can be much more numerically stable by sparsifying the intermediate
messages before normalizing.
message_start_levels: masks for summing up multiple sets of siblings at
once.
message_end_levels: see message_start_levels.
message_damp_lambda: lambda for message-damping, improves numerical
stability at the cost of some accuracy in the inference/sampling.
min_fft_tree_depth: depth of binary sum tree for inference for smallest
subtree in batch for this layer.
fft_tree_depth: depth of binary sum tree for inference.
combined_msg_width: width of binary sum tree for inference.
"""
def __init__(self,
batch_size,
max_num_sentences,
num_samples,
fft_tree_width,
message_start_levels,
message_end_levels,
message_damp_lambda=0.00,
min_fft_tree_depth=0,
layer_depth="",
k_constraints=None):
self.layer_depth = layer_depth
self.batch_size = batch_size
self.max_num_sentences = max_num_sentences
self.num_samples = num_samples
self.message_end_levels = tf.reshape(message_end_levels,
[batch_size * max_num_sentences, -1])
self.message_start_levels = tf.reshape(message_start_levels,
[batch_size * max_num_sentences, -1])
self.message_damp_lambda = message_damp_lambda
self.fft_tree_depth = int(math.log(fft_tree_width, 2))
self.min_fft_tree_depth = min_fft_tree_depth
self.combined_msg_width = fft_tree_width
self.k_constraints = k_constraints
def compute_down_samples(self, inc_samples):
"""Compute downward samples for this layer of the tree.
Args:
inc_samples: incoming samples from parents.
Returns:
final_samples: outgoing samples to children.
"""
num_samples = self.num_samples
batch_size = self.batch_size * self.max_num_sentences
# sampling routine expects samples dimension on the outside
inc_samples = tf.reshape(inc_samples, [batch_size, num_samples, -1])
inc_samples = tf.transpose(inc_samples, [1, 0, 2])
inc_samples = tf.reshape(inc_samples, [batch_size * num_samples, -1])
prev_samples = inc_samples
for d in reversed(xrange(1, self.fft_tree_depth)):
up_msgs = self.up_msgs[d - 1]
block_size = np.power(2, d + 1)
num_splits = self.combined_msg_width / block_size
less_than_msg_start = tf.less(d, self.message_start_levels)
greater_than_msg_end = tf.greater_equal(d, self.message_end_levels)
no_compute_msg = tf.logical_or(less_than_msg_start, greater_than_msg_end)
no_compute_msg = su.repeat(num_samples, no_compute_msg)
reshaped_prev_samples = tf.concat(0, tf.split(1, num_splits,
prev_samples))
reshaped_prev_idx = tf.expand_dims(
tf.to_int32(tf.argmax(reshaped_prev_samples, 1)), 1)
prev_domain_lens = reshaped_prev_idx + 1
rep_up_msgs = su.repeat(num_samples, up_msgs)
left_up_msgs_repl, right_up_msgs_repl = tf.split(1, 2, tf.concat(
0, tf.split(1, num_splits, rep_up_msgs)))
num_rows = num_splits * batch_size * num_samples
len_mask = su.create_mask(
tf.reshape(prev_domain_lens, [-1]), block_size / 2)
right_up_msgs_repl *= len_mask
right_up_msgs_repl = tf.pad(right_up_msgs_repl,
[[0, 0], [0, block_size / 2]])
left_up_msgs_repl *= len_mask
left_up_msgs_repl = tf.pad(left_up_msgs_repl,
[[0, 0], [0, block_size / 2]])
left_up_msgs_repl, _ = su.normalize(left_up_msgs_repl)
right_up_msgs_repl = tf.reverse_sequence(right_up_msgs_repl, tf.reshape(
tf.to_int64(prev_domain_lens), [-1]), 1)
right_up_msgs_repl, _ = su.normalize(right_up_msgs_repl)
sliced_factor_marg, _ = su.normalize(left_up_msgs_repl *
right_up_msgs_repl)
sliced_factor_marg = tf.slice(sliced_factor_marg, [0, 0],
[num_rows, block_size / 2])
left_samples, left_idx = su.sample_categorical(tf.log(sliced_factor_marg))
left_samples = tf.slice(left_samples, [0, 0], [num_rows, block_size / 2])
right_idx = prev_domain_lens - left_idx - 1
right_samples = tf.one_hot(tf.reshape(right_idx, [-1]), block_size / 2)
cur_samples = tf.concat(1, tf.split(0, num_splits, tf.concat(
1, [left_samples, right_samples])))
cur_samples = tf.select(no_compute_msg, prev_samples, cur_samples)
prev_samples = cur_samples
final_samples = tf.reshape(
prev_samples,
[num_samples, self.batch_size, self.max_num_sentences, -1])
final_samples = tf.transpose(final_samples, [1, 2, 0, 3])
return final_samples
def compute_down_msg(self, inc_msg):
"""Compute downward BP messages for this layer of the tree.
Args:
inc_msg: incoming messages from parents.
Returns:
final_msg: outgoing messages to children.
final_marg: marginals for variables at this layer.
"""
batch_size = self.batch_size * self.max_num_sentences
inc_msg = tf.reshape(inc_msg, [batch_size, -1])
message_start_levels = self.message_start_levels
message_end_levels = self.message_end_levels
prev_msg = inc_msg
for d in reversed(xrange(1, self.fft_tree_depth)):
less_than_msg_start = tf.less(d, message_start_levels)
greater_than_msg_end = tf.greater_equal(d, message_end_levels)
no_compute_msg = tf.logical_or(less_than_msg_start, greater_than_msg_end)
up_msgs = self.up_msgs[d - 1]
block_size = np.power(2, d + 1)
num_splits = self.combined_msg_width / block_size
prev_msgs = tf.concat(0, tf.split(1, num_splits, prev_msg))
left_right_up_msgs = tf.concat(0, tf.split(1, num_splits, up_msgs))
left_up_msgs, right_up_msgs = tf.split(1, 2, left_right_up_msgs)
left_down_msgs = ffttii.positive_correl(prev_msgs, tf.pad(
right_up_msgs, [[0, 0], [0, block_size / 2]]))
left_down_msgs = tf.slice(left_down_msgs, [0, 0],
[num_splits * batch_size, block_size / 2])
left_down_msgs, _ = su.normalize(left_down_msgs)
# left_down_msgs=lam*up_uni+(1-lam)*left_down_msgs
left_margs, _ = su.normalize(left_up_msgs * left_down_msgs)
right_down_msgs = ffttii.positive_correl(prev_msgs, tf.pad(
left_up_msgs, [[0, 0], [0, block_size / 2]]))
right_down_msgs = tf.slice(right_down_msgs, [0, 0],
[num_splits * batch_size, block_size / 2])
right_down_msgs, _ = su.normalize(right_down_msgs)
# right_down_msgs=lam*up_uni+(1-lam)*right_down_msgs
right_margs, _ = su.normalize(right_up_msgs * right_down_msgs)
new_msg = tf.concat(1, tf.split(0, num_splits, tf.concat(
1, [left_down_msgs, right_down_msgs])))
new_margs = tf.concat(1, tf.split(0, num_splits,
tf.concat(1,
[left_margs, right_margs])))
new_msg = tf.select(no_compute_msg, prev_msg, new_msg)
margs = tf.select(no_compute_msg, new_msg, new_margs)
prev_msg = new_msg
final_msg = tf.reshape(prev_msg,
[self.batch_size, self.max_num_sentences, -1])
final_marg = tf.reshape(margs,
[self.batch_size, self.max_num_sentences, -1])
return final_msg, final_marg
def compute_up_msg(self, inc_msg, running_log_zs):
"""Compute upward BP messages for this layer of the tree.
Args:
inc_msg: incoming messages from children.
running_log_zs: running elementwise log-normalizers for messages.
Returns:
out_msg: outgoing messages to parents.
log_zs: new elementwise log-normalizers for messages.
"""
# inc_msg is shape [batch_size,combined_msg_width]