forked from clementchadebec/benchmark_VAE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_RHVAE.py
982 lines (737 loc) · 29.6 KB
/
test_RHVAE.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
import os
from copy import deepcopy
import pytest
import torch
from pythae.customexception import BadInheritanceError
from pythae.models import RHVAE, AutoModel, RHVAEConfig
from pythae.models.rhvae.rhvae_config import RHVAEConfig
from pythae.pipelines import GenerationPipeline, TrainingPipeline
from pythae.samplers import (
GaussianMixtureSamplerConfig,
IAFSamplerConfig,
MAFSamplerConfig,
NormalSamplerConfig,
TwoStageVAESamplerConfig,
)
from pythae.trainers import BaseTrainer, BaseTrainerConfig
from tests.data.custom_architectures import (
Decoder_AE_Conv,
Encoder_VAE_Conv,
Metric_MLP_Custom,
NetBadInheritance,
)
PATH = os.path.dirname(os.path.abspath(__file__))
device = "cuda" if torch.cuda.is_available() else "cpu"
@pytest.fixture(params=[RHVAEConfig(), RHVAEConfig(latent_dim=5)])
def model_configs_no_input_dim(request):
return request.param
@pytest.fixture(
params=[
RHVAEConfig(
input_dim=(1, 28, 28), latent_dim=1, n_lf=1, reconstruction_loss="bce"
),
RHVAEConfig(input_dim=(1, 2, 18), latent_dim=2, n_lf=1),
]
)
def model_configs(request):
return request.param
@pytest.fixture
def custom_encoder(model_configs):
return Encoder_VAE_Conv(model_configs)
@pytest.fixture
def custom_decoder(model_configs):
return Decoder_AE_Conv(model_configs)
@pytest.fixture
def custom_metric(model_configs):
return Metric_MLP_Custom(model_configs)
class Test_Model_Building:
@pytest.fixture()
def bad_net(self):
return NetBadInheritance()
def test_build_model(self, model_configs):
rhvae = RHVAE(model_configs)
assert all(
[
rhvae.n_lf == model_configs.n_lf,
rhvae.temperature == model_configs.temperature,
]
)
def test_raises_bad_inheritance(self, model_configs, bad_net):
with pytest.raises(BadInheritanceError):
rhvae = RHVAE(model_configs, encoder=bad_net)
with pytest.raises(BadInheritanceError):
rhvae = RHVAE(model_configs, decoder=bad_net)
with pytest.raises(BadInheritanceError):
rhvae = RHVAE(model_configs, metric=bad_net)
def test_raises_no_input_dim(
self, model_configs_no_input_dim, custom_encoder, custom_decoder, custom_metric
):
with pytest.raises(AttributeError):
rhvae = RHVAE(model_configs_no_input_dim)
with pytest.raises(AttributeError):
rhvae = RHVAE(model_configs_no_input_dim, encoder=custom_encoder)
with pytest.raises(AttributeError):
rhvae = RHVAE(model_configs_no_input_dim, decoder=custom_decoder)
with pytest.raises(AttributeError):
rhvae = RHVAE(model_configs_no_input_dim, metric=custom_metric)
rhvae = RHVAE(
model_configs_no_input_dim,
encoder=custom_encoder,
decoder=custom_decoder,
metric=custom_metric,
)
def test_build_custom_arch(
self, model_configs, custom_encoder, custom_decoder, custom_metric
):
rhvae = RHVAE(model_configs, encoder=custom_encoder, decoder=custom_decoder)
assert rhvae.encoder == custom_encoder
assert not rhvae.model_config.uses_default_encoder
assert rhvae.decoder == custom_decoder
assert not rhvae.model_config.uses_default_encoder
assert rhvae.model_config.uses_default_metric
rhvae = RHVAE(model_configs, metric=custom_metric)
assert rhvae.model_config.uses_default_encoder
assert rhvae.model_config.uses_default_encoder
assert rhvae.metric == custom_metric
assert not rhvae.model_config.uses_default_metric
class Test_Model_Saving:
def test_default_model_saving(self, tmpdir, model_configs):
tmpdir.mkdir("dummy_folder")
dir_path = dir_path = os.path.join(tmpdir, "dummy_folder")
model = RHVAE(model_configs)
# set random M_tens and centroids from testing
model.M_tens = torch.randn(3, 10, 10)
model.centroids_tens = torch.randn(3, 10, 10)
model.state_dict()["encoder.layers.0.0.weight"][0] = 0
model.save(dir_path=dir_path)
assert set(os.listdir(dir_path)) == set(
["model_config.json", "model.pt", "environment.json"]
)
# reload model
model_rec = AutoModel.load_from_folder(dir_path)
# check configs are the same
assert model_rec.model_config.__dict__ == model.model_config.__dict__
assert all(
[
torch.equal(model_rec.state_dict()[key], model.state_dict()[key])
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens, model.M_tens)
assert torch.equal(model_rec.centroids_tens, model.centroids_tens)
assert callable(model_rec.G)
assert callable(model_rec.G_inv)
def test_custom_encoder_model_saving(self, tmpdir, model_configs, custom_encoder):
tmpdir.mkdir("dummy_folder")
dir_path = dir_path = os.path.join(tmpdir, "dummy_folder")
model = RHVAE(model_configs, encoder=custom_encoder)
model.state_dict()["encoder.layers.0.0.weight"][0] = 0
model.save(dir_path=dir_path)
assert set(os.listdir(dir_path)) == set(
["model_config.json", "model.pt", "encoder.pkl", "environment.json"]
)
# reload model
model_rec = AutoModel.load_from_folder(dir_path)
# check configs are the same
assert model_rec.model_config.__dict__ == model.model_config.__dict__
assert all(
[
torch.equal(model_rec.state_dict()[key], model.state_dict()[key])
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens, model.M_tens)
assert torch.equal(model_rec.centroids_tens, model.centroids_tens)
assert callable(model_rec.G)
assert callable(model_rec.G_inv)
def test_custom_decoder_model_saving(self, tmpdir, model_configs, custom_decoder):
tmpdir.mkdir("dummy_folder")
dir_path = dir_path = os.path.join(tmpdir, "dummy_folder")
model = RHVAE(model_configs, decoder=custom_decoder)
model.state_dict()["encoder.layers.0.0.weight"][0] = 0
model.save(dir_path=dir_path)
assert set(os.listdir(dir_path)) == set(
["model_config.json", "model.pt", "decoder.pkl", "environment.json"]
)
# reload model
model_rec = AutoModel.load_from_folder(dir_path)
# check configs are the same
assert model_rec.model_config.__dict__ == model.model_config.__dict__
assert all(
[
torch.equal(model_rec.state_dict()[key], model.state_dict()[key])
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens, model.M_tens)
assert torch.equal(model_rec.centroids_tens, model.centroids_tens)
assert callable(model_rec.G)
assert callable(model_rec.G_inv)
def test_custom_metric_model_saving(self, tmpdir, model_configs, custom_metric):
tmpdir.mkdir("dummy_folder")
dir_path = dir_path = os.path.join(tmpdir, "dummy_folder")
model = RHVAE(model_configs, metric=custom_metric)
model.state_dict()["encoder.layers.0.0.weight"][0] = 0
model.save(dir_path=dir_path)
assert set(os.listdir(dir_path)) == set(
["model_config.json", "model.pt", "metric.pkl", "environment.json"]
)
# reload model
model_rec = AutoModel.load_from_folder(dir_path)
# check configs are the same
assert model_rec.model_config.__dict__ == model.model_config.__dict__
assert all(
[
torch.equal(model_rec.state_dict()[key], model.state_dict()[key])
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens, model.M_tens)
assert torch.equal(model_rec.centroids_tens, model.centroids_tens)
assert callable(model_rec.G)
assert callable(model_rec.G_inv)
def test_full_custom_model_saving(
self, tmpdir, model_configs, custom_encoder, custom_decoder, custom_metric
):
tmpdir.mkdir("dummy_folder")
dir_path = dir_path = os.path.join(tmpdir, "dummy_folder")
model = RHVAE(
model_configs,
encoder=custom_encoder,
decoder=custom_decoder,
metric=custom_metric,
)
model.state_dict()["encoder.layers.0.0.weight"][0] = 0
model.save(dir_path=dir_path)
assert set(os.listdir(dir_path)) == set(
[
"model_config.json",
"model.pt",
"encoder.pkl",
"decoder.pkl",
"metric.pkl",
"environment.json",
]
)
# reload model
model_rec = AutoModel.load_from_folder(dir_path)
# check configs are the same
assert model_rec.model_config.__dict__ == model.model_config.__dict__
assert all(
[
torch.equal(model_rec.state_dict()[key], model.state_dict()[key])
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens, model.M_tens)
assert torch.equal(model_rec.centroids_tens, model.centroids_tens)
assert callable(model_rec.G)
assert callable(model_rec.G_inv)
model_rec.to(device)
z = torch.randn(2, model_configs.latent_dim).to(device)
assert model_rec.G(z).shape == (
2,
model_configs.latent_dim,
model_configs.latent_dim,
)
assert model_rec.G_inv(z).shape == (
2,
model_configs.latent_dim,
model_configs.latent_dim,
)
def test_raises_missing_files(
self, tmpdir, model_configs, custom_encoder, custom_decoder, custom_metric
):
tmpdir.mkdir("dummy_folder")
dir_path = dir_path = os.path.join(tmpdir, "dummy_folder")
model = RHVAE(
model_configs,
encoder=custom_encoder,
decoder=custom_decoder,
metric=custom_metric,
)
model.state_dict()["encoder.layers.0.0.weight"][0] = 0
model.save(dir_path=dir_path)
os.remove(os.path.join(dir_path, "metric.pkl"))
# check raises decoder.pkl is missing
with pytest.raises(FileNotFoundError):
model_rec = AutoModel.load_from_folder(dir_path)
os.remove(os.path.join(dir_path, "decoder.pkl"))
# check raises decoder.pkl is missing
with pytest.raises(FileNotFoundError):
model_rec = AutoModel.load_from_folder(dir_path)
os.remove(os.path.join(dir_path, "encoder.pkl"))
# check raises encoder.pkl is missing
with pytest.raises(FileNotFoundError):
model_rec = AutoModel.load_from_folder(dir_path)
os.remove(os.path.join(dir_path, "model.pt"))
# check raises encoder.pkl is missing
with pytest.raises(FileNotFoundError):
model_rec = AutoModel.load_from_folder(dir_path)
os.remove(os.path.join(dir_path, "model_config.json"))
# check raises encoder.pkl is missing
with pytest.raises(FileNotFoundError):
model_rec = AutoModel.load_from_folder(dir_path)
class Test_Model_forward:
@pytest.fixture
def demo_data(self):
data = torch.load(os.path.join(PATH, "data/mnist_clean_train_dataset_sample"))[
:
]
return data # This is an extract of 3 data from MNIST (unnormalized) used to test custom architecture
@pytest.fixture
def rhvae(self, model_configs, demo_data):
model_configs.input_dim = tuple(demo_data["data"][0].shape)
return RHVAE(model_configs)
def test_model_train_output(self, rhvae, demo_data):
# model_configs.input_dim = demo_data['data'][0].shape[-1]
# rhvae = RHVAE(model_configs)
rhvae.train()
out = rhvae(demo_data)
assert set(
[
"loss",
"recon_x",
"z",
"z0",
"rho",
"eps0",
"gamma",
"mu",
"log_var",
"G_inv",
"G_log_det",
]
) == set(out.keys())
rhvae.update()
def test_model_output(self, rhvae, demo_data):
# model_configs.input_dim = demo_data['data'][0].shape[-1]
rhvae.eval()
out = rhvae(demo_data)
assert set(
[
"loss",
"recon_x",
"z",
"z0",
"rho",
"eps0",
"gamma",
"mu",
"log_var",
"G_inv",
"G_log_det",
]
) == set(out.keys())
assert out.z.shape[0] == demo_data["data"].shape[0]
assert out.recon_x.shape == demo_data["data"].shape
class Test_Model_interpolate:
@pytest.fixture(
params=[
torch.rand(3, 2, 3, 1),
torch.rand(3, 2, 2),
torch.load(os.path.join(PATH, "data/mnist_clean_train_dataset_sample"))[:][
"data"
],
]
)
def demo_data(self, request):
return request.param
@pytest.fixture()
def granularity(self):
return int(torch.randint(1, 10, (1,)))
@pytest.fixture
def ae(self, model_configs, demo_data):
model_configs.input_dim = tuple(demo_data[0].shape)
return RHVAE(model_configs)
def test_interpolate(self, ae, demo_data, granularity):
with pytest.raises(AssertionError):
ae.interpolate(demo_data, demo_data[1:], granularity)
interp = ae.interpolate(demo_data, demo_data, granularity)
assert tuple(interp.shape) == (
demo_data.shape[0],
granularity,
) + (demo_data.shape[1:])
class Test_Model_reconstruct:
@pytest.fixture(
params=[
torch.rand(3, 2, 3, 1),
torch.rand(3, 2, 2),
torch.load(os.path.join(PATH, "data/mnist_clean_train_dataset_sample"))[:][
"data"
],
]
)
def demo_data(self, request):
return request.param
@pytest.fixture
def ae(self, model_configs, demo_data):
model_configs.input_dim = tuple(demo_data[0].shape)
return RHVAE(model_configs)
def test_reconstruct(self, ae, demo_data):
recon = ae.reconstruct(demo_data)
assert tuple(recon.shape) == demo_data.shape
class Test_NLL_Compute:
@pytest.fixture
def demo_data(self):
data = torch.load(os.path.join(PATH, "data/mnist_clean_train_dataset_sample"))[
:
]
return data # This is an extract of 3 data from MNIST (unnormalized) used to test custom architecture
@pytest.fixture
def rhvae(self, model_configs, demo_data):
model_configs.input_dim = tuple(demo_data["data"][0].shape)
return RHVAE(model_configs)
@pytest.fixture(params=[(20, 10), (11, 22)])
def nll_params(self, request):
return request.param
def test_nll_compute(self, rhvae, demo_data, nll_params):
nll = rhvae.get_nll(
data=demo_data["data"], n_samples=nll_params[0], batch_size=nll_params[1]
)
assert isinstance(nll, float)
assert nll < 0
@pytest.mark.slow
class Test_RHVAE_Training:
@pytest.fixture
def train_dataset(self):
return torch.load(os.path.join(PATH, "data/mnist_clean_train_dataset_sample"))
@pytest.fixture(
params=[BaseTrainerConfig(num_epochs=3, steps_saving=2, learning_rate=1e-5)]
)
def training_configs(self, tmpdir, request):
tmpdir.mkdir("dummy_folder")
dir_path = os.path.join(tmpdir, "dummy_folder")
request.param.output_dir = dir_path
return request.param
@pytest.fixture(params=[torch.rand(1), torch.rand(1), torch.rand(1)])
def rhvae(
self, model_configs, custom_encoder, custom_decoder, custom_metric, request
):
# randomized
alpha = request.param
if alpha < 0.125:
model = RHVAE(model_configs)
elif 0.125 <= alpha < 0.25:
model = RHVAE(model_configs, encoder=custom_encoder)
elif 0.25 <= alpha < 0.375:
model = RHVAE(model_configs, decoder=custom_decoder)
elif 0.375 <= alpha < 0.5:
model = RHVAE(model_configs, metric=custom_metric)
elif 0.5 <= alpha < 0.625:
model = RHVAE(model_configs, encoder=custom_encoder, decoder=custom_decoder)
elif 0.625 <= alpha < 0:
model = RHVAE(model_configs, encoder=custom_encoder, metric=custom_metric)
elif 0.750 <= alpha < 0.875:
model = RHVAE(model_configs, decoder=custom_decoder, metric=custom_metric)
else:
model = RHVAE(
model_configs,
encoder=custom_encoder,
decoder=custom_decoder,
metric=custom_metric,
)
return model
@pytest.fixture
def trainer(self, rhvae, train_dataset, training_configs):
trainer = BaseTrainer(
model=rhvae,
train_dataset=train_dataset,
eval_dataset=train_dataset,
training_config=training_configs,
)
trainer.prepare_training()
return trainer
return optimizer
def test_rhvae_train_step(self, trainer):
start_model_state_dict = deepcopy(trainer.model.state_dict())
step_1_loss = trainer.train_step(epoch=1)
step_1_model_state_dict = deepcopy(trainer.model.state_dict())
# check that weights were updated
assert not all(
[
torch.equal(start_model_state_dict[key], step_1_model_state_dict[key])
for key in start_model_state_dict.keys()
]
)
def test_rhvae_eval_step(self, trainer):
start_model_state_dict = deepcopy(trainer.model.state_dict())
step_1_loss = trainer.eval_step(epoch=1)
step_1_model_state_dict = deepcopy(trainer.model.state_dict())
# check that weights were not updated
assert all(
[
torch.equal(start_model_state_dict[key], step_1_model_state_dict[key])
for key in start_model_state_dict.keys()
]
)
def test_rhvae_predict_step(self, trainer, train_dataset):
start_model_state_dict = deepcopy(trainer.model.state_dict())
inputs, recon, generated = trainer.predict(trainer.model)
step_1_model_state_dict = deepcopy(trainer.model.state_dict())
# check that weights were not updated
assert all(
[
torch.equal(start_model_state_dict[key], step_1_model_state_dict[key])
for key in start_model_state_dict.keys()
]
)
assert inputs.cpu() in train_dataset.data
assert recon.shape == inputs.shape
assert generated.shape == inputs.shape
def test_rhvae_main_train_loop(self, trainer):
start_model_state_dict = deepcopy(trainer.model.state_dict())
trainer.train()
step_1_model_state_dict = deepcopy(trainer.model.state_dict())
# check that weights were updated
assert not all(
[
torch.equal(start_model_state_dict[key], step_1_model_state_dict[key])
for key in start_model_state_dict.keys()
]
)
def test_checkpoint_saving(self, rhvae, trainer, training_configs):
dir_path = training_configs.output_dir
# Make a training step
step_1_loss = trainer.train_step(epoch=1)
model = deepcopy(trainer.model)
optimizer = deepcopy(trainer.optimizer)
trainer.save_checkpoint(dir_path=dir_path, epoch=0, model=model)
checkpoint_dir = os.path.join(dir_path, "checkpoint_epoch_0")
assert os.path.isdir(checkpoint_dir)
files_list = os.listdir(checkpoint_dir)
assert set(["model.pt", "optimizer.pt", "training_config.json"]).issubset(
set(files_list)
)
# check pickled custom decoder
if not rhvae.model_config.uses_default_decoder:
assert "decoder.pkl" in files_list
else:
assert not "decoder.pkl" in files_list
# check pickled custom encoder
if not rhvae.model_config.uses_default_encoder:
assert "encoder.pkl" in files_list
else:
assert not "encoder.pkl" in files_list
# check pickled custom metric
if not rhvae.model_config.uses_default_metric:
assert "metric.pkl" in files_list
else:
assert not "metric.pkl" in files_list
model_rec_state_dict = torch.load(os.path.join(checkpoint_dir, "model.pt"))[
"model_state_dict"
]
model_rec_state_dict = torch.load(os.path.join(checkpoint_dir, "model.pt"))[
"model_state_dict"
]
assert all(
[
torch.equal(
model_rec_state_dict[key].cpu(), model.state_dict()[key].cpu()
)
for key in model.state_dict().keys()
]
)
# check reload full model
model_rec = AutoModel.load_from_folder(os.path.join(checkpoint_dir))
assert all(
[
torch.equal(
model_rec.state_dict()[key].cpu(), model.state_dict()[key].cpu()
)
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens.cpu(), model.M_tens.cpu())
assert torch.equal(model_rec.centroids_tens.cpu(), model.centroids_tens.cpu())
assert type(model_rec.encoder.cpu()) == type(model.encoder.cpu())
assert type(model_rec.decoder.cpu()) == type(model.decoder.cpu())
assert type(model_rec.metric.cpu()) == type(model.metric.cpu())
optim_rec_state_dict = torch.load(os.path.join(checkpoint_dir, "optimizer.pt"))
assert all(
[
dict_rec == dict_optimizer
for (dict_rec, dict_optimizer) in zip(
optim_rec_state_dict["param_groups"],
optimizer.state_dict()["param_groups"],
)
]
)
assert all(
[
dict_rec == dict_optimizer
for (dict_rec, dict_optimizer) in zip(
optim_rec_state_dict["state"], optimizer.state_dict()["state"]
)
]
)
def test_checkpoint_saving_during_training(self, rhvae, trainer, training_configs):
#
target_saving_epoch = training_configs.steps_saving
dir_path = training_configs.output_dir
model = deepcopy(trainer.model)
trainer.train()
training_dir = os.path.join(
dir_path, f"RHVAE_training_{trainer._training_signature}"
)
assert os.path.isdir(training_dir)
checkpoint_dir = os.path.join(
training_dir, f"checkpoint_epoch_{target_saving_epoch}"
)
assert os.path.isdir(checkpoint_dir)
files_list = os.listdir(checkpoint_dir)
# check files
assert set(["model.pt", "optimizer.pt", "training_config.json"]).issubset(
set(files_list)
)
# check pickled custom decoder
if not rhvae.model_config.uses_default_decoder:
assert "decoder.pkl" in files_list
else:
assert not "decoder.pkl" in files_list
# check pickled custom encoder
if not rhvae.model_config.uses_default_encoder:
assert "encoder.pkl" in files_list
else:
assert not "encoder.pkl" in files_list
# check pickled custom metric
if not rhvae.model_config.uses_default_metric:
assert "metric.pkl" in files_list
else:
assert not "metric.pkl" in files_list
model_rec_state_dict = torch.load(os.path.join(checkpoint_dir, "model.pt"))[
"model_state_dict"
]
assert not all(
[
torch.equal(model_rec_state_dict[key], model.state_dict()[key])
for key in model.state_dict().keys()
]
)
def test_final_model_saving(self, rhvae, trainer, training_configs):
dir_path = training_configs.output_dir
trainer.train()
model = deepcopy(trainer._best_model)
training_dir = os.path.join(
dir_path, f"RHVAE_training_{trainer._training_signature}"
)
assert os.path.isdir(training_dir)
final_dir = os.path.join(training_dir, f"final_model")
assert os.path.isdir(final_dir)
files_list = os.listdir(final_dir)
assert set(["model.pt", "model_config.json", "training_config.json"]).issubset(
set(files_list)
)
# check pickled custom decoder
if not rhvae.model_config.uses_default_decoder:
assert "decoder.pkl" in files_list
else:
assert not "decoder.pkl" in files_list
# check pickled custom encoder
if not rhvae.model_config.uses_default_encoder:
assert "encoder.pkl" in files_list
else:
assert not "encoder.pkl" in files_list
# check pickled custom metric
if not rhvae.model_config.uses_default_metric:
assert "metric.pkl" in files_list
else:
assert not "metric.pkl" in files_list
# check reload full model
model_rec = AutoModel.load_from_folder(os.path.join(final_dir))
assert all(
[
torch.equal(
model_rec.state_dict()[key].cpu(), model.state_dict()[key].cpu()
)
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens.cpu(), model.M_tens.cpu())
assert torch.equal(model_rec.centroids_tens.cpu(), model.centroids_tens.cpu())
assert type(model_rec.encoder.cpu()) == type(model.encoder.cpu())
assert type(model_rec.decoder.cpu()) == type(model.decoder.cpu())
assert type(model_rec.metric.cpu()) == type(model.metric.cpu())
def test_rhvae_training_pipeline(self, rhvae, train_dataset, training_configs):
dir_path = training_configs.output_dir
# build pipeline
pipeline = TrainingPipeline(model=rhvae, training_config=training_configs)
assert pipeline.training_config.__dict__ == training_configs.__dict__
# Launch Pipeline
pipeline(
train_data=train_dataset.data, # gives tensor to pipeline
eval_data=train_dataset.data, # gives tensor to pipeline
)
model = deepcopy(pipeline.trainer._best_model)
training_dir = os.path.join(
dir_path, f"RHVAE_training_{pipeline.trainer._training_signature}"
)
assert os.path.isdir(training_dir)
final_dir = os.path.join(training_dir, f"final_model")
assert os.path.isdir(final_dir)
files_list = os.listdir(final_dir)
assert set(["model.pt", "model_config.json", "training_config.json"]).issubset(
set(files_list)
)
# check pickled custom decoder
if not rhvae.model_config.uses_default_decoder:
assert "decoder.pkl" in files_list
else:
assert not "decoder.pkl" in files_list
# check pickled custom encoder
if not rhvae.model_config.uses_default_encoder:
assert "encoder.pkl" in files_list
else:
assert not "encoder.pkl" in files_list
# check pickled custom metric
if not rhvae.model_config.uses_default_metric:
assert "metric.pkl" in files_list
else:
assert not "metric.pkl" in files_list
# check reload full model
model_rec = AutoModel.load_from_folder(os.path.join(final_dir))
assert all(
[
torch.equal(
model_rec.state_dict()[key].cpu(), model.state_dict()[key].cpu()
)
for key in model.state_dict().keys()
]
)
assert torch.equal(model_rec.M_tens.cpu(), model.M_tens.cpu())
assert torch.equal(model_rec.centroids_tens.cpu(), model.centroids_tens.cpu())
assert type(model_rec.encoder.cpu()) == type(model.encoder.cpu())
assert type(model_rec.decoder.cpu()) == type(model.decoder.cpu())
assert type(model_rec.metric.cpu()) == type(model.metric.cpu())
class Test_RHVAE_Generation:
@pytest.fixture
def train_data(self):
return torch.load(
os.path.join(PATH, "data/mnist_clean_train_dataset_sample")
).data
@pytest.fixture()
def ae_model(self):
return RHVAE(RHVAEConfig(input_dim=(1, 28, 28), latent_dim=7))
@pytest.fixture(
params=[
NormalSamplerConfig(),
GaussianMixtureSamplerConfig(),
MAFSamplerConfig(),
IAFSamplerConfig(),
TwoStageVAESamplerConfig(),
]
)
def sampler_configs(self, request):
return request.param
def test_fits_in_generation_pipeline(self, ae_model, sampler_configs, train_data):
pipeline = GenerationPipeline(model=ae_model, sampler_config=sampler_configs)
gen_data = pipeline(
num_samples=11,
batch_size=7,
output_dir=None,
return_gen=True,
train_data=train_data,
eval_data=train_data,
training_config=BaseTrainerConfig(num_epochs=1),
)
assert gen_data.shape[0] == 11