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

# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring

""" Test FSDP with regnet-like model. """

12
import contextlib
13
from itertools import product
Min Xu's avatar
Min Xu committed
14
import random
15
16
17
18
import tempfile

import pytest
import torch
19
from torch.cuda.amp import GradScaler
20
import torch.multiprocessing as mp
21
22
23
24
25
26
27
28
29
30
31
32
from torch.nn import (
    AdaptiveAvgPool2d,
    BatchNorm2d,
    Conv2d,
    CrossEntropyLoss,
    Linear,
    Module,
    ReLU,
    Sequential,
    Sigmoid,
    SyncBatchNorm,
)
33
from torch.nn.parallel import DistributedDataParallel as DDP
34
35
36
from torch.optim import SGD

from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP
Min Xu's avatar
Min Xu committed
37
from fairscale.nn.data_parallel import TrainingState, auto_wrap_bn
38
from fairscale.utils import torch_version
39
40
41
42
43
44
45
from fairscale.utils.testing import (
    dist_init,
    objects_are_equal,
    rmf,
    skip_if_single_gpu,
    state_dict_norm,
    teardown,
46
    torch_cuda_version,
47
48
)

49
50
51
if torch_version() >= (1, 8, 0):
    from fairscale.optim.grad_scaler import ShardedGradScaler

52
53
54
55
56
57
# Const test params.
#   Reduce iterations to 1 for debugging.
#   Change world_size to 8 on beefy machines for better test coverage.
_world_size = 2
_iterations = 5

58
59
# Cover different ReLU flavors. Different workers may have different values since
# this is a file level global. This is intensional to cover different behaviors.
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
_relu_inplace = True
if random.randint(0, 1) == 0:
    _relu_inplace = False

# TODO (Min): test apex BN when available in the future.
try:
    import apex

    apex_bn_converter = apex.parallel.convert_syncbn_model
except ImportError:
    apex_bn_converter = None
pytorch_bn_converter = SyncBatchNorm.convert_sync_batchnorm  # type: ignore
_single_rank_pg = False


class ResBlock(Module):
    """Conv block in regnet with residual connection."""

    def __init__(self, width_in, width_out):
        super().__init__()
        self.proj = Conv2d(width_in, width_out, (1, 1), (2, 2), bias=False)
        self.bn = BatchNorm2d(width_out)
        self.f = Sequential(
            Sequential(  # block a
84
85
86
                Conv2d(width_in, width_out, (1, 1), (1, 1), bias=False),
                BatchNorm2d(width_out),
                ReLU(_relu_inplace),
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
            ),
            Sequential(  # block b
                Conv2d(width_out, width_out, (3, 3), (2, 2), (1, 1), groups=2, bias=False),
                BatchNorm2d(width_out),
                ReLU(_relu_inplace),
            ),
            Sequential(  # block se
                AdaptiveAvgPool2d((1, 1)),
                Sequential(
                    Conv2d(width_out, 2, (1, 1), (1, 1), bias=False),
                    ReLU(_relu_inplace),
                    Conv2d(2, width_out, (1, 1), (1, 1), bias=False),
                    Sigmoid(),
                ),
            ),
            Conv2d(width_out, width_out, (1, 1), (1, 1), bias=False),  # block c
            BatchNorm2d(width_out),  # final_bn
        )
        self.relu = ReLU()
        self.need_fsdp_wrap = True

    def forward(self, x):
        x = self.bn(self.proj(x)) + self.f(x)
        return self.relu(x)

112
113

class Model(Module):
114
115
    """SSL model with trunk and head."""

116
    def __init__(self, conv_bias, linear_bias):
117
        super().__init__()
118
        print(f"relu inplace: {_relu_inplace}, conv bias: {conv_bias}, linear bias: {linear_bias}")
119
120
121

        self.trunk = Sequential()
        self.trunk.need_fsdp_wrap = True  # Set a flag for later wrapping.
122
        stem = Sequential(Conv2d(2, 4, (3, 3), (2, 2), (1, 1), bias=conv_bias), BatchNorm2d(4), ReLU(_relu_inplace))
123
124
125
126
127
        any_stage_block1_0 = ResBlock(4, 8)
        self.trunk.add_module("stem", stem)
        self.trunk.add_module("any_stage_block1", Sequential(any_stage_block1_0))

        self.head = Sequential(
128
            Sequential(Linear(16, 16, bias=linear_bias), ReLU(), Linear(16, 8, bias=linear_bias)),  # projection_head
129
130
            Linear(8, 15, bias=False),  # prototypes0
        )
131
132

    def forward(self, x):
133
134
        x = self.trunk(x).reshape(-1)
        x = self.head(x)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
        return x


# We get a bit fancy here. Since the scope is `module`, this is run only
# once no matter how many tests variations for FSDP are requested to run
# to compare with the DDP reference. For example, a single DDP
# reference run is needed for both flatten and non-flatten param FSDP.
#
# Note, this runs DDP twice with and without mixed precision and asserts
# the resulting weights are different.
#
# This fixture captures and returns:
#
#   - model state_dict before training
#   - model data inputs
#   - model state_dict after training
@pytest.fixture(scope="module")
def ddp_ref():
153
154
155
156
157
158
159
160
161
    # Cover different bias flavors. Use random instead of parameterize them to reduce
    # the test runtime. Otherwise, we would have covered all cases exhaustively.
    conv_bias = True
    if random.randint(0, 1) == 0:
        conv_bias = False
    linear_bias = True
    if random.randint(0, 1) == 0:
        linear_bias = False

162
    # Get a reference model state
163
    model = Model(conv_bias, linear_bias)
164
    state_before = model.state_dict()
165

166
    # Get reference inputs per rank.
167
168
169
170
    world_size = _world_size
    iterations = _iterations
    print(f"Getting DDP reference for world_size {world_size} and iterations {iterations}")
    inputs = [[] for i in range(world_size)]
171
172
173
174
    for rank in range(world_size):
        for i in range(iterations):
            inputs[rank].append(torch.rand(2, 2, 2, 2))

175
176
177
    # Run reference DDP training 4 times, fp and mp, sync_bn or not.
    state_after = {}
    for precision, sync_bn in product(["full", "mixed"], ["none", "pytorch"]):
178
179
180
181
        temp_file_name = tempfile.mkstemp()[1]
        unused = tempfile.mkstemp()[1]
        rank_0_output = tempfile.mkstemp()[1]
        try:
Min Xu's avatar
Min Xu committed
182
            fsdp_config = None  # This means we use DDP in _distributed_worker.
183
            mp.spawn(
Min Xu's avatar
Min Xu committed
184
                _distributed_worker,
185
186
187
                args=(
                    world_size,
                    fsdp_config,
188
                    None,
189
190
191
192
193
194
195
                    precision == "mixed",
                    temp_file_name,
                    unused,
                    state_before,
                    inputs,
                    rank_0_output,
                    None,
196
197
198
                    sync_bn,
                    conv_bias,
                    linear_bias,
199
200
201
202
                ),
                nprocs=world_size,
                join=True,
            )
203
            state_after[(precision, sync_bn)] = torch.load(rank_0_output)
204
205
206
207
208
        finally:
            rmf(temp_file_name)
            rmf(unused)
            rmf(rank_0_output)

209
210
211
212
    # Sanity check DDP's final states.
    states = list(state_after.values())
    for state in states[1:]:
        assert state_dict_norm(states[0]) != state_dict_norm(state)
213

214
    return state_before, inputs, conv_bias, linear_bias, state_after
215
216
217
218
219
220
221


# A fixture to get tempfiles and ensure they are cleaned up.
@pytest.fixture()
def temp_files():
    temp_file_name = tempfile.mkstemp()[1]
    unused = tempfile.mkstemp()[1]
222

223
224
225
226
227
228
229
    yield temp_file_name, unused

    # temp files could have been removed, so we use rmf.
    rmf(temp_file_name)
    rmf(unused)


Min Xu's avatar
Min Xu committed
230
def _distributed_worker(
231
232
233
    rank,
    world_size,
    fsdp_config,
234
    fsdp_wrap_bn,
235
236
237
238
239
240
241
    ddp_mixed_precision,
    tempfile_name,
    unused,
    state_before,
    inputs,
    rank_0_output,
    state_after,
242
243
244
    sync_bn,
    conv_bias,
    linear_bias,
245
):
Min Xu's avatar
Min Xu committed
246
247
    torch.backends.cudnn.deterministic = True

248
249
250
    result = dist_init(rank, world_size, tempfile_name, unused)
    assert result, "Dist init failed"

251
252
253
254
    ddp = True
    if fsdp_config:
        ddp = False
        assert isinstance(fsdp_config, dict), str(fsdp_config)
255
256
257
        if fsdp_config["mixed_precision"]:
            # To match DDP in AMP -O1, we need fp32 reduce scatter.
            fsdp_config["fp32_reduce_scatter"] = True
258

259
    model = Model(conv_bias, linear_bias)
260
261
262
    model.load_state_dict(state_before)
    model = model.cuda()

263
264
265
266
267
268
269
270
271
272
273
    class DummyScaler:
        def scale(self, loss):
            return loss

        def step(self, optim):
            optim.step()

        def update(self):
            pass

    scaler = DummyScaler()
274
    if ddp:
275
276
        if sync_bn == "pytorch":
            model = pytorch_bn_converter(model)
277
278
279
        model = DDP(model, device_ids=[rank], broadcast_buffers=True)
        if ddp_mixed_precision:
            scaler = GradScaler()
Min Xu's avatar
Min Xu committed
280
    else:
281
282
283
        # Note, different rank may wrap in different order due to different random
        # seeds. But results should be the same.
        if random.randint(0, 1) == 0:
284
            print(f"auto_wrap_bn {fsdp_wrap_bn}, then sync_bn {sync_bn}")
285
286
            if fsdp_wrap_bn:
                model = auto_wrap_bn(model, _single_rank_pg)
287
288
            if sync_bn == "pytorch":
                model = pytorch_bn_converter(model)
289
        else:
290
291
292
            print(f"sync_bn {sync_bn}, then auto_wrap_bn {fsdp_wrap_bn}")
            if sync_bn == "pytorch":
                model = pytorch_bn_converter(model)
293
294
            if fsdp_wrap_bn:
                model = auto_wrap_bn(model, _single_rank_pg)
295
        model = FSDP(model, **fsdp_config).cuda()
296
297
298
299
300
        if fsdp_config["mixed_precision"]:
            scaler = ShardedGradScaler()
        # Print the model for verification.
        if rank == 0:
            print(model)
301
    optim = SGD(model.parameters(), lr=0.1)
302
    loss_func = CrossEntropyLoss()
303

304
305
306
307
308
309
    for in_data in inputs[rank]:
        in_data = in_data.cuda()
        context = contextlib.suppress()
        if ddp and ddp_mixed_precision:
            in_data = in_data.half()
            context = torch.cuda.amp.autocast(enabled=True)
310
311
        if not ddp and fsdp_config["mixed_precision"]:
            context = torch.cuda.amp.autocast(enabled=True)
312
313
        with context:
            out = model(in_data)
314
315
316
317
318
            fake_label = torch.zeros(1, dtype=torch.long).cuda()
            loss = loss_func(out.unsqueeze(0), fake_label)
        scaler.scale(loss).backward()
        scaler.step(optim)
        scaler.update()
319
320
        optim.zero_grad()

321
322
323
324
325
326
327
328
329
330
331
332
    if ddp:
        # Save the rank 0 state_dict to the output file.
        if rank == 0:
            state_after = model.module.cpu().state_dict()
            torch.save(state_after, rank_0_output)
    else:
        model.assert_state(TrainingState.IDLE)
        # Ensure final state equals to the state_after.
        fsdp_state = model.state_dict()
        # Move tensors to CPU to compare numerics.
        for k, v in fsdp_state.items():
            fsdp_state[k] = v.cpu()
333
334
335
336
337
338
339
340
341
        # Change False to True to enable this when you want to debug the mismatch.
        if False and rank == 0:

            def dump(d):
                for k, v in d.items():
                    print(k, v)

            dump(state_after)
            dump(fsdp_state)
342
343
344
345
        # If sync_bn is used, all ranks should have the same state, so we can compare with
        # rank 0 state on every rank. Otherwise, only compare rank 0 with rank 0.
        if sync_bn != "none" or rank == 0:
            assert objects_are_equal(state_after, fsdp_state, raise_exception=True)
346

347
348
349
    teardown()


350
# We use strings for precision and flatten params instead of bool to
351
352
353
354
# make the pytest output more readable.
@skip_if_single_gpu
@pytest.mark.parametrize("precision", ["full", "mixed"])
@pytest.mark.parametrize("flatten", ["flatten", "no_flatten"])
355
356
@pytest.mark.parametrize("sync_bn", ["none", "pytorch"])
def test_regnet(temp_files, ddp_ref, precision, flatten, sync_bn):
357
358
    if torch_version() < (1, 8, 0):
        pytest.skip("pytorch version >= 1.8.0 required")
359

360
    state_before, inputs, conv_bias, linear_bias, state_after = ddp_ref
361

362
    state_after = state_after[(precision, sync_bn)]
363
364
365
366
367

    fsdp_config = {}
    fsdp_config["mixed_precision"] = precision == "mixed"
    fsdp_config["flatten_parameters"] = flatten == "flatten"

368
369
370
371
372
    # When linear bias is True, DDP's AMP O1 and FSDP's default AMP O1.5 is different,
    # we force FSDP to use AMP O1 here by setting compute_dtype to float32.
    if linear_bias:
        fsdp_config["compute_dtype"] = torch.float32

373
374
375
    if fsdp_config["mixed_precision"] and torch_cuda_version() < (11, 0):
        pytest.skip("Only CUDA 11 is supported with AMP equivalency")

376
    # Wrap BN half of the time.
377
378
379
    wrap_bn = True
    if random.randint(0, 1) == 0:
        wrap_bn = False
380
381
382
    # Except, always wrap BN in mixed precision + sync_bn mode, due to error of sync_bn wrapping,
    # regardless of compute_dtype.
    if fsdp_config["mixed_precision"] and sync_bn != "none":
383
384
        wrap_bn = True

385
386
387
388
389
390
    # When BN is not wrapped (i.e. not in full precision), FSDP's compute_dtype needs to
    # be fp32 to match DDP (otherwise, numerical errors happen on BN's running_mean/running_var
    # buffers).
    if fsdp_config["mixed_precision"] and not wrap_bn:
        fsdp_config["compute_dtype"] = torch.float32

391
    world_size = _world_size
392
    mp.spawn(
Min Xu's avatar
Min Xu committed
393
        _distributed_worker,
394
395
396
397
398
399
400
401
402
403
404
        args=(
            world_size,
            fsdp_config,
            wrap_bn,
            None,
            temp_files[0],
            temp_files[1],
            state_before,
            inputs,
            None,
            state_after,
405
406
407
            sync_bn,
            conv_bias,
            linear_bias,
408
        ),
409
410
        nprocs=world_size,
        join=True,
411
    )