-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
3872 lines (3173 loc) · 147 KB
/
models.py
File metadata and controls
3872 lines (3173 loc) · 147 KB
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 math
from typing import List
import numpy as np
from torch import nn
from torch.nn import functional as F
import torch
import timm
from optimizer import get_optimizer, get_scheduler
from configs import JEPAConfig
from utils import calculate_max_timesteps
from typing import Dict
from loss import VICRegLoss
vicreg_loss = VICRegLoss()
def build_mlp(layers_dims: List[int]):
layers = []
for i in range(len(layers_dims) - 2):
layers.append(nn.Linear(layers_dims[i], layers_dims[i + 1]))
layers.append(nn.BatchNorm1d(layers_dims[i + 1]))
layers.append(nn.ReLU(True))
layers.append(nn.Linear(layers_dims[-2], layers_dims[-1]))
return nn.Sequential(*layers)
class MockModel(torch.nn.Module):
"""
Does nothing. Just for testing.
"""
def __init__(self, device="cuda", bs=64, n_steps=17, output_dim=256):
super().__init__()
self.device = device
self.bs = bs
self.n_steps = n_steps
self.repr_dim = 256
def forward(self, states, actions):
"""
Args:
During training:
states: [B, T, Ch, H, W]
During inference:
states: [B, 1, Ch, H, W]
actions: [B, T-1, 2]
Output:
predictions: [B, T, D]
"""
return torch.randn((self.bs, self.n_steps, self.repr_dim)).to(self.device)
class Prober(torch.nn.Module):
def __init__(
self,
embedding: int,
arch: str,
output_shape: List[int],
):
super().__init__()
self.output_dim = np.prod(output_shape)
self.output_shape = output_shape
self.arch = arch
arch_list = list(map(int, arch.split("-"))) if arch != "" else []
f = [embedding] + arch_list + [self.output_dim]
layers = []
for i in range(len(f) - 2):
layers.append(torch.nn.Linear(f[i], f[i + 1]))
layers.append(torch.nn.ReLU(True))
layers.append(torch.nn.Linear(f[-2], f[-1]))
self.prober = torch.nn.Sequential(*layers)
def forward(self, e):
output = self.prober(e)
return output
# --- JEPA Architecture ---
class BaseModel(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
def forward(self, *args, **kwargs):
raise NotImplementedError
def training_step(self, batch):
raise NotImplementedError
def validation_step(self, batch):
raise NotImplementedError
# Encoder class adjusted to accept config
class Encoder(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.repr_dim = config.embed_dim
self.conv = nn.Sequential(
nn.Conv2d(
config.in_c, 32, kernel_size=3, stride=2, padding=1
), # Conv2d layer
nn.ReLU(),
)
self.flatten = nn.Flatten()
self.fc = nn.Linear(32 * 33 * 33, self.repr_dim) # Fully connected layer
def forward(self, x):
# x: (B*T, C, H, W) = (B*T, 2, 65, 65)
x = self.conv(x) # (B*T, 2, 65, 65) -> (B*T, 32, 33, 33)
x = self.flatten(x) # (B*T, 32, 33, 33) -> (B*T, 32*33*33)
x = self.fc(x) # (B*T, 32*33*33) -> (B*T, embed_dim)
return x # (B*T, embed_dim)
# Predictor class adjusted to accept config
class Predictor(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.repr_dim = config.embed_dim
self.action_proj = nn.Linear(
config.action_dim, self.repr_dim
) # Project action to repr_dim
# Optionally, you can add a projection for the state embedding
# self.state_proj = nn.Linear(self.repr_dim, self.repr_dim)
# For simplicity, we'll assume identity for state embedding
self.fc = nn.Sequential(
nn.ReLU(),
nn.Linear(self.repr_dim, self.repr_dim), # Further processing
)
def forward(self, s_embed, a):
# s_embed: (B*(T-1), repr_dim)
# a: (B*(T-1), action_dim)
a_proj = self.action_proj(a) # (B*(T-1), repr_dim)
# s_proj = self.state_proj(s_embed) # If projecting s_embed
s_proj = s_embed # If not projecting s_embed
x = s_proj + a_proj # Element-wise addition: (B*(T-1), repr_dim)
x = self.fc(x) # Further processing: (B*(T-1), repr_dim)
return x # (B*(T-1), repr_dim)
# JEPA model adjusted to accept config
class JEPA(BaseModel):
def __init__(self, config):
super().__init__(config)
self.enc = Encoder(config)
self.pred = Predictor(config)
self.optimizer = get_optimizer(config, self.parameters())
self.scheduler = get_scheduler(self.optimizer, config)
self.config = config
self.repr_dim = config.embed_dim
def forward(self, states, actions, teacher_forcing=True):
B, _, C, H, W = states.shape # states: (B, T, C, H, W)
T = actions.shape[1] + 1 # Number of timesteps | actions: (B, T-1, action_dim)
if teacher_forcing:
states = states.view(B * T, C, H, W) # Reshape to (B*T, C, H, W)
enc_states = self.enc(states) # (B*T, embed_dim)
enc_states = enc_states.view(B, T, -1) # (B, T, embed_dim)
preds = torch.zeros_like(enc_states) # preds: (B, T, embed_dim)
preds[:, 0, :] = enc_states[:, 0, :] # Initialize first timestep
# Prepare inputs for the predictor
states_embed = enc_states[:, :-1, :] # (B, T-1, embed_dim)
states_embed = states_embed.reshape(
-1, self.config.embed_dim
) # (B*(T-1), embed_dim)
actions = actions.reshape(
-1, self.config.action_dim
) # (B*(T-1), action_dim)
pred_states = self.pred(states_embed, actions) # (B*(T-1), embed_dim)
pred_states = pred_states.view(
B, T - 1, self.config.embed_dim
) # (B, T-1, embed_dim)
preds[:, 1:, :] = pred_states # Assign predictions to preds
return (
preds,
enc_states,
) # preds: (B, T, embed_dim), enc_states: (B, T, embed_dim)
else:
states_0 = states[:, 0, :, :, :] # (B, C, H, W)
enc_state = self.enc(states_0) # (B, embed_dim)
preds = [enc_state] # List to store predictions
for t in range(1, T):
action_t_minus1 = actions[:, t - 1, :] # (B, action_dim)
state_embed_t_minus1 = preds[-1] # Use the last predicted embedding
pred_state = self.pred(
state_embed_t_minus1, action_t_minus1
) # (B, embed_dim)
preds.append(pred_state)
# Stack predictions and true encodings along the time dimension
preds = torch.stack(preds, dim=1) # (B, T, embed_dim)
return preds
def compute_mse_loss(self, preds, enc_s):
# preds, enc_s: (B, T, embed_dim)
loss = F.mse_loss(
preds[:, 1:], enc_s[:, 1:]
) # Compute MSE loss for timesteps 1 to T-1
return loss
def compute_vicreg_loss(self, preds, enc_s, gamma=1.0, epsilon=1e-4):
"""
Compute VICReg loss with invariance, variance, and covariance terms.
Args:
preds: Predicted embeddings from the predictor. Shape (B, T, embed_dim).
enc_s: Target embeddings from the encoder. Shape (B, T, embed_dim).
gamma: Target standard deviation for variance term.
epsilon: Small value to avoid numerical instability.
Returns:
vicreg_loss: The combined VICReg loss.
"""
# taking from config
lambda_invariance = self.config.vicreg_loss.lambda_invariance
mu_variance = self.config.vicreg_loss.mu_variance
nu_covariance = self.config.vicreg_loss.nu_covariance
preds, enc_s = preds[:, 1:], enc_s[:, 1:]
# Flatten temporal dimensions for batch processing
B, T, embed_dim = preds.shape
Z = preds.reshape(B * T, embed_dim) # Predicted embeddings
Z_prime = enc_s.reshape(B * T, embed_dim) # Target embeddings
# --- Invariance Term ---
invariance_loss = torch.mean(
torch.sum((Z - Z_prime) ** 2, dim=1)
) # Mean squared Euclidean distance
# --- Variance Term ---
# Compute standard deviation along the batch dimension
std_Z = torch.sqrt(Z.var(dim=0, unbiased=False) + epsilon)
std_Z_prime = torch.sqrt(Z_prime.var(dim=0, unbiased=False) + epsilon)
variance_loss = torch.mean(F.relu(gamma - std_Z)) + torch.mean(
F.relu(gamma - std_Z_prime)
)
# --- Covariance Term ---
# Center the embeddings
Z_centered = Z - Z.mean(dim=0, keepdim=True)
Z_prime_centered = Z_prime - Z_prime.mean(dim=0, keepdim=True)
# Compute covariance matrices
cov_Z = (Z_centered.T @ Z_centered) / (B * T - 1)
cov_Z_prime = (Z_prime_centered.T @ Z_prime_centered) / (B * T - 1)
# Sum of squared off-diagonal elements
cov_loss_Z = torch.sum(cov_Z**2) - torch.sum(torch.diag(cov_Z) ** 2)
cov_loss_Z_prime = torch.sum(cov_Z_prime**2) - torch.sum(
torch.diag(cov_Z_prime) ** 2
)
covariance_loss = cov_loss_Z + cov_loss_Z_prime
# --- Total VICReg Loss ---
vicreg_loss = (
lambda_invariance * invariance_loss
+ mu_variance * variance_loss
+ nu_covariance * covariance_loss
)
return vicreg_loss, invariance_loss, variance_loss, covariance_loss
def training_step(self, batch, device):
states, actions = batch.states.to(device, non_blocking=True), batch.actions.to(
device, non_blocking=True
)
preds, enc_s = self.forward(states, actions)
# loss = self.compute_mse_loss(preds, enc_s) # Normal Loss Calculation
loss, invariance_loss, variance_loss, covariance_loss = (
self.compute_vicreg_loss(preds, enc_s)
) # VICReg Loss Calculation
self.optimizer.zero_grad()
loss.backward()
# Compute grad_norm without clipping
grad_norm = 0.0
for p in self.parameters():
if p.grad is not None:
param_norm = p.grad.data.norm(2)
grad_norm += param_norm.item() ** 2
grad_norm = grad_norm**0.5
self.optimizer.step()
self.scheduler.step() # Step the scheduler
learning_rate = self.optimizer.param_groups[0]["lr"]
# Compute the absolute value of the action weights
action_weight = (
self.pred.action_proj.weight
) # Get weights from the action projection layer
action_weight_abs = (
action_weight.abs().mean().item()
) # Compute the mean absolute value
# Compute deviation from identity for fc layer
fc_weight = self.pred.fc[
1
].weight # Get the weights of the Linear layer inside fc
identity_matrix = torch.eye(fc_weight.size(0), fc_weight.size(1)).to(
fc_weight.device
)
deviation_from_identity = torch.norm(
fc_weight - identity_matrix, p="fro"
) / torch.norm(identity_matrix, p="fro")
# Prepare the output dictionary
output = {
"loss": loss.item(),
"grad_norm": grad_norm,
"learning_rate": learning_rate,
"action_weight_abs": action_weight_abs,
"deviation_from_identity_pred_final_proj": deviation_from_identity.item(), # Log the deviation
"invariance_loss": invariance_loss,
"variance_loss": variance_loss,
"covariance_loss": covariance_loss,
# Add more loggable values here if needed
}
# Non-loggable data
output["non_logs"] = {
"states": states.detach(),
"actions": actions.detach(),
"enc_embeddings": enc_s.detach(),
"pred_embeddings": preds.detach(),
}
return output
def validation_step(self, batch):
states, actions = batch.states, batch.actions
preds, enc_s = self.forward(states, actions)
loss = self.compute_mse_loss(preds, enc_s)
learning_rate = self.optimizer.param_groups[0]["lr"]
# Compute the absolute value of the action weights
action_weight = (
self.pred.action_proj.weight
) # Get weights from the action projection layer
action_weight_abs = (
action_weight.abs().mean().item()
) # Compute the mean absolute value
# Compute deviation from identity for fc layer
fc_weight = self.pred.fc[
1
].weight # Get the weights of the Linear layer inside fc
identity_matrix = torch.eye(fc_weight.size(0), fc_weight.size(1)).to(
fc_weight.device
)
deviation_from_identity = torch.norm(
fc_weight - identity_matrix, p="fro"
) / torch.norm(identity_matrix, p="fro")
# Prepare the output dictionary
output = {
"loss": loss.item(),
"learning_rate": learning_rate,
"action_weight_abs": action_weight_abs,
"deviation_from_identity_pred_final_proj": deviation_from_identity.item(), # Log the deviation
}
# Non-loggable data
output["non_logs"] = {
"states": states.detach(),
"actions": actions.detach(),
"enc_embeddings": enc_s.detach(),
"pred_embeddings": preds.detach(),
}
return output
# AdversarialJEPA model adjusted to accept config
class Discriminator(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, input_dim // 2),
nn.ReLU(),
nn.Linear(input_dim // 2, 1),
nn.Sigmoid(),
)
def forward(self, x):
# x: (N, input_dim)
return self.net(x) # (N, input_dim) -> (N, 1)
class ActionRegularizer(nn.Module):
def __init__(self, embed_dim, action_dim, action_reg_hidden_dim):
super().__init__()
self.action_reg_net = nn.Sequential(
nn.Linear(embed_dim, action_reg_hidden_dim),
nn.ReLU(),
nn.Linear(action_reg_hidden_dim, action_dim),
)
def forward(self, states_embed, pred_states):
# Calculate embedding differences
embedding_diff = (
pred_states - states_embed
) # Difference between input and output of predictor
# Predict actions from embedding differences
predicted_actions = self.action_reg_net(embedding_diff) # (B*(T-1), action_dim)
return predicted_actions
class AdversarialJEPAWithRegularization(BaseModel):
def __init__(self, config):
super().__init__(config)
self.enc = Encoder(config)
self.pred = Predictor(config)
self.disc = Discriminator(config.embed_dim)
self.action_reg_net = ActionRegularizer(
config.embed_dim, config.action_dim, config.action_reg_hidden_dim
)
self.gen_opt = get_optimizer(
config,
list(self.enc.parameters())
+ list(self.pred.parameters())
+ list(self.action_reg_net.parameters()),
)
self.disc_opt = get_optimizer(config, self.disc.parameters())
self.gen_sched = get_scheduler(self.gen_opt, config)
self.disc_sched = get_scheduler(self.disc_opt, config)
self.config = config
self.repr_dim = config.embed_dim
def forward(self, states, actions, teacher_forcing=True):
B, _, C, H, W = states.shape # states: (B, T, C, H, W)
T = actions.shape[1] + 1 # Number of timesteps | actions: (B, T-1, action_dim)
if teacher_forcing:
states = states.view(B * T, C, H, W) # Reshape to (B*T, C, H, W)
enc_states = self.enc(states) # (B*T, embed_dim)
enc_states = enc_states.view(B, T, -1) # (B, T, embed_dim)
preds = torch.zeros_like(enc_states) # preds: (B, T, embed_dim)
preds[:, 0, :] = enc_states[:, 0, :] # Initialize first timestep
# Prepare inputs for the predictor
states_embed = enc_states[:, :-1, :] # (B, T-1, embed_dim)
states_embed = states_embed.reshape(
-1, self.config.embed_dim
) # (B*(T-1), embed_dim)
actions = actions.reshape(
-1, self.config.action_dim
) # (B*(T-1), action_dim)
pred_states = self.pred(states_embed, actions) # (B*(T-1), embed_dim)
pred_states = pred_states.view(
B, T - 1, self.config.embed_dim
) # (B, T-1, embed_dim)
preds[:, 1:, :] = pred_states # Assign predictions to preds
return (
preds,
enc_states,
) # preds: (B, T, embed_dim), enc_states: (B, T, embed_dim)
else:
states_0 = states[:, 0, :, :, :] # (B, C, H, W)
enc_state = self.enc(states_0) # (B, embed_dim)
preds = [enc_state] # List to store predictions
for t in range(1, T):
action_t_minus1 = actions[:, t - 1, :] # (B, action_dim)
state_embed_t_minus1 = preds[-1] # Use the last predicted embedding
pred_state = self.pred(
state_embed_t_minus1, action_t_minus1
) # (B, embed_dim)
preds.append(pred_state)
# Stack predictions and true encodings along the time dimension
preds = torch.stack(preds, dim=1) # (B, T, embed_dim)
return preds
def compute_mse_loss(self, preds, enc_s):
# preds, enc_s: (B, T, embed_dim)
loss = F.mse_loss(
preds[:, 1:], enc_s[:, 1:]
) # Compute MSE loss for timesteps 1 to T-1
return loss
def compute_regularization_loss(self, states_embed, pred_states, actions):
"""
Computes the regularization loss based on the embedding difference and actions.
"""
# Predict actions from embedding differences
predicted_actions = self.action_reg_net(
states_embed, pred_states
) # (B*(T-1), action_dim)
actions = actions.view(
-1, self.config.action_dim
) # Flatten actions to (B*(T-1), action_dim)
# Compute MSE loss between predicted and actual actions
reg_loss = F.mse_loss(predicted_actions, actions)
return reg_loss
def compute_vicreg_loss(self, preds, enc_s, gamma=1.0, epsilon=1e-4):
"""
Compute VICReg loss with invariance, variance, and covariance terms.
Args:
preds: Predicted embeddings from the predictor. Shape (B, T, embed_dim).
enc_s: Target embeddings from the encoder. Shape (B, T, embed_dim).
gamma: Target standard deviation for variance term.
epsilon: Small value to avoid numerical instability.
Returns:
vicreg_loss: The combined VICReg loss.
"""
# taking from config
lambda_invariance = self.config.vicreg_loss.lambda_invariance
mu_variance = self.config.vicreg_loss.mu_variance
nu_covariance = self.config.vicreg_loss.nu_covariance
preds, enc_s = preds[:, 1:], enc_s[:, 1:]
# Flatten temporal dimensions for batch processing
B, T, embed_dim = preds.shape
Z = preds.reshape(B * T, embed_dim) # Predicted embeddings
Z_prime = enc_s.reshape(B * T, embed_dim) # Target embeddings
# --- Invariance Term ---
invariance_loss = torch.mean(
torch.sum((Z - Z_prime) ** 2, dim=1)
) # Mean squared Euclidean distance
# --- Variance Term ---
# Compute standard deviation along the batch dimension
std_Z = torch.sqrt(Z.var(dim=0, unbiased=False) + epsilon)
std_Z_prime = torch.sqrt(Z_prime.var(dim=0, unbiased=False) + epsilon)
variance_loss = torch.mean(F.relu(gamma - std_Z)) + torch.mean(
F.relu(gamma - std_Z_prime)
)
# --- Covariance Term ---
# Center the embeddings
Z_centered = Z - Z.mean(dim=0, keepdim=True)
Z_prime_centered = Z_prime - Z_prime.mean(dim=0, keepdim=True)
# Compute covariance matrices
cov_Z = (Z_centered.T @ Z_centered) / (B * T - 1)
cov_Z_prime = (Z_prime_centered.T @ Z_prime_centered) / (B * T - 1)
# Sum of squared off-diagonal elements
cov_loss_Z = torch.sum(cov_Z**2) - torch.sum(torch.diag(cov_Z) ** 2)
cov_loss_Z_prime = torch.sum(cov_Z_prime**2) - torch.sum(
torch.diag(cov_Z_prime) ** 2
)
covariance_loss = cov_loss_Z + cov_loss_Z_prime
# --- Total VICReg Loss ---
vicreg_loss = (
lambda_invariance * invariance_loss
+ mu_variance * variance_loss
+ nu_covariance * covariance_loss
)
return vicreg_loss, invariance_loss, variance_loss, covariance_loss
def compute_discriminator_loss(self, preds, enc_s):
"""
Computes the discriminator loss using real and fake embeddings.
"""
# Extract embeddings
real_embeddings = enc_s[:, 1:].reshape(-1, self.config.embed_dim)
fake_embeddings = preds[:, 1:].detach().reshape(-1, self.config.embed_dim)
# Create labels
real_labels = torch.ones(
real_embeddings.size(0), 1, device=real_embeddings.device
)
fake_labels = torch.zeros(
fake_embeddings.size(0), 1, device=fake_embeddings.device
)
# Discriminator predictions
real_predictions = self.disc(real_embeddings)
fake_predictions = self.disc(fake_embeddings)
# Compute binary cross-entropy losses
disc_loss_real = F.binary_cross_entropy(real_predictions, real_labels)
disc_loss_fake = F.binary_cross_entropy(fake_predictions, fake_labels)
# Average the losses
disc_loss = (disc_loss_real + disc_loss_fake) / 2
return disc_loss
def compute_generator_loss(self, preds):
fake_embeddings = preds[:, 1:].detach().reshape(-1, self.config.embed_dim)
real_labels = torch.ones(
fake_embeddings.size(0), 1, device=fake_embeddings.device
)
gen_predictions = self.disc(preds[:, 1:].reshape(-1, self.config.embed_dim))
gen_loss = F.binary_cross_entropy(gen_predictions, real_labels)
return gen_loss
def training_step(self, batch, device):
states, actions = batch.states.to(device, non_blocking=True), batch.actions.to(
device, non_blocking=True
)
# Step 1: Train the discriminator
with torch.no_grad(): # Detach generator computations to avoid unnecessary graph retention
preds, enc_s = self.forward(states, actions)
disc_loss = self.compute_discriminator_loss(preds, enc_s)
self.disc_opt.zero_grad()
disc_loss.backward()
self.disc_opt.step()
# Step 2: Train the generator
preds, enc_s = self.forward(states, actions) # Perform forward pass again
gen_loss = self.compute_generator_loss(preds)
reg_loss = self.compute_regularization_loss(
enc_s[:, :-1].reshape(-1, self.config.embed_dim),
preds[:, 1:].reshape(-1, self.config.embed_dim),
actions.reshape(-1, self.config.action_dim),
)
vicreg_loss, invariance_loss, variance_loss, covariance_loss = (
self.compute_vicreg_loss(preds, enc_s)
)
total_loss = (
self.config.delta_gen * gen_loss
+ self.config.lambda_reg * reg_loss
+ vicreg_loss
)
self.gen_opt.zero_grad()
total_loss.backward()
self.gen_opt.step()
# Update learning rate schedulers
self.gen_sched.step()
self.disc_sched.step()
learning_rate = self.gen_opt.param_groups[0]["lr"]
disc_learning_rate = self.disc_opt.param_groups[0]["lr"]
# Compute the absolute value of the action weights
action_weight = (
self.pred.action_proj.weight
) # Get weights from the action projection layer
action_weight_abs = (
action_weight.abs().mean().item()
) # Compute the mean absolute value
# Compute deviation from identity for fc layer
fc_weight = self.pred.fc[
1
].weight # Get the weights of the Linear layer inside fc
identity_matrix = torch.eye(fc_weight.size(0), fc_weight.size(1)).to(
fc_weight.device
)
deviation_from_identity = torch.norm(
fc_weight - identity_matrix, p="fro"
) / torch.norm(identity_matrix, p="fro")
# Prepare the output dictionary
output = {
"loss": total_loss.item(),
"gen_loss": gen_loss.item(),
"reg_loss": reg_loss.item(),
"vicreg_loss": vicreg_loss.item(),
"invariance_loss": invariance_loss.item(),
"variance_loss": variance_loss.item(),
"covariance_loss": covariance_loss.item(),
"disc_loss": disc_loss.item(),
"learning_rate": learning_rate,
"disc_learning_rate": disc_learning_rate,
"action_weight_abs": action_weight_abs,
"deviation_from_identity_pred_final_proj": deviation_from_identity.item(), # Log the deviation
}
# Non-loggable data
output["non_logs"] = {
"states": states.detach(),
"actions": actions.detach(),
"enc_embeddings": enc_s.detach(),
"pred_embeddings": preds.detach(),
}
return output
def validation_step(self, batch):
states, actions = batch.states, batch.actions
preds, enc_s = self.forward(states, actions)
loss = self.compute_mse_loss(preds, enc_s)
# Compute the absolute value of the action weights
action_weight = (
self.pred.action_proj.weight
) # Get weights from the action projection layer
action_weight_abs = (
action_weight.abs().mean().item()
) # Compute the mean absolute value
# Compute deviation from identity for fc layer
fc_weight = self.pred.fc[
1
].weight # Get the weights of the Linear layer inside fc
identity_matrix = torch.eye(fc_weight.size(0), fc_weight.size(1)).to(
fc_weight.device
)
deviation_from_identity = torch.norm(
fc_weight - identity_matrix, p="fro"
) / torch.norm(identity_matrix, p="fro")
# Prepare the output dictionary
output = {
"loss": loss.item(),
"action_weight_abs": action_weight_abs,
"deviation_from_identity_pred_final_proj": deviation_from_identity.item(), # Log the deviation
}
# Non-loggable data
output["non_logs"] = {
"states": states.detach(),
"actions": actions.detach(),
"enc_embeddings": enc_s.detach(),
"pred_embeddings": preds.detach(),
}
return output
class AdversarialJEPA(BaseModel):
def __init__(self, config):
super().__init__(config)
self.enc = Encoder(config)
self.pred = Predictor(config)
self.disc = Discriminator(config.embed_dim)
self.opt = get_optimizer(config, self.parameters())
self.disc_opt = get_optimizer(config, self.disc.parameters())
self.scheduler = get_scheduler(self.opt, config)
self.scheduler_disc = get_scheduler(self.disc_opt, config)
self.config = config
self.repr_dim = config.embed_dim
def forward(self, states, actions, teacher_forcing=True):
B, _, C, H, W = states.shape # states: (B, T, C, H, W)
T = actions.shape[1] + 1 # Number of timesteps | actions: (B, T-1, action_dim)
if teacher_forcing:
states = states.view(B * T, C, H, W) # Reshape to (B*T, C, H, W)
enc_states = self.enc(states) # (B*T, embed_dim)
enc_states = enc_states.view(B, T, -1) # (B, T, embed_dim)
preds = torch.zeros_like(enc_states) # preds: (B, T, embed_dim)
preds[:, 0, :] = enc_states[:, 0, :] # Initialize first timestep
# Prepare inputs for the predictor
states_embed = enc_states[:, :-1, :] # (B, T-1, embed_dim)
states_embed = states_embed.reshape(
-1, self.config.embed_dim
) # (B*(T-1), embed_dim)
actions = actions.reshape(
-1, self.config.action_dim
) # (B*(T-1), action_dim)
pred_states = self.pred(states_embed, actions) # (B*(T-1), embed_dim)
pred_states = pred_states.view(
B, T - 1, self.config.embed_dim
) # (B, T-1, embed_dim)
preds[:, 1:, :] = pred_states # Assign predictions to preds
return (
preds,
enc_states,
) # preds: (B, T, embed_dim), enc_states: (B, T, embed_dim)
else:
states_0 = states[:, 0, :, :, :] # (B, C, H, W)
enc_state = self.enc(states_0) # (B, embed_dim)
preds = [enc_state] # List to store predictions
for t in range(1, T):
action_t_minus1 = actions[:, t - 1, :] # (B, action_dim)
state_embed_t_minus1 = preds[-1] # Use the last predicted embedding
pred_state = self.pred(
state_embed_t_minus1, action_t_minus1
) # (B, embed_dim)
preds.append(pred_state)
# Stack predictions and true encodings along the time dimension
preds = torch.stack(preds, dim=1) # (B, T, embed_dim)
return preds
def compute_mse_losses(self, preds, enc_s):
real_embeds = enc_s[:, 1:].reshape(
-1, self.config.embed_dim
) # (B*(T-1), embed_dim)
fake_embeds = (
preds[:, 1:].detach().reshape(-1, self.config.embed_dim)
) # (B*(T-1), embed_dim)
real_labels = torch.ones(real_embeds.size(0), 1).to(
real_embeds.device
) # (B*(T-1), 1)
fake_labels = torch.zeros(fake_embeds.size(0), 1).to(
fake_embeds.device
) # (B*(T-1), 1)
real_preds = self.disc(real_embeds) # (B*(T-1), 1)
fake_preds = self.disc(fake_embeds) # (B*(T-1), 1)
disc_loss_real = F.binary_cross_entropy(real_preds, real_labels)
disc_loss_fake = F.binary_cross_entropy(fake_preds, fake_labels)
disc_loss = (disc_loss_real + disc_loss_fake) / 2
# Generator (Predictor) loss
gen_preds = self.disc(
preds[:, 1:].detach().reshape(-1, self.config.embed_dim)
) # (B*(T-1), 1)
pred_labels = torch.ones(gen_preds.size(0), 1).to(
gen_preds.device
) # (B*(T-1), 1)
gen_loss = F.binary_cross_entropy(gen_preds, pred_labels)
# Reconstruction loss
rec_loss = F.mse_loss(preds[:, 1:], enc_s[:, 1:]) # (B, T-1, embed_dim)
# Total loss
total_loss = gen_loss + rec_loss
return disc_loss, total_loss
def training_step(self, batch, device):
states, actions = batch.states.to(device, non_blocking=True), batch.actions.to(
device, non_blocking=True
)
preds, enc_s = self.forward(states, actions)
# Update Discriminator
disc_loss, total_loss = self.compute_mse_losses(preds, enc_s)
self.disc_opt.zero_grad()
disc_loss.backward(retain_graph=True)
self.disc_opt.step()
# Update Encoder and Predictor
self.opt.zero_grad()
total_loss.backward()
# Compute grad_norm without clipping
grad_norm = 0.0
for p in list(self.enc.parameters()) + list(self.pred.parameters()):
if p.grad is not None:
param_norm = p.grad.data.norm(2)
grad_norm += param_norm.item() ** 2
grad_norm = grad_norm**0.5
self.opt.step()
self.scheduler.step() # Step the scheduler
self.scheduler_disc.step() # Step the scheduler
learning_rate = self.opt.param_groups[0][
"lr"
] # Assuming same LR for all optimizers
disc_learning_rate = self.disc_opt.param_groups[0][
"lr"
] # Assuming same LR for all optimizers
# Compute the absolute value of the action weights
action_weight = (
self.pred.action_proj.weight
) # Get weights from the action projection layer
action_weight_abs = (
action_weight.abs().mean().item()
) # Compute the mean absolute value
# Compute deviation from identity for fc layer
fc_weight = self.pred.fc[
1
].weight # Get the weights of the Linear layer inside fc
identity_matrix = torch.eye(fc_weight.size(0), fc_weight.size(1)).to(
fc_weight.device
)
deviation_from_identity = torch.norm(
fc_weight - identity_matrix, p="fro"
) / torch.norm(identity_matrix, p="fro")
# Prepare the output dictionary
output = {
"loss": total_loss.item(),
"disc_loss": disc_loss.item(),
"grad_norm": grad_norm,
"learning_rate": learning_rate,
"disc_learning_rate": disc_learning_rate,
"action_weight_abs": action_weight_abs,
"deviation_from_identity_pred_final_proj": deviation_from_identity.item(), # Log the deviation
}
# Non-loggable data
output["non_logs"] = {
"states": states.detach(),
"actions": actions.detach(),
"enc_embeddings": enc_s.detach(),
"pred_embeddings": preds.detach(),
}
return output
def validation_step(self, batch):
states, actions = batch.states, batch.actions
preds, enc_s = self.forward(states, actions)
loss = self.compute_mse_loss(preds, enc_s)
learning_rate = self.optimizer.param_groups[0]["lr"]
# Compute the absolute value of the action weights
action_weight = (
self.pred.action_proj.weight
) # Get weights from the action projection layer
action_weight_abs = (
action_weight.abs().mean().item()
) # Compute the mean absolute value
# Compute deviation from identity for fc layer
fc_weight = self.pred.fc[
1
].weight # Get the weights of the Linear layer inside fc
identity_matrix = torch.eye(fc_weight.size(0), fc_weight.size(1)).to(
fc_weight.device
)
deviation_from_identity = torch.norm(
fc_weight - identity_matrix, p="fro"
) / torch.norm(identity_matrix, p="fro")
# Prepare the output dictionary
output = {
"loss": loss.item(),
"learning_rate": learning_rate,
"action_weight_abs": action_weight_abs,
"deviation_from_identity_pred_final_proj": deviation_from_identity.item(), # Log the deviation
}
# Non-loggable data
output["non_logs"] = {
"states": states.detach(),
"actions": actions.detach(),
"enc_embeddings": enc_s.detach(),
"pred_embeddings": preds.detach(),
}
return output
# InfoMaxJEPA model adjusted to accept config
class InfoMaxJEPA(BaseModel):
def __init__(self, config):
super().__init__(config)
self.enc = Encoder(config)
self.pred = Predictor(config)
self.optimizer = get_optimizer(config, self.parameters())
self.scheduler = get_scheduler(self.optimizer, config)
self.config = config
self.repr_dim = config.embed_dim