-
Notifications
You must be signed in to change notification settings - Fork 0
/
timings.py
60 lines (48 loc) · 1.46 KB
/
timings.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
import torch
from torch import nn
from sillyode import sillyode
from torchdiffeq import odeint, odeint_adjoint
import time
def tictoc(s=None):
global _t1
if s is not None:
print(f'{s} : {time.time() - _t1 : .2f} s')
_t1 = time.time()
class F(nn.Module):
def __init__(self, dtype=torch.float64):
super().__init__()
self.a = nn.Parameter(torch.tensor(2.0, dtype=dtype))
self.b = nn.Parameter(torch.tensor(3.0, dtype=dtype))
def forward(self, t, y):
r = torch.empty_like(y)
r[0] = -(self.a * y[1])**3
r[1] = self.b * y[0]
return r
def run_code(backward, ode_method):
dtype = torch.double
t = torch.linspace(0, 2.5, 50, dtype=dtype)
y0 = torch.tensor([1.5, 0.5], dtype=dtype, requires_grad=True)
func = F(dtype)
if backward:
yt = ode_method(func, y0, t)
loss = torch.sum(yt ** 3)
loss.backward()
else:
with torch.no_grad():
yt = ode_method(func, y0, t)
return yt
if __name__ == '__main__':
n = 100
for t, s in [(False, 'No .backward()'), (True, 'With .backward()')]:
print(s)
tictoc()
for _ in range(n):
run_code(t, odeint)
tictoc(' torchdiffeq.odeint')
for _ in range(n):
run_code(t, odeint_adjoint)
tictoc(' torchdiffeq.odeint_adjoint')
for _ in range(n):
run_code(t, sillyode)
tictoc(' sillyode')
print()