From 1ac5d3ffe56d7c89fd25565f0db05115bccbd5b3 Mon Sep 17 00:00:00 2001 From: qsunnyy Date: Sat, 15 Mar 2025 17:47:57 +0800 Subject: [PATCH 1/5] add dp config and processgroups Signed-off-by: qsunnyy Signed-off-by: q00832892 --- distributed/utils.py | 123 +++++++++++++++++ examples/offline_inference_data_parallel.py | 98 ++++++++++++++ vllm_ascend/__init__.py | 5 + vllm_ascend/config.py | 46 +++++++ vllm_ascend/forward_context.py | 138 ++++++++++++++++++++ 5 files changed, 410 insertions(+) create mode 100644 distributed/utils.py create mode 100644 examples/offline_inference_data_parallel.py create mode 100644 vllm_ascend/config.py create mode 100644 vllm_ascend/forward_context.py diff --git a/distributed/utils.py b/distributed/utils.py new file mode 100644 index 000000000000..f3f196cec976 --- /dev/null +++ b/distributed/utils.py @@ -0,0 +1,123 @@ +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. +# This file is a part of the vllm-ascend project. +# Adapted from vllm/tests/kernels/test_moe.py +# Copyright 2023 The vLLM team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch.distributed import ProcessGroup, is_hccl_available +from torch.distributed.distributed_c10d import (Backend, PrefixStore, + _get_default_timeout, + is_nccl_available) +from torch.distributed.rendezvous import rendezvous +from vllm.distributed import utils + + +def stateless_init_torch_distributed_process_group( + host: str, port: int, rank: int, world_size: int, + backend: str) -> ProcessGroup: + """ + A replacement for `torch.distributed.init_process_group` that does not + pollute the global state. The created ProcessGroup object can be used for + some operations such as `allreduce`, because it does not depend on the + global rank. However, some operations such as `broadcast` cannot be used + because it depends on the global rank. + This function is useful when we are not sure about the total number of + processes in the process group. For example, we may have process + 1, 2, ..., 8 who want to communicate, and process 9 might be the same + process as process 1, or it might be a different process; process 10 + might be the same process as process 5, or it might be a different process. + In this case, how can we reliably form a communication channel within + process 9 and 10, without affecting the communication channel within + process 1, 2, ..., 8? + + One possible solution is to figure out if process 9 and 10 are the same + as process 1 and 5 beforehand, and then form a communication channel + based on the information, adjusting the ranks and world_size etc. However, + figuring out the information is not always easy, and it will interfere + with the main communication channel. + + Our solution is to always form a communication channel with process 1, 2, + ..., 8, and then use this function to form another communication channel + with process 9 and 10. This way, regardless of whether process 9 and 10 + are the same as process 1 and 5, the main communication channel is + always formed with process 1, 2, ..., 8, and the additional communication + channel is formed with process 9 and 10. + """ + init_method = f"tcp://{host}:{port}" + backend = Backend(backend) # it is basically string + timeout = _get_default_timeout(backend) + + store, rank, world_size = next( + rendezvous(init_method, rank, world_size, timeout=timeout)) + store.set_timeout(timeout) + + group_rank = rank + group_size = world_size + + # Use a PrefixStore to avoid accidental overrides of keys used by + # different systems (e.g. RPC) in case the store is multi-tenant. + prefix_store = PrefixStore(init_method, store) + + pg_options = ProcessGroup.Options(backend=backend, timeout=timeout) + + pg: ProcessGroup = ProcessGroup( + prefix_store, + group_rank, + group_size, + pg_options, + ) + + if backend == "gloo": + from torch.distributed.distributed_c10d import ProcessGroupGloo + backend_class = ProcessGroupGloo(prefix_store, + group_rank, + group_size, + timeout=timeout) + backend_type = ProcessGroup.BackendType.GLOO + device = torch.device("cpu") + backend_class._set_sequence_number_for_group() + pg._register_backend(device, backend_type, backend_class) + + elif backend == "nccl": + assert is_nccl_available() + from torch.distributed.distributed_c10d import ProcessGroupNCCL + + backend_options = ProcessGroupNCCL.Options() + backend_options._timeout = timeout + + backend_class = ProcessGroupNCCL(prefix_store, group_rank, group_size, + backend_options) + backend_type = ProcessGroup.BackendType.NCCL + device = torch.device("cuda") + backend_class._set_sequence_number_for_group() + pg._register_backend(device, backend_type, backend_class) + + elif backend == "hccl": + assert is_hccl_available() + import torch_npu # noqa + from torch_npu._C._distributed_c10d import ProcessGroupHCCL + backend_options = ProcessGroupHCCL.Options() + backend_options._timeout = timeout + backend_class = ProcessGroupHCCL(prefix_store, group_rank, group_size, + backend_options) + device = torch.device("npu") + backend_class._set_sequence_number_for_group() + backend_type = ProcessGroup.BackendType.CUSTOM + pg._register_backend(device, backend_type, backend_class) + + return pg + + +utils.stateless_init_torch_distributed_process_group = stateless_init_torch_distributed_process_group diff --git a/examples/offline_inference_data_parallel.py b/examples/offline_inference_data_parallel.py new file mode 100644 index 000000000000..4b84b76ad5dd --- /dev/null +++ b/examples/offline_inference_data_parallel.py @@ -0,0 +1,98 @@ +# +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. +# This file is a part of the vllm-ascend project. +# Adapted from vllm-project/vllm/examples/offline_inference/basic.py +# Copyright 2023 The vLLM team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import gc +import os +from multiprocessing import Process + + +def main(dp_size, dp_rank, dp_master_ip, dp_master_port, tp_size): + os.environ["VLLM_DP_RANK"] = str(dp_rank) + os.environ["VLLM_DP_SIZE"] = str(dp_size) + os.environ["VLLM_DP_MASTER_IP"] = dp_master_ip + os.environ["VLLM_DP_MASTER_PORT"] = str(dp_master_port) + os.environ["ASCEND_RT_VISIBLE_DEVICES"] = ",".join( + str(i) for i in range(dp_rank * tp_size, (dp_rank + 1) * tp_size)) + + import torch + import torch_npu # noqa + from vllm import LLM, SamplingParams + from vllm.distributed.parallel_state import ( + destroy_distributed_environment, destroy_model_parallel) + + import vllm_ascend # noqa + + prompts = [ + "Hello, my name is", + "The president of the United States is", + "The capital of France is", + "The future of AI is", + ] * 4 + + promts_per_rank = len(prompts) // dp_size + start = dp_rank * promts_per_rank + end = start + promts_per_rank + prompts = prompts[start:end] + if len(prompts) == 0: + prompts = ["Placeholder"] + print(f"DP rank {dp_rank} needs to process {len(prompts)} prompts") + + sampling_params = SamplingParams(temperature=0.8, + top_p=0.95, + max_tokens=4, + min_tokens=4) + + # Create an LLM. + llm = LLM(model="/home/foundation_model/q00832892/DeepSeek-V2-Lite-Chat/", + tensor_parallel_size=tp_size, + enable_expert_parallel=True, + enforce_eager=True, + trust_remote_code=True, + max_model_len=4096) + + outputs = llm.generate(prompts, sampling_params) + # Print the outputs. + for output in outputs: + prompt = output.prompt + generated_text = output.outputs[0].text + print(f"DP rank {dp_rank}, Prompt: {prompt!r}, " + f"Generated text: {generated_text!r}") + + del llm + destroy_model_parallel() + destroy_distributed_environment() + gc.collect() + torch.npu.empty_cache() + + +if __name__ == "__main__": + dp_master_ip = "127.0.0.1" + dp_master_port = 29500 + procs = [] + + TP_size = 2 + DP_size = 2 + for i in range(DP_size): + proc = Process(target=main, + args=(DP_size, i, dp_master_ip, dp_master_port, + TP_size)) + proc.start() + procs.append(proc) + for proc in procs: + proc.join() diff --git a/vllm_ascend/__init__.py b/vllm_ascend/__init__.py index c3b766127fa9..be00401a70ff 100644 --- a/vllm_ascend/__init__.py +++ b/vllm_ascend/__init__.py @@ -15,6 +15,11 @@ # limitations under the License. # +from . import config # noqa +from . import engine # noqa +from . import forward_context # noqa +from .distributed import utils # noqa + def register(): """Register the NPU platform.""" diff --git a/vllm_ascend/config.py b/vllm_ascend/config.py new file mode 100644 index 000000000000..4acba8a4d9b7 --- /dev/null +++ b/vllm_ascend/config.py @@ -0,0 +1,46 @@ +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. +# This file is a part of the vllm-ascend project. +# Adapted from vllm/tests/kernels/test_moe.py +# Copyright 2023 The vLLM team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from torch.distributed import ProcessGroup, ReduceOp +from vllm.config import ParallelConfig + + +def stateless_init_dp_group(self) -> "ProcessGroup": + from vllm.distributed.utils import \ + stateless_init_torch_distributed_process_group + + dp_group = stateless_init_torch_distributed_process_group( + self.data_parallel_master_ip, + self.get_next_dp_init_port(), + self.data_parallel_rank, + self.data_parallel_size, + backend="hccl") + + return dp_group + + +def has_unfinished_dp(dp_group: "ProcessGroup", has_unfinished: bool) -> bool: + + tensor = torch.tensor([has_unfinished], dtype=torch.int32, device="npu") + torch.distributed.all_reduce(tensor, op=ReduceOp.MAX, group=dp_group) + aggregated_has_unfinished = bool(tensor.item()) + return aggregated_has_unfinished + + +ParallelConfig.stateless_init_dp_group = stateless_init_dp_group +ParallelConfig.has_unfinished_dp = has_unfinished_dp diff --git a/vllm_ascend/forward_context.py b/vllm_ascend/forward_context.py new file mode 100644 index 000000000000..b6976eb71fe4 --- /dev/null +++ b/vllm_ascend/forward_context.py @@ -0,0 +1,138 @@ +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. +# This file is a part of the vllm-ascend project. +# Adapted from vllm/tests/kernels/test_moe.py +# Copyright 2023 The vLLM team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import time +from collections import defaultdict +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any, Optional + +import torch +import torch.distributed as dist +import vllm.envs as envs +from vllm import forward_context +from vllm.config import VllmConfig +from vllm.forward_context import DPMetadata, ForwardContext +from vllm.logger import init_logger + +logger = init_logger(__name__) + +last_logging_time: float = 0 +forward_start_time: float = 0 +batchsize_logging_interval: float = envs.VLLM_LOG_BATCHSIZE_INTERVAL +batchsize_forward_time: defaultdict = defaultdict(list) + +if TYPE_CHECKING: + from vllm.attention.backends.abstract import AttentionMetadata # noqa + +track_batchsize: bool = envs.VLLM_LOG_BATCHSIZE_INTERVAL >= 0 + +_forward_context: Optional[ForwardContext] = None + + +def get_forward_context() -> ForwardContext: + """Get the current forward context.""" + assert _forward_context is not None, ( + "Forward context is not set. " + "Please use `set_forward_context` to set the forward context.") + return _forward_context + + +@contextmanager +def set_forward_context(attn_metadata: Any, + vllm_config: VllmConfig, + virtual_engine: int = 0, + num_tokens: int = 0): + """A context manager that stores the current forward context, + can be attention metadata, etc. + Here we can inject common logic for every model forward pass. + """ + global forward_start_time + need_to_track_batchsize = track_batchsize and attn_metadata is not None + if need_to_track_batchsize: + forward_start_time = time.perf_counter() + dp_metadata: Optional[DPMetadata] = None + if vllm_config.parallel_config.data_parallel_size > 1: + dp_size = vllm_config.parallel_config.data_parallel_size + dp_rank = vllm_config.parallel_config.data_parallel_rank + if attn_metadata is not None: + if hasattr(attn_metadata, "num_prefill_tokens"): + # for v0 attention backends + batchsize = attn_metadata.num_prefill_tokens + \ + attn_metadata.num_decode_tokens + else: + # for v1 attention backends + batchsize = attn_metadata.num_input_tokens + else: + batchsize = num_tokens + num_tokens_across_dp = [0] * dp_size + num_tokens_across_dp[dp_rank] = batchsize + num_tokens_tensor = torch.tensor(num_tokens_across_dp, + device="npu", + dtype=torch.int32) + from vllm.distributed.parallel_state import get_dp_group + dist.all_reduce(num_tokens_tensor, group=get_dp_group().device_group) + cu_tokens_across_dp_npu = torch.cumsum(num_tokens_tensor, dim=0) + dp_metadata = DPMetadata(cu_tokens_across_dp_npu) + + global _forward_context + prev_context = _forward_context + _forward_context = ForwardContext( + no_compile_layers=vllm_config.compilation_config. + static_forward_context, + virtual_engine=virtual_engine, + attn_metadata=attn_metadata, + dp_metadata=dp_metadata) + try: + yield + finally: + global last_logging_time, batchsize_logging_interval + if need_to_track_batchsize: + if hasattr(attn_metadata, "num_prefill_tokens"): + # for v0 attention backends + batchsize = attn_metadata.num_prefill_tokens + \ + attn_metadata.num_decode_tokens + else: + # for v1 attention backends + batchsize = attn_metadata.num_input_tokens + # we use synchronous scheduling right now, + # adding a sync point here should not affect + # scheduling of the next batch + torch.cuda.synchronize() + now = time.perf_counter() + # time measurement is in milliseconds + batchsize_forward_time[batchsize].append( + (now - forward_start_time) * 1000) + if now - last_logging_time > batchsize_logging_interval: + last_logging_time = now + forward_stats = [] + for bs, times in batchsize_forward_time.items(): + if len(times) <= 1: + # can be cudagraph / profiling run + continue + medium = torch.quantile(torch.tensor(times), q=0.5).item() + medium = round(medium, 2) + forward_stats.append((bs, len(times), medium)) + forward_stats.sort(key=lambda x: x[1], reverse=True) + if forward_stats: + logger.info(("Batchsize forward time stats " + "(batchsize, count, median_time(ms)): %s"), + forward_stats) + _forward_context = prev_context + + +forward_context.set_forward_context = set_forward_context +forward_context.get_forward_context = get_forward_context From 4e13b009c665c4d7449899e9d4d5d1fd559be3c4 Mon Sep 17 00:00:00 2001 From: qsunnyy Date: Sat, 15 Mar 2025 17:50:16 +0800 Subject: [PATCH 2/5] compatible with v0 engine Signed-off-by: qsunnyy Signed-off-by: q00832892 --- .../distributed}/utils.py | 1 + vllm_ascend/engine/llm_engine.py | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+) rename {distributed => vllm_ascend/distributed}/utils.py (99%) create mode 100644 vllm_ascend/engine/llm_engine.py diff --git a/distributed/utils.py b/vllm_ascend/distributed/utils.py similarity index 99% rename from distributed/utils.py rename to vllm_ascend/distributed/utils.py index f3f196cec976..6dda71ce94a9 100644 --- a/distributed/utils.py +++ b/vllm_ascend/distributed/utils.py @@ -33,6 +33,7 @@ def stateless_init_torch_distributed_process_group( some operations such as `allreduce`, because it does not depend on the global rank. However, some operations such as `broadcast` cannot be used because it depends on the global rank. + This function is useful when we are not sure about the total number of processes in the process group. For example, we may have process 1, 2, ..., 8 who want to communicate, and process 9 might be the same diff --git a/vllm_ascend/engine/llm_engine.py b/vllm_ascend/engine/llm_engine.py new file mode 100644 index 000000000000..836d54126221 --- /dev/null +++ b/vllm_ascend/engine/llm_engine.py @@ -0,0 +1,54 @@ +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. +# This file is a part of the vllm-ascend project. +# Adapted from vllm/tests/kernels/test_moe.py +# Copyright 2023 The vLLM team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def apply_custom_engine_patch(): + from vllm.config import ParallelConfig + from vllm.config import VllmConfig as vllm_config # noqa + from vllm.engine.arg_utils import EngineArgs # noqa + from vllm.engine.llm_engine import LLMEngine + + original_init = LLMEngine.__init__ + + def new_init(self, *args, **kwargs): + original_init(self, *args, **kwargs) + self.dp_enabled = self.parallel_config.data_parallel_size > 1 # noqa + self.should_execute_dummy_batch = False + if self.dp_enabled: + self.dp_group = self.parallel_config.stateless_init_dp_group() + + def new_has_unfinished_requests(self) -> bool: + has_unfinished = any(scheduler.has_unfinished_seqs() + for scheduler in self.scheduler) + if not self.dp_enabled: + return has_unfinished + return new_has_unfinished_requests_dp(self, has_unfinished) + + def new_has_unfinished_requests_dp(self, has_unfinished: bool) -> bool: + aggregated_has_unfinished = ParallelConfig.has_unfinished_dp( + self.dp_group, has_unfinished) + if not has_unfinished and aggregated_has_unfinished: + self.should_execute_dummy_batch = True + return aggregated_has_unfinished + + LLMEngine.__init__ = new_init + LLMEngine.has_unfinished_requests = new_has_unfinished_requests + LLMEngine.has_unfinished_requests_dp = new_has_unfinished_requests_dp + print("[Success] Custom LLMEngine patch applied!") + + +apply_custom_engine_patch() From e964f1ed860bda1411114cd3addd4bc199d76e6b Mon Sep 17 00:00:00 2001 From: q00832892 Date: Mon, 17 Mar 2025 09:53:51 +0800 Subject: [PATCH 3/5] fix circular import and absolute path Signed-off-by: q00832892 --- examples/offline_inference_data_parallel.py | 2 +- vllm_ascend/__init__.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/offline_inference_data_parallel.py b/examples/offline_inference_data_parallel.py index 4b84b76ad5dd..8f639940353d 100644 --- a/examples/offline_inference_data_parallel.py +++ b/examples/offline_inference_data_parallel.py @@ -59,7 +59,7 @@ def main(dp_size, dp_rank, dp_master_ip, dp_master_port, tp_size): min_tokens=4) # Create an LLM. - llm = LLM(model="/home/foundation_model/q00832892/DeepSeek-V2-Lite-Chat/", + llm = LLM(model="deepseek-ai/DeepSeek-V2-Lite-Chat", tensor_parallel_size=tp_size, enable_expert_parallel=True, enforce_eager=True, diff --git a/vllm_ascend/__init__.py b/vllm_ascend/__init__.py index be00401a70ff..0f205e564b07 100644 --- a/vllm_ascend/__init__.py +++ b/vllm_ascend/__init__.py @@ -15,14 +15,14 @@ # limitations under the License. # -from . import config # noqa -from . import engine # noqa -from . import forward_context # noqa -from .distributed import utils # noqa def register(): """Register the NPU platform.""" + from . import config # noqa + from . import engine # noqa + from . import forward_context # noqa + from .distributed import utils # noqa return "vllm_ascend.platform.NPUPlatform" From a2fda7ce67d8ef86bdd192ef5d8a6b393c880707 Mon Sep 17 00:00:00 2001 From: q00832892 Date: Mon, 17 Mar 2025 10:02:57 +0800 Subject: [PATCH 4/5] fix codecheck Signed-off-by: q00832892 --- vllm_ascend/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/vllm_ascend/__init__.py b/vllm_ascend/__init__.py index 0f205e564b07..f231add395fa 100644 --- a/vllm_ascend/__init__.py +++ b/vllm_ascend/__init__.py @@ -16,7 +16,6 @@ # - def register(): """Register the NPU platform.""" from . import config # noqa From 825a9d2c76bcb1046f9a044d039787f6c02feef4 Mon Sep 17 00:00:00 2001 From: q00832892 Date: Mon, 17 Mar 2025 10:47:05 +0800 Subject: [PATCH 5/5] enable custom engine Signed-off-by: q00832892 --- vllm_ascend/__init__.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vllm_ascend/__init__.py b/vllm_ascend/__init__.py index f231add395fa..a1d89be63390 100644 --- a/vllm_ascend/__init__.py +++ b/vllm_ascend/__init__.py @@ -18,13 +18,13 @@ def register(): """Register the NPU platform.""" - from . import config # noqa - from . import engine # noqa - from . import forward_context # noqa - from .distributed import utils # noqa return "vllm_ascend.platform.NPUPlatform" def register_model(): + from . import config # noqa + from . import forward_context # noqa + from .distributed import utils # noqa + from .engine import llm_engine # noqa from .models import register_model register_model()