Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ RUN case ${TARGETPLATFORM} in \
WORKDIR /lightllm

COPY ./requirements.txt /lightllm/requirements.txt
COPY docker/requirements.hypercorn.txt /lightllm/docker/requirements.hypercorn.txt
RUN pip install -U pip
RUN pip install --no-cache-dir \
-i https://pypi.org/simple \
Expand Down Expand Up @@ -148,4 +149,6 @@ RUN if [ "${ENABLE_NIXL}" = "1" ]; then \
fi

COPY . /lightllm
RUN pip install -e /lightllm --no-cache-dir
RUN pip install -e /lightllm --no-cache-dir \
&& python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \
&& python lightllm/utils/verify_hypercorn.py
2 changes: 2 additions & 0 deletions docker/requirements.hypercorn.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Hypercorn PR 391. The patched distribution also reports version 0.18.0.
hypercorn @ https://github.com/mayuriphad/hypercorn/archive/52f4134ec2c1366b36246f5a01b219136d1ec454.tar.gz?download=1#sha256=ed82db9986a45b422a0d11d497f38a6a282840df3648ec080dc208cf3e1d7534
11 changes: 11 additions & 0 deletions docs/CN/source/getting_started/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ Lightllm 是一个纯python开发的推理框架,其中的算子使用triton
$ # 安装lightllm的依赖 (摩尔线程 GPU)
$ ./generate_requirements_musa.sh
$ pip install -r requirements-musa.txt

CUDA 与摩尔线程环境均需执行下面的安装或升级步骤。补丁版 Hypercorn 与原版的版本号相同。

.. code-block:: console

$ python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt
$ python lightllm/utils/verify_hypercorn.py
$
$ # 安装lightllm
$ python setup.py install
Expand All @@ -100,5 +107,9 @@ Lightllm 是一个纯python开发的推理框架,其中的算子使用triton
$ # 安装 Lightllm 依赖 (CUDA 13.0)
$ uv pip install -r requirements.txt --torch-backend=cu130
$
$ # 补丁版和原版 Hypercorn 都使用 0.18.0 版本号,源码安装或升级时需替换并校验 HTTP/2 处理模块。
$ uv pip install --reinstall --no-deps -r docker/requirements.hypercorn.txt
$ python lightllm/utils/verify_hypercorn.py
$
$ # 安装 Lightllm
$ uv pip install -e .
2 changes: 2 additions & 0 deletions docs/CN/source/tutorial/pd_master_multiprocess.rst
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ HAProxy。依赖已固定在 ``requirements.txt``:
.. code-block:: bash

pip install -r requirements.txt
python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt
python lightllm/utils/verify_hypercorn.py

.. code-block:: bash

Expand Down
11 changes: 11 additions & 0 deletions docs/EN/source/getting_started/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ You can also install Lightllm from source:
$ # Install Lightllm dependencies (Moore Threads GPU)
$ ./generate_requirements_musa.sh
$ pip install -r requirements-musa.txt

For both CUDA and Moore Threads, finish the installation or upgrade with the following commands. The patched and stock Hypercorn distributions have the same version.

.. code-block:: console

$ python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt
$ python lightllm/utils/verify_hypercorn.py
$
$ # Install Lightllm
$ python setup.py install
Expand All @@ -102,5 +109,9 @@ You can also install Lightllm with `uv <https://docs.astral.sh/uv/>`_:
$ # Install Lightllm dependencies (CUDA 13.0)
$ uv pip install -r requirements.txt --torch-backend=cu130
$
$ # Replace and verify the HTTP/2 handler on source installs and upgrades. Both Hypercorn builds report 0.18.0.
$ uv pip install --reinstall --no-deps -r docker/requirements.hypercorn.txt
$ python lightllm/utils/verify_hypercorn.py
$
$ # Install Lightllm
$ uv pip install -e .
2 changes: 2 additions & 0 deletions docs/EN/source/tutorial/pd_master_multiprocess.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ The entry point uses the native HAProxy bundled in the
.. code-block:: bash

pip install -r requirements.txt
python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt
python lightllm/utils/verify_hypercorn.py

.. code-block:: bash

Expand Down
4 changes: 3 additions & 1 deletion lightllm/server/api_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1325,6 +1325,7 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response:
from .api_openai import _build_multimodal_params, _select_chat_template_tools
from .build_prompt import build_prompt
from .core.objs.sampling_params import SamplingParams
from .httpserver_for_pd_master.prompt_processing import run_prompt_work

raw_body = await raw_request.json()
# LiteLLM validates the body as a Messages creation request, where
Expand All @@ -1340,7 +1341,8 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response:

sampling_params = SamplingParams()
sampling_params.init(tokenizer=g_objs.httpserver_manager.tokenizer, add_special_tokens=False)
input_tokens = g_objs.httpserver_manager.tokens(
input_tokens = await run_prompt_work(
g_objs.httpserver_manager.tokens,
prompt,
multimodal_params,
sampling_params,
Expand Down
160 changes: 122 additions & 38 deletions lightllm/server/api_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import time

import uvloop
from anyio import create_task_group
import requests
import base64
import os
Expand All @@ -45,6 +46,7 @@
from .multimodal_params import MultimodalParams
from .httpserver.manager import HttpServerManager
from .httpserver_for_pd_master.manager import HttpServerManagerForPDMaster
from .httpserver_for_pd_master import prompt_processing
from .api_lightllm import lightllm_get_score
from lightllm.utils.envs_utils import get_env_start_args
from lightllm.utils.log_utils import init_logger
Expand All @@ -58,6 +60,7 @@
from lightllm.server.metrics.manager import MetricClient
from lightllm.utils.envs_utils import get_unique_server_name
from lightllm.utils.shm_port_args import get_shm_port_args
from lightllm.utils.verify_hypercorn import verify_hypercorn
from dataclasses import asdict, dataclass, is_dataclass

from .api_errors import create_error_response, create_server_busy_response
Expand All @@ -71,13 +74,16 @@
ModelListResponse,
)
from .build_prompt import build_prompt, init_tokenizer
from .api_http_pd import PDHeartbeatMonitor, router as pd_router

logger = init_logger(__name__)


@dataclass
class G_Objs:
app: FastAPI = None
pd_heartbeat_monitor: PDHeartbeatMonitor = None
pd_heartbeat_task: asyncio.Task = None
metric_client: MetricClient = None
args: StartArgs = None
g_generate_func: Callable = None
Expand All @@ -89,6 +95,9 @@ class G_Objs:
model_created: int = None

def set_args(self, args: StartArgs):
if args.run_mode == "pd_master":
verify_hypercorn()
prompt_processing.configure_prompt_processing(args.run_mode)
self.args = args
from .api_lightllm import lightllm_generate, lightllm_generate_stream
from .api_tgi import tgi_generate_impl, tgi_generate_stream_impl
Expand Down Expand Up @@ -158,6 +167,86 @@ async def send_wrapper(message):
logger.info(msg)


async def _discard_request_body(receive):
"""Release request chunks as they arrive. Return False on disconnect."""
while True:
message = await receive()
if message["type"] == "http.disconnect":
return False
if not message.get("more_body", False):
return True


async def _reject_pd_request(scope, receive, send):
# Finishing an HTTP/1 response while the client is still uploading can
# reset the connection and lose the 429. Discard chunks without parsing
# JSON or buffering the request body.
http_version = scope.get("http_version", "1.1")
if http_version.startswith("1") and not await _discard_request_body(receive):
return
if scope["path"].startswith("/v1/messages"):
from .api_anthropic import _anthropic_error_response

g_objs.metric_client.counter_inc("lightllm_request_failure")
response = _anthropic_error_response(HTTPStatus.TOO_MANY_REQUESTS, SERVER_BUSY_MESSAGE)
else:
response = create_server_busy_response(ServerBusyError("PD master request or prompt capacity reached"))
if http_version == "2":
# Hypercorn can block its connection reader on a full ASGI input
# queue. Drain it while sending the 429, until EOF or disconnect.
async with create_task_group() as tasks:
tasks.start_soon(_discard_request_body, receive)
await response(scope, receive, send)
return
return await response(scope, receive, send)


class _PDRequestAdmission:
# Reserve before FastAPI parses the body. The ASGI application returns only after
# the response (including SSE) finishes or the request is cancelled.
routes = frozenset(
{
("POST", "/"),
("POST", "/generate"),
("POST", "/generate_stream"),
("POST", "/get_score"),
("POST", "/v1/chat/completions"),
("POST", "/v1/completions"),
("POST", "/v1/responses"),
("POST", "/v1/messages"),
("POST", "/v1/messages/count_tokens"),
("POST", "/tokens"),
("GET", "/tokens"),
}
)

def __init__(self, app):
self.app = app
self.in_flight = 0

async def __call__(self, scope, receive, send):
if (
scope["type"] != "http"
or (scope["method"], scope["path"]) not in self.routes
or g_objs.args is None
or g_objs.args.run_mode != "pd_master"
):
return await self.app(scope, receive, send)

pool = prompt_processing.get_pd_prompt_pool()
if self.in_flight >= g_objs.args.running_max_req_size or (
pool.backed_up() and (pool.subcore or g_objs.pd_heartbeat_monitor.recently_delayed())
):
return await _reject_pd_request(scope, receive, send)

self.in_flight += 1
try:
return await self.app(scope, receive, send)
finally:
self.in_flight -= 1


app.add_middleware(_PDRequestAdmission)
app.add_middleware(_AccessLogMiddleware)


Expand Down Expand Up @@ -204,7 +293,7 @@ async def generation_exception_handler(request: Request, exc: GenerationError) -

@app.get("/liveness")
@app.post("/liveness")
def liveness():
async def liveness():
return {"status": "ok"}


Expand Down Expand Up @@ -259,35 +348,29 @@ async def healthcheck(request: Request):
if g_objs.args.run_mode == "pd_master":
httpserver_manager = g_objs.httpserver_manager
pd_manager = httpserver_manager.pd_manager
if g_objs.args.pd_master_mode == "elastic":
inference_is_healthy = httpserver_manager.is_healthy()
pd_nodes_are_ready = pd_manager.is_pd_nodes_ready()
is_healthy = inference_is_healthy and pd_nodes_are_ready
health_info = {
"inference_healthy": inference_is_healthy,
"pd_nodes_ready": pd_nodes_are_ready,
}
else:
inference_is_healthy = httpserver_manager.is_healthy()
pd_nodes_are_ready = pd_manager.is_pd_nodes_ready()
pd_nodes_are_healthy = (
inference_is_healthy and pd_nodes_are_ready and await pd_manager.check_pd_nodes_health()
)
is_healthy = pd_nodes_are_healthy
health_info = {
"inference_healthy": inference_is_healthy,
"pd_nodes_ready": pd_nodes_are_ready,
"pd_nodes_healthy": pd_nodes_are_healthy,
}

health_info.update(
{
"message": "Ok" if is_healthy else "Error",
"pd_master_mode": g_objs.args.pd_master_mode,
"registered_prefill_nodes": len(pd_manager.prefill_nodes),
"registered_decode_nodes": len(pd_manager.decode_nodes),
}
)
mode = g_objs.args.pd_master_mode
inference_healthy = httpserver_manager.is_healthy()
nodes_ready = pd_manager.is_pd_nodes_ready()
is_healthy = inference_healthy and nodes_ready
if is_healthy and mode != "elastic":
probed_version = pd_manager.registration_version
reachable = await pd_manager.check_pd_nodes_health()
# A reconnect can replace a socket on the same PD_Client_Obj.
same_registrations = pd_manager.registration_version == probed_version
inference_healthy = httpserver_manager.is_healthy()
nodes_ready = pd_manager.is_pd_nodes_ready()
is_healthy = reachable and same_registrations and inference_healthy and nodes_ready

health_info = {
"inference_healthy": inference_healthy,
"pd_nodes_ready": nodes_ready,
"message": "Ok" if is_healthy else "Error",
"pd_master_mode": mode,
"registered_prefill_nodes": len(pd_manager.prefill_nodes),
"registered_decode_nodes": len(pd_manager.decode_nodes),
}
if mode != "elastic":
health_info["pd_nodes_healthy"] = is_healthy
return JSONResponse(health_info, status_code=200 if is_healthy else 503)

from lightllm.utils.health_check import health_check
Expand Down Expand Up @@ -538,14 +621,10 @@ async def tokens(request: Request):
multimodal_params_dict = request_dict.get("multimodal_params", {})
multimodal_params = MultimodalParams(**multimodal_params_dict)
await multimodal_params.verify_and_preload(request)
return JSONResponse(
{
"ntokens": g_objs.httpserver_manager.tokens(
prompt, multimodal_params, sampling_params, sample_params_dict
)
},
status_code=200,
ntokens = await prompt_processing.run_prompt_work(
g_objs.httpserver_manager.tokens, prompt, multimodal_params, sampling_params, sample_params_dict
)
return JSONResponse({"ntokens": ntokens})
except ValueError as e:
return create_error_response(HTTPStatus.BAD_REQUEST, str(e))
except ClientDisconnected as e:
Expand All @@ -569,7 +648,6 @@ async def metrics() -> Response:
app.include_router(rl_router)

# PD 分离控制面接口(worker 发现、P/D 注册与 KV 状态上报),见 api_http_pd.py
from .api_http_pd import router as pd_router

app.include_router(pd_router)

Expand All @@ -595,6 +673,9 @@ async def profiler_stop() -> Response:
@app.on_event("shutdown")
async def shutdown():
logger.info("Received signal to shutdown. Performing graceful shutdown...")
if g_objs.pd_heartbeat_task is not None:
g_objs.pd_heartbeat_task.cancel()
await asyncio.gather(g_objs.pd_heartbeat_task, return_exceptions=True)
await asyncio.sleep(3)

# 杀掉所有子进程
Expand All @@ -614,6 +695,9 @@ async def startup_event():
logger.info("server start up")
loop = asyncio.get_event_loop()
g_objs.set_args(get_env_start_args())
if g_objs.args.run_mode == "pd_master":
g_objs.pd_heartbeat_monitor = PDHeartbeatMonitor()
g_objs.pd_heartbeat_task = loop.create_task(g_objs.pd_heartbeat_monitor.run())
loop.create_task(g_objs.httpserver_manager.handle_loop())
logger.info(f"server start up ok, loop use is {asyncio.get_event_loop()}")
return
Loading
Loading