-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_graph_task.py
1326 lines (1193 loc) · 57.1 KB
/
basic_graph_task.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import bz2
import os
import pickle
import pathlib
from omegaconf import OmegaConf
from typing import Dict, List, Tuple
import networkx as nx
import numpy as np
import torch
import torch.nn as nn
import torch_geometric.data as gd
from networkx.algorithms.isomorphism import is_isomorphic
from torch import Tensor
from torch.utils.data import DataLoader, Dataset
from torch_scatter import scatter_logsumexp
from tqdm import tqdm
from gflownet.algo.config import TBVariant
from gflownet.algo.flow_matching import FlowMatching
from gflownet.algo.trajectory_balance import TrajectoryBalance
from gflownet.config import Config
from gflownet.envs.basic_graph_ctx import BasicGraphContext
from gflownet.envs.graph_building_env import (
Graph,
GraphAction,
GraphActionCategorical,
GraphActionType,
GraphBuildingEnv,
)
from gflownet.models.graph_transformer import GraphTransformer, GraphTransformerGFN
from gflownet.trainer import FlatRewards, GFNAlgorithm, GFNTask, GFNTrainer, RewardScalar
from gflownet.utils.conditioning import LogZConditional
def n_clique_reward(g, n=4):
cliques = list(nx.algorithms.clique.find_cliques(g))
# The number of cliques each node belongs to
num_cliques = np.bincount(sum(cliques, []))
cliques_match = [len(i) == n for i in cliques]
return np.mean(cliques_match) - np.mean(num_cliques)
def colored_n_clique_reward(g, n=4):
cliques = list(nx.algorithms.clique.find_cliques(g))
# The number of cliques each node belongs to
num_cliques = np.bincount(sum(cliques, []))
colors = {i: g.nodes[i]["v"] for i in g.nodes}
def color_match(c):
return np.bincount([colors[i] for i in c]).max() >= n - 1
cliques_match = [float(len(i) == n) * (1 if color_match(i) else 0.5) for i in cliques]
return np.maximum(np.sum(cliques_match) - np.sum(num_cliques) + len(g) - 1, -10)
def even_neighbors_reward(g):
total_correct = 0
for n in g:
num_diff_colr = 0
c = g.nodes[n]["v"]
for i in g.neighbors(n):
num_diff_colr += int(g.nodes[i]["v"] != c)
total_correct += int(num_diff_colr % 2 == 0) - (1 if num_diff_colr == 0 else 0)
return np.float32((total_correct - len(g.nodes) if len(g.nodes) > 3 else -5) * 10 / 7)
def count_reward(g):
ncols = np.bincount([g.nodes[i]["v"] for i in g], minlength=2)
return np.float32(-abs(ncols[0] + ncols[1] / 2 - 3) / 4 * 10)
def generate_two_col_data(data_root, max_nodes=7):
atl = nx.generators.atlas.graph_atlas_g()
# Filter out disconnected graphs
conn = [i for i in atl if 1 <= len(i.nodes) <= max_nodes and nx.is_connected(i)]
# Create all possible two-colored graphs
two_col_graphs = [nx.Graph()]
print(len(conn))
pb = tqdm(range(117142), disable=None)
hashes = {}
rejected = 0
def node_eq(a, b):
return a == b
for g in conn:
for i in range(2 ** len(g.nodes)):
g = g.copy()
for j in range(len(g.nodes)):
bit = i % 2
i //= 2
g.nodes[j]["v"] = bit
h = nx.algorithms.graph_hashing.weisfeiler_lehman_graph_hash(g, node_attr="v")
if h not in hashes:
hashes[h] = [g]
two_col_graphs.append(g)
else:
if not any(nx.algorithms.isomorphism.is_isomorphic(g, gp, node_eq) for gp in hashes[h]):
hashes[h].append(g)
two_col_graphs.append(g)
else:
pb.set_description(f"{rejected}", refresh=False)
rejected += 1
pb.update(1)
with bz2.open(data_root + f"/two_col_{max_nodes}_graphs.pkl.bz", "wb") as f:
pickle.dump(two_col_graphs, f)
return two_col_graphs
def load_two_col_data(data_root, max_nodes=7, generate_if_missing=True):
p = data_root + f"/two_col_{max_nodes}_graphs.pkl.bz"
print("Loading", p)
if not os.path.exists(p) and generate_if_missing:
return generate_two_col_data(data_root, max_nodes=max_nodes)
with bz2.open(p, "rb") as f:
data = pickle.load(f)
return data
class GraphTransformerRegressor(GraphTransformer):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.g2o = torch.nn.Linear(kw["num_emb"] * 2, 1)
def forward(self, g: gd.Batch, cond: torch.Tensor):
per_node_pred, per_graph_pred = super().forward(g, cond)
return self.g2o(per_graph_pred)[:, 0]
class LogZDataset(Dataset):
def __init__(
self,
logZs,
batch_size_per_logZ=64,
):
data = []
for logz in logZs:
data.append(logz * torch.ones(batch_size_per_logZ))
data = torch.cat(data).unsqueeze(-1)
self.data = data
self.idcs = np.arange(len(self.data))
def __len__(self):
return len(self.idcs)
def __getitem__(self, idx):
idx = self.idcs[idx]
logZ = self.data[idx]
return logZ
class TwoColorGraphDataset(Dataset):
def __init__(
self,
data,
ctx,
train=True,
output_graphs=False,
split_seed=142857,
ratio=0.9,
max_nodes=7,
reward_func="const",
reward_reshape: bool = False,
reward_corrupt: bool = False,
reward_shuffle: bool = False,
reward_temper: bool = False,
reward_skewed_random: bool = False,
reward_param: float = 0.0,
):
self.data = data
self.ctx = ctx
self.output_graphs = output_graphs
self.reward_func = reward_func
self.reward_reshape = reward_reshape
self.reward_corrupt = reward_corrupt
self.reward_shuffle = reward_shuffle
self.reward_temper = reward_temper
self.reward_skewed_random = reward_skewed_random
self.reward_param = reward_param
self.idcs = [0]
self.max_nodes = max_nodes
if data is None:
return
idcs = np.arange(len(data))
rng = np.random.default_rng(split_seed)
rng.shuffle(idcs)
if train:
self.idcs = idcs[: int(np.floor(ratio * len(data)))]
else:
self.idcs = idcs[int(np.floor(ratio * len(data))) :]
print(train, self.idcs.shape)
self._gc = nx.complete_graph(7)
self._enum_edges = list(self._gc.edges)
self.compute_Fsa = False
self.compute_normalized_Fsa = False
self.regress_to_F = False
# pre-compute log_rewards and apply selected reward trasnformation(s)
log_rewards = self.pre_compute_rewards()
self.adjusted_log_rewards, adjusted_log_rewards = None, log_rewards
if self.reward_reshape:
adjusted_log_rewards = self.monotonic_skew_reward_values(adjusted_log_rewards, lam=self.reward_param)
if self.reward_corrupt:
adjusted_log_rewards = self.corrupt_reward_values(adjusted_log_rewards, std=self.reward_param)
if self.reward_shuffle:
adjusted_log_rewards = self.shuffle_reward_values(adjusted_log_rewards)
if self.reward_temper:
adjusted_log_rewards = self.temper_reward_values(adjusted_log_rewards, beta=self.reward_param)
if self.reward_skewed_random:
adjusted_log_rewards = self.skewed_random_values(size=len(adjusted_log_rewards), sparse_reward=self.reward_param)
if self.reward_reshape or self.reward_corrupt or self.reward_shuffle:
self.adjusted_log_rewards = adjusted_log_rewards
def __len__(self):
return len(self.idcs)
def reward(self, g):
if self.adjusted_log_rewards is not None:
g_idx = self.get_graph_idx(g, self.data)
return self.adjusted_log_rewards[g_idx]
else:
return self.reward_type(g)
def reward_type(self, g):
if len(g.nodes) > self.max_nodes:
return -100
if self.reward_func == "cliques":
return colored_n_clique_reward(g)
elif self.reward_func == "even_neighbors":
return even_neighbors_reward(g)
elif self.reward_func == "count":
return count_reward(g)
elif self.reward_func == "const":
return np.float32(0)
def monotonic_skew_reward_values(self, log_rewards, lam=0.1):
"""
Apply monotonic trasnformation on reward values
"""
return self.adjust_reward_skew(log_rewards, lam)
def corrupt_reward_values(self, log_rewards, std=1.0):
"""
Corrupt reward values with noised. Used to
emulate "Rethinking Generalization" experiments, but for
GFlowNets
TODO:
- Currently only for Guassian noise.
Could add implementation for Laplace and others.
- Currently noise is just over one seed
"""
if std <= 0.:
return log_rewards
rng = np.random.default_rng(12345)
noise = rng.normal(loc=0.0, scale=std, size=np.array(log_rewards).shape)
return list(log_rewards + noise)
def shuffle_reward_values(self, log_rewards):
"""
Shuffles reward value pairing for given graphs. Used to
emulate "Rethinking Generalization" experiments, but for
GFlowNets
"""
rng = np.random.default_rng(12345)
aranged_ids = np.arange(start=0, stop=len(log_rewards))
rand_ids = rng.choice(aranged_ids, size=aranged_ids.shape, replace=False)
shuffled_log_rewards = np.array(log_rewards)[rand_ids]
return list(shuffled_log_rewards)
def temper_reward_values(self, log_rewards, beta=1.0):
"""
Temper rewards for pre-computed log_rewards.
"""
return list(np.array(log_rewards) * (1.0 / beta))
def skewed_random_values(self, size_log_rewards, sparse_reward=0.0):
"""
Defines random log-rewards sampled from Rayleigh dsitribution.
Emulates log-reward skew to high and low rewards. 'Sparser' rewards
skew log-reward distribution to higher mass around lower rewards.
"""
rng = np.random.default_rng(12345)
if sparse_reward > 0.0:
x = rng.rayleigh(2.6, size=size_log_rewards) - 10
idcs = (x > 0)
x[idcs] = 0
idcs = (x < -10)
x[idcs] = -10
else:
x = - rng.rayleigh(2.6, size=size_log_rewards)
idcs = (x > 0)
x[idcs] = 0
idcs = (x < -10)
x[idcs] = -10
return x
def adjust_reward_skew(self, log_rewards, lam=0.1):
"""
Skew the reward function towards favouring higher reward
values.
"""
r_bins = list(set(log_rewards))
mono_weights = np.exp(- lam * np.array(r_bins))
log_rewards_skew = []
for r in log_rewards:
i = np.where(r_bins == r)[0][0]
log_rewards_skew.append(mono_weights[i] * r)
log_rewards_skew = np.array(log_rewards_skew) / np.min(log_rewards_skew) * np.min(r_bins)
return list(log_rewards_skew)
def get_graph_idx(self, g, states, default=None):
def iso(u, v):
return is_isomorphic(u, v, lambda a, b: a == b, lambda a, b: a == b)
h = hashg(g)
if h not in self._hash_to_graphs:
if default is not None:
return default
else:
print("Graph not found in cache", h)
for i in g.nodes:
print(i, g.nodes[i])
for i in g.edges:
print(i, g.edges[i])
bucket = self._hash_to_graphs[h]
if len(bucket) == 1:
return bucket[0]
for i in bucket:
if iso(states[i], g):
return i
if default is not None:
return default
raise ValueError(g)
def hashg_for_graphs(self):
states = self.data
_hash_to_graphs = {}
states_hash = [hashg(i) for i in tqdm(states, disable=True)]
for i, h in enumerate(states_hash):
_hash_to_graphs[h] = _hash_to_graphs.get(h, list()) + [i]
return _hash_to_graphs
def pre_compute_rewards(self):
self._hash_to_graphs = self.hashg_for_graphs()
log_rewards = [
self.reward_type(self.data[self.get_graph_idx(g, self.data)])
for g in self.data
]
return log_rewards
def collate_fn(self, batch):
graphs, rewards, idcs = zip(*batch)
batch = self.ctx.collate(graphs)
if self.regress_to_F:
batch.y = torch.as_tensor([self.epc.mdp_graph.nodes[i]["F"] for i in idcs])
else:
batch.y = torch.as_tensor(rewards)
if self.compute_Fsa:
all_targets = []
for data_idx in idcs:
targets = [
torch.zeros_like(getattr(self.epc._Data[data_idx], i.mask_name)) - 100
for i in self.ctx.action_type_order
]
for neighbor in list(self.epc.mdp_graph.neighbors(data_idx)):
for _, edge in self.epc.mdp_graph.get_edge_data(data_idx, neighbor).items():
a, F = edge["a"], edge["F"]
targets[a[0]][a[1], a[2]] = F
if self.compute_normalized_Fsa:
logZ = torch.log(sum([i.exp().sum() for i in targets]))
targets = [i - logZ for i in targets]
all_targets.append(targets)
batch.y = torch.cat([torch.cat(i).flatten() for i in zip(*all_targets)])
return batch
def __getitem__(self, idx):
idx = self.idcs[idx]
g = self.data[idx]
r = torch.tensor(self.reward(g).reshape((1,)))
if self.output_graphs:
return self.ctx.graph_to_Data(g), r, idx
else:
return g, r
class BasicGraphTask(GFNTask):
def __init__(
self,
cfg: Config,
dataset: TwoColorGraphDataset,
rng: np.random.Generator = None,
):
self.dataset = dataset
self.cfg = cfg
self.rng = rng
self.logZ_conditional = LogZConditional(cfg, rng)
def flat_reward_transform(self, y: Tensor) -> FlatRewards:
return FlatRewards(y.float())
def sample_conditional_information(self, n: int, train_it: int = 0):
if self.cfg.cond.logZ.sample_dist is not None:
return self.logZ_conditional.sample(n)
else:
return {"encoding": torch.zeros((n, 1))}
def cond_info_to_logreward(self, cond_info: Dict[str, Tensor], flat_reward: FlatRewards) -> RewardScalar:
return RewardScalar(flat_reward[:, 0].float())
def compute_flat_rewards(self, mols: List[Graph]) -> Tuple[FlatRewards, Tensor]:
if not len(mols):
return FlatRewards(torch.zeros((0, 1))), torch.zeros((0,)).bool()
is_valid = torch.ones(len(mols)).bool()
flat_rewards = torch.tensor([self.dataset.reward(i) for i in mols]).float().reshape((-1, 1))
return FlatRewards(flat_rewards), is_valid
def encode_conditional_information(self, info):
if self.cfg.cond.logZ.sample_dist is not None:
encoding = self.logZ_conditional.encode(info)
return {"beta": torch.ones(len(info)), "encoding": encoding.float(), "preferences": torch.tensor(info).float()}
else:
encoding = torch.zeros((len(info), 1))
return {"beta": torch.ones(len(info)), "encoding": encoding.float(), "preferences": info.float()}
class UnpermutedGraphEnv(GraphBuildingEnv):
"""When using a tabular model, we want to always give the same graph node order, this environment
just makes sure that happens"""
def set_epc(self, epc):
self.epc = epc
def step(self, g: Graph, ga: GraphAction):
g = super().step(g, ga)
# get_graph_idx hashes the graph and so returns the same idx for the same graph up to isomorphism/node order
return self.epc.states[self.epc.get_graph_idx(g)]
class BasicGraphTaskTrainer(GFNTrainer):
cfg: Config
training_data: TwoColorGraphDataset
test_data: TwoColorGraphDataset
def set_default_hps(self, cfg: Config):
cfg.opt.learning_rate = 1e-4
cfg.opt.weight_decay = 1e-8
cfg.opt.momentum = 0.9
cfg.opt.adam_eps = 1e-8
cfg.opt.lr_decay = 20000
cfg.opt.clip_grad_param = 10
cfg.opt.clip_grad_type = "none" # "norm"
cfg.algo.max_nodes = 7
cfg.algo.global_batch_size = 64
cfg.model.num_emb = 96
cfg.model.num_layers = 8
cfg.algo.valid_offline_ratio = 0
cfg.algo.tb.do_correct_idempotent = True # Important to converge to the true p(x)
cfg.algo.tb.variant = TBVariant.SubTB1
cfg.algo.tb.do_parameterize_p_b = False
cfg.algo.illegal_action_logreward = -30 # Although, all states are legal here, this shouldn't matter
cfg.num_workers = 8
cfg.algo.train_random_action_prob = 0.01
cfg.log_sampled_data = False
# Because we're using a RepeatedPreferencesDataset
cfg.algo.valid_sample_cond_info = True # this should be true (was false o.g.)?
cfg.algo.offline_ratio = 0
def setup(self):
mcfg = self.cfg.task.basic_graph
max_nodes = self.cfg.algo.max_nodes
print(self.cfg.log_dir)
self.rng = np.random.default_rng(142857)
if mcfg.do_tabular_model:
self.env = UnpermutedGraphEnv()
else:
self.env = GraphBuildingEnv()
self._data = load_two_col_data(self.cfg.task.basic_graph.data_root, max_nodes=max_nodes)
if self.cfg.cond.logZ.sample_dist is not None:
self.ctx = BasicGraphContext(max_nodes, num_cond_dim=self.cfg.cond.logZ.num_thermometer_dim + 1, graph_data=self._data, output_gid=True)
else:
self.ctx = BasicGraphContext(max_nodes, num_cond_dim=1, graph_data=self._data, output_gid=True)
self.ctx.use_graph_cache = mcfg.do_tabular_model
self._do_supervised = self.cfg.task.basic_graph.do_supervised
self.training_data = TwoColorGraphDataset(
self._data,
self.ctx,
train=True,
ratio=mcfg.train_ratio,
max_nodes=max_nodes,
reward_func=mcfg.reward_func,
reward_reshape=mcfg.reward_reshape,
reward_corrupt=mcfg.reward_corrupt,
reward_shuffle=mcfg.reward_shuffle,
reward_temper=mcfg.reward_temper,
reward_param=mcfg.reward_param
)
self.test_data = TwoColorGraphDataset(
self._data, self.ctx,
train=False,
ratio=mcfg.train_ratio,
max_nodes=max_nodes,
reward_func=mcfg.reward_func,
reward_reshape=mcfg.reward_reshape,
reward_corrupt=mcfg.reward_corrupt,
reward_shuffle=mcfg.reward_shuffle,
reward_temper=mcfg.reward_temper,
reward_param=mcfg.reward_param
)
self.exact_prob_cb = ExactProbCompCallback(
self,
self.training_data.data,
self.device,
cache_root=self.cfg.task.basic_graph.data_root,
cache_path=self.cfg.task.basic_graph.data_root + f"/two_col_epc_cache_{max_nodes}.pkl",
log_rewards=self.training_data.adjusted_log_rewards if mcfg.reward_reshape or mcfg.reward_corrupt or mcfg.reward_shuffle else None,
logits_shuffle=mcfg.logits_shuffle,
)
if mcfg.do_tabular_model:
self.env.set_epc(self.exact_prob_cb)
if self._do_supervised and not self.cfg.task.basic_graph.regress_to_Fsa:
model = GraphTransformerRegressor(
x_dim=self.ctx.num_node_dim,
e_dim=self.ctx.num_edge_dim,
g_dim=1,
num_emb=self.cfg.model.num_emb,
num_layers=self.cfg.model.num_layers,
num_heads=self.cfg.model.graph_transformer.num_heads,
ln_type=self.cfg.model.graph_transformer.ln_type,
)
elif mcfg.do_tabular_model:
model = TabularHashingModel(self.exact_prob_cb)
if 0:
model.set_values(self.exact_prob_cb)
else:
model = GraphTransformerGFN(
self.ctx,
self.cfg,
do_bck=self.cfg.algo.tb.do_parameterize_p_b,
)
if not self._do_supervised:
self.test_data = RepeatedPreferenceDataset(np.zeros((32, 1)), 8)
self.model = self.sampling_model = model
params = [i for i in self.model.parameters()]
if self.cfg.opt.opt == "adam":
self.opt = torch.optim.Adam(
params,
self.cfg.opt.learning_rate,
(self.cfg.opt.momentum, 0.999),
weight_decay=self.cfg.opt.weight_decay,
eps=self.cfg.opt.adam_eps,
)
elif self.cfg.opt.opt == "SGD":
self.opt = torch.optim.SGD(
params, self.cfg.opt.learning_rate, self.cfg.opt.momentum, weight_decay=self.cfg.opt.weight_decay
)
elif self.cfg.opt.opt == "RMSProp":
self.opt = torch.optim.RMSprop(params, self.cfg.opt.learning_rate, weight_decay=self.cfg.opt.weight_decay)
self.lr_sched = torch.optim.lr_scheduler.LambdaLR(self.opt, lambda steps: 2 ** (-steps / self.cfg.opt.lr_decay))
algo = self.cfg.algo.method
if algo == "TB" or algo == "subTB":
self.algo = TrajectoryBalance(self.env, self.ctx, self.rng, self.cfg)
elif algo == "FM":
self.algo = FlowMatching(self.env, self.ctx, self.rng, self.cfg)
self.algo.model_is_autoregressive = False
#if self.cfg.cond.logZ.sample_dist is None:
# assert "offline_ration == 0 but using conditional logZ for online model", self.cfg.algo.offline_ratio == 0
self.task = BasicGraphTask(
self.cfg,
self.training_data,
np.random.default_rng(self.cfg.seed),
)
if self.cfg.algo.flow_reg:
dist_params = self.cfg.cond.logZ.dist_params
num_logZ = self.cfg.cond.logZ.num_valid_logZ_samples
if self.cfg.cond.logZ.sample_dist is not None:
logZs = np.linspace(dist_params[0], dist_params[1], num_logZ).tolist()
self.test_cond_logZs_data = LogZDataset(logZs, batch_size_per_logZ=self.cfg.algo.global_batch_size)
if self.cfg.algo.supervised_reward_predictor is not None:
self.algo.model_supervised_reward_predictor = GraphTransformerRegressor(
x_dim=self.ctx.num_node_dim,
e_dim=self.ctx.num_edge_dim,
g_dim=1,
num_emb=self.cfg.model.num_emb,
num_layers=self.cfg.model.num_layers,
num_heads=self.cfg.model.graph_transformer.num_heads,
ln_type=self.cfg.model.graph_transformer.ln_type,
)
print("Loading supervised trained model for unseen reward prediction ...")
load_path = self.cfg.algo.supervised_reward_predictor + mcfg.reward_func + '/model_state.pt'
model_pre_state = torch.load(load_path, map_location=self.cfg.device)
self.algo.model_supervised_reward_predictor.load_state_dict(model_pre_state['models_state_dict'][0])
self.algo.model_supervised_reward_predictor.to(self.cfg.device)
print("Done")
# initialize and load model for interpolated sampling
if self.cfg.algo.dir_model_pretrain_for_sampling is not None:
if self._do_supervised and not self.cfg.task.basic_graph.regress_to_Fsa:
self.model_pretrain_for_sampling = GraphTransformerRegressor(
x_dim=self.ctx.num_node_dim,
e_dim=self.ctx.num_edge_dim,
g_dim=1,
num_emb=self.cfg.model.num_emb,
num_layers=self.cfg.model.num_layers,
num_heads=self.cfg.model.graph_transformer.num_heads,
ln_type=self.cfg.model.graph_transformer.ln_type,
)
print("Loading pre-trained model for sampling...")
model_pre_state = torch.load(self.cfg.algo.dir_model_pretrain_for_sampling, map_location=self.cfg.device)
self.model_pretrain_for_sampling.load_state_dict(model_pre_state['models_state_dict'][0])
print("Done")
else:
self.model_pretrain_for_sampling = GraphTransformerGFN(
self.ctx,
self.cfg,
do_bck=self.cfg.algo.tb.do_parameterize_p_b,
)
print("Loading pre-trained model for sampling...")
model_pre_state = torch.load(self.cfg.algo.dir_model_pretrain_for_sampling, map_location=self.cfg.device)
self.model_pretrain_for_sampling.load_state_dict(model_pre_state['models_state_dict'][0])
print("Done")
else:
self.model_pretrain_for_sampling = None
# For offline training -- set p(x) to be used for sampling x ~ p(x)
if isinstance(model, GraphTransformerGFN):
# select use of true log_Z
if self.cfg.algo.use_true_log_Z:
self.cfg.algo.true_log_Z = float(self.exact_prob_cb.logZ)
# select x ~ p(x) sampling
if self.cfg.algo.offline_sampling_g_distribution == "log_rewards": # x ~ R(x)/Z
self.log_sampling_g_distribution = self.exact_prob_cb.true_log_probs
elif self.cfg.algo.offline_sampling_g_distribution == "log_p": # x ~ p(x; \theta)
self.log_sampling_g_distribution = self.exact_prob_cb.compute_prob(model.to(self.cfg.device))[0].cpu().numpy()[:-1]
elif self.cfg.algo.offline_sampling_g_distribution == "l2_log_error_gfn" or self.cfg.algo.offline_sampling_g_distribution == "l1_error_gfn": # x ~ ||p(x; \theta) - p(x)||
model_log_probs = self.exact_prob_cb.compute_prob(model.to(self.cfg.device))[0].cpu().numpy()[:-1]
true_log_probs = self.exact_prob_cb.true_log_probs
err = []
for lq, lp in zip(model_log_probs, true_log_probs):
if self.cfg.algo.offline_sampling_g_distribution == "l2_log_error_gfn":
err.append((lq - lp)**2)
else:
err.append(np.abs(np.exp(lq) - np.exp(lp)))
err = np.array(err)
err = err / np.sum(err)
self.log_sampling_g_distribution = np.log(err)
elif self.cfg.algo.offline_sampling_g_distribution == "uniform": # x ~ Unif(x)
self.log_sampling_g_distribution = -1 * np.ones_like(self.exact_prob_cb.true_log_probs) # uniform distribution
elif self.cfg.algo.offline_sampling_g_distribution == "random":
rng = np.random.default_rng(self.cfg.seed)
self.log_sampling_g_distribution = rng.uniform(0, 10, len(self.exact_prob_cb.true_log_probs))
else:
self.log_sampling_g_distribution = None
self.sampling_tau = self.cfg.algo.sampling_tau
self.mb_size = self.cfg.algo.global_batch_size
self.clip_grad_param = self.cfg.opt.clip_grad_param
self.clip_grad_callback = {
"value": (lambda params: torch.nn.utils.clip_grad_value_(params, self.clip_grad_param)),
"norm": (lambda params: torch.nn.utils.clip_grad_norm_(params, self.clip_grad_param)),
"none": (lambda x: None),
}[self.cfg.opt.clip_grad_type]
self.algo.task = self.task
if self.cfg.task.basic_graph.test_split_type == "random":
pass
elif self.cfg.task.basic_graph.test_split_type == "bck_traj":
train_idcs, test_idcs = self.exact_prob_cb.get_bck_trajectory_test_split(
self.cfg.task.basic_graph.train_ratio
)
self.training_data.idcs = train_idcs
self.test_data.idcs = test_idcs
elif self.cfg.task.basic_graph.test_split_type == "subtrees":
train_idcs, test_idcs = self.exact_prob_cb.get_subtree_test_split(
self.cfg.task.basic_graph.train_ratio, self.cfg.task.basic_graph.test_split_seed
)
self.training_data.idcs = train_idcs
self.test_data.idcs = test_idcs
if not self._do_supervised or self.cfg.task.basic_graph.regress_to_Fsa:
self._callbacks = {"true_px_error": self.exact_prob_cb}
else:
self._callbacks = {}
os.makedirs(self.cfg.log_dir, exist_ok=True)
print("\n\nHyperparameters:\n")
yaml = OmegaConf.to_yaml(self.cfg)
print(yaml)
with open(pathlib.Path(self.cfg.log_dir) / "hps.yaml", "w") as f:
f.write(yaml)
def build_callbacks(self):
return self._callbacks
def step(self, loss: Tensor):
loss.backward()
for i in self.model.parameters():
self.clip_grad_callback(i)
self.opt.step()
self.opt.zero_grad()
self.lr_sched.step()
if self.sampling_tau > 0:
for a, b in zip(self.model.parameters(), self.sampling_model.parameters()):
b.data.mul_(self.sampling_tau).add_(a.data * (1 - self.sampling_tau))
class RepeatedPreferenceDataset(TwoColorGraphDataset):
def __init__(self, preferences, repeat):
self.prefs = preferences
self.repeat = repeat
def __len__(self):
return len(self.prefs) * self.repeat
def __getitem__(self, idx):
assert 0 <= idx < len(self)
return torch.tensor(self.prefs[int(idx // self.repeat)])
def hashg(g):
return nx.algorithms.graph_hashing.weisfeiler_lehman_graph_hash(g, node_attr="v")
class TabularHashingModel(torch.nn.Module):
"""A tabular model to ensure that the objectives converge to the correct solution."""
def __init__(self, epc):
super().__init__()
self.epc = epc
self.action_types = [GraphActionType.Stop, GraphActionType.AddNode, GraphActionType.AddEdge]
# This makes a big array which is then sliced and reshaped into logits.
# We're using the masks's shapes to determine the size of the table because they're the same shape
# as the logits. The [1] is the F(s) prediction used for SubTB.
num_total = 0
self.slices = []
self.shapes = []
print("Making table...")
for gid in tqdm(range(len(self.epc.states))):
this_slice = [num_total]
self.shapes.append(
[
epc._Data[gid].stop_mask.shape,
epc._Data[gid].add_node_mask.shape,
epc._Data[gid].add_edge_mask.shape,
[1],
]
)
ns = [np.prod(i) for i in self.shapes[-1]]
this_slice += list(np.cumsum(ns) + num_total)
num_total += sum(ns)
self.slices.append(this_slice)
self.table = nn.Parameter(torch.zeros((num_total,)))
# For TB we have to have a unique parameter for logZ
self._logZ = nn.Parameter(torch.zeros((1,)))
print("Made table of size", num_total)
def __call__(self, g: gd.Batch, cond_info):
"""This ignores cond_info, which we don't use anyways for now, but beware"""
ns = [self.slices[i] for i in g.gid.cpu()]
shapes = [self.shapes[i] for i in g.gid.cpu()]
items = [[self.table[a:b].reshape(s) for a, b, s in zip(n, n[1:], ss)] for n, ss in zip(ns, shapes)]
logits = zip(*[i[0:3] for i in items])
logF_s = torch.stack([i[-1] for i in items])
masks = [GraphTransformerGFN._action_type_to_mask(None, t, g) for t in self.action_types]
return (
GraphActionCategorical(
g,
logits=[torch.cat(i, 0) * m - 1000 * (1 - m) for i, m in zip(logits, masks)],
keys=[
GraphTransformerGFN._graph_part_to_key[GraphTransformerGFN._action_type_to_graph_part[t]]
for t in self.action_types
],
masks=masks,
types=self.action_types,
),
logF_s,
)
def set_values(self, epc):
"""Set the values of the table to the true values of the MDP. This tabular model should have 0 error."""
for i in tqdm(range(len(epc.states))):
for neighbor in list(epc.mdp_graph.neighbors(i)):
for _, edge in epc.mdp_graph.get_edge_data(i, neighbor).items():
a, F = edge["a"], edge["F"]
self.table.data[self.slices[i][a[0]] + a[1] * self.shapes[i][a[0]][1] + a[2]] = F
self.table.data[self.slices[i][3]] = epc.mdp_graph.nodes[i]["F"]
self._logZ.data = torch.tensor(epc.mdp_graph.nodes[0]["F"]).float()
def logZ(self, cond_info: Tensor):
return self._logZ.tile(cond_info.shape[0]).reshape((-1, 1)) # Why is the reshape necessary?
class ExactProbCompCallback:
ctx: BasicGraphContext
trial: BasicGraphTaskTrainer
mdp_graph: nx.DiGraph
def __init__(
self,
trial,
states,
dev,
mbs=128,
cache_root=None,
cache_path=None,
do_save_px=True,
log_rewards=None,
logits_shuffle=False,
tqdm_disable=None,
ctx=None,
env=None,
):
self.trial = trial
self.ctx = trial.ctx if trial is not None else ctx
self.env = trial.env if trial is not None else env
self.mbs = mbs
self.dev = dev
self.states = states
self.cache_root = cache_root
self.cache_path = cache_path
self.mdp_graph = None
if self.cache_path is not None:
self.load_cache(self.cache_path)
if log_rewards is None:
self.log_rewards = np.array(
[self.trial.training_data.reward(i) for i in tqdm(self.states, disable=tqdm_disable)]
)
else:
self.log_rewards = log_rewards
self.logZ = np.log(np.sum(np.exp(self.log_rewards)))
self.true_log_probs = self.log_rewards - self.logZ
self.logits_shuffle = logits_shuffle
# This is reward-dependent
if self.mdp_graph is not None:
self.recompute_flow()
self.do_save_px = do_save_px
if do_save_px:
os.makedirs(self.trial.cfg.log_dir, exist_ok=True)
self._save_increment = 0
def load_cache(self, cache_path):
print("Loading cache @", cache_path)
cache = torch.load(open(cache_path, "rb"))
self.mdp_graph = cache["mdp"]
self._Data = cache["Data"]
self._hash_to_graphs = cache["hashmap"]
bs, ids = cache["batches"], cache["idces"]
print("Done")
self.precomputed_batches, self.precomputed_indices = (
[i.to(self.dev) for i in bs],
[[(j[0].to(self.dev), j[1].to(self.dev)) for j in i] for i in ids],
)
def compute_metrics(self, log_probs, state_flows, log_rewards_estimate, valid_batch_ids=None):
log_probs = log_probs.cpu().numpy()[:-1]
state_flows = state_flows.cpu().numpy().flatten()
log_rewards_estimate = log_rewards_estimate.cpu().numpy().flatten()
log_rewards = self.log_rewards
lp, p = log_probs, np.exp(log_probs)
lq, q = self.true_log_probs, np.exp(self.true_log_probs)
self.trial.model_log_probs, self.trial.true_log_probs = log_probs, self.true_log_probs
mae_log_probs = np.mean(abs(lp - lq))
js_log_probs = (p * (lp - lq) + q * (lq - lp)).sum() / 2
mae_log_rewards = np.mean(abs(log_rewards_estimate - log_rewards))
print("L1 logpx error", mae_log_probs, "JS divergence", js_log_probs)
if self.do_save_px and self.trial.cfg.cond.logZ.sample_dist is None:
torch.save(log_probs, open(self.trial.cfg.log_dir + f"/log_px_{self._save_increment}.pt", "wb"))
self._save_increment += 1
metrics_dict = {}
if valid_batch_ids is not None:
lp_valid, p_valid = log_probs[valid_batch_ids], np.exp(log_probs[valid_batch_ids])
lq_valid, q_valid = self.true_log_probs[valid_batch_ids], np.exp(self.true_log_probs[valid_batch_ids])
test_mae_log_probs = np.mean(abs(lp_valid - lq_valid))
metrics_dict["test_graphs-L1_logpx_error"] = test_mae_log_probs
if self.trial.cfg.algo.dir_model_pretrain_for_sampling is None:
if isinstance(log_rewards, list):
test_mae_log_rewards = np.mean(abs(log_rewards_estimate[valid_batch_ids] - np.array(log_rewards)[valid_batch_ids]))
else:
test_mae_log_rewards = np.mean(abs(log_rewards_estimate[valid_batch_ids] - log_rewards[valid_batch_ids]))
metrics_dict["test_graphs-L1_log_R_error"] = test_mae_log_rewards
metrics_dict["L1_logpx_error"] = mae_log_probs
metrics_dict["JS_divergence"] = js_log_probs
metrics_dict["L1_log_R_error"] = mae_log_rewards
return metrics_dict
def on_validation_end(self, metrics, valid_batch_ids=None):
# Compute exact sampling probabilities of the model, last probability is p(illegal), remove it.
if self.trial.cfg.cond.logZ.sample_dist is not None:
logZ_true = self.logZ * torch.ones((1, 1)) #* torch.ones((1, self.trial.cfg.cond.logZ.num_thermometer_dim + 1)).to(self.dev)
logZ_true_enc = self.trial.task.encode_conditional_information(logZ_true)
cond_info = logZ_true_enc['encoding'].squeeze(0).to(self.dev)
log_probs, state_flows, log_rewards_estimate = self.compute_prob(self.trial.model, cond_info=cond_info) # compute once using correct logZ
metrics_true_logZ = self.compute_metrics(log_probs, state_flows, log_rewards_estimate, valid_batch_ids)
if self.do_save_px:
torch.save(log_probs, open(self.trial.cfg.log_dir + f"/log_px_val_iter_{self._save_increment}_logZ_{logZ_true.mean()}.pt", "wb"))
dist_params = self.trial.cfg.cond.logZ.dist_params
num_logZ = self.trial.cfg.cond.logZ.num_valid_logZ_samples
metrics_range_logZ = {k: [v] for k, v in metrics_true_logZ.items()}
for logz in np.linspace(dist_params[0], dist_params[1], num_logZ).tolist(): # select size of range for logZ's
logZ_sampled = logz * torch.ones((1, 1)) #* torch.ones((1, self.trial.cfg.cond.logZ.num_thermometer_dim + 1)).to(self.dev)
logZ_sampled_enc = self.trial.task.encode_conditional_information(logZ_sampled)
cond_info = logZ_sampled_enc['encoding'].squeeze(0).to(self.dev)
log_probs, state_flows, log_rewards_estimate = self.compute_prob(self.trial.model, cond_info=cond_info)
metrics_tmp = self.compute_metrics(log_probs, state_flows, log_rewards_estimate, valid_batch_ids)
if self.do_save_px:
torch.save(log_probs, open(self.trial.cfg.log_dir + f"/log_px_val_iter_{self._save_increment}_logZ_{logz}.pt", "wb"))
for k in metrics_range_logZ.keys():
metrics_range_logZ[k].append(metrics_tmp[k])
for k, v in metrics_range_logZ.items():
metrics[k] = np.array(v)
if self.do_save_px:
self._save_increment += 1
else:
log_probs, state_flows, log_rewards_estimate = self.compute_prob(self.trial.model)
metrics_pre = self.compute_metrics(log_probs, state_flows, log_rewards_estimate, valid_batch_ids)
for k, v in metrics_pre.items():
metrics[k] = np.array(v)
def get_graph_idx(self, g, default=None):
def iso(u, v):
return is_isomorphic(u, v, lambda a, b: a == b, lambda a, b: a == b)
h = hashg(g)
if h not in self._hash_to_graphs:
if default is not None:
return default
else:
print("Graph not found in cache", h)
for i in g.nodes:
print(i, g.nodes[i])
for i in g.edges:
print(i, g.edges[i])
bucket = self._hash_to_graphs[h]
if len(bucket) == 1:
return bucket[0]
for i in bucket:
if iso(self.states[i], g):
return i
if default is not None:
return default
raise ValueError(g)
def compute_cache(self, tqdm_disable=None):
states, mbs, dev = self.states, self.mbs, self.dev
mdp_graph = nx.MultiDiGraph()
self.precomputed_batches = []
self.precomputed_indices = []
self._hash_to_graphs = {}
states_hash = [hashg(i) for i in tqdm(states, disable=tqdm_disable)]
self._Data = states_Data = gd.Batch.from_data_list(
[self.ctx.graph_to_Data(i) for i in tqdm(states, disable=tqdm_disable)]
)
for i, h in enumerate(states_hash):
self._hash_to_graphs[h] = self._hash_to_graphs.get(h, list()) + [i]
for bi in tqdm(range(0, len(states), mbs), disable=tqdm_disable):
bs = states[bi : bi + mbs]
bD = states_Data[bi : bi + mbs]
indices = list(range(bi, bi + len(bs)))
batch = self.ctx.collate(bD).to(dev)
self.precomputed_batches.append(batch)
actions = [[] for i in range(len(bs))]
offset = 0
for u, i in enumerate(ctx.action_type_order):
# /!\ This assumes mask.shape == cat.logit[i].shape
mask = getattr(batch, i.mask_name)
batch_key = GraphTransformerGFN._graph_part_to_key[GraphTransformerGFN._action_type_to_graph_part[i]]
batch_idx = (
getattr(batch, f"{batch_key}_batch" if batch_key != "x" else "batch")
if batch_key is not None
else torch.arange(batch.num_graphs, device=dev)
)
mslice = (
batch._slice_dict[batch_key]
if batch_key is not None
else torch.arange(batch.num_graphs + 1, device=dev)