test_comm_ops.py 8.07 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
17
                              tensor_model_parallel_all_gather,
                              tensor_model_parallel_all_reduce)
18

19
from ..utils import init_test_distributed_environment, multi_process_parallel
20
21


Simon Mo's avatar
Simon Mo committed
22
@ray.remote(num_gpus=1, max_calls=1)
23
24
25
26
27
28
29
def all_reduce_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
30
31
32
    # 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
33
34
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)

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


Simon Mo's avatar
Simon Mo committed
50
@ray.remote(num_gpus=1, max_calls=1)
51
52
53
54
55
56
57
def all_gather_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
58
59
60
    # 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
61
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
62
63
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
64
    init_test_distributed_environment(tp_size, pp_size, rank,
65
66
67
68
69
70
71
72
73
74
                                      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)
75
            for r in range(tp_size)
76
77
        ]
        expected = torch.cat(all_tensors, dim=all_gather_dimension)
78
        t = all_tensors[rank % tp_size]
79
        t = tensor_model_parallel_all_gather(t, all_gather_dimension)
80
        torch.testing.assert_close(t, expected)
81
82


83
@ray.remote(num_gpus=1, max_calls=1)
84
85
86
87
88
89
90
def broadcast_tensor_dict_test_worker(
    monkeypatch: pytest.MonkeyPatch,
    tp_size: int,
    pp_size: int,
    rank: int,
    distributed_init_port: str,
):
91
92
93
    # 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
94
    monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
95
96
    device = torch.device(f"cuda:{rank}")
    torch.cuda.set_device(device)
97
    init_test_distributed_environment(tp_size, pp_size, rank,
98
99
                                      distributed_init_port)
    test_dict = {
100
        # device tensor
101
        "a": torch.arange(8, dtype=torch.float32, device="cuda"),
102
103
        # CPU tensor
        "b": torch.arange(16, dtype=torch.int8, device="cpu"),
104
105
106
107
108
109
        "c": "test",
        "d": [1, 2, 3],
        "e": {
            "a": 1,
            "b": 2
        },
110
111
        # empty tensor
        "f": torch.tensor([], dtype=torch.float32, device="cuda"),
112
113
    }

114
    if (rank % tp_size) == 0:
115
116
117
118
        broadcast_tensor_dict(test_dict, src=0)
    else:
        recv_dict = broadcast_tensor_dict(src=0)
        assert len(recv_dict) == len(test_dict)
119
120
        torch.testing.assert_close(recv_dict["a"], test_dict["a"])
        torch.testing.assert_close(recv_dict["b"], test_dict["b"])
121
122
123
        assert recv_dict["c"] == test_dict["c"]
        assert recv_dict["d"] == test_dict["d"]
        assert recv_dict["e"] == test_dict["e"]
124
        torch.testing.assert_close(recv_dict["f"], test_dict["f"])
125
126


127
@ray.remote(num_gpus=1, max_calls=1)
128
129
130
131
132
133
134
135
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)
136
137
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
    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)
164
165
        torch.testing.assert_close(recv_dict["a"], test_dict["a"])
        torch.testing.assert_close(recv_dict["b"], test_dict["b"])
166
167
168
        assert recv_dict["c"] == test_dict["c"]
        assert recv_dict["d"] == test_dict["d"]
        assert recv_dict["e"] == test_dict["e"]
169
        torch.testing.assert_close(recv_dict["f"], test_dict["f"])
170
171
172


@ray.remote(num_gpus=1, max_calls=1)
173
174
175
176
177
178
179
180
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)
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    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:
196
        torch.testing.assert_close(test_tensor, recv_tensor)
197
198


199
200
@pytest.mark.skipif(torch.cuda.device_count() < 2,
                    reason="Need at least 2 GPUs to run the test.")
201
@pytest.mark.parametrize("tp_size", [2])
202
203
204
205
@pytest.mark.parametrize("test_target", [
    all_reduce_test_worker, all_gather_test_worker,
    broadcast_tensor_dict_test_worker
])
206
207
208
209
210
211
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)
212
213
214
215
216
217
218


@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])
219
220
221
222
223
224
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)
225
226
227
228
229
230
231
232
233
234
235
236


@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(
237
238
239
240
241
242
    tp_size: int,
    pp_size: int,
    test_target: Callable[..., Any],
    monkeypatch: pytest.MonkeyPatch,
):
    multi_process_parallel(monkeypatch, tp_size, pp_size, test_target)