-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtest_ema.py
61 lines (48 loc) · 1.71 KB
/
test_ema.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
import pytest
import torch
from torch import nn
from torch._dynamo import config
import heavyball
import heavyball.utils
from benchmark.utils import get_optim
from heavyball.utils import clean, set_torch
config.cache_size_limit = 128
def get_memory():
clean()
torch.cuda.synchronize()
clean()
torch.cuda.synchronize()
return torch.cuda.memory_allocated()
@pytest.mark.parametrize("opt", heavyball.__all__)
@pytest.mark.parametrize("size,depth", [(256, 2)])
def test_foreach(opt, size, depth: int, iterations: int = 128, outer_iterations: int = 3):
set_torch()
opt = getattr(heavyball, opt)
peaks = []
losses = []
for do_ema in [True, False]:
torch.manual_seed(0x2131290)
peaks.append([])
losses.append([])
for i in range(outer_iterations):
model = nn.Sequential(*[nn.Linear(size, size) for _ in range(depth)]).cuda()
o = get_optim(opt, model.parameters(), lr=1e-3)
for _ in range(iterations):
loss = model(torch.randn((1024, size), device='cuda')).square().mean()
loss.backward()
o.step()
o.zero_grad()
if do_ema:
o.ema_update()
o.copy_emas_to_params()
o.copy_params_to_emas()
losses[-1].append(loss.detach())
if do_ema:
o.copy_emas_to_params()
loss = model(torch.randn((1024, size), device='cuda')).square().mean()
losses[-1].append(loss.detach())
del model, o
clean()
for i, (l0, l1) in enumerate(zip(*losses)):
print(i, l0.item(), l1.item())
assert l0.float() <= l1.float()