-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmnn.py
1171 lines (1052 loc) · 51.4 KB
/
smnn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Jiale Chen, Dingling Yao, Adeel Pervez, Dan Alistarh, and Francesco Locatello. Scalable mechanistic neural networks. In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=Oazgf8A24z.
# https://github.com/IST-DASLab/ScalableMNN
import itertools
import math
import torch
try:
import mnn
except ImportError:
mnn = None
def ode_forward(
coefficients: torch.Tensor,
rhs_equation: torch.Tensor,
init_vars: torch.Tensor,
steps: torch.Tensor,
n_steps: int = None,
n_init_var_steps: int = None,
is_step_dim_first: bool = False,
weight_equation: float = 1.,
weight_init_var: float = 1.,
weight_smooth: float = 1.,
enable_central_smoothness: bool = False,
prefer_cuda_graph: bool = True,
frozen_lhs_cache_version: int = 0,
) -> torch.Tensor:
"""
Implementation of the ODE forward pass. The backward pass is optimized.
This implementation has linear time & space complexity.
([b]: broadcastable dimensions, [e]: contiguous or expanded dimensions)
Args:
coefficients: (..., n_steps[b], n_equations, n_dims, n_orders)
rhs_equation: (..., n_steps[b], n_equations[e])
init_vars: (..., n_init_var_steps[b], n_dims[e], n_init_var_orders[e])
steps: (..., n_steps-1[b])
n_steps: int, optional, please specify if it cannot be inferred from the tensor shapes
n_init_var_steps: int, optional, please specify if it cannot be inferred from the tensor shapes
is_step_dim_first: bool, if True, the step dimension is already the first dimension
weight_equation: float, optional weight for the least squares system
weight_init_var: float, optional weight for the least squares system
weight_smooth: float, optional weight for the least squares system
enable_central_smoothness: bool, if True, the central smoothness constraint is used
prefer_cuda_graph: bool, if True, use cuda graph if cuda device is used; automatically disabled for cpu device
frozen_lhs_cache_version: int,
if > 0, the left-hand side matrix is frozen and cached, please specify a unique version id for each lhs
Returns:
out: (..., n_steps, n_dims, n_orders)
"""
if not is_step_dim_first:
# move the step dimension to the first dimension
coefficients: torch.Tensor = move_step_dim_first(coefficients, i=4, revert=False)
rhs_equation: torch.Tensor = move_step_dim_first(rhs_equation, i=2, revert=False)
init_vars: torch.Tensor = move_step_dim_first(init_vars, i=3, revert=False)
steps: torch.Tensor = move_step_dim_first(steps, i=1, revert=False)
dtype: torch.dtype = coefficients.dtype
device: torch.device = coefficients.device
# infer the numbers from the shapes and check if the shapes are compatible
n_steps: int = steps.size(0) + 1 if n_steps is None else n_steps
assert n_steps >= 2
n_init_var_steps: int = init_vars.size(0) if n_init_var_steps is None else n_init_var_steps
n_steps_coefficients, *batch_coefficients, n_equations, n_dims, n_orders = coefficients.shape
assert n_steps_coefficients in [n_steps, 1]
n_steps_rhs_equation, *batch_rhs_equation, n_equations_rhs_equation = rhs_equation.shape
assert n_steps_rhs_equation in [n_steps, 1] and n_equations_rhs_equation == n_equations
n_init_var_steps_rhs_init, *batch_rhs_init, n_dims_rhs_init, n_init_var_orders = init_vars.shape
assert n_init_var_steps_rhs_init in [n_init_var_steps, 1] and n_dims_rhs_init == n_dims
n_steps_steps, *batch_steps = steps.shape
assert n_steps_steps in [n_steps - 1, 1]
batch_lhs: torch.Size = torch.broadcast_shapes(batch_coefficients, batch_steps)
batch: torch.Size = torch.broadcast_shapes(batch_lhs, batch_rhs_equation, batch_rhs_init)
solver_options: dict = {
'enable_central_smoothness': enable_central_smoothness,
'frozen_lhs_cache_version': frozen_lhs_cache_version,
'enable_cuda_graph': prefer_cuda_graph and device.type == 'cuda',
'enable_ldl': True,
}
# compute the solution
if frozen_lhs_cache_version not in LinearSolver.frozen_lhs_caches:
block_diag_0, block_diag_1, block_diag_2, beta = compute_ata_atb(
coefficients,
rhs_equation,
init_vars,
steps,
n_steps,
n_init_var_steps,
weight_equation,
weight_init_var,
weight_smooth,
enable_central_smoothness,
dtype,
device,
n_dims,
n_orders,
n_init_var_orders,
batch,
batch_lhs,
)
x: torch.Tensor = LinearSolver.apply(
block_diag_0,
block_diag_1,
block_diag_2,
beta,
solver_options,
) # (n_steps, ..., n_dims * n_orders, 1)
else:
# use the cached left-hand side matrix
beta: torch.Tensor = compute_atb(
coefficients,
rhs_equation,
init_vars,
n_steps,
n_init_var_steps,
weight_equation,
weight_init_var,
dtype,
device,
n_orders,
n_init_var_orders,
batch,
)
x: torch.Tensor = LinearSolver.apply(None, None, None, beta, solver_options)
# (n_steps, ..., n_dims * n_orders, 1)
x: torch.Tensor = x.reshape(n_steps, *batch, n_dims, n_orders) # (n_steps, ..., n_dims, n_orders)
if not is_step_dim_first:
# move the step dimension back
x: torch.Tensor = move_step_dim_first(x, i=3, revert=True)
return x
def move_step_dim_first(x: torch.Tensor, i: int, revert: bool) -> torch.Tensor:
"""
Move the step (-i-th) dimension to the first (revert=False) or last (revert=True) dimension.
Args:
x: (..., n_steps[b], ...)
i: int
revert: bool
Returns:
out: (n_steps[b], ...) or (..., n_steps[b])
"""
n_tensor_dims: int = x.dim()
if not revert:
dim_order: list[int] = [
n_tensor_dims - i,
*range(n_tensor_dims - i),
*range(n_tensor_dims - i + 1, n_tensor_dims),
]
else:
dim_order: list[int] = [*range(1, n_tensor_dims - i + 1), 0, *range(n_tensor_dims - i + 1, n_tensor_dims)]
return x.permute(dim_order)
def compute_ata_atb(
coefficients: torch.Tensor,
rhs_equation: torch.Tensor,
init_vars: torch.Tensor,
steps: torch.Tensor,
n_steps: int,
n_init_var_steps: int,
weight_equation: float,
weight_init_var: float,
weight_smooth: float,
enable_central_smoothness: bool,
dtype: torch.dtype,
device: torch.device,
n_dims: int,
n_orders: int,
n_init_var_orders: int,
batch: torch.Size,
batch_lhs: torch.Size,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Compute the matrix A^T A and the vector A^T b for the linear solver. The backward pass is by autograd.
([b]: broadcastable dimensions, [e]: contiguous or expanded dimensions)
Args:
coefficients: (n_steps[b], ..., n_equations, n_dims, n_orders)
rhs_equation: (n_steps[b], ..., n_equations[e])
init_vars: (n_init_var_steps[b], ..., n_dims[e], n_init_var_orders[e])
steps: (n_steps-1[b], ...)
n_steps: int
n_init_var_steps: int
weight_equation: float
weight_init_var: float
weight_smooth: float
enable_central_smoothness: bool
dtype: torch.dtype
device: torch.device
n_dims: int
n_orders: int
n_init_var_orders: int
batch: torch.Size
batch_lhs: torch.Size
Returns:
block_diag_0: (n_steps, ..., n_dims * n_orders, n_dims * n_orders),
block_diag_1: (n_steps-1, ..., n_dims * n_orders, n_dims * n_orders),
block_diag_2: (n_steps-2, ..., n_dims * n_orders, n_dims * n_orders),
beta: (n_steps, ..., n_dims * n_orders, 1),
"""
# ode equation constraints
c: torch.Tensor = coefficients.flatten(start_dim=-2) # (n_steps[b], ..., n_equations, n_dims * n_orders)
ct: torch.Tensor = c.transpose(-2, -1) * weight_equation ** 2 # (n_steps[b], ..., n_dims * n_orders, n_equations)
block_diag_0: torch.Tensor = ct @ c # (n_steps[b], ..., n_dims * n_orders, n_dims * n_orders)
beta: torch.Tensor = ct @ rhs_equation[..., None] # (n_steps[b], ..., n_dims * n_orders, 1)
block_diag_0: torch.Tensor = block_diag_0.repeat(
n_steps // block_diag_0.size(0),
*[ss // s for ss, s in zip(batch_lhs, block_diag_0.shape[1:-2])],
1,
1,
) # (n_steps, ..., n_dims * n_orders, n_dims * n_orders)
beta: torch.Tensor = beta.repeat(
n_steps // beta.size(0),
*[ss // s for ss, s in zip(batch, beta.shape[1:-2])],
1,
1,
) # (n_steps, ..., n_dims * n_orders, 1)
# initial-value constraints
weight2_init_var: float = weight_init_var ** 2
init_idx: torch.Tensor = torch.arange(n_init_var_orders, device=device).repeat(n_dims) \
+ (n_orders * torch.arange(n_dims, device=device)).repeat_interleave(n_init_var_orders)
# (n_dims * n_init_var_orders)
block_diag_0[:n_init_var_steps, ..., init_idx, init_idx] += weight2_init_var
beta[:n_init_var_steps, ..., :, 0] += torch.cat([
init_vars * weight2_init_var,
torch.zeros(*init_vars.shape[:-1], n_orders - n_init_var_orders, dtype=dtype, device=device),
], dim=-1).flatten(start_dim=-2)
# smoothness constraints (forward & backward)
order_idx: torch.Tensor = torch.arange(n_orders, device=device) # (n_orders)
sign_vec: torch.Tensor = order_idx % 2 * (-2) + 1 # (n_orders)
sign_map: torch.Tensor = sign_vec * sign_vec[:, None] # (n_orders, n_orders)
expansions: torch.Tensor = steps[..., None] ** order_idx * weight_smooth # (n_steps-1[b], ..., n_orders)
et_e_diag: torch.Tensor = expansions ** 2 # (n_steps-1[b], ..., n_orders)
e_outer: torch.Tensor = expansions[..., None] * expansions[..., None, :] # (n_steps-1[b], ..., n_orders, n_orders)
factorials: torch.Tensor = (-(order_idx - order_idx[:, None] + 1).triu().to(dtype=dtype).lgamma()).exp()
# (n_orders, n_orders)
if enable_central_smoothness:
et_e_diag[..., -1] = 0.
factorials[-1, -1] = 0.
et_ft_f_e: torch.Tensor = e_outer * (factorials.t() @ factorials) # (n_steps-1[b], ..., n_orders, n_orders)
smooth_block_diag_1: torch.Tensor = e_outer * -(factorials + factorials.transpose(-2, -1) * sign_map)
# (n_steps-1[b], ..., n_orders, n_orders)
smooth_block_diag_0: torch.Tensor = torch.zeros(n_steps, *batch_lhs, n_orders, n_orders, dtype=dtype, device=device)
# (n_steps, ..., n_orders, n_orders)
smooth_block_diag_0[:-1] += et_ft_f_e
smooth_block_diag_0[1:] += et_ft_f_e * sign_map
smooth_block_diag_0[:-1, ..., order_idx, order_idx] += et_e_diag
smooth_block_diag_0[1:, ..., order_idx, order_idx] += et_e_diag
smooth_block_diag_1: torch.Tensor = smooth_block_diag_1.repeat(
(n_steps - 1) // smooth_block_diag_1.size(0),
*([1] * len(batch_lhs)),
1,
1,
) # (n_steps-1, ..., n_orders, n_orders)
block_diag_1: torch.Tensor = torch.zeros(
n_steps - 1, *batch_lhs, n_dims * n_orders, n_dims * n_orders, dtype=dtype, device=device,
) # (n_steps-1, ..., n_dims * n_orders, n_dims * n_orders)
if enable_central_smoothness:
steps: torch.Tensor = steps.repeat((n_steps - 1) // steps.size(0), *([1] * len(batch_lhs))) # (n_steps-1, ...)
# smoothness constraints (central)
steps2: torch.Tensor = steps[:-1] + steps[1:] # (n_steps-2, ...)
weight2_smooth: float = weight_smooth ** 2
steps26: torch.Tensor = steps2 ** (n_orders * 2 - 6) * weight2_smooth # (n_steps-2, ...)
steps25: torch.Tensor = steps2 ** (n_orders * 2 - 5) * weight2_smooth # (n_steps-2, ...)
steps24: torch.Tensor = steps2 ** (n_orders * 2 - 4) * weight2_smooth # (n_steps-2, ...)
smooth_block_diag_0[:-2, ..., n_orders - 2, n_orders - 2] += steps26
smooth_block_diag_0[2:, ..., n_orders - 2, n_orders - 2] += steps26
smooth_block_diag_0[1:-1, ..., n_orders - 1, n_orders - 1] += steps24
smooth_block_diag_1[:-1, ..., n_orders - 1, n_orders - 2] += steps25
smooth_block_diag_1[1:, ..., n_orders - 2, n_orders - 1] -= steps25
smooth_block_diag_2: torch.Tensor | None = torch.zeros(
n_steps - 2, *batch_lhs, n_orders, n_orders, dtype=dtype, device=device,
) # (n_steps-2, ..., n_orders, n_orders)
smooth_block_diag_2[..., n_orders - 2, n_orders - 2] = -steps26
block_diag_2: torch.Tensor | None = torch.zeros(
n_steps - 2, *batch_lhs, n_dims * n_orders, n_dims * n_orders, dtype=dtype, device=device,
) # (n_steps-2, ..., n_dims * n_orders, n_dims * n_orders
else:
smooth_block_diag_2 = None
block_diag_2 = None
# copy to n_dims
for dim in range(n_dims):
i1: int = dim * n_orders
i2: int = (dim + 1) * n_orders
block_diag_0[..., i1:i2, i1:i2] += smooth_block_diag_0
block_diag_1[..., i1:i2, i1:i2] = smooth_block_diag_1
if block_diag_2 is not None:
block_diag_2[..., i1:i2, i1:i2] = smooth_block_diag_2
return block_diag_0, block_diag_1, block_diag_2, beta
def compute_atb(
coefficients: torch.Tensor,
rhs_equation: torch.Tensor,
init_vars: torch.Tensor,
n_steps: int,
n_init_var_steps: int,
weight_equation: float,
weight_init_var: float,
dtype: torch.dtype,
device: torch.device,
n_orders: int,
n_init_var_orders: int,
batch: torch.Size,
) -> torch.Tensor:
"""
Compute the vector A^T b for the linear solver. The backward pass is by autograd.
([b]: broadcastable dimensions, [e]: contiguous or expanded dimensions)
Args:
coefficients: (n_steps[b], ..., n_equations, n_dims, n_orders)
rhs_equation: (n_steps[b], ..., n_equations[e])
init_vars: (n_init_var_steps[b], ..., n_dims[e], n_init_var_orders[e])
n_steps: int
n_init_var_steps: int
weight_equation: float
weight_init_var: float
dtype: torch.dtype
device: torch.device
n_orders: int
n_init_var_orders: int
batch: torch.Size
Returns:
beta: (n_steps, ..., n_dims * n_orders, 1)
"""
# ode equation constraints
beta: torch.Tensor = coefficients.flatten(start_dim=-2).transpose(-2, -1) @ (
rhs_equation[..., None] * weight_equation ** 2
) # (n_steps[b], ..., n_dims * n_orders, 1)
beta: torch.Tensor = beta.repeat(
n_steps // beta.size(0),
*[ss // s for ss, s in zip(batch, beta.shape[1:-2])],
1,
1,
) # (n_steps, ..., n_dims * n_orders, 1)
# initial-value constraints
beta[:n_init_var_steps, ..., :, 0] += torch.cat([
init_vars * weight_init_var ** 2,
torch.zeros(*init_vars.shape[:-1], n_orders - n_init_var_orders, dtype=dtype, device=device),
], dim=-1).flatten(start_dim=-2)
return beta
class LinearSolver(torch.autograd.Function):
frozen_lhs_caches: dict[int, tuple] = {}
cuda_graph_info: dict[tuple, dict] = {}
@staticmethod
def forward(
ctx,
block_diag_0: torch.Tensor,
block_diag_1: torch.Tensor,
block_diag_2: torch.Tensor | None,
rhs: torch.Tensor,
solver_options: dict,
) -> torch.Tensor:
"""
Solver forward pass.
Args:
ctx: torch.autograd.function.BackwardCFunction
block_diag_0: (n_steps, ..., n_dims * n_orders, n_dims * n_orders)
block_diag_1: (n_steps-1, ..., n_dims * n_orders, n_dims * n_orders)
block_diag_2: (n_steps-2, ..., n_dims * n_orders, n_dims * n_orders) or None
rhs: (n_steps, ..., n_dims * n_orders, 1)
solver_options: dict
Returns:
out: (n_steps, ..., n_dims * n_orders, 1)
"""
solver = mnn if mnn is not None else LinearSolver
dtype: torch.dtype = rhs.dtype
device: torch.device = rhs.device
n_steps, *batch, n_rows, _ = rhs.shape
ctx.solver_options = solver_options
enable_central_smoothness: bool = solver_options['enable_central_smoothness']
frozen_lhs_cache_version: int = solver_options['frozen_lhs_cache_version']
enable_cuda_graph: bool = solver_options['enable_cuda_graph']
enable_ldl: bool = solver_options['enable_ldl']
if enable_cuda_graph:
torch.cuda.set_device(device)
graph_key: tuple = rhs.shape, dtype, device, enable_central_smoothness, frozen_lhs_cache_version, enable_ldl
if graph_key not in LinearSolver.cuda_graph_info:
# build the CUDA graphs
graph_forward: torch.cuda.CUDAGraph = torch.cuda.CUDAGraph()
graph_substitution: torch.cuda.CUDAGraph = torch.cuda.CUDAGraph()
graph_tensors: dict[str, torch.Tensor] = {
'block_diag_0': torch.empty(n_steps, *batch, n_rows, n_rows, dtype=dtype, device=device),
'block_diag_1': torch.empty(n_steps - 1, *batch, n_rows, n_rows, dtype=dtype, device=device),
'block_diag_2': torch.empty(n_steps - 2, *batch, n_rows, n_rows, dtype=dtype, device=device)
if enable_central_smoothness else None,
'rhs': torch.empty(n_steps, *batch, n_rows, 1, dtype=dtype, device=device),
'tmp_info': torch.empty(batch, dtype=torch.int32, device=device),
}
n_cuda_graph_warmups: int = 10
s: torch.cuda.Stream = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
for _ in range(n_cuda_graph_warmups):
solver.cholesky_inplace(
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
graph_tensors['tmp_info'],
enable_ldl=enable_ldl,
)
solver.substitution_inplace(
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
graph_tensors['rhs'],
enable_ldl=enable_ldl,
)
torch.cuda.current_stream().wait_stream(s)
with torch.cuda.graph(graph_forward):
solver.cholesky_inplace(
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
graph_tensors['tmp_info'],
enable_ldl=enable_ldl,
)
solver.substitution_inplace(
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
graph_tensors['rhs'],
enable_ldl=enable_ldl,
)
s: torch.cuda.Stream = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
for _ in range(n_cuda_graph_warmups):
solver.substitution_inplace(
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
graph_tensors['rhs'],
enable_ldl=enable_ldl,
)
torch.cuda.current_stream().wait_stream(s)
with torch.cuda.graph(graph_substitution):
solver.substitution_inplace(
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
graph_tensors['rhs'],
enable_ldl=enable_ldl,
)
torch.cuda.synchronize(device)
LinearSolver.cuda_graph_info[graph_key] = {
'graph_forward': graph_forward,
'graph_substitution': graph_substitution,
'graph_tensors': graph_tensors,
}
# replay the CUDA graphs
graph_info: dict = LinearSolver.cuda_graph_info[graph_key]
graph_tensors: dict[str, torch.Tensor] = graph_info['graph_tensors']
if frozen_lhs_cache_version not in LinearSolver.frozen_lhs_caches:
graph_tensors['block_diag_0'].copy_(block_diag_0)
graph_tensors['block_diag_1'].copy_(block_diag_1)
if enable_central_smoothness:
graph_tensors['block_diag_2'].copy_(block_diag_2)
graph_tensors['rhs'].copy_(rhs)
graph_forward: torch.cuda.CUDAGraph = graph_info['graph_forward']
graph_forward.replay()
if frozen_lhs_cache_version != 0:
LinearSolver.frozen_lhs_caches[frozen_lhs_cache_version] = (
graph_tensors['block_diag_0'],
graph_tensors['block_diag_1'],
graph_tensors['block_diag_2'],
)
else:
graph_tensors['rhs'].copy_(rhs)
graph_substitution: torch.cuda.CUDAGraph = graph_info['graph_substitution']
graph_substitution.replay()
rhs: torch.Tensor = graph_tensors['rhs'] # (n_steps, ..., n_dims * n_orders, 1)
else: # not enable_cuda_graph
if not frozen_lhs_cache_version in LinearSolver.frozen_lhs_caches:
# compute the LDL/Cholesky decomposition
tmp_info: torch.Tensor = torch.empty(batch, dtype=torch.int32, device=device) # (...)
solver.cholesky_inplace(
block_diag_0,
block_diag_1,
block_diag_2,
tmp_info,
enable_ldl=enable_ldl,
)
if frozen_lhs_cache_version != 0:
LinearSolver.frozen_lhs_caches[frozen_lhs_cache_version] = block_diag_0, block_diag_1, block_diag_2
else:
# use the cached left-hand side matrix
block_diag_0, block_diag_1, block_diag_2 = LinearSolver.frozen_lhs_caches[frozen_lhs_cache_version]
# solve for the results
solver.substitution_inplace(
block_diag_0,
block_diag_1,
block_diag_2,
rhs,
enable_ldl=enable_ldl,
)
# store the variables for the backward pass
ctx.block_diag_0, ctx.block_diag_1, ctx.block_diag_2, ctx.x = block_diag_0, block_diag_1, block_diag_2, rhs
return rhs.clone()
@staticmethod
def backward(
ctx,
rhs: torch.Tensor,
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None, torch.Tensor, None]:
"""
Solver backward pass.
Args:
ctx: torch.autograd.function.BackwardCFunction
rhs: (n_steps, ..., n_dims * n_orders, 1)
Returns:
da0: (n_steps, ..., n_dims * n_orders, n_dims * n_orders)
da1: (n_steps-1, ..., n_dims * n_orders, n_dims * n_orders)
da2: (n_steps-2, ..., n_dims * n_orders, n_dims * n_orders) or None
db: (n_steps, ..., n_dims * n_orders, 1)
None
"""
dtype: torch.dtype = rhs.dtype
device: torch.device = rhs.device
solver_options: dict = ctx.solver_options
enable_central_smoothness: bool = solver_options['enable_central_smoothness']
frozen_lhs_cache_version: int = solver_options['frozen_lhs_cache_version']
enable_cuda_graph: bool = solver_options['enable_cuda_graph']
enable_ldl: bool = solver_options['enable_ldl']
if enable_cuda_graph:
# replay the CUDA graphs
graph_key: tuple = rhs.shape, dtype, device, enable_central_smoothness, frozen_lhs_cache_version, enable_ldl
graph_info: dict = LinearSolver.cuda_graph_info[graph_key]
graph_substitution: torch.cuda.CUDAGraph = graph_info['graph_substitution']
graph_tensors: dict[str, torch.Tensor] = graph_info['graph_tensors']
x: torch.Tensor = -graph_tensors['rhs'] # (n_steps, ..., n_dims * n_orders, 1)
graph_tensors['rhs'].copy_(rhs)
graph_substitution.replay()
rhs: torch.Tensor = graph_tensors['rhs']
else: # not enable_cuda_graph
x: torch.Tensor = -ctx.x # (n_steps, ..., n_dims * n_orders, 1)
rhs: torch.Tensor = rhs.clone()
solver = mnn if mnn is not None else LinearSolver
solver.substitution_inplace(
ctx.block_diag_0, ctx.block_diag_1, ctx.block_diag_2, rhs, enable_ldl=enable_ldl,
)
if frozen_lhs_cache_version == 0:
# compute the gradients
da0: torch.Tensor | None = rhs * x[..., None, :, 0]
da1: torch.Tensor | None = rhs[1:] * x[:-1, ..., None, :, 0] + x[1:] * rhs[:-1, ..., None, :, 0]
if enable_central_smoothness:
da2: torch.Tensor | None = rhs[2:] * x[:-2, ..., None, :, 0] + x[2:] * rhs[:-2, ..., None, :, 0]
else:
da2 = None
else:
da0 = da1 = da2 = None
return da0, da1, da2, rhs, None
@staticmethod
def cholesky_inplace(
block_diag_0: torch.Tensor | list[torch.Tensor],
block_diag_1: torch.Tensor | list[torch.Tensor],
block_diag_2: torch.Tensor | list[torch.Tensor] | None,
tmp_info: torch.Tensor,
enable_ldl: bool = True,
) -> None:
"""
LDL/Cholesky decomposition of the block diagonal matrix (inplace).
Args:
block_diag_0: (n_steps, ..., n_dims * n_orders, n_dims * n_orders), inplace
block_diag_1: (n_steps-1, ..., n_dims * n_orders, n_dims * n_orders), inplace
block_diag_2: (n_steps-2, ..., n_dims * n_orders, n_dims * n_orders), inplace
tmp_info: (...), inplace
enable_ldl: bool, if True, the LDL decomposition is used instead of Cholesky decomposition
Returns:
None
"""
enable_block_diag_2: bool = block_diag_2 is not None
n_steps: int = len(block_diag_0)
for step in range(n_steps):
if enable_block_diag_2 and step >= 2:
torch.linalg.solve_triangular(
block_diag_0[step - 2].transpose(-2, -1),
block_diag_2[step - 2],
upper=True,
left=False,
unitriangular=False,
out=block_diag_2[step - 2],
) # block_diag_2[step - 2] @= block_diag_0[step - 2].t().inv()
LinearSolver.bsubbmm(
block_diag_1[step - 1],
block_diag_2[step - 2],
block_diag_1[step - 2].transpose(-2, -1),
) # block_diag_1[step - 1] -= block_diag_2[step - 2] @ block_diag_1[step - 2].t()
if step >= 1:
torch.linalg.solve_triangular(
block_diag_0[step - 1].transpose(-2, -1),
block_diag_1[step - 1],
upper=True,
left=False,
unitriangular=False,
out=block_diag_1[step - 1],
) # block_diag_1[step - 1] @= block_diag_0[step - 1].t().inv()
if enable_block_diag_2 and step >= 2:
LinearSolver.bsubbmm(
block_diag_0[step],
block_diag_2[step - 2],
block_diag_2[step - 2].transpose(-2, -1),
) # block_diag_0[step] -= block_diag_2[step - 2] @ block_diag_2[step - 2].t()
LinearSolver.bsubbmm(
block_diag_0[step],
block_diag_1[step - 1],
block_diag_1[step - 1].transpose(-2, -1),
) # block_diag_0[step] -= block_diag_1[step - 1] @ block_diag_1[step - 1].t()
torch.linalg.cholesky_ex(
block_diag_0[step],
upper=False,
check_errors=False,
out=(block_diag_0[step], tmp_info),
)
if enable_ldl:
# LDL decomposition https://en.wikipedia.org/wiki/Cholesky_decomposition#Block_variant
# block_diag_0: Cholesky decomposition of D
# block_diag_1: L blocks
# block_diag_2: L blocks
torch.linalg.solve_triangular(
block_diag_0[:-1],
block_diag_1,
upper=False,
left=False,
unitriangular=False,
out=block_diag_1,
) # block_diag_1 @= block_diag_0[:-1].inv()
if enable_block_diag_2:
torch.linalg.solve_triangular(
block_diag_0[:-2],
block_diag_2,
upper=False,
left=False,
unitriangular=False,
out=block_diag_2,
) # block_diag_2 @= block_diag_0[:-2].inv()
@staticmethod
def substitution_inplace(
block_diag_0: torch.Tensor | list[torch.Tensor],
block_diag_1: torch.Tensor | list[torch.Tensor],
block_diag_2: torch.Tensor | list[torch.Tensor] | None,
rhs: torch.Tensor | list[torch.Tensor],
enable_ldl: bool = True,
) -> None:
"""
Solve for the results using the substitution algorithm (inplace).
Args:
block_diag_0: (n_steps, ..., n_dims * n_orders, n_dims * n_orders)
block_diag_1: (n_steps-1, ..., n_dims * n_orders, n_dims * n_orders)
block_diag_2: (n_steps-2, ..., n_dims * n_orders, n_dims * n_orders)
rhs: (n_steps, ..., n_dims * n_orders, 1), inplace
enable_ldl: bool, if True, the LDL decomposition is used instead of Cholesky decomposition
Returns:
None
"""
enable_block_diag_2: bool = block_diag_2 is not None
n_steps: int = len(block_diag_0)
# A X = B => L (D (Lt X)) = B
for step in range(n_steps):
# solve L Z = B, block forward substitution
if enable_block_diag_2 and step >= 2:
LinearSolver.bsubbmm(
rhs[step],
block_diag_2[step - 2],
rhs[step - 2],
) # rhs[step] -= block_diag_2[step - 2] @ rhs[step - 2]
if step >= 1:
LinearSolver.bsubbmm(
rhs[step],
block_diag_1[step - 1],
rhs[step - 1],
) # rhs[step] -= block_diag_1[step - 1] @ rhs[step - 1]
if not enable_ldl:
torch.linalg.solve_triangular(
block_diag_0[step],
rhs[step],
upper=False,
left=True,
unitriangular=False,
out=rhs[step],
) # rhs[step] = block_diag_0[step].inv() @ rhs[step]
if enable_ldl:
# solve D Y = Z, block forward substitution
# torch.cholesky_solve(
# rhs,
# block_diag_0,
# upper=False,
# out=rhs,
# ) # rhs = (block_diag_0 @ block_diag_0.t()).inv() @ rhs
# the above is slow so we use the following instead
torch.linalg.solve_triangular(
block_diag_0,
rhs,
upper=False,
left=True,
unitriangular=False,
out=rhs,
) # rhs = block_diag_0.inv() @ rhs
torch.linalg.solve_triangular(
block_diag_0.transpose(-2, -1),
rhs,
upper=True,
left=True,
unitriangular=False,
out=rhs,
) # rhs = block_diag_0.t().inv() @ rhs
for step in range(n_steps - 1, -1, -1):
# solve Lt X = Y, block backward substitution
if enable_block_diag_2 and step < n_steps - 2:
LinearSolver.bsubbmm(
rhs[step],
block_diag_2[step].transpose(-2, -1),
rhs[step + 2],
) # rhs[step] -= block_diag_2[step].t() @ rhs[step + 2]
if step < n_steps - 1:
LinearSolver.bsubbmm(
rhs[step],
block_diag_1[step].transpose(-2, -1),
rhs[step + 1],
) # rhs[step] -= block_diag_1[step].t() @ rhs[step + 1]
if not enable_ldl:
torch.linalg.solve_triangular(
block_diag_0[step].transpose(-2, -1),
rhs[step],
upper=True,
left=True,
unitriangular=False,
out=rhs[step],
) # rhs[step] = block_diag_0[step].t().inv() @ rhs[step]
@staticmethod
def bsubbmm(c: torch.Tensor, a: torch.Tensor, b: torch.Tensor) -> None:
"""
Compute c -= a @ b
Args:
c: (..., n_dims * n_orders, 1)
a: (..., n_dims * n_orders, n_dims * n_orders)
b: (..., n_dims * n_orders, 1)
Returns:
None
"""
c -= a @ b # (..., n_dims * n_orders, 1)
# not yet supporting multiple batch dims
# a, b, c = a.flatten(end_dim=-3), b.flatten(end_dim=-3), c.flatten(end_dim=-3)
# torch.baddbmm(c, a, b, beta=1, alpha=-1, out=c)
def ode_forward_basic(
coefficients: torch.Tensor,
rhs_equation: torch.Tensor,
rhs_init: torch.Tensor,
steps: torch.Tensor,
n_steps: int = None,
n_init_var_steps: int = None,
) -> torch.Tensor:
"""
Basic (simplest) implementation of the ODE forward pass. The backward pass is fully by autograd.
This implementation has linear time & space complexity.
([b]: broadcastable dimensions, [e]: contiguous or expanded dimensions)
Args:
coefficients: (..., n_steps[b], n_equations, n_dims, n_orders)
rhs_equation: (..., n_steps[b], n_equations[e])
rhs_init: (..., n_init_var_steps[b], n_dims[e], n_init_var_orders[e])
steps: (..., n_steps-1[b])
n_steps: int, optional, please specify if it cannot be inferred from the tensor shapes
n_init_var_steps: int, optional, please specify if it cannot be inferred from the tensor shapes
Returns:
out: (..., n_steps, n_dims, n_orders)
"""
dtype: torch.dtype = coefficients.dtype
device: torch.device = coefficients.device
n_steps: int = steps.size(-1) + 1 if n_steps is None else n_steps
assert n_steps >= 2
n_init_var_steps: int = rhs_init.size(-3) if n_init_var_steps is None else n_init_var_steps
*batch_coefficients, n_steps_coefficients, n_equations, n_dims, n_orders = coefficients.shape
assert n_steps_coefficients in [n_steps, 1]
*batch_rhs_equation, n_steps_rhs_equation, n_equations_rhs_equation = rhs_equation.shape
assert n_steps_rhs_equation in [n_steps, 1] and n_equations_rhs_equation == n_equations
*batch_rhs_init, n_init_var_steps_rhs_init, n_dims_rhs_init, n_init_var_orders = rhs_init.shape
assert n_init_var_steps_rhs_init in [n_init_var_steps, 1] and n_dims_rhs_init == n_dims
*batch_steps, n_steps_steps = steps.shape
assert n_steps_steps in [n_steps - 1, 1]
batch_lhs: torch.Size = torch.broadcast_shapes(batch_coefficients, batch_steps)
batch: torch.Size = torch.broadcast_shapes(batch_lhs, batch_rhs_equation, batch_rhs_init)
# ode equation constraints
c: torch.Tensor = coefficients.flatten(start_dim=-2) # (..., n_steps[b], n_equations, n_dims * n_orders)
ct: torch.Tensor = c.transpose(-2, -1) # (..., n_steps[b], n_dims * n_orders, n_equations)
block_diag_0: torch.Tensor = ct @ c # (..., n_steps[b], n_dims * n_orders, n_dims * n_orders)
beta: torch.Tensor = ct @ rhs_equation[..., None] # (..., n_steps[b], n_dims * n_orders, 1)
block_diag_0: torch.Tensor = block_diag_0.repeat(
*[ss // s for ss, s in zip(batch_lhs, block_diag_0.shape[:-3])],
n_steps // block_diag_0.size(-3),
1,
1,
) # (..., n_steps, n_dims * n_orders, n_dims * n_orders)
beta: torch.Tensor = beta.repeat(
*[ss // s for ss, s in zip(batch, beta.shape[:-3])],
n_steps // beta.size(-3),
1,
1,
) # (..., n_steps, n_dims * n_orders, 1)
# initial-value constraints
init_idx: torch.Tensor = torch.arange(n_init_var_orders, device=device).repeat(n_dims) \
+ (n_orders * torch.arange(n_dims, device=device)).repeat_interleave(n_init_var_orders)
# (n_dims * n_init_var_orders)
block_diag_0[..., :n_init_var_steps, init_idx, init_idx] += 1.
beta[..., :n_init_var_steps, :, 0] += torch.cat([
rhs_init,
torch.zeros(*rhs_init.shape[:-1], n_orders - n_init_var_orders, dtype=dtype, device=device),
], dim=-1).flatten(start_dim=-2)
# smoothness constraints (forward & backward)
order_idx: torch.Tensor = torch.arange(n_orders, device=device) # (n_orders)
sign_vec: torch.Tensor = order_idx % 2 * (-2) + 1 # (n_orders)
sign_map: torch.Tensor = sign_vec * sign_vec[:, None] # (n_orders, n_orders)
expansions: torch.Tensor = steps[..., None] ** order_idx # (..., n_steps-1[b], n_orders)
et_e_diag: torch.Tensor = expansions ** 2 # (..., n_steps-1[b], n_orders)
et_e_diag[..., -1] = 0.
factorials: torch.Tensor = (-(order_idx - order_idx[:, None] + 1).triu().to(dtype=dtype).lgamma()).exp()
# (n_orders, n_orders)
factorials[-1, -1] = 0.
e_outer: torch.Tensor = expansions[..., None] * expansions[..., None, :] # (..., n_steps-1[b], n_orders, n_orders)
et_ft_f_e: torch.Tensor = e_outer * (factorials.t() @ factorials) # (..., n_steps-1[b], n_orders, n_orders)
smooth_block_diag_1: torch.Tensor = e_outer * -(factorials + factorials.transpose(-2, -1) * sign_map)
# (..., n_steps-1[b], n_orders, n_orders)
smooth_block_diag_0: torch.Tensor = torch.zeros(*batch_lhs, n_steps, n_orders, n_orders, dtype=dtype, device=device)
# (..., n_steps, n_orders, n_orders)
smooth_block_diag_0[..., :-1, :, :] += et_ft_f_e
smooth_block_diag_0[..., 1:, :, :] += et_ft_f_e * sign_map
smooth_block_diag_0[..., :-1, order_idx, order_idx] += et_e_diag
smooth_block_diag_0[..., 1:, order_idx, order_idx] += et_e_diag
smooth_block_diag_1: torch.Tensor = smooth_block_diag_1.repeat(
*([1] * len(batch_lhs)),
(n_steps - 1) // smooth_block_diag_1.size(-3),
1,
1,
) # (..., n_steps-1, n_orders, n_orders)
steps: torch.Tensor = steps.repeat(*([1] * len(batch_lhs)), (n_steps - 1) // steps.size(-1)) # (..., n_steps-1)
# smoothness constraints (central)
steps2: torch.Tensor = steps[..., :-1] + steps[..., 1:] # (..., n_steps-2)
steps26: torch.Tensor = steps2 ** (n_orders * 2 - 6) # (..., n_steps-2)
steps25: torch.Tensor = steps2 ** (n_orders * 2 - 5) # (..., n_steps-2)
steps24: torch.Tensor = steps2 ** (n_orders * 2 - 4) # (..., n_steps-2)
smooth_block_diag_0[..., :-2, n_orders - 2, n_orders - 2] += steps26
smooth_block_diag_0[..., 2:, n_orders - 2, n_orders - 2] += steps26
smooth_block_diag_0[..., 1:-1, n_orders - 1, n_orders - 1] += steps24
smooth_block_diag_1[..., :-1, n_orders - 1, n_orders - 2] += steps25
smooth_block_diag_1[..., 1:, n_orders - 2, n_orders - 1] -= steps25
smooth_block_diag_2: torch.Tensor = torch.zeros(
*batch_lhs, n_steps - 2, n_orders, n_orders, dtype=dtype, device=device,
) # (..., n_steps-2, n_orders, n_orders)
smooth_block_diag_2[..., n_orders - 2, n_orders - 2] = -steps26
# copy to n_dims
block_diag_1: torch.Tensor = torch.zeros(
*batch_lhs, n_steps - 1, n_dims * n_orders, n_dims * n_orders, dtype=dtype, device=device,
) # (..., n_steps-1, n_dims * n_orders, n_dims * n_orders)
block_diag_2: torch.Tensor = torch.zeros(
*batch_lhs, n_steps - 2, n_dims * n_orders, n_dims * n_orders, dtype=dtype, device=device,
) # (..., n_steps-2, n_dims * n_orders, n_dims * n_orders)
for dim in range(n_dims):
i1: int = dim * n_orders
i2: int = (dim + 1) * n_orders
block_diag_0[..., i1:i2, i1:i2] += smooth_block_diag_0
block_diag_1[..., i1:i2, i1:i2] = smooth_block_diag_1
block_diag_2[..., i1:i2, i1:i2] = smooth_block_diag_2
# blocked cholesky decomposition
block_diag_0_list: list[torch.Tensor] = list(block_diag_0.unbind(dim=-3))
block_diag_1_list: list[torch.Tensor] = list(block_diag_1.unbind(dim=-3))
block_diag_2_list: list[torch.Tensor] = list(block_diag_2.unbind(dim=-3))
for step in range(n_steps):
if step >= 2:
block_diag_2_list[step - 2] = torch.linalg.solve_triangular(
block_diag_0_list[step - 2].transpose(-2, -1),
block_diag_2_list[step - 2],
upper=True,
left=False,
)
block_diag_1_list[step - 1] = block_diag_1_list[step - 1] \
- block_diag_2_list[step - 2] @ block_diag_1_list[step - 2].transpose(-2, -1)
if step >= 1:
block_diag_1_list[step - 1] = torch.linalg.solve_triangular(
block_diag_0_list[step - 1].transpose(-2, -1),
block_diag_1_list[step - 1],
upper=True,
left=False,
)
if step >= 2:
block_diag_0_list[step] = block_diag_0_list[step] \
- block_diag_2_list[step - 2] @ block_diag_2_list[step - 2].transpose(-2, -1)
block_diag_0_list[step] = block_diag_0_list[step] \
- block_diag_1_list[step - 1] @ block_diag_1_list[step - 1].transpose(-2, -1)
block_diag_0_list[step], _ = torch.linalg.cholesky_ex(
block_diag_0_list[step],
upper=False,
check_errors=False,
)
# A X = B => L (Lt X) = B
# solve L Y = B, block forward substitution
b_list: list[torch.Tensor] = list(beta.unbind(dim=-3))
y_list: list[torch.Tensor | None] = [None] * n_steps
for step in range(n_steps):
b_step: torch.Tensor = b_list[step]
if step >= 2:
b_step = b_step - block_diag_2_list[step - 2] @ y_list[step - 2]
if step >= 1:
b_step = b_step - block_diag_1_list[step - 1] @ y_list[step - 1]
y_list[step] = torch.linalg.solve_triangular(
block_diag_0_list[step],
b_step,
upper=False,
left=True,
)
# solve Lt X = Y, block backward substitution
x_list: list[torch.Tensor | None] = [None] * n_steps
for step in range(n_steps - 1, -1, -1):
y_step: torch.Tensor = y_list[step]
if step < n_steps - 2:
y_step = y_step - block_diag_2_list[step].transpose(-2, -1) @ x_list[step + 2]
if step < n_steps - 1:
y_step = y_step - block_diag_1_list[step].transpose(-2, -1) @ x_list[step + 1]
x_list[step] = torch.linalg.solve_triangular(
block_diag_0_list[step].transpose(-2, -1),