test_sequence_parallelism.py 11.4 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8

import pytest
import torch

import vllm.envs as envs
from vllm.compilation.fix_functionalization import FixFunctionalizationPass
9
from vllm.compilation.fusion import RMSNormQuantFusionPass
10
from vllm.compilation.fx_utils import find_auto_fn, find_auto_fn_maybe, is_func
11
from vllm.compilation.noop_elimination import NoOpEliminationPass
12
from vllm.compilation.post_cleanup import PostCleanupPass
13
from vllm.compilation.sequence_parallelism import SequenceParallelismPass
14
from vllm.compilation.vllm_inductor_pass import VllmInductorPass
15
16
17
18
19
20
21
from vllm.config import (
    CompilationConfig,
    DeviceConfig,
    ModelConfig,
    PassConfig,
    VllmConfig,
)
22
from vllm.distributed import tensor_model_parallel_all_reduce
23
24
25
26
from vllm.distributed.parallel_state import (
    init_distributed_environment,
    initialize_model_parallel,
)
27
from vllm.model_executor.layers.layernorm import RMSNorm
28
from vllm.model_executor.layers.quantization.utils.w8a8_utils import Fp8LinearOp
29
30
31
32
33
34
from vllm.platforms import current_platform
from vllm.utils import update_environment_variables

from ..utils import multi_gpu_test
from .backend import TestBackend

35
FP8_DTYPE = current_platform.fp8_dtype()
36
37
38
39
40
41
42
43
44
prompts = [
    "Hello, my name is",
    "The president of the United States is",
    "The capital of France is",
    "The future of AI is",
]


class TestModel(torch.nn.Module):
45
46
47
    def __init__(
        self, hidden_size=16, intermediate_size=32, vllm_config: VllmConfig = None
    ):
48
49
50
51
        super().__init__()
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.gate_proj = torch.nn.Parameter(
52
53
            torch.empty((intermediate_size, hidden_size))
        )
54
        self.norm = RMSNorm(intermediate_size, 1e-05)
55
56
57
58
59
60
        # Initialize weights
        torch.nn.init.normal_(self.gate_proj, std=0.02)

    def forward(self, hidden_states, residual):
        """
        Forward pass implementing the operations in the FX graph
61

62
63
64
        Args:
            hidden_states: Input tensor
            residual: Residual tensor from previous layer
65

66
67
68
69
70
71
        Returns:
            Tuple containing the output tensor
        """
        # Reshape input
        view = hidden_states.reshape(-1, self.hidden_size)

72
        # matrix multiplication
73
74
75
76
77
78
79
80
81
82
83
        permute = self.gate_proj.permute(1, 0)
        mm = torch.mm(view, permute)

        # Tensor parallel all-reduce
        all_reduce = tensor_model_parallel_all_reduce(mm)

        # layer normalization
        norm_output, residual_output = self.norm(all_reduce, residual)

        return norm_output, residual_output

84
85
86
87
88
89
    def ops_in_model_before(self):
        return [torch.ops.vllm.all_reduce.default]

    def ops_in_model_after(self):
        return [
            torch.ops.vllm.reduce_scatter.default,
90
            torch.ops.vllm.all_gather.default,
91
92
93
94
95
        ]

    def ops_in_model(self):
        return [torch.ops._C.fused_add_rms_norm.default]

96

97
class TestQuantModel(torch.nn.Module):
98
99
100
    def __init__(
        self, hidden_size=16, intermediate_size=32, vllm_config: VllmConfig = None
    ):
101
102
103
104
        super().__init__()
        self.hidden_size = hidden_size
        self.intermediate_size = intermediate_size
        self.vllm_config = vllm_config
105
106
107
        self.gate_proj = torch.nn.Parameter(
            torch.empty((intermediate_size, hidden_size)), requires_grad=False
        )
108
109
110
111
        self.norm = RMSNorm(intermediate_size, 1e-05)
        # Initialize weights
        torch.nn.init.normal_(self.gate_proj, std=0.02)

112
        self.fp8_linear = Fp8LinearOp(act_quant_static=True)
113
114
115
116

        self.scale = torch.rand(1, dtype=torch.float32)
        # Create a weight that is compatible with torch._scaled_mm,
        # which expects a column-major layout.
117
        self.w = torch.rand(hidden_size, intermediate_size).to(dtype=FP8_DTYPE).t()
118
119
120
121
122
        self.wscale = torch.rand(1, dtype=torch.float32)

    def forward(self, hidden_states, residual):
        """
        Forward pass implementing the operations in the FX graph
123

124
125
126
        Args:
            hidden_states: Input tensor
            residual: Residual tensor from previous layer
127

128
129
130
131
132
133
        Returns:
            Tuple containing the output tensor
        """
        # Reshape input
        view = hidden_states.reshape(-1, self.hidden_size)

134
        # matrix multiplication
135
136
137
138
139
140
141
142
143
        permute = self.gate_proj.permute(1, 0)
        mm = torch.mm(view, permute)

        # Tensor parallel all-reduce
        all_reduce = tensor_model_parallel_all_reduce(mm)

        # layer normalization
        norm_output, residual_output = self.norm(all_reduce, residual)

144
        # scaled_mm with static input quantization
145
146
147
148
149
150
        fp8_linear_result = self.fp8_linear.apply(
            norm_output,
            self.w,
            self.wscale,
            input_scale=self.scale.to(norm_output.device),
        )
151
152
153
154

        return fp8_linear_result, residual_output

    def ops_in_model_before(self):
155
        ops_to_remove = [torch.ops.vllm.all_reduce.default]  # Always removed by SP
156
        # The following are only removed if fusion happens
157
158
159
160
161
162
163
164
165
166
        if (
            self.vllm_config
            and self.vllm_config.compilation_config.pass_config.enable_fusion
        ):
            ops_to_remove.extend(
                [
                    torch.ops._C.fused_add_rms_norm.default,
                    torch.ops._C.static_scaled_fp8_quant.default,
                ]
            )
167
168
169
170
171
        return ops_to_remove

    def ops_in_model_after(self):
        ops_to_add = [
            torch.ops.vllm.reduce_scatter.default,
172
            torch.ops.vllm.all_gather.default,
173
174
        ]
        # The following is only added if fusion happens
175
176
177
178
179
        if (
            self.vllm_config
            and self.vllm_config.compilation_config.pass_config.enable_fusion
        ):
            ops_to_add.append(torch.ops._C.fused_add_rms_norm_static_fp8_quant.default)
180
181
182
        return ops_to_add

    def ops_in_model(self):
183
184
185
186
        if (
            self.vllm_config
            and self.vllm_config.compilation_config.pass_config.enable_fusion
        ):
187
188
            # If fusion happens, the fused op is the one
            # we check for (de)functionalization
189
            return [torch.ops._C.fused_add_rms_norm_static_fp8_quant.default]
190
191
192
193
194
195
196
197
198
        else:
            # If no fusion, the original ops are checked
            return [
                torch.ops._C.fused_add_rms_norm.default,
                # TODO  functionalization pass does not handle this yet
                # torch.ops._C.static_scaled_fp8_quant.default,
            ]


199
@multi_gpu_test(num_gpus=2)
200
@pytest.mark.parametrize("test_model_cls", [TestModel, TestQuantModel])
201
202
203
204
@pytest.mark.parametrize("batch_size", [8])
@pytest.mark.parametrize("seq_len", [16])
@pytest.mark.parametrize("hidden_size", [16])
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
205
@pytest.mark.parametrize("enable_fusion", [True, False])
206
207
208
209
210
211
212
213
214
@pytest.mark.skipif(envs.VLLM_TARGET_DEVICE not in ["cuda"], reason="Only test on CUDA")
def test_sequence_parallelism_pass(
    test_model_cls: type[torch.nn.Module],
    batch_size: int,
    seq_len: int,
    hidden_size: int,
    dtype: torch.dtype,
    enable_fusion: bool,
):
215
216
217
218
219
    num_processes = 2

    def run_torch_spawn(fn, nprocs):
        # need to use torch.mp.spawn otherwise will have problems with
        # torch.distributed and cuda
220
221
222
223
224
225
226
227
228
229
230
231
232
        torch.multiprocessing.spawn(
            fn,
            args=(
                num_processes,
                test_model_cls,
                batch_size,
                seq_len,
                hidden_size,
                dtype,
                enable_fusion,
            ),
            nprocs=nprocs,
        )
233
234
235
236

    run_torch_spawn(sequence_parallelism_pass_on_test_model, num_processes)


237
def sequence_parallelism_pass_on_test_model(
238
239
240
241
242
243
244
245
246
    local_rank: int,
    world_size: int,
    test_model_cls: type[torch.nn.Module],
    batch_size: int,
    seq_len: int,
    hidden_size: int,
    dtype: torch.dtype,
    enable_fusion: bool,
):
247
248
249
250
251
252
253
    current_platform.seed_everything(0)

    device = torch.device(f"cuda:{local_rank}")
    torch.cuda.set_device(device)
    torch.set_default_device(device)
    torch.set_default_dtype(dtype)

254
255
256
257
258
259
260
261
262
    update_environment_variables(
        {
            "RANK": str(local_rank),
            "LOCAL_RANK": str(local_rank),
            "WORLD_SIZE": str(world_size),
            "MASTER_ADDR": "localhost",
            "MASTER_PORT": "12345",
        }
    )
263
264
265
266
267
268
269

    # initialize distributed
    init_distributed_environment()
    initialize_model_parallel(tensor_model_parallel_size=world_size)

    # configure vllm config for SequenceParallelismPass
    vllm_config = VllmConfig()
270
271
272
273
274
275
276
    vllm_config.compilation_config = CompilationConfig(
        pass_config=PassConfig(
            enable_sequence_parallelism=True,
            enable_fusion=enable_fusion,
            enable_noop=True,
        )
    )  # NoOp needed for fusion
277
278
279
280
    vllm_config.device_config = DeviceConfig(device=torch.device("cuda"))

    # this is a fake model name to construct the model config
    # in the vllm_config, it's not really used.
281
    model_name = "RedHatAI/Llama-3.2-1B-Instruct-FP8"
282
283
284
    vllm_config.model_config = ModelConfig(
        model=model_name, trust_remote_code=True, dtype=dtype, seed=42
    )
285

286
    noop_pass = NoOpEliminationPass(vllm_config)
287
    sequence_parallelism_pass = SequenceParallelismPass(vllm_config)
288
289
290
291
292
293
294
295
    assert (
        sequence_parallelism_pass.compilation_config.splitting_ops
        == vllm_config.compilation_config.splitting_ops
    )
    assert (
        sequence_parallelism_pass.compilation_config.use_inductor_graph_partition
        == vllm_config.compilation_config.use_inductor_graph_partition
    )
296
    func_pass = FixFunctionalizationPass(vllm_config)
297
    cleanup_pass = PostCleanupPass(vllm_config)
298

299
    passes_for_backend: list[VllmInductorPass] = [noop_pass, sequence_parallelism_pass]
300
301

    if enable_fusion:
302
        fusion_pass = RMSNormQuantFusionPass(vllm_config)
303
304
        passes_for_backend.append(fusion_pass)

305
306
    passes_for_backend.append(cleanup_pass)

307
308
309
    backend_no_func = TestBackend(*passes_for_backend)
    backend_func = TestBackend(*passes_for_backend, func_pass)

310
    model = test_model_cls(hidden_size, hidden_size * 2, vllm_config=vllm_config)
311

312
    hidden_states = torch.randn((batch_size * seq_len, hidden_size), dtype=dtype)
313
314
315
316
317
318
319
    residual = torch.randn((batch_size * seq_len, hidden_size), dtype=dtype)

    compiled_model_no_func = torch.compile(model, backend=backend_no_func)
    compiled_model_no_func(hidden_states, residual)
    compiled_model_func = torch.compile(model, backend=backend_func)
    compiled_model_func(hidden_states, residual)

320
321
    assert sequence_parallelism_pass.matched_count == 1

322
323
    # In pre-nodes, all reduce should be there,
    # reduce scatter and all gather should not
324
    backend_no_func.check_before_ops(model.ops_in_model_before())
325
326
327

    # In post-nodes, reduce scatter and all gather should be there,
    # all reduce should not
328
    backend_no_func.check_after_ops(model.ops_in_model_after())
329
330

    # check if the functionalization pass is applied
331
    for op in model.ops_in_model():
332
        find_auto_fn(backend_no_func.graph_post_pass.nodes, op)
333
        assert find_auto_fn_maybe(backend_func.graph_post_pass.nodes, op) is None
334
335
336
337

    # make sure the ops were all de-functionalized
    found = dict()
    for node in backend_func.graph_post_pass.nodes:
338
        for op in model.ops_in_model():
339
340
            if is_func(node, op):
                found[op] = True
341
    assert all(found[op] for op in model.ops_in_model())