test_fsdp_regnet.py 6.73 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
Min Xu's avatar
Min Xu committed
13
import random
14
15
16
17
18
19
import tempfile

import pytest
import torch
import torch.multiprocessing as mp
from torch.nn import BatchNorm2d, Conv2d, Module, SyncBatchNorm
20
from torch.nn.parallel import DistributedDataParallel as DDP
21
22
23
from torch.optim import SGD

from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP
Min Xu's avatar
Min Xu committed
24
from fairscale.nn.data_parallel import TrainingState, auto_wrap_bn
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
from fairscale.utils.testing import (
    dist_init,
    objects_are_equal,
    rmf,
    skip_if_single_gpu,
    state_dict_norm,
    teardown,
    torch_version,
)


class Model(Module):
    def __init__(self):
        super().__init__()
        # TODO (Min): for now, we just test pytorch sync_bn here.
        #             this will grow into regnet; testing apex sync_bn, etc.
        self.conv = Conv2d(2, 2, (1, 1))
        self.bn = BatchNorm2d(2)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        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():
    # Get a reference model state
    model = Model()
    state_before = model.state_dict()
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
    # Get reference inputs per rank.
    world_size = 2
    iterations = 100
    inputs = [[]] * world_size
    for rank in range(world_size):
        for i in range(iterations):
            inputs[rank].append(torch.rand(2, 2, 2, 2))

    # Run DDP training twice, fp and mp.
    for precision in ["full", "mixed"]:
        temp_file_name = tempfile.mkstemp()[1]
        unused = tempfile.mkstemp()[1]
        rank_0_output = tempfile.mkstemp()[1]
        try:
            fsdp_config = None  # This means we use DDP in _test_func.
            mp.spawn(
                _test_func,
                args=(
                    world_size,
                    fsdp_config,
                    precision == "mixed",
                    temp_file_name,
                    unused,
                    state_before,
                    inputs,
                    rank_0_output,
                    None,
                ),
                nprocs=world_size,
                join=True,
            )
            if precision == "full":
                state_after_fp = torch.load(rank_0_output)
            else:
                state_after_mp = torch.load(rank_0_output)
        finally:
            rmf(temp_file_name)
            rmf(unused)
            rmf(rank_0_output)

    assert state_dict_norm(state_after_fp) != state_dict_norm(state_after_mp)

    return state_before, inputs, state_after_fp, state_after_mp


# 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]
119

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    yield temp_file_name, unused

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


def _test_func(
    rank,
    world_size,
    fsdp_config,
    ddp_mixed_precision,
    tempfile_name,
    unused,
    state_before,
    inputs,
    rank_0_output,
    state_after,
):
139
140
141
    result = dist_init(rank, world_size, tempfile_name, unused)
    assert result, "Dist init failed"

142
143
144
145
    ddp = True
    if fsdp_config:
        ddp = False
        assert isinstance(fsdp_config, dict), str(fsdp_config)
146
147

    model = Model()
148
149
150
151
    model.load_state_dict(state_before)
    model = model.cuda()

    if ddp:
Min Xu's avatar
Min Xu committed
152
        model = SyncBatchNorm.convert_sync_batchnorm(model)
153
        model = DDP(model, device_ids=[rank])
Min Xu's avatar
Min Xu committed
154
    else:
155
156
157
158
159
160
161
162
163
164
165
        # 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:
            print("auto_wrap_bn, then convert_sync_batchnorm")
            model = auto_wrap_bn(model)
            model = SyncBatchNorm.convert_sync_batchnorm(model)
        else:
            print("convert_sync_batchnorm, then auto_wrap_bn")
            model = SyncBatchNorm.convert_sync_batchnorm(model)
            model = auto_wrap_bn(model)
        model = FSDP(model, **fsdp_config).cuda()
166
167
    optim = SGD(model.parameters(), lr=0.1)

168
169
170
171
172
173
174
175
176
177
    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)
        with context:
            out = model(in_data)
            loss = out.sum()
        loss.backward()
178
179
180
        optim.step()
        optim.zero_grad()

181
182
183
184
185
186
187
188
189
190
191
192
193
194
    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()
        assert objects_are_equal(state_after, fsdp_state, raise_exception=True)

195
196
197
    teardown()


198
# We use strings for precision and flatten params instead of bool to
199
200
201
202
# make the pytest output more readable.
@skip_if_single_gpu
@pytest.mark.parametrize("precision", ["full", "mixed"])
@pytest.mark.parametrize("flatten", ["flatten", "no_flatten"])
203
def test1(temp_files, ddp_ref, precision, flatten):
204
205
206
    if torch_version() < (1, 6, 0):
        pytest.skip("older pytorch doesn't support reduce_scatter")

207
208
209
210
211
212
    state_before, inputs, state_after_fp, state_after_mp = ddp_ref

    if precision == "full":
        state_after = state_after_fp
    else:
        state_after = state_after_mp
213
214
215
216
217
218
219

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

    world_size = 2
    mp.spawn(
220
221
222
223
        _test_func,
        args=(world_size, fsdp_config, None, temp_files[0], temp_files[1], state_before, inputs, None, state_after),
        nprocs=world_size,
        join=True,
224
    )