Repository navigation
Expand file tree
/
Copy pathlightning_modules.py
More file actions
1735 lines (1542 loc) · 68.1 KB
/
Copy pathlightning_modules.py
File metadata and controls
1735 lines (1542 loc) · 68.1 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
"""
© 2026 Nokia
Licensed under the BSD 3-Clause License
SPDX-License-Identifier: BSD-3-Clause
SOCPNet Lightning Modules
This module contains PyTorch Lightning modules for SOCPNet training:
- SOCPDataModule: Data handling and preprocessing
- SOCPNetLightning: Trajectory-based training module
- SOCPNetend2endLightning: End-to-end optimal solution prediction module
"""
import math
import os
import torch
import pytorch_lightning as pl
from torch.optim import AdamW
from torch.utils.data import Dataset, Subset
from torch_geometric.loader import DataLoader
from model import (
SOCPNet,
SOCPNetend2end,
FCNNEnd2End,
)
class LazyDataset(Dataset):
"""Lazy-loading dataset. Accepts one root or a list of roots."""
def __init__(
self,
roots, # str or list[str]
split_name,
filenames, # list[str] or list[list[str]]
learn_fixed_point=False,
traj_geometric_coef=None,
full_tail_supervision=False,
):
if isinstance(roots, str):
roots, filenames = [roots], [filenames]
assert len(roots) == len(filenames)
self.filenames = [
os.path.join(root, split_name,fn )
for root, filename_list in zip(roots, filenames)
for fn in filename_list
]
self.learn_fixed_point = learn_fixed_point
self.traj_geometric_coef = traj_geometric_coef
# If True, supervise the whole padded trajectory tail (those columns
# equal x*), so every unroll step is trained to stay at the optimum.
self.full_tail_supervision = full_tail_supervision
def __len__(self):
return len(self.filenames)
def __getitem__(self, idx):
filename = self.filenames[idx]
graph_data = torch.load(
filename, map_location="cpu", weights_only=False
)
# Only create mask if trajectory exists (train/val data), not for test data
if (
hasattr(graph_data, "trajectory")
and graph_data.trajectory is not None
):
graph_data.trajectory_mask = self._create_mask(graph_data)
return graph_data
def _create_mask(self, graph_data):
"""
mask: torch.Tensor of shape [target_length],
contains 1 for real steps, 0 for padded steps
"""
target_length = graph_data.trajectory.shape[1]
traj_len = graph_data.trajectory_length
# Mask: 1 for real steps, 0 for padded steps
mask = torch.zeros(
target_length,
dtype=torch.float32,
device=graph_data.trajectory.device,
)
if self.full_tail_supervision:
# Every column (padded tail = x*) is supervised => stay at optimum.
end_idx = target_length
elif self.learn_fixed_point:
end_idx = min(traj_len + 1, target_length)
else:
end_idx = min(traj_len, target_length)
mask[:end_idx] = 1.0
# Apply geometric decay to trajectory steps
end_idx = min(traj_len, target_length)
if (
self.traj_geometric_coef is not None
and self.traj_geometric_coef < 1.0
):
for i in range(end_idx):
mask[i] *= self.traj_geometric_coef ** (end_idx - 1 - i)
return mask
class SOCPDataModule(pl.LightningDataModule):
"""LightningDataModule for SOCPNet data handling."""
def __init__(
self,
dataset_paths: str | list[str],
batch_size: int,
num_workers: int = 0,
overfitting_test: bool = False,
end2end_mode: bool = False,
learn_fixed_point: bool = True,
traj_geometric_coef: float | None = None,
full_tail_supervision: bool = False,
):
super().__init__()
assert traj_geometric_coef is None or 0 <= traj_geometric_coef <= 1
self._roots = (
[dataset_paths] if isinstance(dataset_paths, str)
else list(dataset_paths)
)
for r in self._roots:
self._ensure_dataset_root(r)
self.dataset_path = self._roots[0] # primary root for stats
self.batch_size = batch_size
self.num_workers = num_workers
self.end2end_mode = end2end_mode
self.learn_fixed_point = learn_fixed_point
self.traj_geometric_coef = traj_geometric_coef
self.full_tail_supervision = full_tail_supervision
self.overfitting_test = overfitting_test
self.dataset_names = [os.path.basename(os.path.normpath(r))
for r in self._roots]
if self.overfitting_test:
print("Overfitting test mode: using only 1 batch for training!")
@staticmethod
def _ensure_dataset_root(path: str) -> None:
if not os.path.isdir(path):
raise FileNotFoundError(
f"Dataset root must be a valid directory, got: {path}"
)
if not os.path.isfile(os.path.join(path, "info.pt")):
raise FileNotFoundError(f"{path} does not contain info.pt")
def denormalize_trajectory(self, normalized_trajectory):
"""Denormalize trajectory predictions [batch_size * n_dim, T]."""
if self.trajectory_mean is None or self.trajectory_std is None:
return normalized_trajectory
dev = normalized_trajectory.device
mean = self.trajectory_mean.to(dev)
std = self.trajectory_std.to(dev)
return normalized_trajectory * std + mean
def setup(self, stage=None):
infos = [
torch.load(
os.path.join(r, "info.pt"),
map_location="cpu",
weights_only=False,
)
for r in self._roots
]
primary = infos[0]
splits = [info["splits_filenames"] for info in infos]
self.trajectory_mean = primary["trajectory_mean"]
self.trajectory_std = primary["trajectory_std"]
self.x_opt_mean = primary["x_opt_mean"]
self.x_opt_std = primary["x_opt_std"]
self.normalize = primary["metadata"]["normalize"]
# Training: concatenation of all roots (shuffled in dataloader)
self.train_dataset = LazyDataset(
self._roots,
"train",
[s["train"] for s in splits],
self.learn_fixed_point,
self.traj_geometric_coef,
self.full_tail_supervision,
)
# Val, test, and test_items: one dataset per root. Val uses the same
# tail supervision so the val metric matches the training objective.
def _make_split(split):
per_root = [
LazyDataset(r, split, s[split],
learn_fixed_point=self.learn_fixed_point,
full_tail_supervision=self.full_tail_supervision)
for r, s in zip(self._roots, splits)
]
return per_root
self.val_datasets = _make_split("val")
self.test_datasets = _make_split("test")
self.test_items_list = _make_split("test_items")
self.test_items = self.test_items_list[-1]
if len(self._roots) > 1:
print("\n----- Loaded datasets with metadata -----")
for idx, info in enumerate(infos):
print(f"Dataset {idx + 1}: {self.dataset_names[idx]}")
for key, value in info["metadata"].items():
print(f" - {key}: {value}")
else:
print("\n----- Loaded dataset with metadata -----")
for key, value in infos[0]["metadata"].items():
print(f" - {key}: {value}")
print()
def _create_dataloader(self, data, shuffle):
if self.overfitting_test:
data = Subset(data, list(range(min(self.batch_size, len(data)))))
return DataLoader(
data,
batch_size=self.batch_size,
shuffle=shuffle,
num_workers=self.num_workers,
)
def train_dataloader(self):
return self._create_dataloader(self.train_dataset, shuffle=True)
def val_dataloader(self):
return [
self._create_dataloader(d, shuffle=False) for d in self.val_datasets
]
def test_dataloader(self):
def _make(d):
if self.overfitting_test:
d = Subset(d, [0])
return DataLoader(
d, batch_size=1, shuffle=False, num_workers=self.num_workers
)
return [_make(d) for d in self.test_datasets]
class SOCPNetLightning(pl.LightningModule):
"""
LightningModule wrapper for SOCPNet model.
Handles training, validation, testing, and optimization for trajectory-based training.
"""
# Valid values for --loss_type (the supervised trajectory loss).
SUPERVISED_LOSS_NAMES = (
"mse", "soft_dtw", "target_final", "target_k", "traj_logsre"
)
def __init__(
self,
d: int,
T: int,
lr: float,
zero_everything: bool = False,
model_type: str = "SOCPNet",
message_passing_scheme: str = "three_step",
teacher_forcing_p: float = 0.0,
target_length: int | None = None,
aggr: str = "mean",
residual: bool = False,
num_attention_heads: int = 0,
message_passing_depth: int = 1,
loss_type: str = "mse",
train_loss_constraint: bool = False,
train_loss_objective: bool = False,
soft_dtw_gamma: float = 1.0,
target_k_step: int = 5,
train_loss_weight: list | None = None,
train_loss_constraint_weight: list | None = None,
train_loss_objective_weight: list | None = None,
train_loss_fixed_point: float | None = None,
scale_direction: bool = False,
train_loss_scale_direction_weight: list | None = None,
mp_decouple_soc_lc: bool = False,
use_gru_update: bool = False,
use_step_encoding: bool = False,
use_iterate_features: bool = False,
full_tail_supervision: bool = False,
picard_weight: float = 0.0,
picard_rho: float = 0.9,
final_anchor_weight: float = 0.0,
iterfeat_eps: float = 1.0,
lr_schedule: str = "none",
warmup_epochs: int = 0,
max_epochs: int = 200,
**kwargs,
):
super().__init__()
self.save_hyperparameters()
paths = kwargs["dataset_info"]["dataset_path"]
self.val_step_outputs = [[] for x in range(len(paths))]
self.trajectory_mean = kwargs["dataset_info"]["trajectory_mean"]
self.trajectory_std = kwargs["dataset_info"]["trajectory_std"]
self.T = T
self.lr = lr
self.zero_everything = zero_everything
self.target_length = target_length
self.teacher_forcing_p = teacher_forcing_p
self.aggr = aggr
self.residual = residual
self.num_attention_heads = num_attention_heads
self.message_passing_depth = message_passing_depth
assert loss_type in self.SUPERVISED_LOSS_NAMES, (
f"--loss_type must be one of {self.SUPERVISED_LOSS_NAMES}, got {loss_type!r}"
)
self.loss_type = loss_type
self.train_loss_constraint = train_loss_constraint
self.train_loss_objective = train_loss_objective
# Fixed-point consistency loss weight (None disables the term). Enforces
# G(x*) = x*, i.e. the optimum is a stable fixed point of the unroll.
self.train_loss_fixed_point = train_loss_fixed_point
# Scale/direction residual readout + supervised log-step loss. The loss
# matches the model's per-graph predicted log-step to the IPOPT log-step;
# it requires the scale/direction architecture (enabled together).
self.scale_direction = scale_direction
self.soft_dtw_gamma = soft_dtw_gamma
self.target_k_step = target_k_step
# Optional per-timestep weighting (spec: [mode, *params]) for the
# supervised, constraint and objective trajectory losses. Each spec is
# stored as a (mode, params) tuple (None when disabled).
self.train_loss_weight = train_loss_weight
self.train_loss_constraint_weight = train_loss_constraint_weight
self.train_loss_objective_weight = train_loss_objective_weight
self._loss_weight_spec = self._parse_weight_spec(
train_loss_weight, "train_loss_weight"
)
self._cons_weight_spec = self._parse_weight_spec(
train_loss_constraint_weight, "train_loss_constraint_weight"
)
self._obj_weight_spec = self._parse_weight_spec(
train_loss_objective_weight, "train_loss_objective_weight"
)
self.train_loss_scale_direction_weight = train_loss_scale_direction_weight
self._scale_dir_weight_spec = self._parse_weight_spec(
train_loss_scale_direction_weight, "scale_direction_loss"
)
if self._loss_weight_spec[0] is not None and loss_type == "soft_dtw":
raise ValueError(
"--train_loss_weight is not supported with --loss_type "
"soft_dtw (no per-timestep loss to weight)."
)
self.mp_decouple_soc_lc = mp_decouple_soc_lc
self.use_gru_update = use_gru_update
self.use_step_encoding = use_step_encoding
self.use_iterate_features = use_iterate_features
# Picard penalty: relu(d_{t+1} - rho*d_t), with
# d_t = ||x_t - x*|| / ||x*||. Each step must shrink that distance
# by a factor rho < 1. final_anchor is the relative squared error of
# the last iterate against x*.
self.picard_weight = picard_weight
self.picard_rho = picard_rho
self.final_anchor_weight = final_anchor_weight
# Epsilon in the inverse-slack features. At the default 1.0 the proxy
# saturates near active constraints.
self.iterfeat_eps = iterfeat_eps
self.lr_schedule = lr_schedule
self.warmup_epochs = warmup_epochs
self.max_epochs = max_epochs
if model_type == "SOCPNet":
self.model = SOCPNet(
d=d,
out_dim=1,
T=T,
message_passing_scheme=message_passing_scheme,
aggr=aggr,
num_attention_heads=num_attention_heads,
message_passing_depth=message_passing_depth,
mp_decouple_soc_lc=mp_decouple_soc_lc,
use_gru_update=use_gru_update,
use_step_encoding=use_step_encoding,
use_iterate_features=use_iterate_features,
scale_direction=scale_direction,
)
def _zero_everything(self, batch):
"""Zero out all features in a batch."""
batch["var"].x.zero_()
batch["norm"].x.zero_()
batch["cons"].x.zero_()
for edge_type in batch.edge_types:
if "edge_attr" in batch[edge_type]:
batch[edge_type].edge_attr.zero_()
return batch
def _initialize_node_features_with_x0(self, batch, x0):
"""Initialize variable node features with [obj_coeff, l_bound, r_bound, x0]."""
# Graph has [obj_coeff, l_bound, r_bound] (3D), add x0 to make it 4D
if batch["var"].x.shape[1] != 3:
raise ValueError(
f"Expected variable features with shape [N, 3] before adding x0, "
f"but got shape {batch['var'].x.shape}"
)
batch["var"].x = torch.cat([batch["var"].x, x0], dim=1)
return batch
def _predict_one_step(
self,
x_pred,
x_dict,
edge_index_dict,
edge_attr_dict,
batch_dict,
x_gt_t=None,
step_idx=None,
batch=None,
):
# SOCPNet.forward accepts these kwargs. Other models do not.
model_kwargs = {}
if self.use_step_encoding or self.scale_direction:
# The scale head also consumes the (normalized) iteration index.
model_kwargs["step_idx"] = step_idx
if self.use_iterate_features and batch is not None:
# Local KKT info at the current iterate, computed from the problem's
# parameters and the (de-normalized) current iterate prediction.
x_true = self._denormalize_prediction(x_pred)
model_kwargs["iterate_feat_dict"] = self._compute_iterate_features(
batch, x_true
)
model_out = self.model(
x_dict,
edge_index_dict,
edge_attr_dict,
batch_dict,
**model_kwargs,
)
scale = None
direction = None
if self.scale_direction:
# Model returns (scale, direction, x_dict) explicitly in this mode.
# r = exp(clamp(scale)) * unit_direction, applied as a residual step.
scale_raw, readout, x_dict = model_out
var_batch = batch_dict["var"]
d = readout if readout.dim() == 2 else readout.unsqueeze(1) # [N, 1]
G = int(var_batch.max().item()) + 1
sq = torch.zeros(G, device=d.device, dtype=d.dtype)
sq.index_add_(0, var_batch, (d.view(-1) ** 2))
norm = torch.sqrt(sq + 1e-12)[var_batch].unsqueeze(1) # [N, 1]
direction = d / norm
scale = scale_raw.clamp(-20.0, 5.0) # [N, 1], for the log-step loss
step = torch.exp(scale) * direction
xp = x_pred.to(device=d.device, dtype=d.dtype)
if xp.dim() == 1:
xp = xp.unsqueeze(1)
x_pred = xp + step
else:
readout, x_dict = model_out
if self.residual:
xp = x_pred.to(device=readout.device, dtype=readout.dtype)
if xp.dim() == 1:
xp = xp.unsqueeze(1)
x_pred = xp + readout
else:
x_pred = readout
x_in = x_pred
if self.teacher_forcing_p > 0.0 and self.training:
if x_gt_t.dim() == 1:
x_gt_t = x_gt_t.unsqueeze(1)
use_teacher_mask = (
torch.rand(1, device=x_pred.device) < self.teacher_forcing_p
)
x_in = torch.where(use_teacher_mask, x_gt_t, x_pred)
# Cross-iteration variable-node embedding update defined in the model
h_u = self.model.feature_update(x_dict["var"], x_in)
# Store updated embeddings for next iteration
x_dict["var"] = h_u
if self.scale_direction:
return x_pred, x_dict, scale, direction
return x_pred, x_dict
def _predict_trajectory(self, batch):
"""
Unroll the model for T steps. Requires ``batch.trajectory`` with at least
``T + 1`` time columns: ``x0`` at index 0 and ground-truth states for
optional teacher forcing at indices ``1 .. T``.
"""
trajectory = batch.trajectory
x0 = trajectory[:, 0:1]
batch = self._initialize_node_features_with_x0(batch, x0)
if self.zero_everything:
batch = self._zero_everything(batch)
# Get initial node embeddings and edge features
x_dict = self.model.initialize_embeddings(batch)
edge_index_dict = batch.edge_index_dict
edge_attr_dict = batch.edge_attr_dict
batch_dict = {
nt: getattr(batch[nt], "batch", None)
if nt in batch.node_types
else None
for nt in ["var", "norm", "cons", "lin_cons"]
}
x_pred = trajectory[:, 0:1]
pred_list = []
scale_list = []
direction_list = []
for t in range(self.T):
if self.teacher_forcing_p > 0.0 and self.training:
x_gt_t = trajectory[:, t + 1 : t + 2]
x_gt_t = x_gt_t.to(device=x_pred.device, dtype=x_pred.dtype)
else:
x_gt_t = None
if self.scale_direction:
x_pred, x_dict, scale, direction = self._predict_one_step(
x_pred,
x_dict,
edge_index_dict,
edge_attr_dict,
batch_dict,
x_gt_t=x_gt_t,
step_idx=t,
batch=batch,
)
scale_list.append(scale)
direction_list.append(direction)
else:
x_pred, x_dict = self._predict_one_step(
x_pred,
x_dict,
edge_index_dict,
edge_attr_dict,
batch_dict,
x_gt_t=x_gt_t,
step_idx=t,
batch=batch,
)
pred_list.append(x_pred)
if self.scale_direction:
return (
torch.cat(pred_list, dim=-1),
torch.cat(scale_list, dim=-1),
torch.cat(direction_list, dim=-1),
)
return torch.cat(pred_list, dim=-1)
def _fixed_point_loss(self, batch):
"""One-step fixed-point consistency loss (normalized space).
Feeds the optimum x* (last trajectory column) as the current iterate
through a single model step and penalizes any movement away from it:
``||G(x*) - x*||^2``. With residual readout this reduces to ``||delta||^2``.
The optimum is supervised here as an *input*, which the normal
trajectory loss never sees (it only feeds the rollout's own iterates),
so this term teaches the unroll to *stay* at x* once reached.
The 3-D variable features are restored afterwards so the subsequent
trajectory unroll (which re-appends x0) is unaffected.
"""
x_star = batch.trajectory[:, -1:] # [N, 1] normalized optimum
var_x_3d = batch["var"].x # [N, 3] raw problem features (pre-x0)
batch = self._initialize_node_features_with_x0(batch, x_star) # -> [N, 4]
try:
x_dict = self.model.initialize_embeddings(batch)
edge_index_dict = batch.edge_index_dict
edge_attr_dict = batch.edge_attr_dict
batch_dict = {
nt: getattr(batch[nt], "batch", None)
if nt in batch.node_types
else None
for nt in ["var", "norm", "cons", "lin_cons"]
}
# Only the prediction is needed here; in scale/direction mode the
# step also returns (scale, direction), which we ignore.
step_out = self._predict_one_step(
x_star,
x_dict,
edge_index_dict,
edge_attr_dict,
batch_dict,
x_gt_t=x_star,
step_idx=self.T,
batch=batch,
)
x_pred = step_out[0]
finally:
batch["var"].x = var_x_3d # restore for the trajectory rollout
if x_pred.dim() == 1:
x_pred = x_pred.unsqueeze(1)
return ((x_pred - x_star) ** 2).mean()
def _scale_direction_loss(self, batch, var_batch, traj_mask, traj_scales):
"""Per-[G, T] squared error between predicted and IPOPT log-step.
Target ``s*_t = log || x*_{t+1} - x*_t ||`` (normalized space), computed
per graph from ``batch.trajectory``. ``traj_scales`` ``[N, T]`` is the
per-graph scale collected during the unroll (constant within a graph, so
read off the first node of each graph via ``ptr``). Returns the raw
per-step squared error ``[G, T]``; the optional per-timestep weighting
and mask reduction happen once in the caller via ``_weighted_masked_mean``.
"""
traj = batch.trajectory # [N, L] normalized
T = traj_scales.shape[1]
deltas = traj[:, 1 : T + 1] - traj[:, 0:T] # [N, T]
G = traj_mask.shape[0]
step_sq = torch.zeros(G, T, device=deltas.device, dtype=deltas.dtype)
step_sq.index_add_(0, var_batch, deltas ** 2) # per-graph ||.||^2
s_star = 0.5 * torch.log(step_sq + 1e-12) # [G, T]
ptr = batch["var"].ptr
s_pred = traj_scales[ptr[:-1]].squeeze(-1) # [G, T]
if s_pred.dim() == 1:
s_pred = s_pred.unsqueeze(-1)
return (s_pred - s_star) ** 2
def _log_metrics(self, prefix, metrics, batch_size, prog_bar_metric=None):
"""Helper to log metrics consistently."""
for name, value in metrics.items():
if value is None:
continue
self.log(
f"{prefix}/{name}",
value,
on_step=False,
on_epoch=True,
prog_bar=(
name == prog_bar_metric
and not str(prefix).startswith("Test")
),
sync_dist=True,
batch_size=batch_size,
add_dataloader_idx=False,
)
def _get_raw_node_features(self, node_store):
"""Return raw (deprocessed) node features when available."""
return getattr(node_store, "x_deprocessed", node_store.x)
def _get_raw_edge_attr(self, edge_store):
"""Return raw (deprocessed) edge attributes when available."""
return getattr(
edge_store, "edge_attr_deprocessed", edge_store.edge_attr
)
def _get_batch_vector(self, node_store):
"""Return batch vector; fall back to zeros for single-graph batches."""
if hasattr(node_store, "batch") and node_store.batch is not None:
return node_store.batch
return torch.zeros(
node_store.x.shape[0], dtype=torch.long, device=node_store.x.device
)
@staticmethod
def _slog(v):
"""Signed log1p: tames the wide dynamic range of raw problem-scale residuals."""
return torch.sign(v) * torch.log1p(torch.abs(v))
def _compute_iterate_features(self, batch, x_true):
"""Per-iteration local KKT features at the current iterate (raw scale).
Implements local Newton/residual features and the inverse-slack
dual estimates. All quantities are deterministic functions of the current
iterate ``x_true`` and the (raw) problem data.
Returns a dict of per-node-type tensors matching ``model.ITERATE_FEAT_DIMS``.
- var: [slog(x - l), slog(r - x), 1/(|x-l|+1), 1/(|r-x|+1)]
- norm: [slog(A_row x + b)]
- cons: [slog(soc_slack), 1/(|soc_slack|+1)] with soc_slack=(c^T x+d)-||A x+b||
- lin_cons: [slog(g - F x), 1/(|g-F x|+1)]
Inverse-slack channels are interior-point complementarity dual proxies
(lambda_i ~ mu / slack_i); they are large where a constraint/bound is near-active.
"""
device = x_true.device
x = x_true.view(-1) # [N]
eps = self.iterfeat_eps
def dual_proxy(slack):
return 1.0 / (slack.abs() + eps)
# --- Variable bound slacks + bound-multiplier proxies ---
var_raw = self._get_raw_node_features(batch["var"])
l_bound = var_raw[:, 1]
r_bound = var_raw[:, 2]
lower_slack = x - l_bound
upper_slack = r_bound - x
# Guard against infinite/absent bounds (treated as inactive -> no signal).
lower_slack = torch.nan_to_num(lower_slack, nan=0.0, posinf=1e6, neginf=-1e6)
upper_slack = torch.nan_to_num(upper_slack, nan=0.0, posinf=1e6, neginf=-1e6)
var_feat = torch.stack(
[
self._slog(lower_slack),
self._slog(upper_slack),
dual_proxy(lower_slack),
dual_proxy(upper_slack),
],
dim=1,
)
# --- Per-norm row residual s = A_row x + b ---
norm_x_raw = self._get_raw_node_features(batch["norm"]).squeeze(-1)
v2n = batch[("var", "V2N", "norm")]
v2n_vals = self._get_raw_edge_attr(v2n).view(-1)
var_idx = v2n.edge_index[0]
norm_idx = v2n.edge_index[1]
ax = torch.scatter_reduce(
torch.zeros(norm_x_raw.shape[0], device=device),
0, norm_idx, v2n_vals * x[var_idx], "sum",
)
s_k = ax + norm_x_raw
norm_feat = self._slog(s_k).unsqueeze(1)
# --- Per-constraint SOC slack: (c^T x + d) - ||A x + b|| ---
cons_x_raw = self._get_raw_node_features(batch["cons"]).squeeze(-1)
n2c = batch[("norm", "N2C", "cons")].edge_index
s_sq_sum = torch.scatter_reduce(
torch.zeros(cons_x_raw.shape[0], device=device),
0, n2c[1], s_k[n2c[0]] ** 2, "sum",
)
# Additive epsilon keeps the gradient finite at ||A x + b|| = 0
# (sqrt'(0) = inf would otherwise produce NaN gradients).
lhs = torch.sqrt(torch.clamp(s_sq_sum, min=0.0) + 1e-12)
v2c = batch[("var", "V2C", "cons")]
v2c_vals = self._get_raw_edge_attr(v2c).view(-1)
cx = torch.scatter_reduce(
torch.zeros(cons_x_raw.shape[0], device=device),
0, v2c.edge_index[1], v2c_vals * x[v2c.edge_index[0]], "sum",
)
soc_slack = (cx + cons_x_raw) - lhs
cons_feat = torch.stack(
[self._slog(soc_slack), dual_proxy(soc_slack)], dim=1
)
# --- Per-linear-constraint slack: g - F x ---
lin_x_raw = self._get_raw_node_features(batch["lin_cons"]).squeeze(-1)
v2lc = batch[("var", "V2LC", "lin_cons")]
v2lc_vals = self._get_raw_edge_attr(v2lc).view(-1)
fx = torch.scatter_reduce(
torch.zeros(lin_x_raw.shape[0], device=device),
0, v2lc.edge_index[1], v2lc_vals * x[v2lc.edge_index[0]], "sum",
)
lin_slack = lin_x_raw - fx
lin_feat = torch.stack(
[self._slog(lin_slack), dual_proxy(lin_slack)], dim=1
)
return {
"var": var_feat,
"norm": norm_feat,
"cons": cons_feat,
"lin_cons": lin_feat,
}
def get_batch_objective(self, batch, x_true):
"""Compute the linear objective f^T x per graph in the batch (true scale).
Args:
batch: heterogeneous graph batch.
x_true: per-var-node values, [N] (single point) or [N, T]
(whole trajectory).
Returns:
objective: [B] for [N] input, or [B, T] for [N, T] input.
"""
squeeze = x_true.dim() == 1
x = x_true.unsqueeze(-1) if squeeze else x_true # [N, T]
T = x.shape[1]
var_x_raw = self._get_raw_node_features(batch["var"])
f = var_x_raw[:, 0].unsqueeze(-1) # [N, 1]
var_batch = self._get_batch_vector(batch["var"])
batch_size = (
int(var_batch.max().item()) + 1 if var_batch.numel() > 0 else 1
)
obj = torch.scatter_reduce(
torch.zeros(batch_size, T, device=x.device),
0,
var_batch.unsqueeze(-1).expand(-1, T),
f * x,
"sum",
) # [B, T]
return obj.squeeze(-1) if squeeze else obj
def compute_objective_mse_loss(
self, batch, x_pred_final_true, x_target_final_true
):
"""Compute objective loss on the final prediction point (true scale)."""
obj_pred = self.get_batch_objective(batch, x_pred_final_true)
obj_target = self.get_batch_objective(batch, x_target_final_true)
return torch.mean((obj_pred - obj_target) ** 2)
def get_constraint_violations(self, batch, x):
"""Per-constraint violations along a trajectory (true scale).
Args:
batch: heterogeneous graph batch.
x: per-var-node values [N, T] (whole trajectory).
Returns:
violation_soc: [num_cons, T] relu(||A x + b|| - (c^T x + d))
violation_lin: [num_lin_cons, T] relu(F x - g)
"""
assert x.dim() == 2, "get_constraint_violations expects x of shape [N, T]"
device = x.device
T = x.shape[1]
def _scatter(num_rows, index, src): # index [E], src [E, T] -> [rows, T]
return torch.scatter_reduce(
torch.zeros(num_rows, T, device=device),
0,
index.unsqueeze(-1).expand(-1, T),
src,
"sum",
)
norm_x_raw = self._get_raw_node_features(batch["norm"]).squeeze(-1)
cons_x_raw = self._get_raw_node_features(batch["cons"]).squeeze(-1)
lin_cons_x_raw = self._get_raw_node_features(
batch["lin_cons"]
).squeeze(-1)
# A @ x + b (norm nodes)
v2n = batch[("var", "V2N", "norm")]
v2n_vals = self._get_raw_edge_attr(v2n).view(-1, 1)
var_idx, norm_idx = v2n.edge_index
ax = _scatter(norm_x_raw.shape[0], norm_idx, v2n_vals * x[var_idx])
s_k = ax + norm_x_raw.unsqueeze(-1) # [num_norm, T]
# Map norms to constraints and compute SOC LHS per constraint
norm_idx_n2c, cons_idx_n2c = batch[("norm", "N2C", "cons")].edge_index
s_sq_sum = _scatter(
cons_x_raw.shape[0], cons_idx_n2c, s_k[norm_idx_n2c] ** 2
)
# Additive epsilon keeps the gradient finite at ||A x + b|| = 0
# (sqrt'(0) = inf would otherwise produce NaN gradients).
lhs = torch.sqrt(torch.clamp(s_sq_sum, min=0.0) + 1e-12)
# c^T x + d (constraint nodes)
v2c = batch[("var", "V2C", "cons")]
v2c_vals = self._get_raw_edge_attr(v2c).view(-1, 1)
var_idx, cons_idx = v2c.edge_index
cx = _scatter(cons_x_raw.shape[0], cons_idx, v2c_vals * x[var_idx])
rhs = cx + cons_x_raw.unsqueeze(-1)
violation_soc = torch.relu(lhs - rhs) # [num_cons, T]
# Linear constraints: F x <= g
v2lc = batch[("var", "V2LC", "lin_cons")]
v2lc_vals = self._get_raw_edge_attr(v2lc).view(-1, 1)
var_idx, lc_idx = v2lc.edge_index
fx = _scatter(lin_cons_x_raw.shape[0], lc_idx, v2lc_vals * x[var_idx])
violation_lin = torch.relu(fx - lin_cons_x_raw.unsqueeze(-1))
return violation_soc, violation_lin
def _signed_constraints(self, batch, x):
"""Signed constraint values, feasible when g(x) <= 0. x is [N, T].
Same quantities as ``get_constraint_violations``, without the relu.
Returns g_soc [num_cons, T] = ||Ax+b|| - (c^T x + d) and
g_lin [num_lin_cons, T] = Fx - g.
"""
device = x.device
T = x.shape[1]
def _scatter(num_rows, index, src):
return torch.scatter_reduce(
torch.zeros(num_rows, T, device=device, dtype=x.dtype),
0, index.unsqueeze(-1).expand(-1, T), src, "sum",
)
norm_x_raw = self._get_raw_node_features(batch["norm"]).squeeze(-1)
cons_x_raw = self._get_raw_node_features(batch["cons"]).squeeze(-1)
lin_cons_x_raw = self._get_raw_node_features(batch["lin_cons"]).squeeze(-1)
v2n = batch[("var", "V2N", "norm")]
v2n_vals = self._get_raw_edge_attr(v2n).view(-1, 1)
var_idx, norm_idx = v2n.edge_index
ax = _scatter(norm_x_raw.shape[0], norm_idx, v2n_vals * x[var_idx])
s_k = ax + norm_x_raw.unsqueeze(-1)
norm_idx_n2c, cons_idx_n2c = batch[("norm", "N2C", "cons")].edge_index
s_sq_sum = _scatter(cons_x_raw.shape[0], cons_idx_n2c, s_k[norm_idx_n2c] ** 2)
lhs = torch.sqrt(torch.clamp(s_sq_sum, min=0.0) + 1e-12)
v2c = batch[("var", "V2C", "cons")]
v2c_vals = self._get_raw_edge_attr(v2c).view(-1, 1)
var_idx, cons_idx = v2c.edge_index
cx = _scatter(cons_x_raw.shape[0], cons_idx, v2c_vals * x[var_idx])
g_soc = lhs - (cx + cons_x_raw.unsqueeze(-1)) # [num_cons, T]
v2lc = batch[("var", "V2LC", "lin_cons")]
v2lc_vals = self._get_raw_edge_attr(v2lc).view(-1, 1)
var_idx, lc_idx = v2lc.edge_index
fx = _scatter(lin_cons_x_raw.shape[0], lc_idx, v2lc_vals * x[var_idx])
g_lin = fx - lin_cons_x_raw.unsqueeze(-1) # [num_lin, T]
return g_soc, g_lin
def _feasibility_restore(self, batch, x_norm, steps, alpha, clip, collect=False):
"""Gradient steps on the final iterate that reduce constraint violation.
Minimizes V(x) = sum relu(g_soc)^2 + sum relu(g_lin)^2 by
x <- x - clip(alpha * grad V), with g <= 0 feasible. A point that is
already feasible (grad V = 0) is left unchanged. Runs in true scale
and is detached from the training graph.
Returns (restored_norm [N, 1], list of normalized iterates when collect).
"""
std, mean = self.trajectory_std, self.trajectory_mean
x_true = self._denormalize_prediction(x_norm).view(-1, 1)
iterates = []
for _ in range(steps):
with torch.enable_grad():
x_leaf = x_true.detach().requires_grad_(True)
g_soc, g_lin = self._signed_constraints(batch, x_leaf)
V = (torch.relu(g_soc) ** 2).sum() + (torch.relu(g_lin) ** 2).sum()
grad = torch.autograd.grad(V, x_leaf)[0]
step = torch.clamp(alpha * grad, -clip, clip)
x_true = x_true - step
if collect:
iterates.append((x_true - mean) / std)
return (x_true - mean) / std, iterates
def compute_constraint_violation_loss(self, batch, x_pred_true):
"""Mean per-constraint violation (true scale).
x_pred_true: [N] -> scalar (mean over graphs); [N, T] -> per-graph,
per-timestep violations [B, T] (left unreduced for masking/weighting).
"""
device = x_pred_true.device
squeeze = x_pred_true.dim() == 1
x = x_pred_true.unsqueeze(-1) if squeeze else x_pred_true # [N, T]
violation_soc, violation_lin = self.get_constraint_violations(batch, x)
T = x.shape[1]
cons_batch = self._get_batch_vector(batch["cons"])
lin_cons_batch = self._get_batch_vector(batch["lin_cons"])
batch_size = (
int(
max(
cons_batch.max().item() if cons_batch.numel() > 0 else 0,
lin_cons_batch.max().item()
if lin_cons_batch.numel() > 0
else 0,
)
)
+ 1
)
def _sum(index, src): # index [E], src [E, T] -> [batch_size, T]
return torch.scatter_reduce(
torch.zeros(batch_size, T, device=device),
0,
index.unsqueeze(-1).expand(-1, T),
src,
"sum",
)
cons_sum = _sum(cons_batch, violation_soc)
lin_sum = _sum(lin_cons_batch, violation_lin)
cons_count = _sum(cons_batch, torch.ones_like(violation_soc))
lin_count = _sum(lin_cons_batch, torch.ones_like(violation_lin))
total_count = torch.clamp(cons_count + lin_count, min=1.0)
per_graph_violation = (cons_sum + lin_sum) / total_count # [B, T]
return per_graph_violation.mean() if squeeze else per_graph_violation
def _compute_soft_dtw_loss(self, pred, targets, traj_mask, batch_size, var_batch):
"""
Soft-DTW loss between predicted and ground-truth trajectories.
Order-preserving elastic alignment: the predicted trajectory may lag or
lead the ground-truth by a few steps without being penalised for timing
mismatch, while temporal ordering is still respected.
Each graph's trajectory is treated as a multivariate sequence in R^n_dim
(one iterate = one point), and Soft-DTW is computed per graph then averaged.
Args:
pred: [N, T] predicted trajectory (normalised)
targets: [N, T] ground-truth trajectory (normalised)
traj_mask: [B, T] float mask (1 = real step, 0 = padded)
batch_size: int B
var_batch: [N] batch assignment for variable nodes
Returns:
Scalar Soft-DTW loss.
"""
try:
from tslearn.metrics import SoftDTWLossPyTorch
except ImportError:
raise ImportError(