diff --git a/benchmarks/disagg_benchmarks/disagg_overhead_benchmark.sh b/benchmarks/disagg_benchmarks/disagg_overhead_benchmark.sh deleted file mode 100644 index d683835db9..0000000000 --- a/benchmarks/disagg_benchmarks/disagg_overhead_benchmark.sh +++ /dev/null @@ -1,143 +0,0 @@ -#!/bin/bash - -# benchmark the overhead of disaggregated prefill. -# methodology: -# - send all request to prefill vLLM instance. It will buffer KV cache. -# - then send all request to decode instance. -# - The TTFT of decode instance is the overhead. - -set -ex - -kill_gpu_processes() { - # kill all processes on GPU. - pgrep pt_main_thread | xargs -r kill -9 - pgrep python3 | xargs -r kill -9 - # vLLM now names the process with VLLM prefix after https://github.com/vllm-project/vllm/pull/21445 - pgrep VLLM | xargs -r kill -9 - sleep 10 - - # remove vllm config file - rm -rf ~/.config/vllm - - # Print the GPU memory usage - # so that we know if all GPU processes are killed. - gpu_memory_usage=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i 0) - # The memory usage should be 0 MB. - echo "GPU 0 Memory Usage: $gpu_memory_usage MB" -} - -wait_for_server() { - # wait for vllm server to start - # return 1 if vllm server crashes - local port=$1 - timeout 1200 bash -c " - until curl -s localhost:${port}/v1/completions > /dev/null; do - sleep 1 - done" && return 0 || return 1 -} - - -benchmark() { - - export VLLM_LOGGING_LEVEL=DEBUG - export VLLM_HOST_IP=$(hostname -I | awk '{print $1}') - - # compare chunked prefill with disaggregated prefill - - results_folder="./results" - model="meta-llama/Meta-Llama-3.1-8B-Instruct" - dataset_name="sonnet" - dataset_path="../sonnet_4x.txt" - num_prompts=10 - qps=$1 - prefix_len=50 - input_len=2048 - output_len=$2 - - - CUDA_VISIBLE_DEVICES=0 vllm serve $model \ - --port 8100 \ - --max-model-len 10000 \ - --gpu-memory-utilization 0.6 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_rank":0,"kv_parallel_size":2,"kv_buffer_size":5e9}' & - - - CUDA_VISIBLE_DEVICES=1 vllm serve $model \ - --port 8200 \ - --max-model-len 10000 \ - --gpu-memory-utilization 0.6 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_rank":1,"kv_parallel_size":2,"kv_buffer_size":5e9}' & - - wait_for_server 8100 - wait_for_server 8200 - - # let the prefill instance finish prefill - vllm bench serve \ - --backend vllm \ - --model $model \ - --dataset-name $dataset_name \ - --dataset-path $dataset_path \ - --sonnet-input-len $input_len \ - --sonnet-output-len "$output_len" \ - --sonnet-prefix-len $prefix_len \ - --num-prompts $num_prompts \ - --port 8100 \ - --save-result \ - --result-dir $results_folder \ - --result-filename disagg_prefill_tp1.json \ - --request-rate "inf" - - - # send the request to decode. - # The TTFT of this command will be the overhead of disagg prefill impl. - vllm bench serve \ - --backend vllm \ - --model $model \ - --dataset-name $dataset_name \ - --dataset-path $dataset_path \ - --sonnet-input-len $input_len \ - --sonnet-output-len "$output_len" \ - --sonnet-prefix-len $prefix_len \ - --num-prompts $num_prompts \ - --port 8200 \ - --save-result \ - --result-dir $results_folder \ - --result-filename disagg_prefill_tp1_overhead.json \ - --request-rate "$qps" - kill_gpu_processes - -} - - -main() { - - (which wget && which curl) || (apt-get update && apt-get install -y wget curl) - (which jq) || (apt-get -y install jq) - (which socat) || (apt-get -y install socat) - - pip install quart httpx datasets - - cd "$(dirname "$0")" - - cd .. - # create sonnet-4x.txt - echo "" > sonnet_4x.txt - for _ in {1..4} - do - cat sonnet.txt >> sonnet_4x.txt - done - cd disagg_benchmarks - - rm -rf results - mkdir results - - default_qps=1 - default_output_len=1 - benchmark $default_qps $default_output_len - -} - - -main "$@" diff --git a/benchmarks/disagg_benchmarks/disagg_performance_benchmark.sh b/benchmarks/disagg_benchmarks/disagg_performance_benchmark.sh deleted file mode 100644 index 35c86cc845..0000000000 --- a/benchmarks/disagg_benchmarks/disagg_performance_benchmark.sh +++ /dev/null @@ -1,157 +0,0 @@ -#!/bin/bash - -# Requirement: 2x GPUs. - - -# Model: meta-llama/Meta-Llama-3.1-8B-Instruct -# Query: 1024 input tokens, 6 output tokens, QPS 2/4/6/8, 100 requests -# Resource: 2x GPU -# Approaches: -# 2. Chunked prefill: 2 vllm instance with tp=4, equivalent to 1 tp=4 instance with QPS 4 -# 3. Disaggregated prefill: 1 prefilling instance and 1 decoding instance -# Prefilling instance: max_output_token=1 -# Decoding instance: force the input tokens be the same across requests to bypass prefilling - -set -ex - -kill_gpu_processes() { - # kill all processes on GPU. - pgrep pt_main_thread | xargs -r kill -9 - pgrep python3 | xargs -r kill -9 - # vLLM now names the process with VLLM prefix after https://github.com/vllm-project/vllm/pull/21445 - pgrep VLLM | xargs -r kill -9 - for port in 8000 8100 8200; do lsof -t -i:$port | xargs -r kill -9; done - sleep 1 -} - -wait_for_server() { - # wait for vllm server to start - # return 1 if vllm server crashes - local port=$1 - timeout 1200 bash -c " - until curl -s localhost:${port}/v1/completions > /dev/null; do - sleep 1 - done" && return 0 || return 1 -} - - -launch_chunked_prefill() { - model="meta-llama/Meta-Llama-3.1-8B-Instruct" - # disagg prefill - CUDA_VISIBLE_DEVICES=0 vllm serve $model \ - --port 8100 \ - --max-model-len 10000 \ - --enable-chunked-prefill \ - --gpu-memory-utilization 0.6 & - CUDA_VISIBLE_DEVICES=1 vllm serve $model \ - --port 8200 \ - --max-model-len 10000 \ - --enable-chunked-prefill \ - --gpu-memory-utilization 0.6 & - wait_for_server 8100 - wait_for_server 8200 - python3 round_robin_proxy.py & - sleep 1 -} - - -launch_disagg_prefill() { - model="meta-llama/Meta-Llama-3.1-8B-Instruct" - # disagg prefill - CUDA_VISIBLE_DEVICES=0 vllm serve $model \ - --port 8100 \ - --max-model-len 10000 \ - --gpu-memory-utilization 0.6 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_rank":0,"kv_parallel_size":2,"kv_buffer_size":5e9}' & - - CUDA_VISIBLE_DEVICES=1 vllm serve $model \ - --port 8200 \ - --max-model-len 10000 \ - --gpu-memory-utilization 0.6 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_rank":1,"kv_parallel_size":2,"kv_buffer_size":5e9}' & - - wait_for_server 8100 - wait_for_server 8200 - python3 disagg_prefill_proxy_server.py & - sleep 1 -} - - -benchmark() { - results_folder="./results" - model="meta-llama/Meta-Llama-3.1-8B-Instruct" - dataset_name="sonnet" - dataset_path="../sonnet_4x.txt" - num_prompts=100 - qps=$1 - prefix_len=50 - input_len=1024 - output_len=$2 - tag=$3 - - vllm bench serve \ - --backend vllm \ - --model $model \ - --dataset-name $dataset_name \ - --dataset-path $dataset_path \ - --sonnet-input-len $input_len \ - --sonnet-output-len "$output_len" \ - --sonnet-prefix-len $prefix_len \ - --num-prompts $num_prompts \ - --port 8000 \ - --save-result \ - --result-dir $results_folder \ - --result-filename "$tag"-qps-"$qps".json \ - --request-rate "$qps" - - sleep 2 -} - - -main() { - - (which wget && which curl) || (apt-get update && apt-get install -y wget curl) - (which jq) || (apt-get -y install jq) - (which socat) || (apt-get -y install socat) - (which lsof) || (apt-get -y install lsof) - - pip install quart httpx matplotlib aiohttp datasets - - cd "$(dirname "$0")" - - cd .. - # create sonnet-4x.txt so that we can sample 2048 tokens for input - echo "" > sonnet_4x.txt - for _ in {1..4} - do - cat sonnet.txt >> sonnet_4x.txt - done - cd disagg_benchmarks - - rm -rf results - mkdir results - - default_output_len=6 - - export VLLM_HOST_IP=$(hostname -I | awk '{print $1}') - - launch_chunked_prefill - for qps in 2 4 6 8; do - benchmark $qps $default_output_len chunked_prefill - done - kill_gpu_processes - - launch_disagg_prefill - for qps in 2 4 6 8; do - benchmark $qps $default_output_len disagg_prefill - done - kill_gpu_processes - - python3 visualize_benchmark_results.py - -} - - -main "$@" diff --git a/benchmarks/disagg_benchmarks/disagg_prefill_proxy_server.py b/benchmarks/disagg_benchmarks/disagg_prefill_proxy_server.py deleted file mode 100644 index d072c03c44..0000000000 --- a/benchmarks/disagg_benchmarks/disagg_prefill_proxy_server.py +++ /dev/null @@ -1,260 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import argparse -import asyncio -import logging -import os -import time -import uuid -from urllib.parse import urlparse - -import aiohttp -from quart import Quart, Response, make_response, request - -# Configure logging -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - - -def parse_args(): - """parse command line arguments""" - parser = argparse.ArgumentParser(description="vLLM P/D disaggregation proxy server") - - # Add args - parser.add_argument( - "--timeout", - type=float, - default=6 * 60 * 60, - help="Timeout for backend service requests in seconds (default: 21600)", - ) - parser.add_argument( - "--port", - type=int, - default=8000, - help="Port to run the server on (default: 8000)", - ) - parser.add_argument( - "--prefill-url", - type=str, - default="http://localhost:8100", - help="Prefill service base URL (protocol + host[:port])", - ) - parser.add_argument( - "--decode-url", - type=str, - default="http://localhost:8200", - help="Decode service base URL (protocol + host[:port])", - ) - parser.add_argument( - "--kv-host", - type=str, - default="localhost", - help="Hostname or IP used by KV transfer (default: localhost)", - ) - parser.add_argument( - "--prefill-kv-port", - type=int, - default=14579, - help="Prefill KV port (default: 14579)", - ) - parser.add_argument( - "--decode-kv-port", - type=int, - default=14580, - help="Decode KV port (default: 14580)", - ) - - return parser.parse_args() - - -def main(): - """parse command line arguments""" - args = parse_args() - - # Initialize configuration using command line parameters - AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=args.timeout) - PREFILL_SERVICE_URL = args.prefill_url - DECODE_SERVICE_URL = args.decode_url - PORT = args.port - - PREFILL_KV_ADDR = f"{args.kv_host}:{args.prefill_kv_port}" - DECODE_KV_ADDR = f"{args.kv_host}:{args.decode_kv_port}" - - logger.info( - "Proxy resolved KV addresses -> prefill: %s, decode: %s", - PREFILL_KV_ADDR, - DECODE_KV_ADDR, - ) - - app = Quart(__name__) - - # Attach the configuration object to the application instance so helper - # coroutines can read the resolved backend URLs and timeouts without using - # globals. - app.config.update( - { - "AIOHTTP_TIMEOUT": AIOHTTP_TIMEOUT, - "PREFILL_SERVICE_URL": PREFILL_SERVICE_URL, - "DECODE_SERVICE_URL": DECODE_SERVICE_URL, - "PREFILL_KV_ADDR": PREFILL_KV_ADDR, - "DECODE_KV_ADDR": DECODE_KV_ADDR, - } - ) - - def _normalize_base_url(url: str) -> str: - """Remove any trailing slash so path joins behave predictably.""" - return url.rstrip("/") - - def _get_host_port(url: str) -> str: - """Return the hostname:port portion for logging and KV headers.""" - parsed = urlparse(url) - host = parsed.hostname or "localhost" - port = parsed.port - if port is None: - port = 80 if parsed.scheme == "http" else 443 - return f"{host}:{port}" - - PREFILL_BASE = _normalize_base_url(PREFILL_SERVICE_URL) - DECODE_BASE = _normalize_base_url(DECODE_SERVICE_URL) - KV_TARGET = _get_host_port(DECODE_SERVICE_URL) - - def _build_headers(request_id: str) -> dict[str, str]: - """Construct the headers expected by vLLM's P2P disagg connector.""" - headers: dict[str, str] = {"X-Request-Id": request_id, "X-KV-Target": KV_TARGET} - api_key = os.environ.get("OPENAI_API_KEY") - if api_key: - headers["Authorization"] = f"Bearer {api_key}" - return headers - - async def _run_prefill( - request_path: str, - payload: dict, - headers: dict[str, str], - request_id: str, - ): - url = f"{PREFILL_BASE}{request_path}" - start_ts = time.perf_counter() - logger.info("[prefill] start request_id=%s url=%s", request_id, url) - try: - async with ( - aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session, - session.post(url=url, json=payload, headers=headers) as resp, - ): - if resp.status != 200: - error_text = await resp.text() - raise RuntimeError( - f"Prefill backend error {resp.status}: {error_text}" - ) - await resp.read() - logger.info( - "[prefill] done request_id=%s status=%s elapsed=%.2fs", - request_id, - resp.status, - time.perf_counter() - start_ts, - ) - except asyncio.TimeoutError as exc: - raise RuntimeError(f"Prefill service timeout at {url}") from exc - except aiohttp.ClientError as exc: - raise RuntimeError(f"Prefill service unavailable at {url}") from exc - - async def _stream_decode( - request_path: str, - payload: dict, - headers: dict[str, str], - request_id: str, - ): - url = f"{DECODE_BASE}{request_path}" - # Stream tokens from the decode service once the prefill stage has - # materialized KV caches on the target workers. - logger.info("[decode] start request_id=%s url=%s", request_id, url) - try: - async with ( - aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session, - session.post(url=url, json=payload, headers=headers) as resp, - ): - if resp.status != 200: - error_text = await resp.text() - logger.error( - "Decode backend error %s - %s", resp.status, error_text - ) - err_msg = ( - '{"error": "Decode backend error ' + str(resp.status) + '"}' - ) - yield err_msg.encode() - return - logger.info( - "[decode] streaming response request_id=%s status=%s", - request_id, - resp.status, - ) - async for chunk_bytes in resp.content.iter_chunked(1024): - yield chunk_bytes - logger.info("[decode] finished streaming request_id=%s", request_id) - except asyncio.TimeoutError: - logger.error("Decode service timeout at %s", url) - yield b'{"error": "Decode service timeout"}' - except aiohttp.ClientError as exc: - logger.error("Decode service error at %s: %s", url, exc) - yield b'{"error": "Decode service unavailable"}' - - async def process_request(): - """Process a single request through prefill and decode stages""" - try: - original_request_data = await request.get_json() - - # Create prefill request (max_tokens=1) - prefill_request = original_request_data.copy() - prefill_request["max_tokens"] = 1 - if "max_completion_tokens" in prefill_request: - prefill_request["max_completion_tokens"] = 1 - - # Execute prefill stage - # The request id encodes both KV socket addresses so the backend can - # shuttle tensors directly via NCCL once the prefill response - # completes. - request_id = ( - f"___prefill_addr_{PREFILL_KV_ADDR}___decode_addr_" - f"{DECODE_KV_ADDR}_{uuid.uuid4().hex}" - ) - - headers = _build_headers(request_id) - await _run_prefill(request.path, prefill_request, headers, request_id) - - # Execute decode stage and stream response - # Pass the unmodified user request so the decode phase can continue - # sampling with the already-populated KV cache. - generator = _stream_decode( - request.path, original_request_data, headers, request_id - ) - response = await make_response(generator) - response.timeout = None # Disable timeout for streaming response - return response - - except Exception: - logger.exception("Error processing request") - return Response( - response=b'{"error": "Internal server error"}', - status=500, - content_type="application/json", - ) - - @app.route("/v1/completions", methods=["POST"]) - async def handle_request(): - """Handle incoming API requests with concurrency and rate limiting""" - try: - return await process_request() - except asyncio.CancelledError: - logger.warning("Request cancelled") - return Response( - response=b'{"error": "Request cancelled"}', - status=503, - content_type="application/json", - ) - - # Start the Quart server with host can be set to 0.0.0.0 - app.run(port=PORT) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/disagg_benchmarks/round_robin_proxy.py b/benchmarks/disagg_benchmarks/round_robin_proxy.py deleted file mode 100644 index b1df2f2558..0000000000 --- a/benchmarks/disagg_benchmarks/round_robin_proxy.py +++ /dev/null @@ -1,63 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import asyncio -import itertools - -import aiohttp -from aiohttp import web - - -class RoundRobinProxy: - def __init__(self, target_ports): - self.target_ports = target_ports - self.port_cycle = itertools.cycle(self.target_ports) - - async def handle_request(self, request): - target_port = next(self.port_cycle) - target_url = f"http://localhost:{target_port}{request.path_qs}" - - async with aiohttp.ClientSession() as session: - try: - # Forward the request - async with session.request( - method=request.method, - url=target_url, - headers=request.headers, - data=request.content, - ) as response: - # Start sending the response - resp = web.StreamResponse( - status=response.status, headers=response.headers - ) - await resp.prepare(request) - - # Stream the response content - async for chunk in response.content.iter_any(): - await resp.write(chunk) - - await resp.write_eof() - return resp - - except Exception as e: - return web.Response(text=f"Error: {str(e)}", status=500) - - -async def main(): - proxy = RoundRobinProxy([8100, 8200]) - app = web.Application() - app.router.add_route("*", "/{path:.*}", proxy.handle_request) - - runner = web.AppRunner(app) - await runner.setup() - site = web.TCPSite(runner, "localhost", 8000) - await site.start() - - print("Proxy server started on http://localhost:8000") - - # Keep the server running - await asyncio.Event().wait() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/benchmarks/disagg_benchmarks/visualize_benchmark_results.py b/benchmarks/disagg_benchmarks/visualize_benchmark_results.py deleted file mode 100644 index 74fa56d076..0000000000 --- a/benchmarks/disagg_benchmarks/visualize_benchmark_results.py +++ /dev/null @@ -1,47 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import json - -import matplotlib.pyplot as plt -import pandas as pd - -if __name__ == "__main__": - data = [] - for name in ["disagg_prefill", "chunked_prefill"]: - for qps in [2, 4, 6, 8]: - with open(f"results/{name}-qps-{qps}.json") as f: - x = json.load(f) - x["name"] = name - x["qps"] = qps - data.append(x) - - df = pd.DataFrame.from_dict(data) - dis_df = df[df["name"] == "disagg_prefill"] - chu_df = df[df["name"] == "chunked_prefill"] - - plt.style.use("bmh") - plt.rcParams["font.size"] = 20 - - for key in [ - "mean_ttft_ms", - "median_ttft_ms", - "p99_ttft_ms", - "mean_itl_ms", - "median_itl_ms", - "p99_itl_ms", - ]: - fig, ax = plt.subplots(figsize=(11, 7)) - plt.plot( - dis_df["qps"], dis_df[key], label="disagg_prefill", marker="o", linewidth=4 - ) - plt.plot( - chu_df["qps"], chu_df[key], label="chunked_prefill", marker="o", linewidth=4 - ) - ax.legend() - - ax.set_xlabel("QPS") - ax.set_ylabel(key) - ax.set_ylim(bottom=0) - fig.savefig(f"results/{key}.png") - plt.close(fig) diff --git a/docs/design/p2p_nccl_connector.md b/docs/design/p2p_nccl_connector.md deleted file mode 100644 index c1de955b6f..0000000000 --- a/docs/design/p2p_nccl_connector.md +++ /dev/null @@ -1,319 +0,0 @@ -# P2P NCCL Connector - -An implementation of xPyD with dynamic scaling based on point-to-point communication, partly inspired by Dynamo. - -## Detailed Design - -### Overall Process - -As shown in Figure 1, the overall process of this **PD disaggregation** solution is described through a request flow: - -1. The client sends an HTTP request to the Proxy/Router's `/v1/completions` interface. -2. The Proxy/Router selects a **1P1D (1 Prefill instance + 1 Decode instance)** through either through round-robin or random selection, generates a `request_id` (rules to be introduced later), modifies the `max_tokens` in the HTTP request message to **1**, and then forwards the request to the **P instance**. -3. Immediately afterward, the Proxy/Router forwards the **original HTTP request** to the **D instance**. -4. The **P instance** performs **Prefill** and then **actively sends the generated KV cache** to the D instance (using **PUT_ASYNC** mode). The D instance's `zmq_addr` can be resolved through the `request_id`. -5. The **D instance** has a **dedicated thread** for receiving the KV cache (to avoid blocking the main process). The received KV cache is saved into the **GPU memory buffer**, the size of which is determined by the vLLM startup parameter `kv_buffer_size`. When the GPU buffer is full, the KV cache is stored in the **local Tensor memory pool**. -6. During the **Decode**, the D instance's main process retrieves the KV cache (transmitted by the P instance) from either the **GPU buffer** or the **memory pool**, thereby **skipping Prefill**. -7. After completing **Decode**, the D instance returns the result to the **Proxy/Router**, which then forwards it to the **client**. - -![image1](https://github.com/user-attachments/assets/fb01bde6-755b-49f7-ad45-48a94b1e10a7) - -### Proxy/Router (Demo) - -A simple HTTP service acts as the entry point for client requests and starts a background thread to listen for P/D instances reporting their HTTP IP and PORT, as well as ZMQ IP and PORT. It maintains a dictionary of `http_addr -> zmq_addr`. The `http_addr` is the IP:PORT for the vLLM instance's request, while the `zmq_addr` is the address for KV cache handshake and metadata reception. - -The Proxy/Router is responsible for selecting 1P1D based on the characteristics of the client request, such as the prompt, and generating a corresponding `request_id`, for example: - -```text -cmpl-___prefill_addr_10.0.1.2:21001___decode_addr_10.0.1.3:22001_93923d63113b4b338973f24d19d4bf11-0 -``` - -Currently, to quickly verify whether xPyD can work, a round-robin selection of 1P1D is used. In the future, it is planned to use a trie combined with the load status of instances to select appropriate P and D. - -Each P/D instance periodically sends a heartbeat packet to the Proxy/Router (currently every 3 seconds) to register (i.e., report `http_addr -> zmq_addr`) and keep the connection alive. If an instance crashes and fails to send a ping for a certain period of time, the Proxy/Router will remove the timed-out instance (this feature has not yet been developed). - -### KV Cache Transfer Methods - -There are three methods for KVCache transfer: PUT, GET, and PUT_ASYNC. These methods can be specified using the `--kv-transfer-config` and `kv_connector_extra_config` parameters, specifically through the `send_type` field. Both PUT and PUT_ASYNC involve the P instance actively sending KVCache to the D instance. The difference is that PUT is a synchronous transfer method that blocks the main process, while PUT_ASYNC is an asynchronous transfer method. PUT_ASYNC uses a dedicated thread for sending KVCache, which means it does not block the main process. In contrast, the GET method involves the P instance saving the KVCache to the memory buffer after computing the prefill. The D instance then actively retrieves the computed KVCache from the P instance once it has allocated space for the KVCache. - -Experimental results have shown that the performance of these methods, from highest to lowest, is as follows: PUT_ASYNC → GET → PUT. - -### P2P Communication via ZMQ & NCCL - -As long as the address of the counterpart is known, point-to-point KV cache transfer (using NCCL) can be performed, without being constrained by rank and world size. To support dynamic scaling (expansion and contraction) of instances with PD disaggregation. This means that adding or removing P/D instances does not require a full system restart. - -Each P/D instance only needs to create a single `P2pNcclEngine` instance. This instance maintains a ZMQ Server, which runs a dedicated thread to listen on the `zmq_addr` address and receive control flow requests from other instances. These requests include requests to establish an NCCL connection and requests to send KVCache metadata (such as tensor shapes and data types). However, it does not actually transmit the KVCache data itself. - -When a P instance and a D instance transmit KVCache for the first time, they need to establish a ZMQ connection and an NCCL group. For subsequent KVCache transmissions, this ZMQ connection and NCCL group are reused. The NCCL group consists of only two ranks, meaning the world size is equal to 2. This design is intended to support dynamic scaling, which means that adding or removing P/D instances does not require a full system restart. As long as the address of the counterpart is known, point-to-point KVCache transmission can be performed, without being restricted by rank or world size. - -### NCCL Group Topology - -Currently, only symmetric TP (Tensor Parallelism) methods are supported for KVCache transmission. Asymmetric TP and PP (Pipeline Parallelism) methods will be supported in the future. Figure 2 illustrates the 1P2D setup, where each instance has a TP (Tensor Parallelism) degree of 2. There are a total of 7 NCCL groups: three vLLM instances each have one NCCL group with TP=2. Additionally, the 0th GPU card of the P instance establishes an NCCL group with the 0th GPU card of each D instance. Similarly, the 1st GPU card of the P instance establishes an NCCL group with the 1st GPU card of each D instance. - -![image2](https://github.com/user-attachments/assets/837e61d6-365e-4cbf-8640-6dd7ab295b36) - -Each NCCL group occupies a certain amount of GPU memory buffer for communication, the size of which is primarily influenced by the `NCCL_MAX_NCHANNELS` environment variable. When `NCCL_MAX_NCHANNELS=16`, an NCCL group typically occupies 100MB, while when `NCCL_MAX_NCHANNELS=8`, it usually takes up 52MB. For large-scale xPyD configurations—such as DeepSeek's 96P144D—this implementation is currently not feasible. Moving forward, we are considering using RDMA for point-to-point communication and are also keeping an eye on UCCL. - -### GPU Memory Buffer and Tensor Memory Pool - -The trade-off in the size of the memory buffer is as follows: For P instances, the memory buffer is not required in PUT and PUT_ASYNC modes, but it is necessary in GET mode. For D instances, a memory buffer is needed in all three modes. The memory buffer for D instances should not be too large. Similarly, for P instances in GET mode, the memory buffer should also not be too large. The memory buffer of D instances is used to temporarily store KVCache sent by P instances. If it is too large, it will reduce the KVCache space available for normal inference by D instances, thereby decreasing the inference batch size and ultimately leading to a reduction in output throughput. The size of the memory buffer is configured by the parameter `kv_buffer_size`, measured in bytes, and is typically set to 5%~10% of the memory size. - -If the `--max-num-seqs` parameter for P instances is set to a large value, due to the large batch size, P instances will generate a large amount of KVCache simultaneously. This may exceed the capacity of the memory buffer of D instances, resulting in KVCache loss. Once KVCache is lost, D instances need to recompute Prefill, which is equivalent to performing Prefill twice. Consequently, the time-to-first-token (TTFT) will significantly increase, leading to degraded performance. - -To address the above issues, I have designed and developed a local Tensor memory pool for storing KVCache, inspired by the buddy system used in Linux memory modules. Since the memory is sufficiently large, typically in the TB range on servers, there is no need to consider prefix caching or using block-based designs to reuse memory, thereby saving space. When the memory buffer is insufficient, KVCache can be directly stored in the Tensor memory pool, and D instances can subsequently retrieve KVCache from it. The read and write speed is that of PCIe, with PCIe 4.0 having a speed of approximately 21 GB/s, which is usually faster than the Prefill speed. Otherwise, solutions like Mooncake and lmcache would not be necessary. The Tensor memory pool acts as a flood diversion area, typically unused except during sudden traffic surges. In the worst-case scenario, my solution performs no worse than the normal situation with a Cache store. - -## Install vLLM - -```shell -pip install "vllm>=0.9.2" -``` - -## Run xPyD - -### Instructions - -- The following examples are run on an A800 (80GB) device, using the Meta-Llama-3.1-8B-Instruct model. -- Pay attention to the setting of the `kv_buffer_size` (in bytes). The empirical value is 10% of the GPU memory size. This is related to the kvcache size. If it is too small, the GPU memory buffer for temporarily storing the received kvcache will overflow, causing the kvcache to be stored in the tensor memory pool, which increases latency. If it is too large, the kvcache available for inference will be reduced, leading to a smaller batch size and decreased throughput. -- For Prefill instances, when using non-GET mode, the `kv_buffer_size` can be set to 1, as Prefill currently does not need to receive kvcache. However, when using GET mode, a larger `kv_buffer_size` is required because it needs to store the kvcache sent to the D instance. -- You may need to modify the `kv_buffer_size` and `port` in the following commands (if there is a conflict). -- `PUT_ASYNC` offers the best performance and should be prioritized. -- The `--port` must be consistent with the `http_port` in the `--kv-transfer-config`. -- The `disagg_proxy_p2p_nccl_xpyd.py` script will use port 10001 (for receiving client requests) and port 30001 (for receiving service discovery from P and D instances). -- The node running the proxy must have `quart` installed. -- Supports multiple nodes; you just need to modify the `proxy_ip` and `proxy_port` in `--kv-transfer-config`. -- In the following examples, it is assumed that **the proxy's IP is 10.0.1.1**. - -### Run 1P3D - -#### Proxy (e.g. 10.0.1.1) - -```shell -cd {your vllm directory}/examples/disaggregated/p2p_nccl_xpyd/ -python3 disagg_proxy_p2p_nccl_xpyd.py & -``` - -#### Prefill1 (e.g. 10.0.1.2 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=0 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20001 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.9 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_buffer_size":"1e1","kv_port":"21001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20001"}}' > /var/vllm.log 2>&1 & - ``` - -#### Decode1 (e.g. 10.0.1.3 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=1 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20002 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.7 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_buffer_size":"8e9","kv_port":"22001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20002"}}' > /var/vllm.log 2>&1 & - ``` - -#### Decode2 (e.g. 10.0.1.4 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=2 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20003 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.7 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_buffer_size":"8e9","kv_port":"23001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20003"}}' > /var/vllm.log 2>&1 & - ``` - -#### Decode3 (e.g. 10.0.1.5 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=3 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20004 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.7 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_buffer_size":"8e9","kv_port":"24001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20004"}}' > /var/vllm.log 2>&1 & - ``` - -### Run 3P1D - -#### Proxy (e.g. 10.0.1.1) - -```shell -cd {your vllm directory}/examples/disaggregated/p2p_nccl_xpyd/ -python3 disagg_proxy_p2p_nccl_xpyd.py & -``` - -#### Prefill1 (e.g. 10.0.1.2 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=0 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20001 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.9 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_buffer_size":"1e1","kv_port":"21001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20001"}}' > /var/vllm.log 2>&1 & - ``` - -#### Prefill2 (e.g. 10.0.1.3 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=1 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20002 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.9 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_buffer_size":"1e1","kv_port":"22001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20002"}}' > /var/vllm.log 2>&1 & - ``` - -#### Prefill3 (e.g. 10.0.1.4 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=2 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20003 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.9 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_buffer_size":"1e1","kv_port":"23001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20003"}}' > /var/vllm.log 2>&1 & - ``` - -#### Decode1 (e.g. 10.0.1.5 or 10.0.1.1) - -??? console "Command" - - ```shell - CUDA_VISIBLE_DEVICES=3 vllm serve {your model directory} \ - --host 0.0.0.0 \ - --port 20004 \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --served-model-name base_model \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.7 \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_buffer_size":"8e9","kv_port":"24001","kv_connector_extra_config":{"proxy_ip":"10.0.1.1","proxy_port":"30001","http_port":"20004"}}' > /var/vllm.log 2>&1 & - ``` - -## Single request - -```shell -curl -X POST -s http://10.0.1.1:10001/v1/completions \ --H "Content-Type: application/json" \ --d '{ - "model": "base_model", - "prompt": "San Francisco is a", - "max_tokens": 10, - "temperature": 0 -}' -``` - -## Benchmark - -??? console "Command" - - ```shell - vllm bench serve \ - --backend vllm \ - --model base_model \ - --tokenizer meta-llama/Llama-3.1-8B-Instruct \ - --dataset-name "random" \ - --host 10.0.1.1 \ - --port 10001 \ - --random-input-len 1024 \ - --random-output-len 1024 \ - --ignore-eos \ - --burstiness 100 \ - --percentile-metrics "ttft,tpot,itl,e2el" \ - --metric-percentiles "90,95,99" \ - --seed $(date +%s) \ - --trust-remote-code \ - --request-rate 3 \ - --num-prompts 1000 - ``` - -## Shut down - -```shell -pgrep python | xargs kill -9 && pkill -f python -``` - -## Test data - -### **Scenario**: 1K input & 200 output tokens, E2E P99 latency ~2s - -![testdata](https://github.com/user-attachments/assets/cef0953b-4567-4bf9-b940-405b92a28eb1) diff --git a/docs/features/disagg_prefill.md b/docs/features/disagg_prefill.md index 1e959c55f1..e7a503dd14 100644 --- a/docs/features/disagg_prefill.md +++ b/docs/features/disagg_prefill.md @@ -29,7 +29,6 @@ Now supports 9 types of connectors: --kv-transfer-config '{"kv_connector":"NixlConnector","kv_role":"kv_both", "kv_buffer_device":"cuda", "kv_connector_extra_config":{"backends":["UCX", "GDS"]}}' ``` -- **P2pNcclConnector**: refer to [examples/disaggregated/p2p_nccl_xpyd/disagg_example_p2p_nccl_xpyd.sh](../../examples/disaggregated/p2p_nccl_xpyd/disagg_example_p2p_nccl_xpyd.sh) for the example usage of P2pNcclConnector disaggregated prefilling. - **MooncakeConnector**: refer to [examples/disaggregated/mooncake_connector/run_mooncake_connector.sh](../../examples/disaggregated/mooncake_connector/run_mooncake_connector.sh) for the example usage of MooncakeConnector disaggregated prefilling. For detailed usage guide, see [MooncakeConnector Usage Guide](mooncake_connector_usage.md). - **MoRIIOConnector** (ROCm only): see [MoRI-IO Usage Guide](moriio_connector_usage.md) for example usage and detailed documentation. - **MultiConnector**: take advantage of the kv_connector_extra_config: dict[str, Any] already present in KVTransferConfig to stash all the connectors we want in an ordered list of kwargs.such as: diff --git a/examples/disaggregated/disaggregated_prefill.py b/examples/disaggregated/disaggregated_prefill.py deleted file mode 100644 index f619fa584f..0000000000 --- a/examples/disaggregated/disaggregated_prefill.py +++ /dev/null @@ -1,127 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -""" -This file demonstrates the example usage of disaggregated prefilling -We will launch 2 vllm instances (GPU 0 for prefill and GPU 1 for decode), -and then transfer the KV cache between them. -""" - -import os -import time -from multiprocessing import Event, Process - -from vllm import LLM, SamplingParams -from vllm.config import KVTransferConfig - - -def run_prefill(prefill_done): - # We use GPU 0 for prefill node. - os.environ["CUDA_VISIBLE_DEVICES"] = "0" - - # The prefill node receives two requests, while the decode node receives - # three requests. So the decode node will only receive the KV Cache for - # requests 1 and 3. The decode node will use the KV Cache of requests 1 - # and 3 and do prefilling on request 2. - prompts = [ - "Hello, my name is", - "Hi, your name is", - # The decode node will actually "prefill" this request. - "Tell me a very long story", - ] - sampling_params = SamplingParams(temperature=0, top_p=0.95, max_tokens=1) - - # Using P2pNcclConnector to transmit KV caches between vLLM instances. - # This instance is the prefill node (kv_producer, rank 0). - # The number of parallel instances for KV cache transfer is set to 2, - # as required for P2pNcclConnector. - ktc = KVTransferConfig( - kv_connector="P2pNcclConnector", - kv_role="kv_producer", - kv_rank=0, - kv_parallel_size=2, - ) - - # Set GPU memory utilization to 0.8 for an A6000 GPU with 40GB - # memory. You may need to adjust the value to fit your GPU. - llm = LLM( - model="meta-llama/Meta-Llama-3.1-8B-Instruct", - kv_transfer_config=ktc, - max_model_len=2000, - gpu_memory_utilization=0.8, - ) - - llm.generate(prompts, sampling_params) - print("Prefill node is finished.") - prefill_done.set() - - # To keep the prefill node running in case the decode node is not done; - # otherwise, the script might exit prematurely, causing incomplete decoding. - try: - while True: - time.sleep(1) - except KeyboardInterrupt: - print("Script stopped by user.") - - -def run_decode(prefill_done): - # We use GPU 1 for decode node. - os.environ["CUDA_VISIBLE_DEVICES"] = "1" - - prompts = [ - "Hello, my name is", - "Hi, your name is", - "Tell me a very long story", - ] - sampling_params = SamplingParams(temperature=0, top_p=0.95) - - # Using P2pNcclConnector to transmit KV caches between vLLM instances. - # This instance is the decode node (kv_consumer, rank 1). - # The number of parallel instances for KV cache transfer is set to 2, - # as required for P2pNcclConnector. - ktc = KVTransferConfig( - kv_connector="P2pNcclConnector", - kv_role="kv_consumer", - kv_rank=1, - kv_parallel_size=2, - ) - - # Set GPU memory utilization to 0.8 for an A6000 GPU with 40GB - # memory. You may need to adjust the value to fit your GPU. - llm = LLM( - model="meta-llama/Meta-Llama-3.1-8B-Instruct", - kv_transfer_config=ktc, - max_model_len=2000, - gpu_memory_utilization=0.8, - ) - - # Wait for the producer to start the pipe - print("Waiting for prefill node to finish...") - prefill_done.wait() - - # At this point when the prefill_done is set, the kv-cache should have been - # transferred to this decode node, so we can start decoding. - outputs = llm.generate(prompts, sampling_params) - for output in outputs: - prompt = output.prompt - generated_text = output.outputs[0].text - print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}") - - -def main(): - prefill_done = Event() - prefill_process = Process(target=run_prefill, args=(prefill_done,)) - decode_process = Process(target=run_decode, args=(prefill_done,)) - - # Start prefill node - prefill_process.start() - - # Start decode node - decode_process.start() - - # Terminate the prefill node when decode is finished - decode_process.join() - prefill_process.terminate() - - -if __name__ == "__main__": - main() diff --git a/examples/disaggregated/disaggregated_prefill.sh b/examples/disaggregated/disaggregated_prefill.sh deleted file mode 100644 index 3022711d7e..0000000000 --- a/examples/disaggregated/disaggregated_prefill.sh +++ /dev/null @@ -1,125 +0,0 @@ -#!/bin/bash -# This file demonstrates the example usage of disaggregated prefilling -# We will launch 2 vllm instances (1 for prefill and 1 for decode), -# and then transfer the KV cache between them. - -set -xe - -echo "🚧🚧 Warning: The usage of disaggregated prefill is experimental and subject to change 🚧🚧" -sleep 1 - -# meta-llama/Meta-Llama-3.1-8B-Instruct or deepseek-ai/DeepSeek-V2-Lite -MODEL_NAME=${HF_MODEL_NAME:-meta-llama/Meta-Llama-3.1-8B-Instruct} - -# Trap the SIGINT signal (triggered by Ctrl+C) -trap 'cleanup' INT - -# Cleanup function -cleanup() { - echo "Caught Ctrl+C, cleaning up..." - # Cleanup commands - pgrep python | xargs kill -9 - pkill -f python - echo "Cleanup complete. Exiting." - exit 0 -} - - -if [[ -z "${VLLM_HOST_IP:-}" ]]; then - export VLLM_HOST_IP=127.0.0.1 - echo "Using default VLLM_HOST_IP=127.0.0.1 (override by exporting VLLM_HOST_IP before running this script)" -else - echo "Using provided VLLM_HOST_IP=${VLLM_HOST_IP}" -fi - - -# install quart first -- required for disagg prefill proxy serve -if python3 -c "import quart" &> /dev/null; then - echo "Quart is already installed." -else - echo "Quart is not installed. Installing..." - python3 -m pip install quart -fi - -# a function that waits vLLM server to start -wait_for_server() { - local port=$1 - timeout 1200 bash -c " - until curl -i localhost:${port}/v1/models > /dev/null; do - sleep 1 - done" && return 0 || return 1 -} - - -# You can also adjust --kv-ip and --kv-port for distributed inference. - -# prefilling instance, which is the KV producer -CUDA_VISIBLE_DEVICES=0 vllm serve "$MODEL_NAME" \ - --host 0.0.0.0 \ - --port 8100 \ - --max-model-len 100 \ - --gpu-memory-utilization 0.8 \ - --trust-remote-code \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_producer","kv_rank":0,"kv_parallel_size":2,"kv_buffer_size":"1e9","kv_port":"14579","kv_connector_extra_config":{"proxy_ip":"'"$VLLM_HOST_IP"'","proxy_port":"30001","http_ip":"'"$VLLM_HOST_IP"'","http_port":"8100","send_type":"PUT_ASYNC"}}' & - -# decoding instance, which is the KV consumer -CUDA_VISIBLE_DEVICES=1 vllm serve "$MODEL_NAME" \ - --host 0.0.0.0 \ - --port 8200 \ - --max-model-len 100 \ - --gpu-memory-utilization 0.8 \ - --trust-remote-code \ - --kv-transfer-config \ - '{"kv_connector":"P2pNcclConnector","kv_role":"kv_consumer","kv_rank":1,"kv_parallel_size":2,"kv_buffer_size":"1e10","kv_port":"14580","kv_connector_extra_config":{"proxy_ip":"'"$VLLM_HOST_IP"'","proxy_port":"30001","http_ip":"'"$VLLM_HOST_IP"'","http_port":"8200","send_type":"PUT_ASYNC"}}' & - -# wait until prefill and decode instances are ready -wait_for_server 8100 -wait_for_server 8200 - -# launch a proxy server that opens the service at port 8000 -# the workflow of this proxy: -# - send the request to prefill vLLM instance (port 8100), change max_tokens -# to 1 -# - after the prefill vLLM finishes prefill, send the request to decode vLLM -# instance -# NOTE: the usage of this API is subject to change --- in the future we will -# introduce "vllm connect" to connect between prefill and decode instances -python3 ../../benchmarks/disagg_benchmarks/disagg_prefill_proxy_server.py & -sleep 1 - -# serve two example requests -output1=$(curl -X POST -s http://localhost:8000/v1/completions \ --H "Content-Type: application/json" \ --d '{ -"model": "'"$MODEL_NAME"'", -"prompt": "San Francisco is a", -"max_tokens": 10, -"temperature": 0 -}') - -output2=$(curl -X POST -s http://localhost:8000/v1/completions \ --H "Content-Type: application/json" \ --d '{ -"model": "'"$MODEL_NAME"'", -"prompt": "Santa Clara is a", -"max_tokens": 10, -"temperature": 0 -}') - - -# Cleanup commands -pgrep python | xargs kill -9 -pkill -f python - -echo "" - -sleep 1 - -# Print the outputs of the curl requests -echo "" -echo "Output of first request: $output1" -echo "Output of second request: $output2" - -echo "🎉🎉 Successfully finished 2 test requests! 🎉🎉" -echo "" diff --git a/examples/disaggregated/p2p_nccl_xpyd/disagg_example_p2p_nccl_xpyd.sh b/examples/disaggregated/p2p_nccl_xpyd/disagg_example_p2p_nccl_xpyd.sh deleted file mode 100644 index 603f9eb915..0000000000 --- a/examples/disaggregated/p2p_nccl_xpyd/disagg_example_p2p_nccl_xpyd.sh +++ /dev/null @@ -1,245 +0,0 @@ -#!/bin/bash - -# ============================================================================= -# vLLM Disaggregated Serving Script - P2P NCCL XpYd Architecture -# ============================================================================= -# This script demonstrates disaggregated prefill and decode serving using -# P2P NCCL communication. The architecture supports various XpYd configurations: -# -# - 1P3D: 1 Prefill server + 3 Decode servers (current default) -# - 3P1D: 3 Prefill servers + 1 Decode server -# - etc. -# -# Configuration can be customized via environment variables: -# MODEL: Model to serve -# PREFILL_GPUS: Comma-separated GPU IDs for prefill servers -# DECODE_GPUS: Comma-separated GPU IDs for decode servers -# PREFILL_PORTS: Comma-separated ports for prefill servers -# DECODE_PORTS: Comma-separated ports for decode servers -# PROXY_PORT: Proxy server port used to setup XpYd connection. -# TIMEOUT_SECONDS: Server startup timeout -# ============================================================================= - -# Configuration - can be overridden via environment variables -MODEL=${MODEL:-meta-llama/Llama-3.1-8B-Instruct} -TIMEOUT_SECONDS=${TIMEOUT_SECONDS:-1200} -PROXY_PORT=${PROXY_PORT:-30001} - -# Default 1P3D configuration (1 Prefill + 3 Decode) -PREFILL_GPUS=${PREFILL_GPUS:-0} -DECODE_GPUS=${DECODE_GPUS:-1,2,3} -PREFILL_PORTS=${PREFILL_PORTS:-20003} -DECODE_PORTS=${DECODE_PORTS:-20005,20007,20009} - -echo "Warning: P2P NCCL disaggregated prefill XpYd support for vLLM v1 is experimental and subject to change." -echo "" -echo "Architecture Configuration:" -echo " Model: $MODEL" -echo " Prefill GPUs: $PREFILL_GPUS, Ports: $PREFILL_PORTS" -echo " Decode GPUs: $DECODE_GPUS, Ports: $DECODE_PORTS" -echo " Proxy Port: $PROXY_PORT" -echo " Timeout: ${TIMEOUT_SECONDS}s" -echo "" - -PIDS=() - -# Switch to the directory of the current script -cd "$(dirname "${BASH_SOURCE[0]}")" - -check_required_files() { - local files=("disagg_proxy_p2p_nccl_xpyd.py") - for file in "${files[@]}"; do - if [[ ! -f "$file" ]]; then - echo "Required file $file not found in $(pwd)" - exit 1 - fi - done -} - -check_hf_token() { - if [ -z "$HF_TOKEN" ]; then - echo "HF_TOKEN is not set. Please set it to your Hugging Face token." - echo "Example: export HF_TOKEN=your_token_here" - exit 1 - fi - if [[ "$HF_TOKEN" != hf_* ]]; then - echo "HF_TOKEN is not a valid Hugging Face token. Please set it to your Hugging Face token." - exit 1 - fi - echo "HF_TOKEN is set and valid." -} - -check_num_gpus() { - # Check if the number of GPUs are >=2 via nvidia-smi - num_gpus=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l) - if [ "$num_gpus" -lt 2 ]; then - echo "You need at least 2 GPUs to run disaggregated prefill." - exit 1 - else - echo "Found $num_gpus GPUs." - fi -} - -ensure_python_library_installed() { - echo "Checking if $1 is installed..." - if ! python3 -c "import $1" > /dev/null 2>&1; then - echo "$1 is not installed. Please install it via pip install $1." - exit 1 - else - echo "$1 is installed." - fi -} - -cleanup() { - echo "Stopping everything…" - trap - INT TERM # prevent re-entrancy - pkill -9 -f "disagg_proxy_p2p_nccl_xpyd.py" - kill -- -$$ # negative PID == "this whole process-group" - wait # reap children so we don't leave zombies - exit 0 -} - -wait_for_server() { - local port=$1 - local timeout_seconds=$TIMEOUT_SECONDS - local start_time=$(date +%s) - - echo "Waiting for server on port $port..." - - while true; do - if curl -s "localhost:${port}/v1/completions" > /dev/null; then - echo "Server on port $port is ready." - return 0 - fi - - local now=$(date +%s) - if (( now - start_time >= timeout_seconds )); then - echo "Timeout waiting for server on port $port" - return 1 - fi - - sleep 1 - done -} - -main() { - check_required_files - check_hf_token - check_num_gpus - ensure_python_library_installed pandas - ensure_python_library_installed datasets - ensure_python_library_installed vllm - ensure_python_library_installed quart - - trap cleanup INT - trap cleanup USR1 - trap cleanup TERM - - echo "Launching disaggregated serving components..." - echo "Please check the log files for detailed output:" - echo " - prefill*.log: Prefill server logs" - echo " - decode*.log: Decode server logs" - echo " - proxy.log: Proxy server log" - - # ============================================================================= - # Launch Proxy Server - # ============================================================================= - echo "" - echo "Starting proxy server on port $PROXY_PORT..." - python3 disagg_proxy_p2p_nccl_xpyd.py & - PIDS+=($!) - - # Parse GPU and port arrays - IFS=',' read -ra PREFILL_GPU_ARRAY <<< "$PREFILL_GPUS" - IFS=',' read -ra DECODE_GPU_ARRAY <<< "$DECODE_GPUS" - IFS=',' read -ra PREFILL_PORT_ARRAY <<< "$PREFILL_PORTS" - IFS=',' read -ra DECODE_PORT_ARRAY <<< "$DECODE_PORTS" - - # ============================================================================= - # Launch Prefill Servers (X Producers) - # ============================================================================= - echo "" - echo "Starting ${#PREFILL_GPU_ARRAY[@]} prefill server(s)..." - for i in "${!PREFILL_GPU_ARRAY[@]}"; do - local gpu_id=${PREFILL_GPU_ARRAY[$i]} - local port=${PREFILL_PORT_ARRAY[$i]} - local kv_port=$((21001 + i)) - - echo " Prefill server $((i+1)): GPU $gpu_id, Port $port, KV Port $kv_port" - CUDA_VISIBLE_DEVICES=$gpu_id vllm serve "$MODEL" \ - --enforce-eager \ - --host 0.0.0.0 \ - --port "$port" \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.9 \ - --kv-transfer-config \ - "{\"kv_connector\":\"P2pNcclConnector\",\"kv_role\":\"kv_producer\",\"kv_buffer_size\":\"1e1\",\"kv_port\":\"$kv_port\",\"kv_connector_extra_config\":{\"proxy_ip\":\"0.0.0.0\",\"proxy_port\":\"$PROXY_PORT\",\"http_port\":\"$port\",\"send_type\":\"PUT_ASYNC\",\"nccl_num_channels\":\"16\"}}" > prefill$((i+1)).log 2>&1 & - PIDS+=($!) - done - - # ============================================================================= - # Launch Decode Servers (Y Decoders) - # ============================================================================= - echo "" - echo "Starting ${#DECODE_GPU_ARRAY[@]} decode server(s)..." - for i in "${!DECODE_GPU_ARRAY[@]}"; do - local gpu_id=${DECODE_GPU_ARRAY[$i]} - local port=${DECODE_PORT_ARRAY[$i]} - local kv_port=$((22001 + i)) - - echo " Decode server $((i+1)): GPU $gpu_id, Port $port, KV Port $kv_port" - CUDA_VISIBLE_DEVICES=$gpu_id vllm serve "$MODEL" \ - --enforce-eager \ - --host 0.0.0.0 \ - --port "$port" \ - --tensor-parallel-size 1 \ - --seed 1024 \ - --dtype float16 \ - --max-model-len 10000 \ - --max-num-batched-tokens 10000 \ - --max-num-seqs 256 \ - --trust-remote-code \ - --gpu-memory-utilization 0.7 \ - --kv-transfer-config \ - "{\"kv_connector\":\"P2pNcclConnector\",\"kv_role\":\"kv_consumer\",\"kv_buffer_size\":\"8e9\",\"kv_port\":\"$kv_port\",\"kv_connector_extra_config\":{\"proxy_ip\":\"0.0.0.0\",\"proxy_port\":\"$PROXY_PORT\",\"http_port\":\"$port\",\"send_type\":\"PUT_ASYNC\",\"nccl_num_channels\":\"16\"}}" > decode$((i+1)).log 2>&1 & - PIDS+=($!) - done - - # ============================================================================= - # Wait for All Servers to Start - # ============================================================================= - echo "" - echo "Waiting for all servers to start..." - for port in "${PREFILL_PORT_ARRAY[@]}" "${DECODE_PORT_ARRAY[@]}"; do - if ! wait_for_server "$port"; then - echo "Failed to start server on port $port" - cleanup - # shellcheck disable=SC2317 - exit 1 - fi - done - - echo "" - echo "All servers are up. Starting benchmark..." - - # ============================================================================= - # Run Benchmark - # ============================================================================= - cd ../../../benchmarks/ - vllm bench serve --port 10001 --seed "$(date +%s)" \ - --model "$MODEL" \ - --dataset-name random --random-input-len 7500 --random-output-len 200 \ - --num-prompts 200 --burstiness 100 --request-rate 2 | tee benchmark.log - - echo "Benchmarking done. Cleaning up..." - - cleanup -} - -main diff --git a/examples/disaggregated/p2p_nccl_xpyd/disagg_proxy_p2p_nccl_xpyd.py b/examples/disaggregated/p2p_nccl_xpyd/disagg_proxy_p2p_nccl_xpyd.py deleted file mode 100644 index 0c7d32d786..0000000000 --- a/examples/disaggregated/p2p_nccl_xpyd/disagg_proxy_p2p_nccl_xpyd.py +++ /dev/null @@ -1,190 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import os -import socket -import threading -import time -import uuid -from typing import Any - -import aiohttp -import msgpack -import zmq -from quart import Quart, make_response, request - -count = 0 -prefill_instances: dict[str, Any] = {} # http_address: (zmq_address, stamp) -decode_instances: dict[str, Any] = {} # http_address: (zmq_address, stamp) - -prefill_cv = threading.Condition() -decode_cv = threading.Condition() - -DEFAULT_PING_SECONDS = 5 - - -def _remove_oldest_instances(instances: dict[str, Any]) -> None: - oldest_key = next(iter(instances), None) - while oldest_key is not None: - value = instances[oldest_key] - if value[1] > time.time(): - break - print(f"🔴Remove [HTTP:{oldest_key}, ZMQ:{value[0]}, stamp:{value[1]}]") - instances.pop(oldest_key, None) - oldest_key = next(iter(instances), None) - - -def _listen_for_register(poller, router_socket): - while True: - socks = dict(poller.poll()) - if router_socket in socks: - remote_address, message = router_socket.recv_multipart() - # data: {"type": "P", "http_address": "ip:port", - # "zmq_address": "ip:port"} - data = msgpack.loads(message) - if data["type"] == "P": - global prefill_instances - global prefill_cv - with prefill_cv: - node = prefill_instances.get(data["http_address"], None) - prefill_instances[data["http_address"]] = ( - data["zmq_address"], - time.time() + DEFAULT_PING_SECONDS, - ) - _remove_oldest_instances(prefill_instances) - - elif data["type"] == "D": - global decode_instances - global decode_cv - with decode_cv: - node = decode_instances.get(data["http_address"], None) - decode_instances[data["http_address"]] = ( - data["zmq_address"], - time.time() + DEFAULT_PING_SECONDS, - ) - _remove_oldest_instances(decode_instances) - else: - print( - "Unexpected, Received message from %s, data: %s", - remote_address, - data, - ) - return - - if node is None: - print(f"🔵Add [HTTP:{data['http_address']}, ZMQ:{data['zmq_address']}]") - - -def start_service_discovery(hostname, port): - if not hostname: - hostname = socket.gethostname() - if port == 0: - raise ValueError("Port cannot be 0") - - context = zmq.Context() - router_socket = context.socket(zmq.ROUTER) - router_socket.bind(f"tcp://{hostname}:{port}") - - poller = zmq.Poller() - poller.register(router_socket, zmq.POLLIN) - - _listener_thread = threading.Thread( - target=_listen_for_register, args=[poller, router_socket], daemon=True - ) - _listener_thread.start() - return _listener_thread - - -AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60) - -app = Quart(__name__) - - -def random_uuid() -> str: - return str(uuid.uuid4().hex) - - -async def forward_request(url, data, request_id): - async with aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session: - headers = { - "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}", - "X-Request-Id": request_id, - } - async with session.post(url=url, json=data, headers=headers) as response: - if response.status == 200: - if True: - async for chunk_bytes in response.content.iter_chunked(1024): - yield chunk_bytes - else: - content = await response.read() - yield content - - -@app.route("/v1/completions", methods=["POST"]) -@app.route("/v1/chat/completions", methods=["POST"]) -async def handle_request(): - try: - original_request_data = await request.get_json() - - prefill_request = original_request_data.copy() - # change max_tokens = 1 to let it only do prefill - prefill_request["max_tokens"] = 1 - if "max_completion_tokens" in prefill_request: - prefill_request["max_completion_tokens"] = 1 - - global count - global prefill_instances - global prefill_cv - with prefill_cv: - prefill_list = list(prefill_instances.items()) - prefill_addr, prefill_zmq_addr = prefill_list[count % len(prefill_list)] - prefill_zmq_addr = prefill_zmq_addr[0] - - global decode_instances - global decode_cv - with decode_cv: - decode_list = list(decode_instances.items()) - decode_addr, decode_zmq_addr = decode_list[count % len(decode_list)] - decode_zmq_addr = decode_zmq_addr[0] - - print( - f"handle_request count: {count}, [HTTP:{prefill_addr}, " - f"ZMQ:{prefill_zmq_addr}] 👉 [HTTP:{decode_addr}, " - f"ZMQ:{decode_zmq_addr}]" - ) - count += 1 - - request_id = ( - f"___prefill_addr_{prefill_zmq_addr}___decode_addr_" - f"{decode_zmq_addr}_{random_uuid()}" - ) - - # finish prefill - async for _ in forward_request( - f"http://{prefill_addr}{request.path}", prefill_request, request_id - ): - continue - - # return decode - generator = forward_request( - f"http://{decode_addr}{request.path}", original_request_data, request_id - ) - response = await make_response(generator) - response.timeout = None - - return response - - except Exception as e: - import sys - import traceback - - exc_info = sys.exc_info() - print("Error occurred in disagg prefill proxy server") - print(e) - print("".join(traceback.format_exception(*exc_info))) - - -if __name__ == "__main__": - t = start_service_discovery("0.0.0.0", 30001) - app.run(host="0.0.0.0", port=10001) - t.join() diff --git a/vllm/config/kv_transfer.py b/vllm/config/kv_transfer.py index b22af99f70..9f206ff5d4 100644 --- a/vllm/config/kv_transfer.py +++ b/vllm/config/kv_transfer.py @@ -48,8 +48,7 @@ class KVTransferConfig: Currently only 1P1D is supported.""" kv_parallel_size: int = 1 - """The number of parallel instances for KV cache transfer. For - P2pNcclConnector, this should be 2.""" + """The number of parallel instances for KV cache transfer.""" kv_ip: str = "127.0.0.1" """The KV connector ip, used to build distributed connection.""" diff --git a/vllm/distributed/kv_transfer/kv_connector/factory.py b/vllm/distributed/kv_transfer/kv_connector/factory.py index a2676b2dfe..75290f6a01 100644 --- a/vllm/distributed/kv_transfer/kv_connector/factory.py +++ b/vllm/distributed/kv_transfer/kv_connector/factory.py @@ -161,12 +161,6 @@ KVConnectorFactory.register_connector( "ExampleHiddenStatesConnector", ) -KVConnectorFactory.register_connector( - "P2pNcclConnector", - "vllm.distributed.kv_transfer.kv_connector.v1.p2p.p2p_nccl_connector", - "P2pNcclConnector", -) - KVConnectorFactory.register_connector( "LMCacheConnectorV1", "vllm.distributed.kv_transfer.kv_connector.v1.lmcache_connector", diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_common.py b/vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_common.py index 40f880f6de..73694ce321 100644 --- a/vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_common.py +++ b/vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_common.py @@ -324,7 +324,7 @@ class MoRIIOConstants: DEFAULT_DEFER_TIMEOUT = 60.0 -# The router embeds both zmq_addresses in the request_id (similar to P2pNcclConnector): +# The router embeds both zmq_addresses in the request_id: # "___prefill_addr_{zmq}___decode_addr_{zmq}_{32-hex-uuid}" # MoRIIO zmq_address format: "host:IP,handshake:PORT,notify:PORT" # diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/__init__.py b/vllm/distributed/kv_transfer/kv_connector/v1/p2p/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py b/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py deleted file mode 100644 index d4b7b79647..0000000000 --- a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py +++ /dev/null @@ -1,478 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any - -import regex as re -import torch - -from vllm.config import VllmConfig -from vllm.distributed.kv_transfer.kv_connector.v1.base import ( - KVConnectorBase_V1, - KVConnectorMetadata, - KVConnectorRole, -) -from vllm.distributed.kv_transfer.kv_connector.v1.p2p.p2p_nccl_engine import ( - P2pNcclEngine, -) -from vllm.distributed.parallel_state import get_world_group -from vllm.logger import init_logger -from vllm.v1.attention.backend import AttentionMetadata -from vllm.v1.core.sched.output import SchedulerOutput - -if TYPE_CHECKING: - from vllm.forward_context import ForwardContext - from vllm.v1.core.kv_cache_manager import KVCacheBlocks - from vllm.v1.kv_cache_interface import KVCacheConfig - from vllm.v1.request import Request - -logger = init_logger(__name__) - - -@dataclass -class ReqMeta: - # Request Id - request_id: str - # Request block ids - block_ids: torch.Tensor - # Request num tokens - num_tokens: int - - @staticmethod - def make_meta( - request_id: str, token_ids: list[int], block_ids: list[int], block_size: int - ) -> "ReqMeta": - block_ids_tensor = torch.tensor(block_ids) - return ReqMeta( - request_id=request_id, - block_ids=block_ids_tensor, - num_tokens=len(token_ids), - ) - - -@dataclass -class P2pNcclConnectorMetadata(KVConnectorMetadata): - requests: list[ReqMeta] - - def __init__(self): - self.requests = [] - - def add_request( - self, - request_id: str, - token_ids: list[int], - block_ids: list[int], - block_size: int, - ) -> None: - self.requests.append( - ReqMeta.make_meta(request_id, token_ids, block_ids, block_size) - ) - - -class P2pNcclConnector(KVConnectorBase_V1): - def __init__( - self, - vllm_config: "VllmConfig", - role: KVConnectorRole, - kv_cache_config: "KVCacheConfig", - ): - super().__init__( - vllm_config=vllm_config, - role=role, - kv_cache_config=kv_cache_config, - ) - self._block_size = vllm_config.cache_config.block_size - self._requests_need_load: dict[str, Any] = {} - self.is_producer = self._kv_transfer_config.is_kv_producer - self.chunked_prefill: dict[str, tuple[list[int], list[int] | None]] = {} - - self._rank = get_world_group().rank if role == KVConnectorRole.WORKER else 0 - self._local_rank = ( - get_world_group().local_rank if role == KVConnectorRole.WORKER else 0 - ) - - self.p2p_nccl_engine = ( - P2pNcclEngine( - local_rank=self._local_rank, - config=self._kv_transfer_config, - hostname="", - port_offset=self._rank, - ) - if role == KVConnectorRole.WORKER - else None - ) - - # ============================== - # Worker-side methods - # ============================== - - def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: - """Start loading the KV cache from the connector buffer to vLLM's - paged KV buffer. - - Args: - forward_context (ForwardContext): the forward context. - **kwargs: additional arguments for the load operation - - Note: - The number of elements in kv_caches and layer_names should be - the same. - """ - - # Only consumer/decode loads KV Cache - if self.is_producer: - return - - assert self.p2p_nccl_engine is not None - - attn_metadata = forward_context.attn_metadata - if attn_metadata is None: - return - - def inject_kv_into_layer( - layer: torch.Tensor, - kv_cache: torch.Tensor, - block_ids: torch.Tensor, - request_id: str, - ) -> None: - """ - Inject KV cache data into a given attention layer tensor. - - This function updates `layer` in-place with values from `kv_cache`. - All backends (MLA, FlashAttention, FlashInfer, TritonAttention) - are indexed along the first dimension (block index). - - If the number of provided block IDs does not match the number of KV - blocks, only the overlapping portion is updated, and a warning is - logged. - - Args: - layer (torch.Tensor): The attention layer KV tensor to update. - kv_cache (torch.Tensor): The KV cache tensor to inject. - block_ids (torch.Tensor): Indices of the blocks to update. - request_id (str): Request identifier used for logging. - - Returns: - None. The function modifies `layer` in-place. - """ - num_block = kv_cache.shape[0] - self.check_tensors_except_dim(layer, kv_cache, 0) - if len(block_ids) == num_block: - layer[block_ids, ...] = kv_cache - else: - layer[block_ids[:num_block], ...] = kv_cache - logger.warning( - "🚧kv_cache does not match, block_ids:%d, " - "num_block:%d, request_id:%s", - len(block_ids), - num_block, - request_id, - ) - - # Get the metadata - metadata: KVConnectorMetadata = self._get_connector_metadata() - assert isinstance(metadata, P2pNcclConnectorMetadata) - - if metadata is None: - return - - # Load the KV for each request each layer - for request in metadata.requests: - request_id = request.request_id - ip, port = self.parse_request_id(request_id, False) - remote_address = ip + ":" + str(port + self._rank) - for layer_name in forward_context.no_compile_layers: - layer = forward_context.no_compile_layers[layer_name] - - # Only process layers that have kv_cache - # attribute (attention layers) Skip non-attention - # layers like FusedMoE - kv_cache = getattr(layer, "kv_cache", None) - if kv_cache is None: - continue - - layer = kv_cache - - kv_cache = self.p2p_nccl_engine.recv_tensor( - request.request_id + "#" + layer_name, remote_address - ) - - if kv_cache is None: - logger.warning("🚧kv_cache is None, %s", request.request_id) - continue - - inject_kv_into_layer( - layer, kv_cache, request.block_ids, request.request_id - ) - - def wait_for_layer_load(self, layer_name: str) -> None: - """Blocking until the KV for a specific layer is loaded into vLLM's - paged buffer. - - This interface will be useful for layer-by-layer pipelining. - - Args: - layer_name: the name of that layer - """ - return - - def save_kv_layer( - self, - layer_name: str, - kv_layer: torch.Tensor, - attn_metadata: AttentionMetadata, - **kwargs: Any, - ) -> None: - """Start saving the KV cache of the layer from vLLM's paged buffer - to the connector. - - Args: - layer_name (str): the name of the layer. - kv_layer (torch.Tensor): the paged KV buffer of the current - layer in vLLM. - attn_metadata (AttentionMetadata): the attention metadata. - **kwargs: additional arguments for the save operation. - """ - - # Only producer/prefill saves KV Cache - if not self.is_producer: - return - - assert self.p2p_nccl_engine is not None - - connector_metadata = self._get_connector_metadata() - assert isinstance(connector_metadata, P2pNcclConnectorMetadata) - for request in connector_metadata.requests: - request_id = request.request_id - ip, port = self.parse_request_id(request_id, True) - remote_address = ip + ":" + str(port + self._rank) - - kv_cache = kv_layer[request.block_ids, ...] - self.p2p_nccl_engine.send_tensor( - request_id + "#" + layer_name, kv_cache, remote_address - ) - - def wait_for_save(self): - if self.is_producer: - assert self.p2p_nccl_engine is not None - self.p2p_nccl_engine.wait_for_sent() - - def get_finished( - self, finished_req_ids: set[str], **kwargs: Any - ) -> tuple[set[str] | None, set[str] | None]: - """ - Notifies worker-side connector ids of requests that have - finished generating tokens. - - Returns: - ids of requests that have finished asynchronous transfer, - tuple of (sending/saving ids, recving/loading ids). - The finished saves/sends req ids must belong to a set provided in a - call to this method (this call or a prior one). - """ - - assert self.p2p_nccl_engine is not None - - no_compile_layers = self._vllm_config.compilation_config.static_forward_context - return self.p2p_nccl_engine.get_finished(finished_req_ids, no_compile_layers) - - # ============================== - # Scheduler-side methods - # ============================== - - def get_num_new_matched_tokens( - self, - request: "Request", - num_computed_tokens: int, - ) -> tuple[int, bool]: - """ - Get number of new tokens that can be loaded from the - external KV cache beyond the num_computed_tokens. - - Args: - request (Request): the request object. - num_computed_tokens (int): the number of locally - computed tokens for this request - - Returns: - the number of tokens that can be loaded from the - external KV cache beyond what is already computed. - """ - if self.is_producer: - return 0, False - - prompt_token_ids = request.prompt_token_ids or [] - num_external_tokens = len(prompt_token_ids) - 1 - num_computed_tokens - - if num_external_tokens < 0: - num_external_tokens = 0 - - return num_external_tokens, False - - def update_state_after_alloc( - self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int - ): - """ - Update KVConnector state after block allocation. - """ - if not self.is_producer and num_external_tokens > 0: - self._requests_need_load[request.request_id] = ( - request, - blocks.get_block_ids()[0], - ) - - def build_connector_meta( - self, - scheduler_output: SchedulerOutput, - ) -> KVConnectorMetadata: - """Build the connector metadata for this step. - - This function should NOT modify any fields in the scheduler_output. - Also, calling this function will reset the state of the connector. - - Args: - scheduler_output (SchedulerOutput): the scheduler output object. - """ - - meta = P2pNcclConnectorMetadata() - - for new_req in scheduler_output.scheduled_new_reqs: - if self.is_producer: - num_scheduled_tokens = (scheduler_output.num_scheduled_tokens)[ - new_req.req_id - ] - num_tokens = num_scheduled_tokens + new_req.num_computed_tokens - # the request's prompt is chunked prefill - if num_tokens < len(new_req.prompt_token_ids or []): - # 'CachedRequestData' has no attribute 'prompt_token_ids' - self.chunked_prefill[new_req.req_id] = ( - new_req.block_ids[0], - new_req.prompt_token_ids, - ) - continue - # the request's prompt is not chunked prefill - meta.add_request( - request_id=new_req.req_id, - token_ids=new_req.prompt_token_ids or [], - block_ids=new_req.block_ids[0], - block_size=self._block_size, - ) - continue - if new_req.req_id in self._requests_need_load: - meta.add_request( - request_id=new_req.req_id, - token_ids=new_req.prompt_token_ids or [], - block_ids=new_req.block_ids[0], - block_size=self._block_size, - ) - self._requests_need_load.pop(new_req.req_id) - - cached_reqs = scheduler_output.scheduled_cached_reqs - for i, req_id in enumerate(cached_reqs.req_ids): - num_computed_tokens = cached_reqs.num_computed_tokens[i] - new_block_ids = cached_reqs.new_block_ids[i] - resumed_from_preemption = req_id in cached_reqs.resumed_req_ids - - if self.is_producer: - num_scheduled_tokens = scheduler_output.num_scheduled_tokens[req_id] - num_tokens = num_scheduled_tokens + num_computed_tokens - assert req_id in self.chunked_prefill - assert new_block_ids is not None - block_ids = new_block_ids[0] - if not resumed_from_preemption: - block_ids = self.chunked_prefill[req_id][0] + block_ids - prompt_token_ids = self.chunked_prefill[req_id][1] - assert prompt_token_ids is not None - # the request's prompt is chunked prefill again - if num_tokens < len(prompt_token_ids): - self.chunked_prefill[req_id] = (block_ids, prompt_token_ids) - continue - # the request's prompt is all prefilled finally - meta.add_request( - request_id=req_id, - token_ids=prompt_token_ids, - block_ids=block_ids, - block_size=self._block_size, - ) - self.chunked_prefill.pop(req_id, None) - continue - - # NOTE(rob): here we rely on the resumed requests being - # the first N requests in the list scheduled_cache_reqs. - if not resumed_from_preemption: - break - if req_id in self._requests_need_load: - request, _ = self._requests_need_load.pop(req_id) - total_tokens = num_computed_tokens + 1 - token_ids = request.all_token_ids[:total_tokens] - - # NOTE(rob): For resumed req, new_block_ids is all - # of the block_ids for the request. - assert new_block_ids is not None - block_ids = new_block_ids[0] - - meta.add_request( - request_id=req_id, - token_ids=token_ids, - block_ids=block_ids, - block_size=self._block_size, - ) - - self._requests_need_load.clear() - return meta - - def request_finished( - self, - request: "Request", - block_ids: list[int], - ) -> tuple[bool, dict[str, Any] | None]: - """ - Called when a request has finished, before its blocks are freed. - - Returns: - True if the request is being saved/sent asynchronously and blocks - should not be freed until the request_id is returned from - get_finished(). - Optional KVTransferParams to be included in the request outputs - returned by the engine. - """ - - self.chunked_prefill.pop(request.request_id, None) - - return False, None - - # ============================== - # Static methods - # ============================== - - @staticmethod - def parse_request_id(request_id: str, is_prefill=True) -> tuple[str, int]: - # Regular expression to match the string hostname and integer port - if is_prefill: - pattern = r"___decode_addr_(.*):(\d+)" - else: - pattern = r"___prefill_addr_(.*):(\d+)___" - - # Use re.search to find the pattern in the request_id - match = re.search(pattern, request_id) - if match: - # Extract the ranks - ip = match.group(1) - port = int(match.group(2)) - - return ip, port - raise ValueError(f"Request id {request_id} does not contain hostname and port") - - @staticmethod - def check_tensors_except_dim(tensor1, tensor2, dim): - shape1 = tensor1.size() - shape2 = tensor2.size() - - if len(shape1) != len(shape2) or not all( - s1 == s2 for i, (s1, s2) in enumerate(zip(shape1, shape2)) if i != dim - ): - raise NotImplementedError( - "Currently, only symmetric TP is supported. Asymmetric TP, PP," - "and others will be supported in future PRs." - ) diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_engine.py b/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_engine.py deleted file mode 100644 index 1c1410f390..0000000000 --- a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_engine.py +++ /dev/null @@ -1,632 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import json -import logging -import os -import threading -import time -from collections import deque -from contextlib import contextmanager -from dataclasses import dataclass -from typing import Any - -import msgpack -import torch -import zmq - -from vllm.config.kv_transfer import KVTransferConfig -from vllm.distributed.device_communicators.pynccl_wrapper import ( - NCCLLibrary, - buffer_type, - cudaStream_t, - ncclComm_t, - ncclDataTypeEnum, -) -from vllm.distributed.kv_transfer.kv_connector.v1.p2p.tensor_memory_pool import ( # noqa: E501 - TensorMemoryPool, -) -from vllm.utils.network_utils import get_ip -from vllm.utils.torch_utils import current_stream - -logger = logging.getLogger(__name__) - -DEFAULT_MEM_POOL_SIZE_GB = 32 - - -@contextmanager -def set_p2p_nccl_context(num_channels: str): - original_values: dict[str, Any] = {} - env_vars = [ - "NCCL_MAX_NCHANNELS", - "NCCL_MIN_NCHANNELS", - "NCCL_CUMEM_ENABLE", - "NCCL_BUFFSIZE", - "NCCL_PROTO", # LL,LL128,SIMPLE - "NCCL_ALGO", # RING,TREE - ] - - for var in env_vars: - original_values[var] = os.environ.get(var) - - logger.info("set_p2p_nccl_context, original_values: %s", original_values) - - try: - os.environ["NCCL_MAX_NCHANNELS"] = num_channels - os.environ["NCCL_MIN_NCHANNELS"] = num_channels - os.environ["NCCL_CUMEM_ENABLE"] = "1" - yield - finally: - for var in env_vars: - if original_values[var] is not None: - os.environ[var] = original_values[var] - else: - os.environ.pop(var, None) - - -@dataclass -class SendQueueItem: - tensor_id: str - remote_address: str - tensor: torch.Tensor - - -class P2pNcclEngine: - def __init__( - self, - local_rank: int, - config: KVTransferConfig, - hostname: str = "", - port_offset: int = 0, - library_path: str | None = None, - ) -> None: - self.config = config - self.rank = port_offset - self.local_rank = local_rank - self.device = torch.device(f"cuda:{self.local_rank}") - self.nccl = NCCLLibrary(library_path) - - if not hostname: - hostname = get_ip() - port = int(self.config.kv_port) + port_offset - if port == 0: - raise ValueError("Port cannot be 0") - self._hostname = hostname - self._port = port - - # Each card corresponds to a ZMQ address. - self.zmq_address = f"{self._hostname}:{self._port}" - - # If `proxy_ip` or `proxy_port` is `""`, - # then the ping thread will not be enabled. - proxy_ip = self.config.get_from_extra_config("proxy_ip", "") - proxy_port = self.config.get_from_extra_config("proxy_port", "") - if proxy_ip == "" or proxy_port == "": - self.proxy_address = "" - self.http_address = "" - else: - self.proxy_address = proxy_ip + ":" + proxy_port - # the `http_port` must be consistent with the port of OpenAI. - http_port = self.config.get_from_extra_config("http_port", None) - if http_port is None: - example_cfg = { - "kv_connector": "P2pNcclConnector", - "kv_connector_extra_config": {"http_port": 8000}, - } - example = ( - f"--port=8000 --kv-transfer-config='{json.dumps(example_cfg)}'" - ) - raise ValueError( - "kv_connector_extra_config.http_port is required. " - f"Example: {example}" - ) - self.http_address = f"{self._hostname}:{http_port}" - - self.context = zmq.Context() - self.router_socket = self.context.socket(zmq.ROUTER) - self.router_socket.bind(f"tcp://{self.zmq_address}") - - self.poller = zmq.Poller() - self.poller.register(self.router_socket, zmq.POLLIN) - - self.send_store_cv = threading.Condition() - self.send_queue_cv = threading.Condition() - self.recv_store_cv = threading.Condition() - - self.send_stream = torch.cuda.Stream() - self.recv_stream = torch.cuda.Stream() - - mem_pool_size_gb = float( - self.config.get_from_extra_config( - "mem_pool_size_gb", DEFAULT_MEM_POOL_SIZE_GB - ) - ) - self.pool = TensorMemoryPool( - max_block_size=int(mem_pool_size_gb * 1024**3) - ) # GB - - # The sending type includes tree mutually exclusive options: - # PUT, GET, PUT_ASYNC. - self.send_type = self.config.get_from_extra_config("send_type", "PUT_ASYNC") - if self.send_type == "GET": - # tensor_id: torch.Tensor - self.send_store: dict[str, torch.Tensor] = {} - else: - # PUT or PUT_ASYNC - # tensor_id: torch.Tensor - self.send_queue: deque[SendQueueItem] = deque() - if self.send_type == "PUT_ASYNC": - self._send_thread = threading.Thread( - target=self.send_async, daemon=True - ) - self._send_thread.start() - - # tensor_id: torch.Tensor/(addr, dtype, shape) - self.recv_store: dict[str, Any] = {} - self.recv_request_id_to_tensor_ids: dict[str, set[str]] = {} - self.send_request_id_to_tensor_ids: dict[str, set[str]] = {} - self.socks: dict[str, Any] = {} # remote_address: client socket - self.comms: dict[str, Any] = {} # remote_address: (ncclComm_t, rank) - - self.buffer_size = 0 - self.buffer_size_threshold = float(self.config.kv_buffer_size) - - self.nccl_num_channels = self.config.get_from_extra_config( - "nccl_num_channels", "8" - ) - - self._listener_thread = threading.Thread( - target=self.listen_for_requests, daemon=True - ) - self._listener_thread.start() - - self._ping_thread = None - if port_offset == 0 and self.proxy_address != "": - self._ping_thread = threading.Thread(target=self.ping, daemon=True) - self._ping_thread.start() - - logger.info( - "💯P2pNcclEngine init, rank:%d, local_rank:%d, http_address:%s, " - "zmq_address:%s, proxy_address:%s, send_type:%s, buffer_size_" - "threshold:%.2f, nccl_num_channels:%s", - self.rank, - self.local_rank, - self.http_address, - self.zmq_address, - self.proxy_address, - self.send_type, - self.buffer_size_threshold, - self.nccl_num_channels, - ) - - def create_connect(self, remote_address: str | None = None): - assert remote_address is not None - if remote_address not in self.socks: - sock = self.context.socket(zmq.DEALER) - sock.setsockopt_string(zmq.IDENTITY, self.zmq_address) - sock.connect(f"tcp://{remote_address}") - self.socks[remote_address] = sock - if remote_address in self.comms: - logger.info( - "👋comm exists, remote_address:%s, comms:%s", - remote_address, - self.comms, - ) - return sock, self.comms[remote_address] - - unique_id = self.nccl.ncclGetUniqueId() - data = {"cmd": "NEW", "unique_id": bytes(unique_id.internal)} - sock.send(msgpack.dumps(data)) - - with torch.accelerator.device_index(self.device.index): - rank = 0 - with set_p2p_nccl_context(self.nccl_num_channels): - comm: ncclComm_t = self.nccl.ncclCommInitRank(2, unique_id, rank) - self.comms[remote_address] = (comm, rank) - logger.info( - "🤝ncclCommInitRank Success, %s👉%s, MyRank:%s", - self.zmq_address, - remote_address, - rank, - ) - - return self.socks[remote_address], self.comms[remote_address] - - def send_tensor( - self, - tensor_id: str, - tensor: torch.Tensor, - remote_address: str | None = None, - ) -> bool: - if remote_address is None: - with self.recv_store_cv: - self.recv_store[tensor_id] = tensor - self.recv_store_cv.notify() - return True - - item = SendQueueItem( - tensor_id=tensor_id, remote_address=remote_address, tensor=tensor - ) - - if self.send_type == "PUT": - return self.send_sync(item) - - if self.send_type == "PUT_ASYNC": - with self.send_queue_cv: - self.send_queue.append(item) - self.send_queue_cv.notify() - return True - - # GET - with self.send_store_cv: - tensor_size = tensor.element_size() * tensor.numel() - if tensor_size > self.buffer_size_threshold: - logger.warning( - "❗[GET]tensor_id:%s, tensor_size:%d, is greater than" - "buffer size threshold :%d, skip send to %s, rank:%d", - tensor_id, - tensor_size, - self.buffer_size_threshold, - remote_address, - self.rank, - ) - return False - while self.buffer_size + tensor_size > self.buffer_size_threshold: - assert len(self.send_store) > 0 - oldest_tensor_id = next(iter(self.send_store)) - oldest_tensor = self.send_store.pop(oldest_tensor_id) - oldest_tensor_size = ( - oldest_tensor.element_size() * oldest_tensor.numel() - ) - self.buffer_size -= oldest_tensor_size - logger.debug( - "⛔[GET]Send to %s, tensor_id:%s, tensor_size:%d," - " buffer_size:%d, oldest_tensor_size:%d, rank:%d", - remote_address, - tensor_id, - tensor_size, - self.buffer_size, - oldest_tensor_size, - self.rank, - ) - - self.send_store[tensor_id] = tensor - self.buffer_size += tensor_size - logger.debug( - "🔵[GET]Send to %s, tensor_id:%s, tensor_size:%d, " - "shape:%s, rank:%d, buffer_size:%d(%.2f%%)", - remote_address, - tensor_id, - tensor_size, - tensor.shape, - self.rank, - self.buffer_size, - self.buffer_size / self.buffer_size_threshold * 100, - ) - return True - - def recv_tensor( - self, - tensor_id: str, - remote_address: str | None = None, - ) -> torch.Tensor: - if self.send_type == "PUT" or self.send_type == "PUT_ASYNC": - start_time = time.time() - with self.recv_store_cv: - while tensor_id not in self.recv_store: - self.recv_store_cv.wait() - tensor = self.recv_store[tensor_id] - - if tensor is not None: - if isinstance(tensor, tuple): - addr, dtype, shape = tensor - tensor = self.pool.load_tensor(addr, dtype, shape, self.device) - else: - self.buffer_size -= tensor.element_size() * tensor.numel() - else: - duration = time.time() - start_time - logger.warning( - "🔴[PUT]Recv From %s, tensor_id:%s, duration:%.3fms, rank:%d", - remote_address, - tensor_id, - duration * 1000, - self.rank, - ) - return tensor - - # GET - if remote_address is None: - return None - - if remote_address not in self.socks: - self.create_connect(remote_address) - - sock = self.socks[remote_address] - comm, rank = self.comms[remote_address] - - data = {"cmd": "GET", "tensor_id": tensor_id} - sock.send(msgpack.dumps(data)) - - message = sock.recv() - data = msgpack.loads(message) - if data["ret"] != 0: - logger.warning( - "🔴[GET]Recv From %s, tensor_id: %s, ret: %d", - remote_address, - tensor_id, - data["ret"], - ) - return None - - with torch.cuda.stream(self.recv_stream): - tensor = torch.empty( - data["shape"], dtype=getattr(torch, data["dtype"]), device=self.device - ) - - self.recv(comm, tensor, rank ^ 1, self.recv_stream) - - return tensor - - def listen_for_requests(self): - while True: - socks = dict(self.poller.poll()) - if self.router_socket not in socks: - continue - - remote_address, message = self.router_socket.recv_multipart() - data = msgpack.loads(message) - if data["cmd"] == "NEW": - unique_id = self.nccl.unique_id_from_bytes(bytes(data["unique_id"])) - with torch.accelerator.device_index(self.device.index): - rank = 1 - with set_p2p_nccl_context(self.nccl_num_channels): - comm: ncclComm_t = self.nccl.ncclCommInitRank( - 2, unique_id, rank - ) - self.comms[remote_address.decode()] = (comm, rank) - logger.info( - "🤝ncclCommInitRank Success, %s👈%s, MyRank:%s", - self.zmq_address, - remote_address.decode(), - rank, - ) - elif data["cmd"] == "PUT": - tensor_id = data["tensor_id"] - try: - with torch.cuda.stream(self.recv_stream): - tensor = torch.empty( - data["shape"], - dtype=getattr(torch, data["dtype"]), - device=self.device, - ) - self.router_socket.send_multipart([remote_address, b"0"]) - comm, rank = self.comms[remote_address.decode()] - self.recv(comm, tensor, rank ^ 1, self.recv_stream) - tensor_size = tensor.element_size() * tensor.numel() - if self.buffer_size + tensor_size > self.buffer_size_threshold: - # Store Tensor in memory pool - addr = self.pool.store_tensor(tensor) - tensor = (addr, tensor.dtype, tensor.shape) - logger.warning( - "🔴[PUT]Recv Tensor, Out Of Threshold, " - "%s👈%s, data:%s, addr:%d", - self.zmq_address, - remote_address.decode(), - data, - addr, - ) - else: - self.buffer_size += tensor_size - - except torch.cuda.OutOfMemoryError: - self.router_socket.send_multipart([remote_address, b"1"]) - tensor = None - logger.warning( - "🔴[PUT]Recv Tensor, Out Of Memory, %s👈%s, data:%s", - self.zmq_address, - remote_address.decode(), - data, - ) - - with self.recv_store_cv: - self.recv_store[tensor_id] = tensor - self.have_received_tensor_id(tensor_id) - self.recv_store_cv.notify() - - elif data["cmd"] == "GET": - tensor_id = data["tensor_id"] - with self.send_store_cv: - tensor = self.send_store.pop(tensor_id, None) - if tensor is not None: - data = { - "ret": 0, - "shape": tensor.shape, - "dtype": str(tensor.dtype).replace("torch.", ""), - } - # LRU - self.send_store[tensor_id] = tensor - self.have_sent_tensor_id(tensor_id) - else: - data = {"ret": 1} - - self.router_socket.send_multipart([remote_address, msgpack.dumps(data)]) - - if data["ret"] == 0: - comm, rank = self.comms[remote_address.decode()] - self.send(comm, tensor.to(self.device), rank ^ 1, self.send_stream) - else: - logger.warning( - "🚧Unexpected, Received message from %s, data:%s", - remote_address, - data, - ) - - def have_sent_tensor_id(self, tensor_id: str): - request_id = tensor_id.split("#")[0] - if request_id not in self.send_request_id_to_tensor_ids: - self.send_request_id_to_tensor_ids[request_id] = set() - self.send_request_id_to_tensor_ids[request_id].add(tensor_id) - - def have_received_tensor_id(self, tensor_id: str): - request_id = tensor_id.split("#")[0] - if request_id not in self.recv_request_id_to_tensor_ids: - self.recv_request_id_to_tensor_ids[request_id] = set() - self.recv_request_id_to_tensor_ids[request_id].add(tensor_id) - - def send_async(self): - while True: - with self.send_queue_cv: - while not self.send_queue: - self.send_queue_cv.wait() - item = self.send_queue.popleft() - if not self.send_queue: - self.send_queue_cv.notify() - self.send_sync(item) - - def wait_for_sent(self): - if self.send_type == "PUT_ASYNC": - start_time = time.time() - with self.send_queue_cv: - while self.send_queue: - self.send_queue_cv.wait() - duration = time.time() - start_time - logger.debug( - "🚧[PUT_ASYNC]It took %.3fms to wait for the send_queue" - " to be empty, rank:%d", - duration * 1000, - self.rank, - ) - - def send_sync(self, item: SendQueueItem) -> bool: - if item.remote_address is None: - return False - if item.remote_address not in self.socks: - self.create_connect(item.remote_address) - - tensor = item.tensor - - sock = self.socks[item.remote_address] - comm, rank = self.comms[item.remote_address] - data = { - "cmd": "PUT", - "tensor_id": item.tensor_id, - "shape": tensor.shape, - "dtype": str(tensor.dtype).replace("torch.", ""), - } - sock.send(msgpack.dumps(data)) - - response = sock.recv() - if response != b"0": - logger.error( - "🔴Send Tensor, Peer Out Of Memory/Threshold, %s 👉 %s, " - "MyRank:%s, data:%s, tensor:%s, size:%fGB, response:%s", - self.zmq_address, - item.remote_address, - rank, - data, - tensor.shape, - tensor.element_size() * tensor.numel() / 1024**3, - response.decode(), - ) - return False - - self.send(comm, tensor.to(self.device), rank ^ 1, self.send_stream) - - if self.send_type == "PUT_ASYNC": - self.have_sent_tensor_id(item.tensor_id) - - return True - - def get_finished( - self, finished_req_ids: set[str], no_compile_layers - ) -> tuple[set[str] | None, set[str] | None]: - """ - Notifies worker-side connector ids of requests that have - finished generating tokens. - - Returns: - ids of requests that have finished asynchronous transfer, - tuple of (sending/saving ids, recving/loading ids). - The finished saves/sends req ids must belong to a set provided in a - call to this method (this call or a prior one). - """ - - # Clear the buffer upon request completion. - for request_id in finished_req_ids: - for layer_name in no_compile_layers: - tensor_id = request_id + "#" + layer_name - if tensor_id in self.recv_store: - with self.recv_store_cv: - tensor = self.recv_store.pop(tensor_id, None) - self.send_request_id_to_tensor_ids.pop(request_id, None) - self.recv_request_id_to_tensor_ids.pop(request_id, None) - if isinstance(tensor, tuple): - addr, _, _ = tensor - self.pool.free(addr) - - # TODO:Retrieve requests that have already sent the KV cache. - finished_sending: set[str] = set() - - # TODO:Retrieve requests that have already received the KV cache. - finished_recving: set[str] = set() - - return finished_sending or None, finished_recving or None - - def ping(self): - sock = self.context.socket(zmq.DEALER) - sock.setsockopt_string(zmq.IDENTITY, self.zmq_address) - logger.debug("ping start, zmq_address:%s", self.zmq_address) - sock.connect(f"tcp://{self.proxy_address}") - data = { - "type": "P" if self.config.is_kv_producer else "D", - "http_address": self.http_address, - "zmq_address": self.zmq_address, - } - while True: - sock.send(msgpack.dumps(data)) - time.sleep(3) - - def send(self, comm, tensor: torch.Tensor, dst: int, stream=None): - assert tensor.device == self.device, ( - f"this nccl communicator is created to work on {self.device}, " - f"but the input tensor is on {tensor.device}" - ) - if stream is None: - stream = current_stream() - - with torch.cuda.stream(stream): - self.nccl.ncclSend( - buffer_type(tensor.data_ptr()), - tensor.numel(), - ncclDataTypeEnum.from_torch(tensor.dtype), - dst, - comm, - cudaStream_t(stream.cuda_stream), - ) - stream.synchronize() - - def recv(self, comm, tensor: torch.Tensor, src: int, stream=None): - assert tensor.device == self.device, ( - f"this nccl communicator is created to work on {self.device}, " - f"but the input tensor is on {tensor.device}" - ) - if stream is None: - stream = current_stream() - - with torch.cuda.stream(stream): - self.nccl.ncclRecv( - buffer_type(tensor.data_ptr()), - tensor.numel(), - ncclDataTypeEnum.from_torch(tensor.dtype), - src, - comm, - cudaStream_t(stream.cuda_stream), - ) - stream.synchronize() - - def close(self) -> None: - self._listener_thread.join() - if self.send_type == "PUT_ASYNC": - self._send_thread.join() - if self._ping_thread is not None: - self._ping_thread.join() diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/tensor_memory_pool.py b/vllm/distributed/kv_transfer/kv_connector/v1/p2p/tensor_memory_pool.py deleted file mode 100644 index 899f1eae86..0000000000 --- a/vllm/distributed/kv_transfer/kv_connector/v1/p2p/tensor_memory_pool.py +++ /dev/null @@ -1,273 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import atexit -import ctypes -import math -from dataclasses import dataclass - -import torch - -from vllm.logger import init_logger - -logger = init_logger(__name__) - - -@dataclass -class MemoryBlock: - size: int - addr: int - - -"""A memory pool for managing pinned host memory allocations for tensors. - -This class implements a buddy allocation system to efficiently manage pinned -host memory for tensor storage. It supports allocation, deallocation, and -tensor storage/retrieval operations. - -Key Features: -- Uses power-of-two block sizes for efficient buddy allocation -- Supports splitting and merging of memory blocks -- Provides methods to store CUDA tensors in pinned host memory -- Allows loading tensors from pinned memory back to device -- Automatically cleans up memory on destruction - -Attributes: - max_block_size (int): Maximum block size (rounded to nearest power of two) - min_block_size (int): Minimum block size (rounded to nearest power of two) - free_lists (dict): Dictionary of free memory blocks by size - allocated_blocks (dict): Dictionary of currently allocated blocks - base_tensor (torch.Tensor): Base pinned memory tensor - base_address (int): Base memory address of the pinned memory region - -Example: - >>> pool = TensorMemoryPool(max_block_size=1024*1024) - >>> tensor = torch.randn(100, device='cuda') - >>> addr = pool.store_tensor(tensor) - >>> loaded_tensor = pool.load_tensor(addr, tensor.dtype, - ... tensor.shape, 'cuda') - >>> pool.free(addr) -""" - - -class TensorMemoryPool: - """Initializes the memory pool with given size constraints. - - Args: - max_block_size (int): Maximum size of memory blocks to manage - min_block_size (int, optional): Minimum size of memory blocks - to manage. Defaults to 512. - - Raises: - ValueError: If block sizes are invalid or max_block_size is less - than min_block_size - """ - - def __init__(self, max_block_size: int, min_block_size: int = 512): - if max_block_size <= 0 or min_block_size <= 0: - raise ValueError("Block sizes must be positive") - if max_block_size < min_block_size: - raise ValueError("Max block size must be greater than min block size") - - self.max_block_size = self._round_to_power_of_two(max_block_size) - self.min_block_size = self._round_to_power_of_two(min_block_size) - - self.free_lists: dict[int, dict[int, MemoryBlock]] = {} - self.allocated_blocks: dict[int, MemoryBlock] = {} - - self._initialize_free_lists() - self._allocate_pinned_memory() - - atexit.register(self.cleanup) - - def _round_to_power_of_two(self, size: int) -> int: - return 1 << (size - 1).bit_length() - - def _initialize_free_lists(self): - size = self.max_block_size - while size >= self.min_block_size: - self.free_lists[size] = {} - size //= 2 - - def _allocate_pinned_memory(self): - self.base_tensor = torch.empty( - self.max_block_size // 4, dtype=torch.float32, pin_memory=True - ) - self.base_address = self.base_tensor.data_ptr() - initial_block = MemoryBlock(size=self.max_block_size, addr=self.base_address) - self.free_lists[self.max_block_size][initial_block.addr] = initial_block - - logger.debug( - "TensorMemoryPool, base_address:%d, max_block_size:%d", - self.base_address, - self.max_block_size, - ) - - def allocate(self, size: int) -> int: - """Allocates a memory block of at least the requested size. - - Args: - size (int): Minimum size of memory to allocate - - Returns: - int: Address of the allocated memory block - - Raises: - ValueError: If size is invalid or insufficient memory is available - """ - if size <= 0: - raise ValueError("Allocation size must be positive") - - required_size = self._round_to_power_of_two(max(size, self.min_block_size)) - if required_size > self.max_block_size: - raise ValueError("Requested size exceeds maximum block size") - - current_size = required_size - while current_size <= self.max_block_size: - if self.free_lists[current_size]: - _, block = self.free_lists[current_size].popitem() - self._split_block(block, required_size) - self.allocated_blocks[block.addr] = block - return block.addr - current_size *= 2 - - raise ValueError("Insufficient memory") - - def _split_block(self, block: MemoryBlock, required_size: int): - while block.size > required_size and block.size // 2 >= self.min_block_size: - buddy_size = block.size // 2 - buddy_addr = block.addr + buddy_size - - buddy = MemoryBlock(size=buddy_size, addr=buddy_addr) - block.size = buddy_size - - self.free_lists[buddy_size][buddy.addr] = buddy - - def free(self, addr: int): - """Frees an allocated memory block. - - Args: - addr (int): Address of the block to free - - Raises: - ValueError: If address is invalid or not allocated - """ - if addr not in self.allocated_blocks: - raise ValueError("Invalid address to free") - - block = self.allocated_blocks.pop(addr) - self._merge_buddies(block) - - def _merge_buddies(self, block: MemoryBlock): - MAX_MERGE_DEPTH = 30 - depth = 0 - - while depth < MAX_MERGE_DEPTH: - buddy_offset = ( - block.size - if (block.addr - self.base_address) % (2 * block.size) == 0 - else -block.size - ) - buddy_addr = block.addr + buddy_offset - buddy = self.free_lists[block.size].get(buddy_addr) - if buddy: - del self.free_lists[buddy.size][buddy.addr] - merged_addr = min(block.addr, buddy.addr) - merged_size = block.size * 2 - block = MemoryBlock(size=merged_size, addr=merged_addr) - depth += 1 - else: - break - self.free_lists[block.size][block.addr] = block - - def store_tensor(self, tensor: torch.Tensor) -> int: - """Stores a CUDA tensor in pinned host memory. - - Args: - tensor (torch.Tensor): CUDA tensor to store - - Returns: - int: Address where the tensor is stored - - Raises: - ValueError: If tensor is not on CUDA or allocation fails - """ - if not tensor.is_cuda: - raise ValueError("Only CUDA tensors can be stored") - - size = tensor.element_size() * tensor.numel() - addr = self.allocate(size) - block = self.allocated_blocks[addr] - - if block.size < size: - self.free(addr) - raise ValueError( - f"Allocated block size {block.size} is smaller than " - f"required size {size}" - ) - - try: - buffer = (ctypes.c_byte * block.size).from_address(block.addr) - cpu_tensor = torch.frombuffer( - buffer, dtype=tensor.dtype, count=tensor.numel() - ).reshape(tensor.shape) - except ValueError as err: - self.free(addr) - raise ValueError(f"Failed to create tensor view: {err}") from err - - cpu_tensor.copy_(tensor) - - return addr - - def load_tensor( - self, - addr: int, - dtype: torch.dtype, - shape: tuple[int, ...], - device: torch.device, - ) -> torch.Tensor: - """Loads a tensor from pinned host memory to the specified device. - - Args: - addr (int): Address where tensor is stored - dtype (torch.dtype): Data type of the tensor - shape (tuple[int, ...]): Shape of the tensor - device: Target device for the loaded tensor - - Returns: - torch.Tensor: The loaded tensor on the specified device - - Raises: - ValueError: If address is invalid or sizes don't match - """ - if addr not in self.allocated_blocks: - raise ValueError("Invalid address to load") - - block = self.allocated_blocks[addr] - num_elements = math.prod(shape) - dtype_size = torch.tensor([], dtype=dtype).element_size() - required_size = num_elements * dtype_size - - if required_size > block.size: - raise ValueError("Requested tensor size exceeds block size") - - buffer = (ctypes.c_byte * block.size).from_address(block.addr) - cpu_tensor = torch.frombuffer(buffer, dtype=dtype, count=num_elements).reshape( - shape - ) - - cuda_tensor = torch.empty(shape, dtype=dtype, device=device) - - cuda_tensor.copy_(cpu_tensor) - - return cuda_tensor - - def cleanup(self): - """Cleans up all memory resources and resets the pool state.""" - self.free_lists.clear() - self.allocated_blocks.clear() - if hasattr(self, "base_tensor"): - del self.base_tensor - - def __del__(self): - self.cleanup()