-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_models_old.py
1366 lines (1123 loc) · 45.5 KB
/
graph_models_old.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
"""
This file defines graph models for scene classification.
The model should be able to convert (maybe do this in a different class) the
object list it is given into a scene graph. The model should take two graphs as
input and output the probability of the two graphs being the same.
How to compute distance in the space of graphs ? Several approaches could be
considered : use global variable as a graph embedding, use graph-graph
comparisons with attention, or train a distance function on time-series of
graphs being jittred.
"""
import time
import numpy as np
import torch
# import torch_geometric
import graph_nets_old as gn
try:
from torch_scatter import scatter_mean
from torch_geometric.nn import MetaLayer
from torch_geometric.data import Data
except:
from graph_nets import MetaLayer
from scatter import scatter_mean
from utils import Data
from graph_utils import data_from_graph_maker
from graph_utils import cross_graph_ei_maker
###############################################################################
# #
# Models #
# #
###############################################################################
class GraphModelDouble(torch.nn.Module):
"""
Base class for all models operating on two input graphs.
Graph models are on CPU by default, call .cuda() to pass computation on
GPU.
"""
def __init__(self):
super(GraphModelDouble, self).__init__()
self.GPU = False
self.data_from_graph = data_from_graph_maker()
# not all models use this, maybe subclass into CrossGraphModel
self.cross_graph_ei = cross_graph_ei_maker()
self.task_type = 'parts_task' # by default
def get_features(self, f_dict):
"""
Gets the input and output features for graph processing.
"""
f_e = f_dict['f_e']
f_x = f_dict['f_x']
f_u = f_dict['f_u']
f_out = f_dict['f_out']
return f_e, f_x, f_u, f_out
def cuda(self):
super(GraphModelDouble, self).cuda()
self.GPU = True
self.data_from_graph = data_from_graph_maker(cuda=True)
self.cross_graph_ei = cross_graph_ei_maker(cuda=True)
def cpu(self):
super(GraphModelDouble, self).cpu()
self.GPU = False
self.data_from_graph = data_from_graph_maker(cuda=False)
self.cross_graph_ei = cross_graph_ei_maker(cuda=False)
def reset_parameters(self):
"""
Resets all the parameters of the neural networks in the model.
"""
# for keys in
pass
class GraphModelSimple(torch.nn.Module):
"""
Base class for all models operating on one input graph.
Graph models are on CPU by default, call .cuda() to pass computation on
GPU.
"""
def __init__(self):
super(GraphModelSimple, self).__init__()
self.GPU = False
self.data_from_graph = data_from_graph_maker()
# not all models use this, maybe subclass into CrossGraphModel
self.task_type = 'parts_task' # by default
def get_features(self, f_dict):
"""
Gets the input and output features for graph processing.
"""
f_e = f_dict['f_e']
f_x = f_dict['f_x']
f_u = f_dict['f_u']
f_out = f_dict['f_out']
return f_e, f_x, f_u, f_out
def cuda(self):
super(GraphModelSimple, self).cuda()
self.GPU = True
self.data_from_graph = data_from_graph_maker(cuda=True)
def cpu(self):
super(GraphModelSimple, self).cpu()
self.GPU = False
self.data_from_graph = data_from_graph_maker(cuda=False)
def reset_parameters(self):
"""
Resets all the parameters of the neural networks in the model.
"""
# for keys in
pass
class ObjectMean(GraphModelDouble):
"""
Simple object-based embedding model.
"""
def __init__(self,
mlp_layers,
f_dict):
"""
This is one of the simplest graph models we can imagine, acting on
objects.
There is no encoder, graph features are taken as is, and the mean
of all objects is used as embedding. The concatenation of the two
embeddings of the two scenes is then fed to an MLP that produces the
final prediction.
The model is equivalent to doing the mean of all objects present in
the scene, which is a very rough approximation. If this performs
well, it means that our task is really too easy.
This model shall be used as a baseline to quantify the effects of
aggregating with attention, and of message-passing, in graph-based
embedding models, whose second part of the architecture remains
constant.
"""
super(ObjectMean, self).__init__()
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
self.final_mlp = model_fn(2*f_x, f_out)
def forward(self, graph1, graph2):
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
return self.final_mlp(torch.cat([u1, u2], 1))
class ObjectMeanDirectAttention(GraphModelDouble):
"""
Graph Embedding model, where aggregation is done by a weighted mean, and
the attention vectors are computed on a separate basis for each node.
We only use the node features for aggregation (?).
"""
def __init__(self,
mlp_layers,
f_dict):
"""
This model is also a very simple one : we use the given node features
compute scalar attentions over nodes, and use those as weights in the
node feature aggregation. This aggregation is then used as an
embedding for the graph.
We test this model agains the simpler one with no attention, and as a
baseline (or ablation model) for the message-passing embeddings.
"""
super(ObjectMeanDirectAttention, self).__init__()
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
f_a = 1 # attentions are scalars
self.attention_model = gn.DirectNodeModel(f_x, model_fn, f_a)
self.final_mlp = model_fn(2*f_x, f_out)
def embedding(self, graph):
"""
Returns the embedding of the graph, as a weighted mean of the node
features with attention scalars computed by an mlp on all node features
successively.
"""
x, edge_index, e, u, batch = self.data_from_graph(graph)
a_x = self.attention_model(x, edge_index, e, u, batch)
return scatter_mean(x * a_x, batch, dim=0) # see if this works
def forward(self, graph1, graph2):
"""
Forward pass.
"""
u1 = self.embedding(graph1)
u2 = self.embedding(graph2)
return self.final_mlp(torch.cat([u1, u2], 1))
class GraphEmbedding(GraphModelDouble):
"""
GraphEmbedding model.
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict):
"""
This model processes the inputs into two graphs that undergo a certain
number of recurrent message-passing rounds that yield two embeddings
that can then serve as a basis for comparison.
One graph is processed to give a latent representation for each node
and edge, and also to give an attention graph over nodes and edges.
This attention graph is used as weights for the edge and node features
to be aggregated in the embedding.
"""
super(GraphEmbedding, self).__init__()
self.N = N
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
# self.time_dict = {} # dict for logging computation duration
self.encoder = MetaLayer(
gn.DirectEdgeModel(f_e, model_fn, h),
gn.DirectNodeModel(f_x, model_fn, h),
gn.DirectGlobalModel(f_u, model_fn, h))
# set the different parameters
self.reccurent = MetaLayer(
gn.EdgeModelDiff(f_e + h, f_x + h, f_u + h, model_fn, h),
gn.NodeModel(h, f_x + h, f_u + h, model_fn, h),
gn.GlobalModel(h, h, f_u + h, model_fn, h))
self.attention_maker = MetaLayer(
gn.EdgeModelDiff(h, h, h, model_fn, h),
gn.NodeModel(h, h, h, model_fn, h),
gn.GlobalModel(h, h, h, model_fn, h))
# maybe change final embedding size
self.aggregator = gn.GlobalModel(h, h, h, model_fn, h)
self.final_mlp = model_fn(2 * h, f_out)
def graph_embedding(self, x, edge_index, e, u, batch):
"""
Graph Embedding.
"""
out_list = []
x_h, e_h, u_h = self.encoder(
x, edge_index, e, u, batch)
for _ in range(self.N):
x_cat = torch.cat([x, x_h], 1)
e_cat = torch.cat([e, e_h], 1)
u_cat = torch.cat([u, u_h], 1)
x_h, e_h, u_h = self.reccurent(
x_cat,
edge_index,
e_cat,
u_cat,
batch)
x_a, e_a, u_a = self.attention_maker(
x_h, edge_index, e_h, u_h, batch)
x_agg, e_agg, u_agg = x_a * x_h, e_a * e_h, u_a * u_h
out_list.append(self.aggregator(x_agg,
edge_index,
e_agg,
u_agg,
batch))
return out_list
def forward(self, graph1, graph2):
"""
Difference between embeddings.
TODO optimize this.
"""
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
l1 = self.graph_embedding(x1, edge_index1, e1, u1, batch1)
l2 = self.graph_embedding(x2, edge_index2, e2, u2, batch2)
# diff = u1 - u2
return [self.final_mlp(torch.cat([u1, u2], 1))
for u1, u2 in zip(l1, l2)]
class Simplified_GraphEmbedding(GraphModelDouble):
"""
A variation on the original GraphEmbedding model.
"""
def __init__(self,
mlp_layers,
h,
f_dict):
"""
This model is a simpler, cleaner version of the GraphEmbedding model.
In this model, all aggregations are done only on nodes, and not
on edges : edges do not carry features useful for the aggregation any
more, but only serve for passing messages between nodes.
In this simple model, we do not have an encoder, the node, edge and
global features are used as such. There is only one layer of GNN.
"""
super(Simplified_GraphEmbedding, self).__init__()
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
# aggregation with attention
self.gnn = MetaLayer(
gn.EdgeModelConcat(f_e, f_x, f_u, model_fn, h),
gn.NodeModel(h, f_x, f_u, model_fn, h),
gn.GlobalModelNodeAttention(h, h, f_u, model_fn, h))
self.mlp = model_fn(2 * h, f_out)
def graph_embedding(self, x, edge_index, e, u, batch):
"""
In this case the embedding is simple : we apply the gnn once, and use
the global vector as embedding.
"""
x_h, e_h, u_h = self.gnn(x, edge_index, e, u, batch)
return u_h
def forward(self, graph1, graph2):
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
u1 = self.graph_embedding(x1, edge_index1, e1, u1, batch1)
u2 = self.graph_embedding(x2, edge_index2, e2, u2, batch2)
return self.mlp(torch.cat([u1, u2], 1))
class GraphDifference(GraphModelDouble):
"""
GraphModelDouble.
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict,
mapping_fn):
"""
Initialization of a GraphDifference model.
The model works by encoding and then processing the inputs of the
graphs, then mapping with a provided mapping, the two graphs
together node by node and merging them in a single graph where the
features are the node-wise and edge-wise features for nodes and edges
respectively. This difference graph is then processed by a final graph
network, and the resulting global feature is fed to the final mlp.
Arguments :
- mlp_layers (list of ints): the number of units in each hidden
layer in the mlps used in the graph networks.
- h (int): the size of the latent graph features (for edges, nodes
and global)
- N (int): number of passes for the GN blocks
- f_dict : dictionnary of feature sizes
- mapping_fn (function): a function that takes in two graphs and
returns a tensor representing a permutation of the indices
to map the second graph on the first one.
"""
super(GraphModelDouble, self).__init__()
self.N = N
model_fn = gn.mlp_fn(mlp_layers)
self.mapping_fn = mapping_fn
f_e, f_x, f_u, f_out = self.get_features(f_dict)
self.encoder = MetaLayer(
gn.DirectEdgeModel(f_e, model_fn, h),
gn.DirectNodeModel(f_x, model_fn, h),
gn.DirectGlobalModel(f_u, model_fn, h))
# set the different parameters
self.reccurent = MetaLayer(
gn.EdgeModelDiff(f_e + h, f_x + h, f_u + h, model_fn, h),
gn.NodeModel(h, f_x + h, f_u + h, model_fn, h),
gn.GlobalModel(h, h, f_u + h, model_fn, h))
self.encoder_final = MetaLayer(
gn.DirectEdgeModel(h, model_fn, h),
gn.DirectNodeModel(h, model_fn, h),
gn.DirectGlobalModel(h, model_fn, h))
self.reccurent_final = MetaLayer(
gn.EdgeModelDiff(2*h, 2*h, 2*h, model_fn, h),
gn.NodeModel(h, 2*h, 2*h, model_fn, h),
gn.GlobalModel(h, h, 2*h, model_fn, h))
self.final_mlp = model_fn(h, f_out)
def processing(self, x, edge_index, e, u, batch):
"""
Processing a single graph, before merging.
"""
x_h, e_h, u_h = self.encoder(
x, edge_index, e, u, batch)
for _ in range(self.N):
x_cat = torch.cat([x, x_h], 1)
e_cat = torch.cat([e, e_h], 1)
u_cat = torch.cat([u, u_h], 1)
x_h, e_h, u_h = self.reccurent(
x_cat,
edge_index,
e_cat,
u_cat,
batch)
return x_h, e_h, u_h
def processing_final(self, x, edge_index, e, u, batch):
"""
Processing a single graph, before merging.
"""
x_h, e_h, u_h = self.encoder_final(
x, edge_index, e, u, batch)
for _ in range(self.N):
x_cat = torch.cat([x, x_h], 1)
e_cat = torch.cat([e, e_h], 1)
u_cat = torch.cat([u, u_h], 1)
x_h, e_h, u_h = self.reccurent_final(
x_cat,
edge_index,
e_cat,
u_cat,
batch)
return x_h, e_h, u_h
def forward(self, graph1, graph2):
"""
Forward pass.
Arguments :
- graph1, graph2 : the two graphs to compare.
"""
mapping = self.mapping_fn(graph2, graph1)
graph2 = permute_graph(graph2, mapping)
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
x1, e1, u1 = self.processing(
x1, edge_index1, e1, u1, batch1)
x2, e2, u2 = self.processing(
x2, edge_index2, e2, u2, batch2)
assert((edge_index1 == edge_index2).all()) # this should pass easily
x, e, u = x1 - x2, e1 - e2, u1 - u2
x, e, u = self.processing_final(
x, edge_index1, e, u, batch1)
return self.final_mlp(u)
class Alternating(GraphModelDouble):
"""
Class for the alternating graph model (v1)
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict,
n=2):
"""
Intitialize the alternating model.
This model alternates between processing one graph and processing the
other, with communication between the two processing operations done
by conditionning the models involved with a shared global vector.
After N rounds of processing, alternating on each graph, the shared
vector is decoded by a final model.
See if training on all outputs is not better than training only on the
final one.
Arguments:
- mlp_layers (list of ints): the number of units in each hidden
layer in the mlps used in the graph networks.
- h (int): the size of the latent graph features (for edges, nodes
and global)
- N (int): number of passes for the GN blocks
- f_dict : dictionnary of feature sizes
- n (int) : number of passes to do in each processing step.
"""
super(Alternating, self).__init__()
self.N = N
self.n = n
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
# encoding the graphs to give the first latent vectors in the
# processing step
self.encoder = MetaLayer(
gn.DirectEdgeModel(f_e, model_fn, h),
gn.DirectNodeModel(f_x, model_fn, h),
gn.DirectGlobalModel(f_u, model_fn, h))
# attention GN Block
self.reccurent = gn.MetaLayer(
gn.EdgeModelDiff(f_e + h, f_x + h, f_u + h, model_fn, h),
gn.NodeModel(h, f_x + h, f_u + h, model_fn, h),
gn.GlobalModel(h, h, f_u + h, model_fn, h))
self.attention_maker = MetaLayer(
gn.EdgeModelDiff(h, h, h, model_fn, h),
gn.NodeModel(h, h, h, model_fn, h),
gn.GlobalModel(h, h, h, model_fn, h))
self.aggregator = gn.GlobalModel(h, h, h, model_fn, h)
self.decoder = model_fn(h, f_out)
def encode(self, x, edge_index, e, u, batch, shared):
"""
Encodes a graph, for subsequent processing.
"""
x_h, e_h, u_h = self.encoder(
x, edge_index, e, u, batch)
def processing(self,
x,
x_h,
edge_index,
e,
e_h,
u,
u_h,
batch,
shared):
"""
Processing step.
shared is the shared vector.
"""
src, dest = edge_index
for _ in range(self.n):
x_cat = torch.cat([x, x_h], 1)
e_cat = torch.cat([e, e_h], 1)
u_cat = torch.cat([u, shared], 1)
x_h, e_h, u_h = self.reccurent(
x_cat,
edge_index,
e_cat,
u_cat,
batch)
x_a, e_a, u_a = self.attention_maker(
x_h, edge_index, e_h, u_h, batch)
x, e, u = x_a * x_h, e_a * e_h, u_a * u_h
u = self.aggregator(x, edge_index, e, u, batch)
return x, e, u
def forward(self, graph1, graph2):
"""
Forward pass
Returns la list of self.N outputs, corresponding to each alternating
step.
"""
outputs = []
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
x1h, e1h, u1h = self.encoder(
x1, edge_index1, e1, u1, batch1)
x2h, e2h, u2h = self.encoder(
x2, edge_index2, e2, u2, batch2)
for _ in range(self.N):
# alternative processing
x1h, e1h, u1h = self.processing(
x1, x1h, edge_index1, e1, e1h, u1, u1h, batch1, u2h)
x2h, e2h, u2h = self.processing(
x2, x2h, edge_index2, e2, e2h, u2, u2h, batch2, u1h)
outputs.append(self.decoder(u2h))
return outputs
class Alternatingv2(GraphModelDouble):
"""
Class for the alternating graph model (v2)
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict,
n=2):
"""
Intitialize the alternating model.
This model alternates between processing one graph and processing the
other, with communication between the two processing operations done
by conditionning the models involved with a shared global vector.
After N rounds of processing, alternating on each graph, the shared
vector is decoded by a final model.
See if training on all outputs is not better than training only on the
final one.
Arguments:
- mlp_layers (list of ints): the number of units in each hidden
layer in the mlps used in the graph networks.
- h (int): the size of the latent graph features (for edges, nodes
and global)
- N (int): number of passes for the GN blocks
- f_dict : dictionnary of feature sizes
- n (int) : number of passes to do in each processing step.
"""
super(Alternatingv2, self).__init__()
self.N = N
self.n = n
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
# encoding the graphs to give the first latent vectors in the
# processing step
self.encoder = MetaLayer(
gn.DirectEdgeModel(f_e, model_fn, h),
gn.DirectNodeModel(f_x, model_fn, h),
gn.DirectGlobalModel(f_u, model_fn, h))
# attention GN Block
self.reccurent = gn.AttentionLayer(
gn.EdgeModelDiff(f_e + h, f_x + h, f_u + h, model_fn, h),
gn.EdgeModelDiff(f_e + h, f_x + h, f_u + h, model_fn, h),
gn.NodeModel(h, f_x + h, f_u + h, model_fn, h),
gn.NodeOnlyGlobalModel(h, h, f_u + h, model_fn, h))
self.decoder = model_fn(h, f_out)
def processing(self,
x,
x_h,
edge_index,
e,
e_h,
u,
u_h,
batch,
shared):
"""
Processing step.
shared is the shared vector.
"""
src, dest = edge_index
for _ in range(self.n):
x_cat = torch.cat([x, x_h, shared[batch]], 1)
e_cat = torch.cat([e, e_h, shared[batch[src]]], 1)
u_cat = torch.cat([u, u_h, shared], 1)
x_h, e_h, u_h = self.reccurent(
x_cat,
edge_index,
e_cat,
u_cat,
batch)
return x_h, e_h, u_h
def forward(self, graph1, graph2):
"""
Forward pass
Returns la list of self.N outputs, corresponding to each alternating
step.
"""
outputs = []
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
x1h, e1h, u1h = self.encoder(
x1, edge_index1, e1, u1, batch1)
x2h, e2h, u2h = self.encoder(
x2, edge_index2, e2, u2, batch2)
for _ in range(self.N):
# alternative processing
x1h, e1h, u1h = self.processing(
x1, x1h, edge_index1, e1, e1h, u1, u1h, batch1, u2h)
x2h, e2h, u2h = self.processing(
x2, x2h, edge_index2, e2, e2h, u2, u2h, batch2, u1h)
outputs.append(self.decoder(u2h))
return outputs
class AlternatingSimple(GraphModelDouble):
"""
Simple version of the Alternating model.
"""
def __init__(self,
mlp_layers,
N,
f_dict):
"""
Simpler version of the alternating model. In this model there is no
encoder network, we only have 1 layer of GNN on each processing step.
We condition on the output global embedding from the processing on the
previous graph, and we only condition the node computations since there
are less nodes than edges (this is a choice that can be discussed).
We aggregate nodes with attention in the global model.
We use the same gnn for processing both inputs.
In this model, since we may want to chain the passes, we let the number
of input features unchanged.
"""
super(AlternatingSimple, self).__init__()
model_fn = gn.mlp_fn(mlp_layers)
self.N = N
f_e, f_x, f_u, f_out = self.get_features(f_dict)
self.gnn = MetaLayer(
gn.EdgeModelDiff(f_e, f_x + f_u, f_u, model_fn, f_e),
gn.NodeModel(f_e, f_x + f_u, f_u, model_fn, f_x),
gn.GlobalModelNodeAttention(f_e, f_x, f_u, model_fn, f_u))
self.mlp = model_fn(2 * f_u, f_out)
def forward(self, graph1, graph2):
"""
Forward pass. We alternate computing on 1 graph and then on the other.
We initialize the conditioning vector at 0.
At each step we concatenate the global vectors to the node vectors.
"""
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
out_list = []
for _ in range(self.N):
# we can do N passes of this
x1 = torch.cat([x1, u2[batch1]], 1)
x1, e1, u1 = self.gnn(x1, edge_index1, e1, u1, batch1)
x2 = torch.cat([x2, u1[batch2]], 1)
x2, e2, u2 = self.gnn(x2, edge_index2, e2, u2, batch2)
out_list.append(self.mlp(torch.cat([u1, u2], 1)))
return out_list
class GraphMatchingNetwork(GraphModelDouble):
"""
Graph Merging network.
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict):
"""
This model takes two graphs as input and merges them by forming a
single graph where all the nodes of the first graph are connected to
all the nodes of the second.
"""
super(GraphMatching, self).__init__()
self.N = N
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
self.encoder = MetaLayer(
gn.DirectEdgeModel(f_e, model_fn, h),
gn.DirectNodeModel(f_x, model_fn, h),
gn.DirectGlobalModel(f_u, model_fn, h))
self.reccurent = gn.CosineAttentionLayer(
gn.EdgeModelDiff(f_e + h, f_x + h, f_u + h, model_fn, h),
gn.CosineSimNodeModel(h, f_x + h, f_u + h, model_fn, h),
gn.GlobalModel(h, h, f_u + h, model_fn, h))
self.attention_maker = MetaLayer(
gn.EdgeModelDiff(h, h, h, model_fn, h),
gn.NodeModel(h, h, h, model_fn, h),
gn.GlobalModel(h, h, h, model_fn, h))
self.cosine_attention = gn.CosineAttention(h, h, h)
# maybe change final embedding size
self.aggregator = gn.GlobalModel(h, h, h, model_fn, h)
self.final_mlp = model_fn(2 * h, f_out)
def processing(self,
x,
x_src,
edge_index,
e,
u,
batch,):
pass
def forward(self, graph1, graph2):
"""
Forward pass.
"""
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
# encode first
x1h, e1h, u1h = self.encoder(
x1, edge_index1, e1, u1, batch1)
x2h, e2h, u2h = self.encoder(
x2, edge_index2, e2, u2, batch2)
for _ in range(self.N):
# prepare vectors for first graph processing
x1_cat = torch.cat([x1, x1_h])
x_src_cat = torch.cat([x2, x2h]) # source is graph2
e1_cat = torch.cat([e1, e1_h])
u1_cat = torch.cat([u1, u1_h])
x1h, e1h, u1h = self.reccurent(x1_cat,
x_src_cat,
e1_cat,
u1_cat)
# prepare vectors for second graph processing
x2_cat = torch.cat([x2, x2_h])
x_src_cat = torch.cat([x1, x1h]) # source is graph1
e2_cat = torch.cat([e2, e2_h])
u2_cat = torch.cat([u2, u2_h])
x2h, e2h, u2h = self.reccurent(x2_cat,
x_src_cat,
e2_cat,
u2_cat)
x1_a, e1_a, u1_a = self.attention_maker(
x1_h, edge_index, e1_h, u1_h, batch)
x1, e1, u1 = x1_h * x1_a, e1_h * e1_a, u1_h * u1_a
u1 = self.aggregator(x1, edge_index, e1, u1, batch)
x2_a, e2_a, u2_a = self.attention_maker(
x2_h, edge_index, e2_h, u2_h, batch)
x2, e2, u2 = x2_h * x2_a, e2_h * e2_a, u2_h * u2_a
u2 = self.aggregator(x2, edge_index, e2, u2, batch)
return self.final_mlp(torch.cat([u1, u2]))
class GraphMatchingSimple(GraphModelDouble):
"""
Simpler version of the Graph Matching Network.
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict):
"""
This simpler version of the GMN has only one layer of internal
propagation.
"""
super(GraphMatchingSimple, self).__init__()
self.N = N
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
self.gnn = gn.CosineAttentionLayer(
gn.EdgeModelDiff(f_e, f_x, f_u, model_fn, h),
gn.CosineAttention(h, f_x, f_u),
gn.CosineSimNodeModel(h, f_x, f_u, model_fn, h),
gn.GlobalModel(h, h, f_u, model_fn, h))
self.mlp = model_fn(2 * h, f_out)
def forward(self, graph1, graph2):
"""
Forward pass.
"""
# if self.cg_ei is None or self.b_size != len(graph1.y):
# # artificially constructing this reduces the model's generality
# # we want to have models that can also reason on different
# # graphs
# # there should be a way to compute thsi for any two graphs
# # at the cost of some generality
# n_obj = len(graph1.x) // len(graph1.y)
# self.b_size = len(graph1.y)
# ei = complete_edge_index(n_obj)
# self.cg_ei = ei
# for i in range(self.b_size - 1):
# self.cg_ei = torch.cat([self.cg_ei, ei + (i + 1) * n_obj], 1)
# build complete cross-graph edge index tensor
x1, edge_index1, e1, u1, batch1 = self.data_from_graph(graph1)
x2, edge_index2, e2, u2, batch2 = self.data_from_graph(graph2)
cg_ei = self.cross_graph_ei(batch1, batch2)
x1, e1, u1 = self.gnn(x1,
x2,
edge_index1,
torch.flip(cg_ei, (0,)),
e1,
u1,
batch1,
batch2)
x2, e2, u2 = self.gnn(x2,
x1,
edge_index2,
cg_ei,
e2,
u2,
batch2,
batch1)
return self.mlp(torch.cat([u1, u2], 1))
class GraphMatchingv2(GraphModelDouble):
"""
New version of the GMN, with learned cross-graph attentions.
We use the nodes and edges for aggregation.
"""
def __init__(self,
mlp_layers,
h,
N,
f_dict):
"""
Initialization.
The motivation for this model is that in the standard implementation of
the GMN model, the cross graph attentions between two nodes decreases
when the nodes are similar (to implement matching : the less the
graph match, the more cross-graph attention there is, because the
learned distance function should be higher).
The intuition behind our model is somewhat the opposite : our model
should be able to select, in the bigger scene, the objects that are
also present in the smaller one, and not attend to the other ones.
"""
super(GraphMatchingv2, self).__init__()
self.N = N
model_fn = gn.mlp_fn(mlp_layers)
f_e, f_x, f_u, f_out = self.get_features(f_dict)
self.gnn = gn.CrossGraphAttentionLayer(
gn.LearnedCrossGraphAttention(f_x, model_fn),
gn.EdgeModelDiff(f_e, f_x, f_u, model_fn, h), # edgemodelconcat here ?
gn.NodeModel(h, f_x, f_u, model_fn, h),
gn.GlobalModel(h, h, f_u, model_fn, h))
self.mlp = model_fn(2 * h, f_out)
def forward(self, graph1, graph2):
"""
Forward pass.