test_sync_batchnorm.py 6.63 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.

import functools
import tempfile

import pytest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
13
import torch.nn as nn
14
15
16
from torch.nn.parallel import DistributedDataParallel as DDP

from fairscale.experimental.nn import SyncBatchNorm
17
from fairscale.nn.checkpoint import checkpoint_wrapper
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="cuda required")


def pg_worker(rank, world_size, init_file, func, *args):
    dist.init_process_group(dist.Backend.NCCL, init_method="file://" + init_file, rank=rank, world_size=world_size)
    func(*args)
    dist.destroy_process_group()


def pg_test(world_size=torch.cuda.device_count()):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            mp.spawn(pg_worker, args=(world_size, tempfile.mkstemp()[1], func, *kwargs.values()), nprocs=world_size)

        globals()["test_" + func.__name__] = wrapper
        return func

    return decorator


def check_parity(torch_bn, fs_bn, x):
41
42
43
44
    yh = torch.randn_like(x)
    torch_x = x.detach()
    torch_x.requires_grad = True
    torch_y = torch_bn(torch_x)
45
    torch_y.backward(yh)
46
47
48
    fs_x = x.detach()
    fs_x.requires_grad = True
    fs_y = fs_bn(fs_x)
49
    fs_y.backward(yh)
50
51
52
53
54
55
56
57
    torch.testing.assert_allclose(torch_y, fs_y)
    torch.testing.assert_allclose(torch_bn.running_mean, fs_bn.running_mean)
    torch.testing.assert_allclose(torch_bn.running_var, fs_bn.running_var)
    torch.testing.assert_allclose(torch_bn.weight, fs_bn.weight)
    torch.testing.assert_allclose(torch_bn.bias, fs_bn.bias)
    torch.testing.assert_allclose(torch_bn.weight.grad, fs_bn.weight.grad)
    torch.testing.assert_allclose(torch_bn.bias.grad, fs_bn.bias.grad)
    torch.testing.assert_allclose(torch_x.grad, fs_x.grad)
58
59
60


def check_parity_ddp(torch_bn, fs_bn, x):
61
    yh = torch.randn_like(x)
62
63
64
    rank = dist.get_rank()
    torch_ddp = DDP(torch_bn, device_ids=[rank])
    torch_bn = torch_ddp.module
65
66
67
    torch_x = x.detach()
    torch_x.requires_grad = True
    torch_y = torch_ddp(torch_x)
68
    torch_y.backward(yh)
69
70
71
72
73
    fs_ddp = DDP(fs_bn, device_ids=[rank])
    fs_bn = fs_ddp.module
    fs_x = x.detach()
    fs_x.requires_grad = True
    fs_y = fs_ddp(fs_x)
74
    fs_y.backward(yh)
75
    torch.testing.assert_allclose(torch_y, fs_y)
76
77
78
79
    torch.testing.assert_allclose(torch_x.grad, fs_x.grad)
    if isinstance(torch_bn, nn.Sequential):
        torch_bn = torch_bn[0]
        fs_bn = fs_bn[0]
80
81
82
83
84
85
    torch.testing.assert_allclose(torch_bn.running_mean, fs_bn.running_mean)
    torch.testing.assert_allclose(torch_bn.running_var, fs_bn.running_var)
    torch.testing.assert_allclose(torch_bn.weight, fs_bn.weight)
    torch.testing.assert_allclose(torch_bn.bias, fs_bn.bias)
    torch.testing.assert_allclose(torch_bn.weight.grad, fs_bn.weight.grad)
    torch.testing.assert_allclose(torch_bn.bias.grad, fs_bn.bias.grad)
86
87
88
89
90
91
92
93
94
95
96
97
98
99


@pg_test(world_size=1)
def parity3d_bn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4, 4, 4).cuda()
    torch_bn = torch.nn.BatchNorm3d(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
    check_parity(torch_bn, fs_bn, x)


100
101
102
103
104
105
@pytest.mark.skip("broken at head")
def test_parity3d_checkpoint_syncbn():
    assert 1 == 2


# @pg_test()
106
107
108
109
110
111
112
113
def parity3d_checkpoint_syncbn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4, 4, 4).cuda() * rank
    torch_bn = torch.nn.SyncBatchNorm(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
114
    fs_bn = checkpoint_wrapper(fs_bn)
115
116
117
    check_parity_ddp(torch_bn, fs_bn, x)


118
119
120
121
122
123
@pytest.mark.skip("broken at head")
def test_parity3d_checkpoint_syncbn_twice():
    assert 1 == 2


# @pg_test()
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def parity3d_checkpoint_syncbn_twice():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4, 4, 4).cuda() * rank
    torch_bn = torch.nn.SyncBatchNorm(3)
    torch_bn = nn.Sequential(torch_bn, torch_bn).cuda()
    fs_bn = SyncBatchNorm(3)
    fs_bn = nn.Sequential(fs_bn, fs_bn).cuda()
    fs_bn = checkpoint_wrapper(fs_bn)
    check_parity_ddp(torch_bn, fs_bn, x)


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
@pg_test()
def parity3d_syncbn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4, 4, 4).cuda() * rank
    torch_bn = torch.nn.SyncBatchNorm(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
    check_parity_ddp(torch_bn, fs_bn, x)


@pg_test(world_size=1)
def parity2d_bn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4, 4).cuda()
    torch_bn = torch.nn.BatchNorm2d(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
    check_parity(torch_bn, fs_bn, x)


@pg_test()
def parity2d_syncbn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4, 4).cuda() * rank
    torch_bn = torch.nn.SyncBatchNorm(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
    check_parity_ddp(torch_bn, fs_bn, x)


@pg_test(world_size=1)
def parity1d_bn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4).cuda()
    torch_bn = torch.nn.BatchNorm1d(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
    check_parity(torch_bn, fs_bn, x)


@pg_test()
def parity1d_syncbn():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)
    torch.manual_seed(rank)

    x = torch.randn(4, 3, 4).cuda()
    torch_bn = torch.nn.SyncBatchNorm(3).cuda()
    fs_bn = SyncBatchNorm(3).cuda()
    check_parity_ddp(torch_bn, fs_bn, x)
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


@pg_test()
def memory_allocated():
    rank = dist.get_rank()
    torch.cuda.set_device(rank)

    x = torch.randn(50, 2048, 7, 7).to(rank)
    torch_bn = torch.nn.SyncBatchNorm(2048).cuda()
    torch_bn = DDP(torch_bn, device_ids=[rank])
    fs_bn = SyncBatchNorm(2048).cuda()
    fs_bn = DDP(fs_bn, device_ids=[rank])
    torch_x = x.detach()
    torch_x.requires_grad = True
    fs_x = x.detach()
    fs_x.requires_grad = True
    torch.cuda.empty_cache()
    mem_at_start = torch.cuda.memory_stats()["allocated_bytes.all.current"]
    torch_y = torch_bn(torch_x)
    torch.cuda.empty_cache()
    mem_after_torch = torch.cuda.memory_stats()["allocated_bytes.all.current"]
    fs_y = fs_bn(fs_x)
    torch.cuda.empty_cache()
    mem_final = torch.cuda.memory_stats()["allocated_bytes.all.current"]
    torch_used = mem_after_torch - mem_at_start
    fs_used = mem_final - mem_after_torch
    assert fs_used < (torch_used * 1.01), f"{fs_used} < {torch_used * 1.01}"