test_comm_ops.py 9.29 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
3
"""Test the communication operators.

4
Run `pytest tests/distributed/test_comm_ops.py`.
5
"""
6
7
8
9

from __future__ import annotations

from typing import Any, Callable
10

11
import pytest
Simon Mo's avatar
Simon Mo committed
12
import ray
13
import torch
14

15
from vllm.distributed import (broadcast_tensor_dict, get_pp_group,
16
                              tensor_model_parallel_all_gather,
17
18
                              tensor_model_parallel_all_reduce,
                              tensor_model_parallel_reduce_scatter)
19

20
from ..utils import init_test_distributed_environment, multi_process_parallel
21
22


Simon Mo's avatar
Simon Mo committed
23
@ray.remote(num_gpus=1, max_calls=1)
24
25
26
27
28
29
30
def all_reduce_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
31
32
33
    # it is important to delete the CUDA_VISIBLE_DEVICES environment variable
    # so that each worker can see all the GPUs
    # they will be able to set the device to the correct GPU
34
35
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)

36
37
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
38
    init_test_distributed_environment(tp_size, pp_size, rank,
39
40
41
42
                                      distributed_init_port)
    num_elements = 8
    all_tensors = [
        torch.arange(num_elements, dtype=torch.float32, device="cuda") *
43
        (r + 1) for r in range(tp_size)
44
45
    ]
    expected = torch.sum(torch.stack(all_tensors, dim=0), dim=0)
46
    t = all_tensors[rank % tp_size]
47
    t = tensor_model_parallel_all_reduce(t)
48
    torch.testing.assert_close(t, expected)
49
50


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@ray.remote(num_gpus=1, max_calls=1)
def reduce_scatter_test_worker(monkeypatch: pytest.MonkeyPatch, tp_size: int,
                               pp_size: int, rank: int,
                               distributed_init_port: str):
    # it is important to delete the CUDA_VISIBLE_DEVICES environment variable
    # so that each worker can see all the GPUs
    # they will be able to set the device to the correct GPU
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
    init_test_distributed_environment(tp_size, pp_size, rank,
                                      distributed_init_port)

    num_elements = 8
    all_tensors = [
        torch.arange(num_elements, dtype=torch.float32, device="cuda") *
        (r + 1) for r in range(tp_size)
    ]

    index = rank % tp_size
    partition_size = num_elements // tp_size
    all_reduce = torch.sum(torch.stack(all_tensors, dim=0), dim=0)
    expected = all_reduce[index * partition_size:(index + 1) * partition_size]
    t = all_tensors[index]
    t = tensor_model_parallel_reduce_scatter(t, 0)
    torch.testing.assert_close(t, expected)


Simon Mo's avatar
Simon Mo committed
79
@ray.remote(num_gpus=1, max_calls=1)
80
81
82
83
84
85
86
def all_gather_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
87
88
89
    # it is important to delete the CUDA_VISIBLE_DEVICES environment variable
    # so that each worker can see all the GPUs
    # they will be able to set the device to the correct GPU
90
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
91
92
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
93
    init_test_distributed_environment(tp_size, pp_size, rank,
94
95
96
97
98
99
100
101
102
103
                                      distributed_init_port)
    num_dimensions = 3
    tensor_size = list(range(2, num_dimensions + 2))
    total_size = 1
    for s in tensor_size:
        total_size *= s
    for all_gather_dimension in range(num_dimensions):
        all_tensors = [
            torch.arange(total_size, dtype=torch.float32,
                         device="cuda").reshape(tensor_size) * (r + 1)
104
            for r in range(tp_size)
105
106
        ]
        expected = torch.cat(all_tensors, dim=all_gather_dimension)
107
        t = all_tensors[rank % tp_size]
108
        t = tensor_model_parallel_all_gather(t, all_gather_dimension)
109
        torch.testing.assert_close(t, expected)
110
111


112
@ray.remote(num_gpus=1, max_calls=1)
113
114
115
116
117
118
119
def broadcast_tensor_dict_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
120
121
122
    # it is important to delete the CUDA_VISIBLE_DEVICES environment variable
    # so that each worker can see all the GPUs
    # they will be able to set the device to the correct GPU
123
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
124
125
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
126
    init_test_distributed_environment(tp_size, pp_size, rank,
127
128
                                      distributed_init_port)
    test_dict = {
129
        # device tensor
130
        "a": torch.arange(8, dtype=torch.float32, device="cuda"),
131
132
        # CPU tensor
        "b": torch.arange(16, dtype=torch.int8, device="cpu"),
133
134
135
136
137
138
        "c": "test",
        "d": [1, 2, 3],
        "e": {
            "a": 1,
            "b": 2
        },
139
140
        # empty tensor
        "f": torch.tensor([], dtype=torch.float32, device="cuda"),
141
142
    }

143
    if (rank % tp_size) == 0:
144
145
146
147
        broadcast_tensor_dict(test_dict, src=0)
    else:
        recv_dict = broadcast_tensor_dict(src=0)
        assert len(recv_dict) == len(test_dict)
148
149
        torch.testing.assert_close(recv_dict["a"], test_dict["a"])
        torch.testing.assert_close(recv_dict["b"], test_dict["b"])
150
151
152
        assert recv_dict["c"] == test_dict["c"]
        assert recv_dict["d"] == test_dict["d"]
        assert recv_dict["e"] == test_dict["e"]
153
        torch.testing.assert_close(recv_dict["f"], test_dict["f"])
154
155


156
@ray.remote(num_gpus=1, max_calls=1)
157
158
159
160
161
162
163
164
def send_recv_tensor_dict_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
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
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
    init_test_distributed_environment(tp_size, pp_size, rank,
                                      distributed_init_port)

    test_dict = {
        # device tensor
        "a": torch.arange(8, dtype=torch.float32, device="cuda"),
        # CPU tensor
        "b": torch.arange(16, dtype=torch.int8, device="cpu"),
        "c": "test",
        "d": [1, 2, 3],
        "e": {
            "a": 1,
            "b": 2
        },
        # empty tensor
        "f": torch.tensor([], dtype=torch.float32, device="cuda"),
    }

    if not get_pp_group().is_first_rank:
        recv_dict = get_pp_group().recv_tensor_dict()

    if not get_pp_group().is_last_rank:
        get_pp_group().send_tensor_dict(test_dict)

    if not get_pp_group().is_first_rank:
        assert len(recv_dict) == len(test_dict)
193
194
        torch.testing.assert_close(recv_dict["a"], test_dict["a"])
        torch.testing.assert_close(recv_dict["b"], test_dict["b"])
195
196
197
        assert recv_dict["c"] == test_dict["c"]
        assert recv_dict["d"] == test_dict["d"]
        assert recv_dict["e"] == test_dict["e"]
198
        torch.testing.assert_close(recv_dict["f"], test_dict["f"])
199
200
201


@ray.remote(num_gpus=1, max_calls=1)
202
203
204
205
206
207
208
209
def send_recv_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
    init_test_distributed_environment(tp_size, pp_size, rank,
                                      distributed_init_port)

    size = 64
    test_tensor = torch.arange(64, dtype=torch.float32, device="cuda")

    if not get_pp_group().is_first_rank:
        recv_tensor = get_pp_group().recv(size, dtype=torch.float32)

    if not get_pp_group().is_last_rank:
        get_pp_group().send(test_tensor)

    if not get_pp_group().is_first_rank:
225
        torch.testing.assert_close(test_tensor, recv_tensor)
226
227


228
229
@pytest.mark.skipif(torch.cuda.device_count() < 2,
                    reason="Need at least 2 GPUs to run the test.")
230
@pytest.mark.parametrize("tp_size", [2])
231
232
233
234
@pytest.mark.parametrize("test_target", [
    all_reduce_test_worker, all_gather_test_worker,
    broadcast_tensor_dict_test_worker
])
235
236
237
238
239
240
def test_multi_process_tensor_parallel(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    test_target: Callable[..., Any],
):
    multi_process_parallel(monkeypatch, tp_size, 1, test_target)
241
242
243
244
245
246
247


@pytest.mark.skipif(torch.cuda.device_count() < 2,
                    reason="Need at least 2 GPUs to run the test.")
@pytest.mark.parametrize("pp_size", [2])
@pytest.mark.parametrize(
    "test_target", [send_recv_test_worker, send_recv_tensor_dict_test_worker])
248
249
250
251
252
253
def test_multi_process_pipeline_parallel(
    monkeypatch: pytest.MonkeyPatch,
    pp_size: int,
    test_target: Callable[..., Any],
):
    multi_process_parallel(monkeypatch, 1, pp_size, test_target)
254
255
256
257
258
259
260
261
262
263
264
265


@pytest.mark.skipif(torch.cuda.device_count() < 4,
                    reason="Need at least 4 GPUs to run the test.")
@pytest.mark.parametrize("tp_size", [2])
@pytest.mark.parametrize("pp_size", [2])
@pytest.mark.parametrize("test_target", [
    send_recv_test_worker, send_recv_tensor_dict_test_worker,
    all_reduce_test_worker, all_gather_test_worker,
    broadcast_tensor_dict_test_worker
])
def test_multi_process_tensor_parallel_pipeline_parallel(
266
267
268
269
270
271
    tp_size: int,
    pp_size: int,
    test_target: Callable[..., Any],
    monkeypatch: pytest.MonkeyPatch,
):
    multi_process_parallel(monkeypatch, tp_size, pp_size, test_target)