-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_example.py
More file actions
1653 lines (1339 loc) · 57 KB
/
test_example.py
File metadata and controls
1653 lines (1339 loc) · 57 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
from taylorvar.taylor_mode_utils import *
import torch
def test_swish_derivatives():
"""测试Swish激活函数的导数"""
x = torch.tensor([[-2.0, -1.0, 0.0, 1.0, 2.0]], requires_grad=True,dtype=torch.float64)
# 获取Swish及其导数函数
fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('swish')
# fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('tanh')
# fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('sigmoid')
# fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('relu')
# fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('cube')
# fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('square')
print("\n=== 测试 Swish 激活函数 ===")
print("函数值:", fn(x))
print("一阶导:", fn_prime(x))
print("二阶导:", fn_double_prime(x))
print("三阶导:", fn_triple_prime(x))
# 与数值微分对比验证
from torch.autograd import grad
def autograd_derivative(f, x, order=1):
derivatives = []
current_grad = f(x)
derivatives.append(current_grad)
for i in range(1, order + 1):
current_grad = grad(current_grad.sum(), x, create_graph=True)[0]
derivatives.append(current_grad)
return derivatives[-1]
print("\n微分对比:")
print("一阶导数差异:", torch.abs(fn_prime(x) - autograd_derivative(fn, x, 1)).max().item())
print("二阶导数差异:", torch.abs(fn_double_prime(x) - autograd_derivative(fn, x, 2)).max().item())
print("三阶导数差异:", torch.abs(fn_triple_prime(x) - autograd_derivative(fn, x, 3)).max().item())
def test_custom_activation():
"""测试自定义激活函数的导数计算"""
x = torch.tensor([[-1.0, 0.0, 1.0], [-2.0, -1.0, 0.0]], requires_grad=True, dtype=torch.float64)
def custom_fn(x):
return torch.sin(x) * x**2
fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives(custom_fn)
print("\n=== 测试自定义函数 sin(x)*x² ===")
print("函数值:", fn(x))
print("一阶导:", fn_prime(x))
print("二阶导:", fn_double_prime(x))
print("三阶导:", fn_triple_prime(x))
# 与自动微分对比验证
from torch.autograd import grad
def autograd_derivative(f, x, order=1):
derivatives = []
current_grad = f(x)
derivatives.append(current_grad)
for i in range(1, order + 1):
current_grad = grad(current_grad.sum(), x, create_graph=True)[0]
derivatives.append(current_grad)
return derivatives[-1]
print("\n自动微分对比:")
print("一阶导数差异:", torch.abs(fn_prime(x) - autograd_derivative(fn, x, 1)).max().item())
print("二阶导数差异:", torch.abs(fn_double_prime(x) - autograd_derivative(fn, x, 2)).max().item())
print("三阶导数差异:", torch.abs(fn_triple_prime(x) - autograd_derivative(fn, x, 3)).max().item())
# 数值微分
def numerical_derivative(f, x, order=1, eps=1e-4):
if order == 1:
return (f(x + eps) - f(x - eps)) / (2 * eps)
else:
def wrapped(x):
return numerical_derivative(f, x, order-1, eps)
return (wrapped(x + eps) - wrapped(x - eps)) / (2 * eps)
print("\n数值微分对比:")
print("一阶导数差异:", torch.abs(fn_prime(x) - numerical_derivative(fn, x, 1)).max().item())
print("二阶导数差异:", torch.abs(fn_double_prime(x) - numerical_derivative(fn, x, 2)).max().item())
print("三阶导数差异:", torch.abs(fn_triple_prime(x) - numerical_derivative(fn, x, 3)).max().item())
def swish(x):
return x * torch.sigmoid(x)
_, ground_truth_prime, ground_truth_double_prime, ground_truth_triple_prime = get_activation_with_derivatives(swish)
_, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives(swish)
print("\nswish 激活函数真解对比:")
print("一阶导数差异:", torch.abs(fn_prime(x) - ground_truth_prime(x)).max().item())
print("二阶导数差异:", torch.abs(fn_double_prime(x) - ground_truth_double_prime(x)).max().item())
print("三阶导数差异:", torch.abs(fn_triple_prime(x) - ground_truth_triple_prime(x)).max().item())
def test_elementwise_activation():
"""
测试激活函数的Taylor展开。
使用简单的立方函数 f(x) = x^3 作为激活函数。
对于 f: R^n → R^n, f(x) = x^3:
- Jacobian: J_{ij} = 3x_i^2 if i=j else 0
- Hessian: H_{ijk} = 6x_i if i=j=k else 0
- Third derivative: 6 if i=j=k else 0
"""
x = torch.tensor([[2.0, -1.0], [1.0, 2.0]], requires_grad=True) # (2,2)
def cube_fn(x): return x**3
def cube_prime(x): return 3*x**2
def cube_double_prime(x): return 6*x
def cube_triple_prime(x): return 6*torch.ones_like(x)
from torch.func import jacrev, vmap
# 计算 Jacobian (first derivative)
def f(x_in):
return cube_fn(x_in).squeeze(0)
jac = vmap(jacrev(f), (0,))(x) # shape: (2,2,1,2)
hess = vmap(jacrev(jacrev(f)), (0,))(x)
third = vmap(jacrev(jacrev(jacrev(f))), (0,))(x)
# 2. TaylorVar
val_init = x
first_init = torch.zeros((1, 2, 2))
first_init[:,0,0] = 1.0
first_init[:,1,1] = 1.0
x_tvar = TaylorVar(val_init, first_init)
f_tvar = x_tvar.elementwise_fn(cube_fn, cube_prime,
cube_double_prime, cube_triple_prime)
print("\n=== 测试激活函数 f(x) = x^3 ===")
print("在点 x =", x[0].tolist())
print("\nJacobian 对比:")
print("Autograd functional:")
print(jac) # 去掉batch维度
print("TaylorVar:")
print(f_tvar.first[...])
print("\nHessian 对比:")
print("Autograd functional:")
print(hess)
print("TaylorVar:")
print(f_tvar.second[...])
print("\n三阶导数对比:")
print("Autograd functional:")
print(third)
print("TaylorVar:")
print(f_tvar.third[...])
def test_linear_layer():
"""
测试线性层的Taylor展开。
对于线性变换 f(x) = Wx + b:
- Jacobian: J = W
- Hessian: H = 0
- Third derivative: 0
"""
# 构造输入和线性层参数
x = torch.tensor([[2.0, -1.0], [1.0, 2.0]], requires_grad=True) # (2,2)
W = torch.tensor([[2.0, 1.0],
[1.0, 3.0]]) # (2,2)
b = torch.tensor([0.5, -1.0]) # (2,)
from torch.func import jacrev, vmap
# 1. PyTorch autograd.functional
def f(x_in):
return (x_in @ W.T + b).squeeze(0)
# 计算 Jacobian (应该等于 W)
jac = vmap(jacrev(f), (0,))(x)
# 计算 Hessian (应该全为0)
hess = vmap(jacrev(jacrev(f)), (0,))(x)
# 计算三阶导数 (应该全为0)
third = vmap(jacrev(jacrev(jacrev(f))), (0,))(x)
# 2. TaylorVar
val_init = x
first_init = torch.zeros((2, 2, 2)) # (batch,d,d)
first_init[:,0,0] = 1.0 # ∂/∂x1
first_init[:,1,1] = 1.0 # ∂/∂x2
x_tvar = TaylorVar(val_init, first_init)
f_tvar = x_tvar.linear(W, b)
print("\n=== 测试线性层 f(x) = Wx + b ===")
print("W =\n", W)
print("b =", b.tolist())
print("在点 x =", x.tolist())
print("\nJacobian 对比:")
print("Autograd functional:")
print(jac)
print("TaylorVar:")
print(f_tvar.first[...]) # 调整维度顺序以匹配
print("\nHessian 对比:")
print("Autograd functional:")
print(hess)
print("TaylorVar:")
print(f_tvar.second[...])
print("\n三阶导数对比:")
print("Autograd functional:")
print(third)
print("TaylorVar:")
print(f_tvar.third[...])
def test_linear_activation_composition():
"""
测试线性层和激活函数的组合。
f(x) = cube(Wx + b),其中 cube(x) = x^3
对于这个复合函数:
1. 线性层 g(x) = Wx + b 的导数:
- Jacobian: J_g = W
- Hessian: H_g = 0
- Third: 0
2. 立方函数 h(y) = y^3 的导数:
- h'(y) = 3y^2
- h''(y) = 6y
- h'''(y) = 6
3. 复合函数 f = h∘g 的导数通过链式法则计算
"""
# 构造输入和参数
x = torch.tensor([[2.0, -1.0], [1.0, 2.0]], requires_grad=True) # (2,2)
W = torch.tensor([[2.0, 1.0],
[1.0, 3.0]]) # (2,2)
b = torch.tensor([0.5, -1.0]) # (2,)
from torch.func import jacrev, vmap
# 1. PyTorch autograd.functional
def f(x_in):
y = x_in @ W.T + b
return y**4
# 计算各阶导数
jac = vmap(jacrev(f), (0,))(x)
hess = vmap(jacrev(jacrev(f)), (0,))(x)
third = vmap(jacrev(jacrev(jacrev(f))), (0,))(x)
# 2. TaylorVar
val_init = x
first_init = torch.zeros((2, 2, 2)) # (batch,d,d)
first_init[:,0,0] = 1.0 # ∂/∂x1
first_init[:,1,1] = 1.0 # ∂/∂x2
x_tvar = TaylorVar(val_init, first_init)
# 先线性层
y_tvar = x_tvar.linear(W, b)
# 再过激活函数
def cube_fn(x): return x**4
def cube_prime(x): return 4*x**3
def cube_double_prime(x): return 12*x**2
def cube_triple_prime(x): return 24*x
z_tvar = y_tvar.elementwise_fn(cube_fn, cube_prime,
cube_double_prime, cube_triple_prime)
print("\n=== 测试复合函数 f(x) = cube(Wx + b) ===")
print("W =\n", W)
print("b =", b.tolist())
print("在点 x =\n", x.tolist())
print("\nJacobian 对比:")
print("Autograd functional:")
print(jac)
print("TaylorVar:")
print(z_tvar.first[...])
print("\nHessian 对比:")
print("Autograd functional:")
print(hess)
print("TaylorVar:")
print(z_tvar.second[...])
print("\n三阶导数对比:")
print("Autograd functional:")
print(third)
print("TaylorVar:")
print(z_tvar.third[...])
def test_linear_multiply_composition():
"""
测试线性层和乘法的组合。
f(x) = (A₁x + b₁)(A₂x + b₂)
对于这个复合函数:
1. 两个线性变换:
g₁(x) = A₁x + b₁
g₂(x) = A₂x + b₂
2. 然后做逐元素乘法:
f(x) = g₁(x) * g₂(x)
"""
# 构造输入和参数
x = torch.tensor([[2.0, -1.0], [1.0, 2.0]], requires_grad=True) # (2,2)
# 第一个线性层参数
W1 = torch.tensor([[2.0, 1.0],
[1.0, 3.0]]) # (2,2)
b1 = torch.tensor([0.5, -1.0]) # (2,)
# 第二个线性层参数
W2 = torch.tensor([[1.0, -1.0],
[2.0, 1.0]]) # (2,2)
b2 = torch.tensor([-0.5, 1.0]) # (2,)
from torch.func import jacrev, vmap
# 1. PyTorch autograd.functional
def f(x_in):
g1 = x_in @ W1.T + b1
g2 = x_in @ W2.T + b2
return g1 * g2
# 计算各阶导数
jac = vmap(jacrev(f), (0,))(x)
hess = vmap(jacrev(jacrev(f)), (0,))(x)
third = vmap(jacrev(jacrev(jacrev(f))), (0,))(x)
# 2. TaylorVar
val_init = x
first_init = torch.zeros((2, 2, 2)) # (batch,d,d)
first_init[:,0,0] = 1.0 # ∂/∂x1
first_init[:,1,1] = 1.0 # ∂/∂x2
x_tvar = TaylorVar(val_init, first_init)
# 计算两个线性变换
g1_tvar = x_tvar.linear(W1, b1)
g2_tvar = x_tvar.linear(W2, b2)
# 做逐元素乘法
f_tvar = g1_tvar * g2_tvar
print("\n=== 测试复合函数 f(x) = (A₁x + b₁)(A₂x + b₂) ===")
print("W1 =\n", W1)
print("b1 =", b1.tolist())
print("W2 =\n", W2)
print("b2 =", b2.tolist())
print("在点 x =\n", x.tolist())
print("\nJacobian 对比:")
print("Autograd functional:")
print(jac)
print("TaylorVar:")
print(f_tvar.first[...])
print("\nHessian 对比:")
print("Autograd functional:")
print(hess)
print("TaylorVar:")
print(f_tvar.second[...])
print("\n三阶导数对比:")
print("Autograd functional:")
print(third)
print("TaylorVar:")
print(f_tvar.third[...])
def test_linear_activation_multiply():
"""
测试激活函数、线性层和乘法的组合。
f(x) = φ(A₁x + b₁) * φ(A₂x + b₂),其中 φ(x) = x⁴
复合过程:
1. 两个线性变换:
g₁(x) = A₁x + b₁
g₂(x) = A₂x + b₂
2. 分别过激活函数:
h₁(x) = φ(g₁(x))
h₂(x) = φ(g₂(x))
3. 最后做逐元素乘法:
f(x) = h₁(x) * h₂(x)
"""
# 构造输入和参数
x = torch.tensor([[2.0, -1.0], [1.0, 2.0]], requires_grad=True) # (2,2)
# 第一个线性层参数
W1 = torch.tensor([[2.0, 1.0],
[1.0, 3.0]]) # (2,2)
b1 = torch.tensor([0.5, -1.0]) # (2,)
# 第二个线性层参数
W2 = torch.tensor([[1.0, -1.0],
[2.0, 1.0]]) # (2,2)
b2 = torch.tensor([-0.5, 1.0]) # (2,)
from torch.func import jacrev, vmap
# 1. PyTorch autograd.functional
def f(x_in):
g1 = x_in @ W1.T + b1
g2 = x_in @ W2.T + b2
return (g1**4) * (g2**4)
# 计算各阶导数
jac = vmap(jacrev(f), (0,))(x)
hess = vmap(jacrev(jacrev(f)), (0,))(x)
third = vmap(jacrev(jacrev(jacrev(f))), (0,))(x)
# 2. TaylorVar
val_init = x
first_init = torch.zeros((2, 2, 2)) # (batch,d,d)
first_init[:,0,0] = 1.0 # ∂/∂x1
first_init[:,1,1] = 1.0 # ∂/∂x2
x_tvar = TaylorVar(val_init, first_init)
# 计算两个分支
def phi(x): return x**4
def phi_prime(x): return 4*x**3
def phi_double_prime(x): return 12*x**2
def phi_triple_prime(x): return 24*x
# 第一个分支: h₁(x) = φ(A₁x + b₁)
g1_tvar = x_tvar.linear(W1, b1)
h1_tvar = g1_tvar.elementwise_fn(phi, phi_prime,
phi_double_prime, phi_triple_prime)
# 第二个分支: h₂(x) = φ(A₂x + b₂)
g2_tvar = x_tvar.linear(W2, b2)
h2_tvar = g2_tvar.elementwise_fn(phi, phi_prime,
phi_double_prime, phi_triple_prime)
# 最后做乘法: f(x) = h₁(x) * h₂(x)
f_tvar = h1_tvar * h2_tvar
print("\n=== 测试复合函数 f(x) = φ(A₁x + b₁) * φ(A₂x + b₂) ===")
print("W1 =\n", W1)
print("b1 =", b1.tolist())
print("W2 =\n", W2)
print("b2 =", b2.tolist())
print("在点 x =\n", x.tolist())
print("\nJacobian 对比:")
print("Autograd functional:")
print(jac)
print("TaylorVar:")
print(f_tvar.first[...])
print("\nHessian 对比:")
print("Autograd functional:")
print(hess)
print("TaylorVar:")
print(f_tvar.second[...])
print("\n三阶导数对比 ([..., 1,1,0]):")
print("Autograd functional:")
print(third[...,1,1,0])
print("TaylorVar:")
print(f_tvar.third[1,1,0])
def test_simple_example():
"""
测试原始示例函数 f(x₁,x₂) = (x₁² + 3x₂)³
计算过程可以分解为:
1. g₁(x) = x₁² (用激活函数)
2. g₂(x) = 3x₂ (用乘法)
3. h(x) = g₁ + g₂ (用加法)
4. f(x) = h³ (用激活函数)
"""
x = torch.tensor([1.5, -2.0], requires_grad=True) # (2)
from torch.func import jacrev, vmap
# 1. PyTorch autograd.functional
def f(x_in):
return (x_in[0]**2 + 3*x_in[1])**3
# 计算各阶导数
jac = jacrev(f)(x)
hess = jacrev(jacrev(f))(x)
third = jacrev(jacrev(jacrev(f)))(x)
# 2. TaylorVar
val_init = x
first_init = torch.zeros((2, 2)) # (d,d)
first_init[0,0] = 1.0 # ∂/∂x₁
first_init[1,1] = 1.0 # ∂/∂x₂
x_tvar = TaylorVar(val_init, first_init)
# 计算 x₁²
def square_fn(x): return x**2
def square_prime(x): return 2*x
def square_double_prime(x): return 2*torch.ones_like(x)
def square_triple_prime(x): return torch.zeros_like(x)
x1_tvar = x_tvar[0]
g1_tvar = x1_tvar.elementwise_fn(square_fn, square_prime,
square_double_prime, square_triple_prime)
# 计算 3x₂
x2_tvar = x_tvar[1]
g2_tvar = 3 * x2_tvar
# 计算 g₁ + g₂
h_tvar = g1_tvar + g2_tvar
# 计算 h³
def cube_fn(x): return x**3
def cube_prime(x): return 3*x**2
def cube_double_prime(x): return 6*x
def cube_triple_prime(x): return 6*torch.ones_like(x)
f_tvar = h_tvar.elementwise_fn(cube_fn, cube_prime,
cube_double_prime, cube_triple_prime)
print("\n=== 测试原始示例 f(x₁,x₂) = (x₁² + 3x₂)³ ===")
print("在点 x =", x[0].tolist())
print("\nJacobian 对比:")
print("Autograd functional:")
print(jac)
print("TaylorVar:")
print(f_tvar.first[...])
print("\nHessian 对比:")
print("Autograd functional:")
print(hess)
print("TaylorVar:")
print(f_tvar.second[...])
print("\n三阶导数对比:")
print("Autograd functional:")
print(third)
print("TaylorVar:")
print(f_tvar.third[...])
def test_other_components():
"""
测试新添加的组件:
1. 减法
2. 形状操作 (reshape, view, flatten)
3. 张量组合 (cat, stack)
4. 维度操作 (squeeze, unsqueeze)
"""
# 构造测试数据
x = torch.tensor([[2.0, -1.0], [1.0, 2.0]], requires_grad=True) # (2,2)
val_init = x
first_init = torch.zeros((2, 2, 2)) # (batch,d,d)
first_init[:,0,0] = 1.0 # ∂/∂x1
first_init[:,1,1] = 1.0 # ∂/∂x2
x_tvar = TaylorVar(val_init, first_init)
# 1. 测试减法
print("\n=== 测试减法 ===")
def f_sub(x): return x - torch.tensor([1.0, 0.5])
y_sub = f_sub(x)
from torch.func import jacrev, vmap
jac_sub = vmap(jacrev(f_sub), (0,))(x)
y_tvar = f_sub(x_tvar)
print("减法结果对比:")
print("Autograd:", y_sub)
print("TaylorVar:", y_tvar.val)
print("Jacobian对比:")
print("Autograd:", jac_sub)
print("TaylorVar:", y_tvar.first[...])
# 2. 测试形状操作
print("\n=== 测试形状操作 ===")
# reshape
reshaped_tvar = x_tvar.reshape(4)
print("Reshape后的形状:")
print("val:", reshaped_tvar.val.shape)
print("first:", reshaped_tvar.first[...].shape)
print("second:", reshaped_tvar.second[...].shape)
print("third:", reshaped_tvar.third[...].shape)
flatten_tvar = x_tvar.flatten()
print("Flatten后的形状:")
print("val:", flatten_tvar.val.shape)
print("first:", flatten_tvar.first[...].shape)
print("second:", flatten_tvar.second[...].shape)
print("third:", flatten_tvar.third[...].shape)
# 3. 测试张量组合
print("\n=== 测试张量组合 ===")
# cat
cat_tvar = TaylorVar.cat([x_tvar, x_tvar], dim=1)
print("Cat后的形状:")
print("val:", cat_tvar.val.shape)
print("first:", cat_tvar.first[...].shape)
print("second:", cat_tvar.second[...].shape)
print("third:", cat_tvar.third[...].shape)
# stack
stack_tvar = TaylorVar.stack([x_tvar, x_tvar], dim=0)
print("Stack后的形状:")
print("val:", stack_tvar.val.shape)
print("first:", stack_tvar.first[...].shape)
print("second:", stack_tvar.second[...].shape)
print("third:", stack_tvar.third[...].shape)
# 4. 测试维度操作
print("\n=== 测试维度操作 ===")
# unsqueeze
unsqueezed_tvar = x_tvar.unsqueeze(1)
print("Unsqueeze后的形状:")
print("val:", unsqueezed_tvar.val.shape)
print("first:", unsqueezed_tvar.first[...].shape)
print("second:", unsqueezed_tvar.second[...].shape)
print("third:", unsqueezed_tvar.third[...].shape)
def test_functional_compatibility():
"""
测试 TaylorVar 与 PyTorch functional API 的兼容性
主要测试:
1. vmap 对 TaylorVar 的批处理
2. jacrev 与 TaylorVar 的交互
3. 组合使用的情况
"""
from torch.func import vmap, jacrev
# 构造测试数据
batch_size = 3
x = torch.tensor([[1.0, -1.0], [2.0, 0.0], [0.0, 2.0]], requires_grad=True) # (3,2)
# swish 激活函数
activation_fn = taylor_activation_wrapper(*get_activation_with_derivatives("swish"))
# 1. 测试基本的 vmap 兼容性
print("\n=== 测试 vmap 兼容性 ===")
def forward_fn(x_single):
"""单样本的前向函数"""
# 构造 TaylorVar
val_init = x_single # (2,)
first_init = torch.zeros((2, 2))
first_init[0,0] = 1.0
first_init[1,1] = 1.0
x_tvar = TaylorVar(val_init, first_init)
y_tvar = x_tvar.linear(torch.tensor([[2.0, 1.0], [1.0, 3.0]]),
torch.tensor([0.5, -1.0]))
z_tvar = activation_fn(y_tvar)
return z_tvar.val
# 使用 vmap 批处理
batched_forward = vmap(forward_fn)
result = batched_forward(x)
print("vmap 批处理结果:", result.shape)
# 2. 测试 vmap 内自动微分
print("\n=== 测试 vmap 内外Taylor mode自动微分 对比 ===")
# swish 激活函数
activation_fn = taylor_activation_wrapper(*get_activation_with_derivatives("swish"))
def batched_forward_jac(x):
"""批量前向函数"""
val_init = x
first_init = torch.zeros(( x.shape[0], 2, 2))
first_init[:,0,0] = 1.0
first_init[:,1,1] = 1.0
x_tvar = TaylorVar(val_init, first_init)
y_tvar = x_tvar.linear(torch.tensor([[2.0, 1.0], [1.0, 3.0]]),
torch.tensor([0.5, -1.0]))
z_tvar = activation_fn(y_tvar)
return z_tvar.first[...]
def forward_fn_jac(x_single):
"""单样本前向函数"""
val_init = x_single
first_init = torch.zeros((2, 2))
first_init[0,0] = 1.0
first_init[1,1] = 1.0
x_tvar = TaylorVar(val_init, first_init)
y_tvar = x_tvar.linear(torch.tensor([[2.0, 1.0], [1.0, 3.0]]),
torch.tensor([0.5, -1.0]))
z_tvar = activation_fn(y_tvar)
return z_tvar.first[...]
vm_jac = vmap(forward_fn_jac)(x)
print("vmap 内自动微分输出形状:", vm_jac.shape)
print("TaylorVar first 形状:", batched_forward_jac(x).shape)
# 3. 测试组合使用
print("\n=== 测试组合使用 ===")
def combined_fn(x_single):
"""结合 TaylorVar 和 jacrev"""
x_tvar = TaylorVar(x_single.unsqueeze(0))
y_tvar = x_tvar.linear(torch.tensor([[2.0, 1.0], [1.0, 3.0]]))
return y_tvar.val.squeeze(0)
# 先 vmap 再 jacrev
batched_jac = vmap(jacrev(combined_fn))(x)
print("Batched Jacobian 形状:", batched_jac.shape)
# 4. 测试与激活函数的兼容性
print("\n=== 测试与激活函数的兼容性 ===")
def activation_fn(x_single):
x_tvar = TaylorVar(x_single.unsqueeze(0))
fn, fn_prime, fn_double_prime, fn_triple_prime = get_activation_with_derivatives('swish')
y_tvar = x_tvar.elementwise_fn(fn, fn_prime, fn_double_prime, fn_triple_prime)
return y_tvar.val.squeeze(0)
# 计算批量 Jacobian
batched_act_jac = vmap(jacrev(activation_fn))(x)
print("Batched Activation Jacobian 形状:", batched_act_jac.shape)
# 5. 对比结果
print("\n=== 结果对比 ===")
def standard_fn(x):
"""标准 PyTorch 函数用于对比"""
y = x @ torch.tensor([[2.0, 1.0], [1.0, 3.0]]).T
return y * y
standard_jac = vmap(jacrev(standard_fn))(x)
first_init = torch.zeros(( x.shape[0], 2, 2))
first_init[:,0,0] = 1.0
first_init[:,1,1] = 1.0
taylor_x = TaylorVar(x, first_init)
y = taylor_x.linear(torch.tensor([[2.0, 1.0], [1.0, 3.0]]))
y= y*y
taylor_jac = y.first[...]
print("标准 Jacobian 与 TaylorVar 结果的最大差异:",
torch.abs(standard_jac - taylor_jac).max().item())
def test_modified_fourier_net():
"""
计算流程:
1. 输入变换: x -> (x-shift_t)*scale
2. 特征扩充: x -> [x, sin(xB1), cos(xB2)]
3. 双分支计算:
- U = act(linear1(x))
- V = act(linear2(x))
4. 中间层循环:
for linear in linears:
out = sigmoid(linear(x))
x = out*U + (1-out)*V
5. 最后两层:
x = act(linear3(x))
x = head(x)
6. 重塑输出: x -> x.reshape(..., 2, -1)
"""
import torch
from torch.func import vmap, jacrev
import time
# 构造测试数据
batch_size = 1000
in_dim = 3
h_dim = 50
out_dim = 2
num_freq = 5
dtype = torch.float64
x = torch.randn(batch_size, in_dim, dtype=dtype, requires_grad=True)
# 构造网络参数
B1 = torch.randn(num_freq, in_dim, dtype=dtype)
B2 = torch.randn(num_freq, in_dim, dtype=dtype)
t0 = torch.tensor(0.0, dtype=dtype)
scale = torch.tensor([1.0, 1.0, 2.0], dtype=dtype)
shift_t = torch.tensor([0.0, 0.0, t0], dtype=dtype)
# 构造线性层参数
aug_dim = in_dim + 2*num_freq
W1 = torch.randn(h_dim, aug_dim, dtype=dtype)
b1 = torch.randn(h_dim, dtype=dtype)
W2 = torch.randn(h_dim, aug_dim, dtype=dtype)
b2 = torch.randn(h_dim, dtype=dtype)
W3 = torch.randn(h_dim, h_dim, dtype=dtype)
b3 = torch.randn(h_dim, dtype=dtype)
W4 = torch.randn(h_dim, h_dim, dtype=dtype)
b4 = torch.randn(h_dim, dtype=dtype)
W5 = torch.randn(h_dim, h_dim, dtype=dtype)
b5 = torch.randn(h_dim, dtype=dtype)
Wh = torch.randn(out_dim, h_dim, dtype=dtype)
# 1. PyTorch autograd 版本
def forward_fn(x_in):
# 输入变换
x = (x_in - shift_t) * scale
# 特征扩充
x_aug = torch.cat([x,
torch.sin(x @ B1.T),
torch.cos(x @ B2.T)], dim=-1)
# # 双分支
U = torch.tanh(x_aug @ W1.T + b1)
V = torch.tanh(x_aug @ W2.T + b2)
# return U
# # 中间层
out = torch.sigmoid(x_aug @ W1.T + b1)
x = out * U + (1-out) * V
# return (1-out)*V
# # 最后两层
x = torch.tanh(x @ W3.T + b3)
x = x @ Wh.T
return x
# 2. TaylorVar 版本
def taylor_forward(x_batch):
# 构造输入 TaylorVar
first_init = torch.zeros(x_batch.shape + (in_dim,))
for i in range(in_dim):
first_init[...,i,i] = 1.0
x_tvar = TaylorVar(x_batch, first_init)
# 输入变换
# breakpoint()
# x_tvar1 = (x_tvar - shift_t)
x_tvar = (x_tvar - shift_t) * scale
# x_tvar.third[0,1,2]
# 特征扩充
sin_B1 = taylor_activation_wrapper(*get_activation_with_derivatives('sin'))
cos_B2 = taylor_activation_wrapper(*get_activation_with_derivatives('cos'))
x_B1 = x_tvar.linear(B1)
x_B2 = x_tvar.linear(B2)
sin_x_B1 = sin_B1(x_B1)
cos_x_B2 = cos_B2(x_B2)
x_aug = TaylorVar.cat([x_tvar, sin_x_B1, cos_x_B2], dim=-1)
# # 双分支
tanh = taylor_activation_wrapper(*get_activation_with_derivatives('tanh'))
sigmoid = taylor_activation_wrapper(*get_activation_with_derivatives('sigmoid'))
U = tanh(x_aug.linear(W1, b1))
V = tanh(x_aug.linear(W2, b2))
# # 中间层
out = sigmoid(x_aug.linear(W1, b1))
x = out * U + (1-out) * V
# 最后两层
x = tanh(x.linear(W3, b3))
x = x.linear(Wh)
return x
# 计算并比较结果
print("\n=== 测试 modified_fourier_net ===")
print(f"batch_size: {batch_size}, in_dim: {in_dim}, h_dim: {h_dim}, out_dim: {out_dim}, num_freq: {num_freq}")
# # 1. 前向传播对比
# y_autograd = forward_fn(x)
# y_taylor = taylor_forward(x)
# print("\n前向传播最大差异:",
# torch.abs(y_autograd - y_taylor.val).max().item())
# 2. Jacobian 对比
time_start = time.time()
for i in range(50):
jac_taylor = taylor_forward(x).first[...]
time_end = time.time()
print(f"Jacobian taylor 计算时间: {(time_end - time_start)/50} 秒")
time_start = time.time()
for i in range(50):
jac_autograd = vmap(jacrev(forward_fn))(x)
time_end = time.time()
print(f"Jacobian autograd 计算时间: {(time_end - time_start)/50} 秒")
print("\nJacobian 最大差异:",
torch.abs(jac_autograd - jac_taylor).max().item())
# 索引后导数对比
out = taylor_forward(x)
y = out[:,0]+out[:,1]
print(y.shape)
# print(y.third[0,1,1:2])
temp = out.third[0,1,1:2]
# print(temp[:,0]+temp[:,1])
# 3. Hessian 对比
time_start = time.time()
for i in range(50):
hess_autograd = vmap(jacrev(jacrev(forward_fn)))(x)
time_end = time.time()
print(f"Hessian autograd 计算时间: {(time_end - time_start)/50} 秒")
time_start = time.time()
for i in range(50):
hess_taylor = taylor_forward(x).second[...]
time_end = time.time()
print(f"Hessian taylor 计算时间: {(time_end - time_start)/50} 秒")
print("Hessian 最大差异:",
torch.abs(hess_autograd - hess_taylor).max().item())
# 4. 三阶导数对比
time_start = time.time()
for i in range(50):
third_autograd = vmap(jacrev(jacrev(jacrev(forward_fn))))(x)
time_end = time.time()
print(f"三阶导数 autograd 计算时间: {(time_end - time_start)/50} 秒")
time_start = time.time()
for i in range(50):
third_taylor = taylor_forward(x).third[...]
time_end = time.time()
print(f"全量三阶导数 taylor 计算时间: {(time_end - time_start)/50} 秒")
time_start = time.time()
third_taylor_012 = taylor_forward(x).third[0,1,2]
time_end = time.time()
print(f" third[0,1,2] 局部计算 taylor 计算时间: {time_end - time_start} 秒")
print("third[0,1,2] 局部计算和全量计算最大差异:",
torch.abs(third_taylor[..., 0,1,2] - third_taylor_012).max().item())
second_taylor_12 = taylor_forward(x).second[1,2]
print("second[1,2] 局部计算和全量计算最大差异:",
torch.abs(second_taylor_12 - hess_taylor[..., 1,2]).max().item())
first_taylor_0 = taylor_forward(x).first[0]
print("first[3] 局部计算和全量计算最大差异:",
torch.abs(first_taylor_0 - jac_taylor[..., 0]).max().item())
# breakpoint()
print("\n三阶导数最大差异:",
torch.abs(third_autograd - third_taylor).max().item())
# # # 5. vmap 内计算taylor 测试
# def single_forward(x_single):
# return taylor_forward(x_single).val
# def single_forward_jac(x_single):
# return taylor_forward(x_single).first
# def single_forward_hess(x_single):
# return taylor_forward(x_single).second
# def single_forward_third(x_single):
# return taylor_forward(x_single).third
# y_vmap = vmap(single_forward)(x)
# y_vmap_jac = vmap(single_forward_jac)(x)
# y_vmap_hess = vmap(single_forward_hess)(x)
# y_vmap_third = vmap(single_forward_third)(x)
# print("\nvmap 批处理最大差异:",
# torch.abs(y_vmap - y_taylor.val).max().item())
# print("\nvmap 批处理 Jacobian 最大差异:",
# torch.abs(y_vmap_jac - y_taylor.first).max().item())
# print("\nvmap 批处理 Hessian 最大差异:",
# torch.abs(y_vmap_hess - y_taylor.second).max().item())
# print("\nvmap 批处理 三阶导数 最大差异:",
# torch.abs(y_vmap_third - y_taylor.third).max().item())
def test_derivative_tensor():
"""
测试 DerivativeTensor 的基本功能:
1. 初始化和存储
2. 全量计算 ([...] 或 [:,:,:])
3. 单个导数分量访问 ([i,j,k])
4. 导数分量块访问 ([i1:i2, j1:j2, k1:k2])
5. 验证计算结果缓存
"""
# 构造测试数据
batch_size, d = 2, 3
x = torch.randn(batch_size, 2) # (batch_size, feature_dim)
# 模拟计算函数
compute_count = 0
def mock_compute(order, parent, idx=None):
nonlocal compute_count
compute_count += 1
if idx is None: # 全量计算
if order == 1:
return torch.ones(batch_size, 2, d)
elif order == 2:
return torch.ones(batch_size, 2, d, d) * 2
else: # order == 3
return torch.ones(batch_size, 2, d, d, d) * 3
else: # 部分计算