This article primarily discusses the deployment of a single LLM model across multiple GPUs on a single node, providing a service that is compatible with the OpenAI interface, as well as the usage of the service API.
For the sake of convenience, we refer to this service as api_server. Regarding parallel services with multiple models, please refer to the guide about Request Distribution Server.
In the following sections, we will first introduce methods for starting the service, choosing the appropriate one based on your application scenario.
Next, we focus on the definition of the service's RESTful API, explore the various ways to interact with the interface, and demonstrate how to try the service through the Swagger UI or LMDeploy CLI tools.
Take the internlm2_5-7b-chat model hosted on huggingface hub as an example, you can choose one the following methods to start the service.
lmdeploy serve api_server internlm/internlm2_5-7b-chat --server-port 23333The arguments of api_server can be viewed through the command lmdeploy serve api_server -h, for instance, --tp to set tensor parallelism, --session-len to specify the max length of the context window, --cache-max-entry-count to adjust the GPU mem ratio for k/v cache etc.
With LMDeploy official docker image, you can run OpenAI compatible server as follows:
docker run --runtime nvidia --gpus all \
-v ~/.cache/huggingface:/root/.cache/huggingface \
--env "HUGGING_FACE_HUB_TOKEN=<secret>" \
-p 23333:23333 \
--ipc=host \
openmmlab/lmdeploy:latest \
lmdeploy serve api_server internlm/internlm2_5-7b-chatThe parameters of api_server are the same with that mentioned in "option 1" section
Connect to a running Kubernetes cluster and deploy the internlm2_5-7b-chat model service with kubectl command-line tool (replace <your token> with your huggingface hub token):
sed 's/{{HUGGING_FACE_HUB_TOKEN}}/<your token>/' k8s/deployment.yaml | kubectl create -f - \
&& kubectl create -f k8s/service.yamlIn the example above the model data is placed on the local disk of the node (hostPath). Consider replacing it with high-availability shared storage if multiple replicas are desired, and the storage can be mounted into container using PersistentVolume.
LMDeploy's RESTful API is compatible with the following three OpenAI interfaces:
- /v1/chat/completions
- /v1/models
- /v1/completions
For /v1/chat/completions, content arrays must contain objects with a supported type.
Unknown or missing block types and non-object blocks return HTTP 400 before generation, including when stream=true.
The error message identifies the location, for example messages[0].content[1].type; unsupported blocks are not silently removed.
You can overview and try out the offered RESTful APIs by the website http://0.0.0.0:23333 as shown in the below image after launching the service successfully.
If you need to integrate the service into your own projects or products, we recommend the following approach:
Explicit request sampling parameters override model/server defaults. If neither
provides a temperature, LMDeploy uses temperature=1.0. To retain the previous
fallback behavior, explicitly set temperature=0.8. Greedy decoding is unchanged.
Set top_k=0 or top_k=-1 to disable top-k filtering, including when overriding
a positive model/server default. Both values are normalized to 0 before reaching
the inference backend. Values below -1 are rejected. This applies to Chat
Completions, Completions, Responses, Anthropic Messages, /generate, and Python
GenerationConfig. With the OpenAI Python client, pass extra_body={"top_k": -1}.
Set return_prompt_text=true on /v1/chat/completions to include the rendered prompt_text in the response. With the Python OpenAI client, pass extra_body={"return_prompt_text": True}; raw JSON may use either the top-level field or the same nested object, with the top-level value taking precedence. Streaming includes the prompt in the first chunk of each choice. The value is the actual template output, so reasoning-effort markers depend on the model's template. Raw input_ids requests have no rendered prompt and return null. The field is omitted unless requested.
Set return_token_ids=true on /v1/chat/completions to return prompt_token_ids
at the response's top level and generated output_ids in each choice. With the
Python OpenAI client, pass extra_body={"return_token_ids": True}. Raw JSON
accepts either the top-level field or the same nested object; the top-level value
takes precedence. The new prompt_token_ids field is omitted unless requested,
independently of return_prompt_text and logprobs.
The prompt IDs are copied from the input prepared for generation, including chat
template tokens; they are not reconstructed by tokenizing prompt_text. Raw
input_ids requests also return the prepared IDs, even without rendered text.
For example, a non-streaming response includes:
{
"prompt_token_ids": [101, 102, 103],
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "..."},
"output_ids": [201, 202],
"finish_reason": "stop"
}
]
}Streaming includes the complete prompt IDs on each choice's first data chunk,
even if it has no visible text. With n > 1, the field may therefore appear in
multiple chunks; merged choices share one top-level copy. Store one complete
prompt list and concatenate only the incremental output_ids separately for
each choice. Usage-only chunks do not include prompt IDs.
Token IDs can support fixed-sequence scoring and debugging of control tokens.
They do not themselves request logprobs or change the existing filtering of stop
tokens in output_ids. Preserve the model/tokenizer revisions and inference
configuration for replay; multimodal requests also need the original media and
preprocessing configuration.
Start with --backend pytorch --logprobs-mode raw_logprobs. Chat requests accept
0 <= top_logprobs <= vocab_size, using the loaded model's output vocabulary,
including multi-process engines. For a 154880-token model, add
"logprobs": true, "top_logprobs": 154880, "max_completion_tokens": 1 to a request.
Oversized counts return HTTP 400; TurboMind retains its limit of 20.
Raw logprobs precede temperature, penalties, and sampling filters. For distribution
analysis, include the selected token's outer score when absent from top_logprobs.
Low-precision scores have rounding error; a full returned distribution can be renormalized for analysis.
Unmapped vocabulary IDs use token_id:<id> with unavailable bytes. Full-vocabulary
responses are large; keep the output-token budget small.
Streaming and non-streaming Chat are supported. Responses ignores top_logprobs;
Messages' return_logprob returns only generated-token scores.
With the default response parser, json_object, json_schema, and regex_schema constrain the entire generated sequence. These modes disable thinking through the chat template and return the constrained output in content, including in streams. Protocol-like strings inside the answer remain literal data. Required tool calls use their own tagged grammar and can still include reasoning.
A nonempty final assistant message is treated as a continuation of that message. Plain-text prefills continue in content; a prefill ending inside an explicit <think> block continues in the reasoning channel.
Raw JSON requests also accept enable_thinking and media_io_kwargs inside extra_body, with top-level values taking precedence. Prefer chat_template_kwargs={"enable_thinking": false} for new integrations; the top-level enable_thinking option is deprecated.
Here is an example of interaction with the endpoint v1/chat/completions service via the openai package.
Before running it, please install the openai package by pip install openai
from openai import OpenAI
client = OpenAI(
api_key='YOUR_API_KEY',
base_url="http://0.0.0.0:23333/v1"
)
model_name = client.models.list().data[0].id
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": " provide three suggestions about time management"},
],
temperature=0.8,
top_p=0.8
)
print(response)If you want to use async functions, may try the following example:
import asyncio
from openai import AsyncOpenAI
async def main():
client = AsyncOpenAI(api_key='YOUR_API_KEY',
base_url='http://0.0.0.0:23333/v1')
model_cards = await client.models.list()._get_page()
response = await client.chat.completions.create(
model=model_cards.data[0].id,
messages=[
{
'role': 'system',
'content': 'You are a helpful assistant.'
},
{
'role': 'user',
'content': ' provide three suggestions about time management'
},
],
temperature=0.8,
top_p=0.8)
print(response)
asyncio.run(main())You can invoke other OpenAI interfaces using similar methods. For more detailed information, please refer to the OpenAI API guide
May refer to api_server_tools.
May refer to api_server_anthropic.
May refer to api_server_responses.
May use openapi-generator-cli to convert http://{server_ip}:{server_port}/openapi.json to java/rust/golang client.
Here is an example:
$ docker run -it --rm -v ${PWD}:/local openapitools/openapi-generator-cli generate -i /local/openapi.json -g rust -o /local/rust
$ ls rust/*
rust/Cargo.toml rust/git_push.sh rust/README.md
rust/docs:
ChatCompletionRequest.md EmbeddingsRequest.md HttpValidationError.md LocationInner.md Prompt.md
DefaultApi.md GenerateRequest.md Input.md Messages.md ValidationError.md
rust/src:
apis lib.rs modelscURL is a tool for observing the output of the RESTful APIs.
- list served models
v1/models
curl http://{server_ip}:{server_port}/v1/models- chat
v1/chat/completions
curl http://{server_ip}:{server_port}/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "intern-s2-preview",
"messages": [{"role": "user", "content": "Hello! How are you?"}]
}'- text completions
v1/completions
curl http://{server_ip}:{server_port}/v1/completions \
-H 'Content-Type: application/json' \
-d '{
"model": "llama",
"prompt": "two steps to build a house:"
}'- score input tokens with the direct PyTorch
/generateendpoint
Start the server with --backend pytorch --logprobs-mode raw_logprobs, then
set return_logprob and logprob_start_len:
curl http://{server_ip}:{server_port}/generate \
-H 'Content-Type: application/json' \
-d '{
"input_ids": [1234, 5678, 9012],
"return_logprob": true,
"logprob_start_len": 0,
"max_tokens": 0
}'meta_info.input_token_logprobs is emitted once. For
N=logprob_start_len, rows align with the processed source token ids after
position N, and every entry is [value, token_id]; the boundary token itself
is not emitted. With direct input_ids, this is input_ids[N + 1:]; with
prompt or image input, the boundary is checked after tokenization and VLM
placeholder expansion. At least one token must follow the boundary; otherwise
the endpoint rejects the request. Both streaming and non-streaming forms return
one terminal payload; streaming then emits [DONE].
This direct route requires max_tokens=0 and speculative decoding disabled.
Input scoring is not available for TurboMind, DistServe, proxy /generate, or
the OpenAI/Anthropic/Responses schemas.
Following are two steps to launch multiple api servers through torchrun. Just create a python script with the following codes.
- Launch the proxy server through
lmdeploy serve proxy. Get the correct proxy server url. - Launch the script through
torchrun --nproc_per_node 2 script.py InternLM/internlm2-chat-1_8b --proxy_url http://{proxy_node_name}:{proxy_node_port}.Note: Please do not use0.0.0.0:8000here, instead, we input the real ip name,11.25.34.55:8000for example.
import os
import socket
from typing import List, Literal
import fire
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def main(model_path: str,
tp: int = 1,
proxy_url: str = 'http://0.0.0.0:8000',
port: int = 23333,
backend: Literal['turbomind', 'pytorch'] = 'turbomind'):
local_rank = int(os.environ.get('LOCAL_RANK', -1))
world_size = int(os.environ.get('WORLD_SIZE', -1))
local_ip = get_host_ip()
if isinstance(port, List):
assert len(port) == world_size
port = port[local_rank]
else:
port += local_rank * 10
if (world_size - local_rank) % tp == 0:
rank_list = ','.join([str(local_rank + i) for i in range(tp)])
command = f'CUDA_VISIBLE_DEVICES={rank_list} lmdeploy serve api_server {model_path} '\
f'--server-name {local_ip} --server-port {port} --tp {tp} '\
f'--proxy-url {proxy_url} --backend {backend}'
print(f'running command: {command}')
os.system(command)
if __name__ == '__main__':
fire.Fire(main)-
When user got
"finish_reason":"length", it means the session is too long to be continued. The session length can be modified by passing--session_lento api_server. -
When OOM appeared at the server side, please reduce the
cache_max_entry_countofbackend_configwhen launching the service. -
Regarding the stop words, we only support characters that encode into a single index. Furthermore, there may be multiple indexes that decode into results containing the stop word. In such cases, if the number of these indexes is too large, we will only use the index encoded by the tokenizer. If you want use a stop symbol that encodes into multiple indexes, you may consider performing string matching on the streaming client side. Once a successful match is found, you can then break out of the streaming loop.
-
To customize a chat template, please refer to chat_template.md.
