test_fused_dense_parallel.py 8.48 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
# Run test with:
# torchrun --no_python --nproc_per_node=8 pytest -q -s tests/ops/test_fused_dense_parallel.py

import math

import torch
import torch.nn.functional as F
import pytest

from apex.transformer import parallel_state
from apex.transformer import tensor_parallel

13
14
from flash_attn.ops.fused_dense import FusedDense, FusedMLP
from flash_attn.ops.fused_dense import ColumnParallelLinear, ParallelFusedMLP
15
16
17
18
19
20
21

is_sm8x = torch.cuda.get_device_capability('cuda')[0] >= 8


@pytest.mark.parametrize('dtype', [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
# @pytest.mark.parametrize('dtype', [torch.bfloat16])
@pytest.mark.parametrize('world_size', [1, 2, 4, 8])
22
23
24
# @pytest.mark.parametrize('world_size', [2])
@pytest.mark.parametrize('sequence_parallel', [True, False])
# @pytest.mark.parametrize('sequence_parallel', [False])
25
@pytest.mark.parametrize('has_bias', [True, False])
26
27
28
29
30
# @pytest.mark.parametrize('has_bias', [False])
@pytest.mark.parametrize('out_features', [1024])
@pytest.mark.parametrize('in_features', [4096])
def test_fused_linear_bias(in_features, out_features, has_bias, sequence_parallel,
                           world_size, dtype):
31
32
33
34
35
36
37
38
39
40
    assert out_features % world_size == 0
    rtol, atol = (3e-3, 3e-2) if dtype == torch.bfloat16 else (3e-3, 3e-3)
    if not torch.distributed.is_initialized():
        torch.distributed.init_process_group(backend='nccl', init_method='env://')
    device = f'cuda:{torch.distributed.get_rank()}'
    assert world_size <= torch.distributed.get_world_size()
    parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
    rank = parallel_state.get_tensor_model_parallel_rank()
    # set seed
    torch.random.manual_seed(0)
41
    batch_size = 2
42
43
44
45
    seqlen = 512
    assert batch_size * seqlen % world_size == 0
    x_pt = torch.randn(batch_size * seqlen, in_features, device=device, dtype=dtype,
                       requires_grad=True)
46
47
48
49
    if sequence_parallel:
        x = tensor_parallel.scatter_to_sequence_parallel_region(x_pt).detach().clone().requires_grad_()
    else:
        x = x_pt.detach().clone().requires_grad_()
50
51
52
53
54

    model_pt = torch.nn.Linear(in_features, out_features, bias=has_bias, device=device, dtype=dtype)
    partition_out_features = out_features // world_size
    model = ColumnParallelLinear(in_features, out_features,
                                 parallel_state.get_tensor_model_parallel_group(), bias=has_bias,
55
                                 sequence_parallel=sequence_parallel, device=device, dtype=dtype)
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    with torch.no_grad():
        model.weight.copy_(
            model_pt.weight[rank * partition_out_features:(rank + 1) * partition_out_features]
        )
        if has_bias:
            model.bias.copy_(
                model_pt.bias[rank * partition_out_features:(rank + 1) * partition_out_features]
            )

    out = model(x)
    out_pt = model_pt(x_pt)
    assert torch.allclose(
        out, out_pt[:, rank * partition_out_features:(rank + 1) * partition_out_features],
        rtol=rtol, atol=atol
    )

    # If we don't divide by batch_size, the gradient gets a bit too large.
    g = torch.randn_like(out_pt) / 32
    out_pt.backward(g)
    out.backward(g[:, rank * partition_out_features:(rank + 1) * partition_out_features])
    parallel_state.destroy_model_parallel()

    partition_batch_dim = batch_size * seqlen // world_size
    assert torch.allclose(
80
81
82
        x.grad,
        x_pt.grad[rank * partition_batch_dim:(rank + 1) * partition_batch_dim]
        if sequence_parallel else x_pt.grad,
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        rtol=rtol, atol=atol
    )
    # The error for d_weight and d_bias is quite a bit higher
    assert torch.allclose(
        model.weight.grad,
        model_pt.weight.grad[rank * partition_out_features:(rank + 1) * partition_out_features],
        rtol=rtol, atol=atol * 10
    )
    if has_bias:
        assert torch.allclose(
            model.bias.grad,
            model_pt.bias.grad[rank * partition_out_features:(rank + 1) * partition_out_features],
            rtol=rtol, atol=atol * 5
        )


@pytest.mark.parametrize('dtype', [torch.float16] + ([torch.bfloat16] if is_sm8x else []))
# @pytest.mark.parametrize('dtype', [torch.bfloat16])
@pytest.mark.parametrize('world_size', [1, 2, 4, 8])
# @pytest.mark.parametrize('world_size', [2])
103
104
@pytest.mark.parametrize('sequence_parallel', [True, False])
# @pytest.mark.parametrize('sequence_parallel', [False])
105
106
@pytest.mark.parametrize('has_bias2', [True, False])
# @pytest.mark.parametrize('has_bias2', [True])
107
108
@pytest.mark.parametrize('out_features', [4096])
@pytest.mark.parametrize('in_features', [1024])
109
def test_fused_mlp(in_features, out_features, has_bias2, sequence_parallel, world_size, dtype):
110
111
112
113
114
115
116
117
118
119
    assert out_features % world_size == 0
    rtol, atol = (3e-3, 3e-2) if dtype == torch.bfloat16 else (3e-3, 3e-3)
    if not torch.distributed.is_initialized():
        torch.distributed.init_process_group(backend='nccl', init_method='env://')
    device = f'cuda:{torch.distributed.get_rank()}'
    assert world_size <= torch.distributed.get_world_size()
    parallel_state.initialize_model_parallel(tensor_model_parallel_size_=world_size)
    rank = parallel_state.get_tensor_model_parallel_rank()
    # set seed
    torch.random.manual_seed(0)
120
    batch_size = 2
121
122
123
124
125
126
127
128
    seqlen = 512
    assert batch_size * seqlen % world_size == 0
    x_pt = torch.randn(batch_size * seqlen, in_features, device=device, dtype=dtype,
                       requires_grad=True)
    # We need to generate g here so that all processes get the same gradient,
    # as rank 0 will have an extra bias that changes the RNG.
    # If we don't divide by batch_size, the gradient gets a bit too large.
    g = torch.randn_like(x_pt) / 32
129
130
131
132
    if sequence_parallel:
        x = tensor_parallel.scatter_to_sequence_parallel_region(x_pt).detach().clone().requires_grad_()
    else:
        x = x_pt.detach().clone().requires_grad_()
133
134
135
136
137
138

    model_pt_fc1 = torch.nn.Linear(in_features, out_features, device=device, dtype=dtype)
    model_pt_fc2 = torch.nn.Linear(out_features, in_features, bias=has_bias2, device=device,
                                   dtype=dtype)
    partition_out_features = out_features // world_size
    partition_in_features = in_features // world_size
139
140
141
142
143
    model = ParallelFusedMLP(in_features, out_features, in_features,
                             process_group=parallel_state.get_tensor_model_parallel_group(),
                             bias2=has_bias2 and rank == 0,
                             sequence_parallel=sequence_parallel,
                             device=device, dtype=dtype)
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

    with torch.no_grad():
        model.fc1.weight.copy_(
            model_pt_fc1.weight[rank * partition_out_features:(rank + 1) * partition_out_features]
        )
        model.fc1.bias.copy_(
            model_pt_fc1.bias[rank * partition_out_features:(rank + 1) * partition_out_features]
        )
        model.fc2.weight.copy_(
            model_pt_fc2.weight[:, rank * partition_out_features:(rank + 1) * partition_out_features]
        )
        if has_bias2 and rank == 0:
            model.fc2.bias.copy_(model_pt_fc2.bias)

    out = model(x)
    out_pt = model_pt_fc2(F.gelu(model_pt_fc1(x_pt), approximate='tanh'))
    partition_batch_dim = batch_size * seqlen // world_size
    assert torch.allclose(
162
163
164
        out,
        out_pt[rank * partition_batch_dim:(rank + 1) * partition_batch_dim]
        if sequence_parallel else out_pt,
165
166
167
168
        rtol=rtol, atol=atol
    )

    out_pt.backward(g)
169
170
    out.backward(g[rank * partition_batch_dim:(rank + 1) * partition_batch_dim]
                 if sequence_parallel else g)
171
172
173
    parallel_state.destroy_model_parallel()

    assert torch.allclose(
174
175
176
        x.grad,
        x_pt.grad[rank * partition_batch_dim:(rank + 1) * partition_batch_dim]
        if sequence_parallel else x_pt.grad,
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
        rtol=rtol, atol=atol
    )
    # The error for d_weight and d_bias is quite a bit higher
    assert torch.allclose(
        model.fc1.weight.grad,
        model_pt_fc1.weight.grad[rank * partition_out_features:(rank + 1) * partition_out_features],
        rtol=rtol, atol=atol * 10
    )
    assert torch.allclose(
        model.fc1.bias.grad,
        model_pt_fc1.bias.grad[rank * partition_out_features:(rank + 1) * partition_out_features],
        rtol=rtol, atol=atol * 5
    )
    assert torch.allclose(
        model.fc2.weight.grad,
        model_pt_fc2.weight.grad[:, rank * partition_out_features:(rank + 1) * partition_out_features],
        rtol=rtol, atol=atol * 10
    )
    if has_bias2 and rank == 0:
        assert torch.allclose(model.fc2.bias.grad, model_pt_fc2.bias.grad, rtol=rtol, atol=atol * 5)