Unverified Commit fd4ea8ef authored by Zhuohan Li's avatar Zhuohan Li Committed by GitHub
Browse files

Use NCCL instead of ray for control-plane communication to remove serialization overhead (#2221)

parent 1066cbd1
...@@ -58,11 +58,10 @@ Next, you need to rewrite the :code:`forward` methods of your model by following ...@@ -58,11 +58,10 @@ Next, you need to rewrite the :code:`forward` methods of your model by following
+ positions: torch.Tensor, + positions: torch.Tensor,
+ kv_caches: List[KVCache], + kv_caches: List[KVCache],
+ input_metadata: InputMetadata, + input_metadata: InputMetadata,
+ cache_events: Optional[List[torch.cuda.Event]], +) -> Optional[SamplerOutput]:
+) -> SamplerOutput:
3. Update the code by considering that :code:`input_ids` and :code:`positions` are now flattened tensors. 1. Update the code by considering that :code:`input_ids` and :code:`positions` are now flattened tensors.
4. Replace the attention operation with either :code:`PagedAttention`, :code:`PagedAttentionWithRoPE`, or :code:`PagedAttentionWithALiBi` depending on the model's architecture. 2. Replace the attention operation with either :code:`PagedAttention`, :code:`PagedAttentionWithRoPE`, or :code:`PagedAttentionWithALiBi` depending on the model's architecture.
.. note:: .. note::
Currently, vLLM supports the basic multi-head attention mechanism and its variant with rotary positional embeddings. Currently, vLLM supports the basic multi-head attention mechanism and its variant with rotary positional embeddings.
......
...@@ -3,8 +3,6 @@ typing-extensions>=4.8.0 ...@@ -3,8 +3,6 @@ typing-extensions>=4.8.0
starlette starlette
psutil psutil
ray >= 2.5.1 ray >= 2.5.1
pandas # Required for Ray data.
pyarrow # Required for Ray data.
sentencepiece # Required for LLaMA tokenizer. sentencepiece # Required for LLaMA tokenizer.
numpy numpy
tokenizers>=0.15.0 tokenizers>=0.15.0
......
ninja # For faster builds. ninja # For faster builds.
psutil psutil
ray >= 2.5.1 ray >= 2.5.1
pandas # Required for Ray data.
pyarrow # Required for Ray data.
sentencepiece # Required for LLaMA tokenizer. sentencepiece # Required for LLaMA tokenizer.
numpy numpy
torch == 2.1.2 torch == 2.1.2
......
...@@ -8,11 +8,11 @@ import pytest ...@@ -8,11 +8,11 @@ import pytest
import requests import requests
def _query_server(prompt: str) -> dict: def _query_server(prompt: str, max_tokens: int = 5) -> dict:
response = requests.post("http://localhost:8000/generate", response = requests.post("http://localhost:8000/generate",
json={ json={
"prompt": prompt, "prompt": prompt,
"max_tokens": 100, "max_tokens": max_tokens,
"temperature": 0, "temperature": 0,
"ignore_eos": True "ignore_eos": True
}) })
...@@ -20,6 +20,10 @@ def _query_server(prompt: str) -> dict: ...@@ -20,6 +20,10 @@ def _query_server(prompt: str) -> dict:
return response.json() return response.json()
def _query_server_long(prompt: str) -> dict:
return _query_server(prompt, max_tokens=500)
@pytest.fixture @pytest.fixture
def api_server(): def api_server():
script_path = Path(__file__).parent.joinpath( script_path = Path(__file__).parent.joinpath(
...@@ -68,10 +72,11 @@ def test_api_server(api_server): ...@@ -68,10 +72,11 @@ def test_api_server(api_server):
for result in pool.map(_query_server, prompts): for result in pool.map(_query_server, prompts):
assert result assert result
with Pool(32) as pool:
# Cancel requests # Cancel requests
prompts = ["canceled requests"] * 100 prompts = ["canceled requests"] * 100
pool.map_async(_query_server, prompts) pool.map_async(_query_server_long, prompts)
time.sleep(0.001) time.sleep(0.01)
pool.terminate() pool.terminate()
pool.join() pool.join()
......
...@@ -49,12 +49,13 @@ def test_copy_blocks( ...@@ -49,12 +49,13 @@ def test_copy_blocks(
src_blocks = random.sample(range(num_blocks), num_mappings) src_blocks = random.sample(range(num_blocks), num_mappings)
remainig_blocks = list(set(range(num_blocks)) - set(src_blocks)) remainig_blocks = list(set(range(num_blocks)) - set(src_blocks))
dst_blocks = random.sample(remainig_blocks, 2 * num_mappings) dst_blocks = random.sample(remainig_blocks, 2 * num_mappings)
block_mapping = {} copy_src = []
copy_dst = []
for i in range(num_mappings): for i in range(num_mappings):
src = src_blocks[i] copy_src.append(src_blocks[i])
dst1 = dst_blocks[2 * i] copy_dst.append(dst_blocks[2 * i])
dst2 = dst_blocks[2 * i + 1] copy_src.append(src_blocks[i])
block_mapping[src] = [dst1, dst2] copy_dst.append(dst_blocks[2 * i + 1])
# Create the KV caches. # Create the KV caches.
key_caches, value_caches = kv_cache_factory(num_blocks, block_size, key_caches, value_caches = kv_cache_factory(num_blocks, block_size,
...@@ -66,15 +67,14 @@ def test_copy_blocks( ...@@ -66,15 +67,14 @@ def test_copy_blocks(
cloned_value_caches = [value_cache.clone() for value_cache in value_caches] cloned_value_caches = [value_cache.clone() for value_cache in value_caches]
# Call the copy blocks kernel. # Call the copy blocks kernel.
cache_ops.copy_blocks(key_caches, value_caches, block_mapping) cache_ops.copy_blocks(key_caches, value_caches, copy_src, copy_dst)
# Run the reference implementation. # Run the reference implementation.
for src, dsts in block_mapping.items(): for src, dst in zip(copy_src, copy_dst):
for dst in dsts: for cloned_key_cache in cloned_key_caches:
for cloned_key_cache in cloned_key_caches: cloned_key_cache[dst].copy_(cloned_key_cache[src])
cloned_key_cache[dst].copy_(cloned_key_cache[src]) for cloned_value_cache in cloned_value_caches:
for cloned_value_cache in cloned_value_caches: cloned_value_cache[dst].copy_(cloned_value_cache[src])
cloned_value_cache[dst].copy_(cloned_value_cache[src])
# Compare the results. # Compare the results.
for key_cache, cloned_key_cache in zip(key_caches, cloned_key_caches): for key_cache, cloned_key_cache in zip(key_caches, cloned_key_caches):
......
...@@ -33,8 +33,9 @@ def test_prepare_prompt(): ...@@ -33,8 +33,9 @@ def test_prepare_prompt():
expected_selected_token_indices.append(selected_token_start_idx + expected_selected_token_indices.append(selected_token_start_idx +
prompt_len - 1) prompt_len - 1)
selected_token_start_idx += max_seq_len selected_token_start_idx += max_seq_len
input_tokens, input_positions, _ = model_runner._prepare_prompt( input_tokens, input_positions, _, return_prompt_lens = (
seq_group_metadata_list) model_runner._prepare_prompt(seq_group_metadata_list))
assert return_prompt_lens == prompt_lens
sampling_metadata = model_runner._prepare_sample(seq_group_metadata_list, sampling_metadata = model_runner._prepare_sample(seq_group_metadata_list,
prompt_lens) prompt_lens)
assert input_tokens.shape == (batch_size, max_seq_len) assert input_tokens.shape == (batch_size, max_seq_len)
......
...@@ -185,14 +185,21 @@ class _AsyncLLMEngine(LLMEngine): ...@@ -185,14 +185,21 @@ class _AsyncLLMEngine(LLMEngine):
""" """
seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule() seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
# Execute the model. if not scheduler_outputs.is_empty():
output = (await self._run_workers_async( # Execute the model.
"execute_model", all_outputs = await self._run_workers_async(
seq_group_metadata_list=seq_group_metadata_list, "execute_model",
blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in, driver_kwargs={
blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out, "seq_group_metadata_list": seq_group_metadata_list,
blocks_to_copy=scheduler_outputs.blocks_to_copy, "blocks_to_swap_in": scheduler_outputs.blocks_to_swap_in,
)) if not scheduler_outputs.is_empty() else [] "blocks_to_swap_out": scheduler_outputs.blocks_to_swap_out,
"blocks_to_copy": scheduler_outputs.blocks_to_copy,
})
# Only the driver worker returns the sampling results.
output = all_outputs[0]
else:
output = []
return self._process_model_outputs(output, scheduler_outputs) return self._process_model_outputs(output, scheduler_outputs)
...@@ -200,30 +207,29 @@ class _AsyncLLMEngine(LLMEngine): ...@@ -200,30 +207,29 @@ class _AsyncLLMEngine(LLMEngine):
self, self,
method: str, method: str,
*args, *args,
get_all_outputs: bool = False, driver_args: Optional[List[Any]] = None,
driver_kwargs: Optional[Dict[str, Any]] = None,
**kwargs, **kwargs,
) -> Any: ) -> Any:
"""Runs the given method on all workers.""" """Runs the given method on all workers."""
coros = [] coros = []
for worker in self.workers:
if self.parallel_config.worker_use_ray:
coros.append(
worker.execute_method.remote(method, *args, **kwargs))
else:
executor = getattr(worker, method)
coros.append(asyncio.get_event_loop().run_in_executor(
None, partial(executor, *args, **kwargs)))
all_outputs = await asyncio.gather(*coros) if driver_args is None:
driver_args = args
if driver_kwargs is None:
driver_kwargs = kwargs
if get_all_outputs: # Run the driver worker asynchronously.
return all_outputs driver_executor = getattr(self.driver_worker, method)
coros.append(asyncio.get_event_loop().run_in_executor(
None, partial(driver_executor, *driver_args, **driver_kwargs)))
# Make sure all workers have the same results. # Run the ray workers asynchronously.
output = all_outputs[0] for worker in self.workers:
for other_output in all_outputs[1:]: coros.append(worker.execute_method.remote(method, *args, **kwargs))
assert output == other_output
return output all_outputs = await asyncio.gather(*coros)
return all_outputs
class AsyncLLMEngine: class AsyncLLMEngine:
...@@ -488,13 +494,12 @@ class AsyncLLMEngine: ...@@ -488,13 +494,12 @@ class AsyncLLMEngine:
engine_configs = engine_args.create_engine_configs() engine_configs = engine_args.create_engine_configs()
parallel_config = engine_configs[2] parallel_config = engine_configs[2]
# Initialize the cluster. # Initialize the cluster.
distributed_init_method, placement_group = initialize_cluster( placement_group = initialize_cluster(parallel_config,
parallel_config, engine_args.engine_use_ray) engine_args.engine_use_ray)
# Create the async LLM engine. # Create the async LLM engine.
engine = cls(parallel_config.worker_use_ray, engine = cls(parallel_config.worker_use_ray,
engine_args.engine_use_ray, engine_args.engine_use_ray,
*engine_configs, *engine_configs,
distributed_init_method,
placement_group, placement_group,
log_requests=not engine_args.disable_log_requests, log_requests=not engine_args.disable_log_requests,
log_stats=not engine_args.disable_log_stats, log_stats=not engine_args.disable_log_stats,
......
import copy import copy
from collections import defaultdict
import os import os
import time import time
from functools import partial from typing import (TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple,
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union Union)
from vllm.config import (CacheConfig, ModelConfig, ParallelConfig, from vllm.config import (CacheConfig, ModelConfig, ParallelConfig,
SchedulerConfig) SchedulerConfig)
...@@ -17,10 +18,9 @@ from vllm.sequence import (SamplerOutput, Sequence, SequenceGroup, ...@@ -17,10 +18,9 @@ from vllm.sequence import (SamplerOutput, Sequence, SequenceGroup,
SequenceGroupOutput, SequenceOutput, SequenceStatus) SequenceGroupOutput, SequenceOutput, SequenceStatus)
from vllm.transformers_utils.tokenizer import (detokenize_incrementally, from vllm.transformers_utils.tokenizer import (detokenize_incrementally,
get_tokenizer) get_tokenizer)
from vllm.utils import Counter from vllm.utils import Counter, set_cuda_visible_devices, get_ip, get_open_port
if ray: if ray:
from ray.air.util.torch_dist import init_torch_dist_process_group
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
if TYPE_CHECKING: if TYPE_CHECKING:
...@@ -53,8 +53,6 @@ class LLMEngine: ...@@ -53,8 +53,6 @@ class LLMEngine:
management. management.
parallel_config: The configuration related to distributed execution. parallel_config: The configuration related to distributed execution.
scheduler_config: The configuration related to the request scheduler. scheduler_config: The configuration related to the request scheduler.
distributed_init_method: The initialization method for distributed
execution. See `torch.distributed.init_process_group` for details.
placement_group: Ray placement group for distributed execution. placement_group: Ray placement group for distributed execution.
Required for distributed execution. Required for distributed execution.
log_stats: Whether to log statistics. log_stats: Whether to log statistics.
...@@ -66,7 +64,6 @@ class LLMEngine: ...@@ -66,7 +64,6 @@ class LLMEngine:
cache_config: CacheConfig, cache_config: CacheConfig,
parallel_config: ParallelConfig, parallel_config: ParallelConfig,
scheduler_config: SchedulerConfig, scheduler_config: SchedulerConfig,
distributed_init_method: str,
placement_group: Optional["PlacementGroup"], placement_group: Optional["PlacementGroup"],
log_stats: bool, log_stats: bool,
) -> None: ) -> None:
...@@ -111,7 +108,7 @@ class LLMEngine: ...@@ -111,7 +108,7 @@ class LLMEngine:
os.environ["RAY_USAGE_STATS_ENABLED"] = "0" os.environ["RAY_USAGE_STATS_ENABLED"] = "0"
self._init_workers_ray(placement_group) self._init_workers_ray(placement_group)
else: else:
self._init_workers(distributed_init_method) self._init_workers()
# Profile the memory usage and initialize the cache. # Profile the memory usage and initialize the cache.
self._init_cache() self._init_cache()
...@@ -126,7 +123,7 @@ class LLMEngine: ...@@ -126,7 +123,7 @@ class LLMEngine:
# List of (timestamp, num_tokens) # List of (timestamp, num_tokens)
self.num_generation_tokens: List[Tuple[float, int]] = [] self.num_generation_tokens: List[Tuple[float, int]] = []
def _init_workers(self, distributed_init_method: str): def _init_workers(self):
# Lazy import the Worker to avoid importing torch.cuda/xformers # Lazy import the Worker to avoid importing torch.cuda/xformers
# before CUDA_VISIBLE_DEVICES is set in the Worker # before CUDA_VISIBLE_DEVICES is set in the Worker
from vllm.worker.worker import Worker from vllm.worker.worker import Worker
...@@ -135,70 +132,122 @@ class LLMEngine: ...@@ -135,70 +132,122 @@ class LLMEngine:
"Ray is required if parallel_config.world_size > 1.") "Ray is required if parallel_config.world_size > 1.")
self.workers: List[Worker] = [] self.workers: List[Worker] = []
worker = Worker( distributed_init_method = f"tcp://{get_ip()}:{get_open_port()}"
self.driver_worker = Worker(
self.model_config, self.model_config,
self.parallel_config, self.parallel_config,
self.scheduler_config, self.scheduler_config,
0, local_rank=0,
distributed_init_method, rank=0,
) distributed_init_method=distributed_init_method,
self.workers.append(worker) is_driver_worker=True,
self._run_workers(
"init_model",
get_all_outputs=True,
)
self._run_workers(
"load_model",
get_all_outputs=True,
max_concurrent_workers=self.parallel_config.
max_parallel_loading_workers,
) )
self._run_workers("init_model")
self._run_workers("load_model")
def _init_workers_ray(self, placement_group: "PlacementGroup", def _init_workers_ray(self, placement_group: "PlacementGroup",
**ray_remote_kwargs): **ray_remote_kwargs):
# Lazy import the Worker to avoid importing torch.cuda/xformers if self.parallel_config.tensor_parallel_size == 1:
# before CUDA_VISIBLE_DEVICES is set in the Worker num_gpus = self.cache_config.gpu_memory_utilization
from vllm.worker.worker import Worker else:
num_gpus = 1
self.workers: List[Worker] = [] self.driver_dummy_worker: RayWorkerVllm = None
for bundle in placement_group.bundle_specs: self.workers: List[RayWorkerVllm] = []
driver_ip = get_ip()
for bundle_id, bundle in enumerate(placement_group.bundle_specs):
if not bundle.get("GPU", 0): if not bundle.get("GPU", 0):
continue continue
if self.parallel_config.tensor_parallel_size == 1: scheduling_strategy = PlacementGroupSchedulingStrategy(
num_gpus = self.cache_config.gpu_memory_utilization placement_group=placement_group,
else: placement_group_capture_child_tasks=True,
num_gpus = 1 placement_group_bundle_index=bundle_id,
)
worker = ray.remote( worker = ray.remote(
num_cpus=0, num_cpus=0,
num_gpus=num_gpus, num_gpus=num_gpus,
scheduling_strategy=PlacementGroupSchedulingStrategy( scheduling_strategy=scheduling_strategy,
placement_group=placement_group,
placement_group_capture_child_tasks=True),
**ray_remote_kwargs, **ray_remote_kwargs,
)(RayWorkerVllm).remote(self.model_config.trust_remote_code) )(RayWorkerVllm).remote(self.model_config.trust_remote_code)
self.workers.append(worker)
worker_ip = ray.get(worker.get_node_ip.remote())
if worker_ip == driver_ip and self.driver_dummy_worker is None:
# If the worker is on the same node as the driver, we use it
# as the resource holder for the driver process.
self.driver_dummy_worker = worker
else:
self.workers.append(worker)
if self.driver_dummy_worker is None:
raise ValueError(
"Ray does not allocate any GPUs on the driver node. Consider "
"adjusting the Ray placement group or running the driver on a "
"GPU node.")
driver_node_id, driver_gpu_ids = ray.get(
self.driver_dummy_worker.get_node_and_gpu_ids.remote())
worker_node_and_gpu_ids = ray.get(
[worker.get_node_and_gpu_ids.remote() for worker in self.workers])
node_workers = defaultdict(list)
node_gpus = defaultdict(list)
node_workers[driver_node_id].append(0)
node_gpus[driver_node_id].extend(driver_gpu_ids)
for i, (node_id, gpu_ids) in enumerate(worker_node_and_gpu_ids,
start=1):
node_workers[node_id].append(i)
node_gpus[node_id].extend(gpu_ids)
for node_id, gpu_ids in node_gpus.items():
node_gpus[node_id] = sorted(gpu_ids)
# Set CUDA_VISIBLE_DEVICES for the driver.
set_cuda_visible_devices(node_gpus[driver_node_id])
for worker, (node_id, _) in zip(self.workers, worker_node_and_gpu_ids):
worker.set_cuda_visible_devices.remote(node_gpus[node_id])
distributed_init_method = f"tcp://{driver_ip}:{get_open_port()}"
# Lazy import the Worker to avoid importing torch.cuda/xformers
# before CUDA_VISIBLE_DEVICES is set in the Worker
from vllm.worker.worker import Worker
# Initialize torch distributed process group for the workers. # Initialize torch distributed process group for the workers.
init_torch_dist_process_group(self.workers, backend="nccl")
model_config = copy.deepcopy(self.model_config) model_config = copy.deepcopy(self.model_config)
parallel_config = copy.deepcopy(self.parallel_config) parallel_config = copy.deepcopy(self.parallel_config)
scheduler_config = copy.deepcopy(self.scheduler_config) scheduler_config = copy.deepcopy(self.scheduler_config)
self._run_workers("init_worker",
get_all_outputs=True, for rank, (worker, (node_id,
worker_init_fn=lambda: Worker( _)) in enumerate(zip(self.workers,
model_config, worker_node_and_gpu_ids),
parallel_config, start=1):
scheduler_config, local_rank = node_workers[node_id].index(rank)
None, worker.init_worker.remote(
None, lambda rank=rank, local_rank=local_rank: Worker(
)) model_config,
self._run_workers( parallel_config,
"init_model", scheduler_config,
get_all_outputs=True, local_rank,
rank,
distributed_init_method,
))
driver_rank = 0
driver_local_rank = node_workers[driver_node_id].index(driver_rank)
self.driver_worker = Worker(
model_config,
parallel_config,
scheduler_config,
driver_local_rank,
driver_rank,
distributed_init_method,
is_driver_worker=True,
) )
self._run_workers("init_model")
self._run_workers( self._run_workers(
"load_model", "load_model",
get_all_outputs=True,
max_concurrent_workers=self.parallel_config. max_concurrent_workers=self.parallel_config.
max_parallel_loading_workers, max_parallel_loading_workers,
) )
...@@ -212,7 +261,6 @@ class LLMEngine: ...@@ -212,7 +261,6 @@ class LLMEngine:
# Get the maximum number of blocks that can be allocated on GPU and CPU. # Get the maximum number of blocks that can be allocated on GPU and CPU.
num_blocks = self._run_workers( num_blocks = self._run_workers(
"profile_num_available_blocks", "profile_num_available_blocks",
get_all_outputs=True,
block_size=self.cache_config.block_size, block_size=self.cache_config.block_size,
gpu_memory_utilization=self.cache_config.gpu_memory_utilization, gpu_memory_utilization=self.cache_config.gpu_memory_utilization,
cpu_swap_space=self.cache_config.swap_space_bytes, cpu_swap_space=self.cache_config.swap_space_bytes,
...@@ -256,11 +304,9 @@ class LLMEngine: ...@@ -256,11 +304,9 @@ class LLMEngine:
engine_configs = engine_args.create_engine_configs() engine_configs = engine_args.create_engine_configs()
parallel_config = engine_configs[2] parallel_config = engine_configs[2]
# Initialize the cluster. # Initialize the cluster.
distributed_init_method, placement_group = initialize_cluster( placement_group = initialize_cluster(parallel_config)
parallel_config)
# Create the LLM engine. # Create the LLM engine.
engine = cls(*engine_configs, engine = cls(*engine_configs,
distributed_init_method,
placement_group, placement_group,
log_stats=not engine_args.disable_log_stats) log_stats=not engine_args.disable_log_stats)
return engine return engine
...@@ -577,14 +623,21 @@ class LLMEngine: ...@@ -577,14 +623,21 @@ class LLMEngine:
""" """
seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule() seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
# Execute the model. if not scheduler_outputs.is_empty():
output = self._run_workers( # Execute the model.
"execute_model", all_outputs = self._run_workers(
seq_group_metadata_list=seq_group_metadata_list, "execute_model",
blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in, driver_kwargs={
blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out, "seq_group_metadata_list": seq_group_metadata_list,
blocks_to_copy=scheduler_outputs.blocks_to_copy, "blocks_to_swap_in": scheduler_outputs.blocks_to_swap_in,
) if not scheduler_outputs.is_empty() else [] "blocks_to_swap_out": scheduler_outputs.blocks_to_swap_out,
"blocks_to_copy": scheduler_outputs.blocks_to_copy,
})
# Only the driver worker returns the sampling results.
output = all_outputs[0]
else:
output = []
return self._process_model_outputs(output, scheduler_outputs) return self._process_model_outputs(output, scheduler_outputs)
...@@ -712,53 +765,38 @@ class LLMEngine: ...@@ -712,53 +765,38 @@ class LLMEngine:
seq.status = SequenceStatus.FINISHED_STOPPED seq.status = SequenceStatus.FINISHED_STOPPED
return return
def _run_workers_in_batch(
self,
workers,
method: str,
*args,
**kwargs,
):
all_outputs = []
for worker in workers:
if self.parallel_config.worker_use_ray:
executor = partial(worker.execute_method.remote, method)
else:
executor = getattr(worker, method)
output = executor(*args, **kwargs)
all_outputs.append(output)
if self.parallel_config.worker_use_ray:
all_outputs = ray.get(all_outputs)
return all_outputs
def _run_workers( def _run_workers(
self, self,
method: str, method: str,
*args, *args,
get_all_outputs: bool = False, driver_args: Optional[List[Any]] = None,
driver_kwargs: Optional[Dict[str, Any]] = None,
max_concurrent_workers: Optional[int] = None, max_concurrent_workers: Optional[int] = None,
**kwargs, **kwargs,
) -> Any: ) -> Any:
"""Runs the given method on all workers.""" """Runs the given method on all workers."""
all_outputs = []
if max_concurrent_workers: if max_concurrent_workers:
work_groups = [ raise NotImplementedError(
self.workers[i:i + max_concurrent_workers] "max_concurrent_workers is not supported yet.")
for i in range(0, len(self.workers), max_concurrent_workers)
] # Start the ray workers first.
else: ray_worker_outputs = [
work_groups = [self.workers] worker.execute_method.remote(method, *args, **kwargs)
for worker in self.workers
]
if driver_args is None:
driver_args = args
if driver_kwargs is None:
driver_kwargs = kwargs
for workers in work_groups: # Start the driver worker after all the ray workers.
all_outputs.extend( driver_worker_output = getattr(self.driver_worker,
self._run_workers_in_batch(workers, method, *args, **kwargs)) method)(*driver_args, **driver_kwargs)
if get_all_outputs: # Get the results of the ray workers.
return all_outputs if self.workers:
ray_worker_outputs = ray.get(ray_worker_outputs)
# Make sure all workers have the same results. return [driver_worker_output] + ray_worker_outputs
output = all_outputs[0]
for other_output in all_outputs[1:]:
assert output == other_output
return output
from typing import Optional, Tuple, TYPE_CHECKING from typing import Optional, List, Tuple, TYPE_CHECKING
from vllm.config import ParallelConfig from vllm.config import ParallelConfig
from vllm.logger import init_logger from vllm.logger import init_logger
from vllm.utils import get_open_port, is_hip from vllm.utils import is_hip, set_cuda_visible_devices, get_ip
logger = init_logger(__name__) logger = init_logger(__name__)
try: try:
import ray import ray
from ray.air.util.torch_dist import TorchDistributedWorker
class RayWorkerVllm(TorchDistributedWorker): class RayWorkerVllm:
"""Ray wrapper for vllm.worker.Worker, allowing Worker to be """Ray wrapper for vllm.worker.Worker, allowing Worker to be
lazliy initialized after Ray sets CUDA_VISIBLE_DEVICES.""" lazliy initialized after Ray sets CUDA_VISIBLE_DEVICES."""
...@@ -30,12 +29,22 @@ try: ...@@ -30,12 +29,22 @@ try:
executor = getattr(self, method) executor = getattr(self, method)
return executor(*args, **kwargs) return executor(*args, **kwargs)
def get_node_ip(self) -> str:
return get_ip()
def get_node_and_gpu_ids(self) -> Tuple[str, List[int]]:
node_id = ray.get_runtime_context().get_node_id()
gpu_ids = ray.get_gpu_ids()
return node_id, gpu_ids
def set_cuda_visible_devices(self, device_ids) -> None:
set_cuda_visible_devices(device_ids)
except ImportError as e: except ImportError as e:
logger.warning(f"Failed to import Ray with {e!r}. " logger.warning(f"Failed to import Ray with {e!r}. "
"For distributed inference, please install Ray with " "For distributed inference, please install Ray with "
"`pip install ray pandas pyarrow`.") "`pip install ray pandas pyarrow`.")
ray = None ray = None
TorchDistributedWorker = None
RayWorkerVllm = None RayWorkerVllm = None
if TYPE_CHECKING: if TYPE_CHECKING:
...@@ -75,13 +84,11 @@ def initialize_cluster( ...@@ -75,13 +84,11 @@ def initialize_cluster(
ray.init(address=ray_address, ignore_reinit_error=True) ray.init(address=ray_address, ignore_reinit_error=True)
if not parallel_config.worker_use_ray: if not parallel_config.worker_use_ray:
# Initialize cluster locally. assert parallel_config.world_size == 1, (
port = get_open_port() "Ray is required if parallel_config.world_size > 1.")
# We need to setup the distributed init method to make sure return None
# the distributed megatron code (e.g., get world size) works correctly.
distributed_init_method = f"tcp://localhost:{port}"
return distributed_init_method, None
# Create placement group for worker processes
current_placement_group = ray.util.get_current_placement_group() current_placement_group = ray.util.get_current_placement_group()
if current_placement_group: if current_placement_group:
# We are in a placement group # We are in a placement group
...@@ -106,12 +113,12 @@ def initialize_cluster( ...@@ -106,12 +113,12 @@ def initialize_cluster(
"The number of required GPUs exceeds the total number of " "The number of required GPUs exceeds the total number of "
"available GPUs in the cluster.") "available GPUs in the cluster.")
# Create a new placement group # Create a new placement group
current_placement_group = ray.util.placement_group([{ placement_group_specs = ([{"GPU": 1}] * parallel_config.world_size)
"GPU": 1 current_placement_group = ray.util.placement_group(
}] * parallel_config.world_size) placement_group_specs)
# Wait until PG is ready - this will block until all # Wait until PG is ready - this will block until all
# requested resources are available, and will timeout # requested resources are available, and will timeout
# if they cannot be provisioned. # if they cannot be provisioned.
ray.get(current_placement_group.ready(), timeout=1800) ray.get(current_placement_group.ready(), timeout=1800)
return None, current_placement_group return current_placement_group
from typing import List, Optional from typing import Optional
import torch import torch
...@@ -16,28 +16,27 @@ class InputMetadata: ...@@ -16,28 +16,27 @@ class InputMetadata:
def __init__( def __init__(
self, self,
prompt_lens: List[int], is_prompt: bool,
slot_mapping: torch.Tensor, slot_mapping: torch.Tensor,
max_context_len: Optional[int], max_context_len: Optional[int],
context_lens: Optional[torch.Tensor], context_lens: Optional[torch.Tensor],
block_tables: Optional[torch.Tensor], block_tables: Optional[torch.Tensor],
use_cuda_graph: bool, use_cuda_graph: bool,
) -> None: ) -> None:
self.prompt_lens = prompt_lens self.is_prompt = is_prompt
self.max_context_len = max_context_len self.max_context_len = max_context_len
self.slot_mapping = slot_mapping self.slot_mapping = slot_mapping
self.context_lens = context_lens self.context_lens = context_lens
self.block_tables = block_tables self.block_tables = block_tables
self.use_cuda_graph = use_cuda_graph self.use_cuda_graph = use_cuda_graph
self.is_prompt = len(prompt_lens) > 0
# Set during the execution of the first attention op. # Set during the execution of the first attention op.
# FIXME(woosuk): This is a hack. # FIXME(woosuk): This is a hack.
self.attn_bias = None self.attn_bias = None
def __repr__(self) -> str: def __repr__(self) -> str:
return ("InputMetadata(" return ("InputMetadata("
f"prompt_lens={self.prompt_lens}, " f"is_prompt={self.is_prompt}, "
f"max_context_len={self.max_context_len}, " f"max_context_len={self.max_context_len}, "
f"slot_mapping={self.slot_mapping}, " f"slot_mapping={self.slot_mapping}, "
f"context_lens={self.context_lens}, " f"context_lens={self.context_lens}, "
......
...@@ -5,7 +5,7 @@ import torch ...@@ -5,7 +5,7 @@ import torch
import torch.nn as nn import torch.nn as nn
from vllm.model_executor.parallel_utils.communication_op import ( from vllm.model_executor.parallel_utils.communication_op import (
tensor_model_parallel_all_gather) tensor_model_parallel_gather)
from vllm.model_executor.sampling_metadata import SamplingMetadata, SamplingTensors from vllm.model_executor.sampling_metadata import SamplingMetadata, SamplingTensors
from vllm.sampling_params import SamplingParams, SamplingType from vllm.sampling_params import SamplingParams, SamplingType
from vllm.sequence import (PromptLogprobs, SampleLogprobs, SamplerOutput, from vllm.sequence import (PromptLogprobs, SampleLogprobs, SamplerOutput,
...@@ -37,7 +37,7 @@ class Sampler(nn.Module): ...@@ -37,7 +37,7 @@ class Sampler(nn.Module):
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
embedding_bias: Optional[torch.Tensor] = None, embedding_bias: Optional[torch.Tensor] = None,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
# Get the hidden states that we use for sampling. # Get the hidden states that we use for sampling.
hidden_states = _prune_hidden_states(hidden_states, sampling_metadata) hidden_states = _prune_hidden_states(hidden_states, sampling_metadata)
...@@ -45,6 +45,14 @@ class Sampler(nn.Module): ...@@ -45,6 +45,14 @@ class Sampler(nn.Module):
logits = _get_logits(hidden_states, embedding, embedding_bias, logits = _get_logits(hidden_states, embedding, embedding_bias,
self.vocab_size) self.vocab_size)
# Only perform sampling in the driver worker.
# Note: `_get_logits` is still distributed across TP workers because
# the `embedding` weight is distributed across TP workers.
# TODO(zhuohan): Change the get_logits part to a separate stage.
if not sampling_metadata.perform_sampling:
return None
assert logits is not None
_, vocab_size = logits.shape _, vocab_size = logits.shape
# Apply logits processors (if any). # Apply logits processors (if any).
...@@ -92,14 +100,15 @@ class Sampler(nn.Module): ...@@ -92,14 +100,15 @@ class Sampler(nn.Module):
def _get_logits(hidden_states: torch.Tensor, embedding: torch.Tensor, def _get_logits(hidden_states: torch.Tensor, embedding: torch.Tensor,
embedding_bias: Optional[torch.Tensor], embedding_bias: Optional[torch.Tensor],
vocab_size: int) -> torch.Tensor: vocab_size: int) -> Optional[torch.Tensor]:
# Get the logits for the next tokens. # Get the logits for the next tokens.
logits = torch.matmul(hidden_states, embedding.t()) logits = torch.matmul(hidden_states, embedding.t())
if embedding_bias is not None: if embedding_bias is not None:
logits += embedding_bias logits += embedding_bias
logits = tensor_model_parallel_all_gather(logits) logits = tensor_model_parallel_gather(logits)
# Remove paddings in vocab (if any). # Remove paddings in vocab (if any).
logits = logits[:, :vocab_size] if logits is not None:
logits = logits[:, :vocab_size]
return logits return logits
......
...@@ -298,7 +298,7 @@ class AquilaForCausalLM(nn.Module): ...@@ -298,7 +298,7 @@ class AquilaForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states, next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -313,7 +313,7 @@ class BaiChuanBaseForCausalLM(nn.Module): ...@@ -313,7 +313,7 @@ class BaiChuanBaseForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states, next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -290,7 +290,7 @@ class BloomForCausalLM(nn.Module): ...@@ -290,7 +290,7 @@ class BloomForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head_weight, hidden_states, next_tokens = self.sampler(self.lm_head_weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -349,7 +349,7 @@ class ChatGLMForCausalLM(nn.Module): ...@@ -349,7 +349,7 @@ class ChatGLMForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head_weight, hidden_states, next_tokens = self.sampler(self.lm_head_weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -394,7 +394,7 @@ class FalconForCausalLM(nn.Module): ...@@ -394,7 +394,7 @@ class FalconForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states, next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -235,7 +235,7 @@ class GPT2LMHeadModel(nn.Module): ...@@ -235,7 +235,7 @@ class GPT2LMHeadModel(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head_weight, hidden_states, next_tokens = self.sampler(self.lm_head_weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -254,7 +254,7 @@ class GPTBigCodeForCausalLM(nn.Module): ...@@ -254,7 +254,7 @@ class GPTBigCodeForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head_weight, hidden_states, next_tokens = self.sampler(self.lm_head_weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
...@@ -240,7 +240,7 @@ class GPTJForCausalLM(nn.Module): ...@@ -240,7 +240,7 @@ class GPTJForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states, next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata, self.lm_head.bias) sampling_metadata, self.lm_head.bias)
return next_tokens return next_tokens
......
...@@ -255,7 +255,7 @@ class GPTNeoXForCausalLM(nn.Module): ...@@ -255,7 +255,7 @@ class GPTNeoXForCausalLM(nn.Module):
self, self,
hidden_states: torch.Tensor, hidden_states: torch.Tensor,
sampling_metadata: SamplingMetadata, sampling_metadata: SamplingMetadata,
) -> SamplerOutput: ) -> Optional[SamplerOutput]:
next_tokens = self.sampler(self.embed_out.weight, hidden_states, next_tokens = self.sampler(self.embed_out.weight, hidden_states,
sampling_metadata) sampling_metadata)
return next_tokens return next_tokens
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment