nemo_rl.models.generation.trtllm.trtllm_http_server#
OpenAI-compatible HTTP server wrapping tensorrt_llm.LLM, serving /v1/chat/completions.
Returns prompt and generated token ids alongside per-token logprobs, and supports Qwen3 tool calling, DeepSeekR1Parser reasoning, and prefix token splicing.
Under PD disaggregation this endpoint is leg-aware. A replica’s
OpenAIDisaggServer drives it twice per request:
context_only– prefill only. Returns the handshake and the prompt token ids, skipping all post-processing; see :func:_context_leg_response.generation_only– decodes and post-processes as usual, but takes the prompt token ids the orchestrator relays from the context leg rather than rebuilding them, so the sequence matches the KV that was transferred.
Module Contents#
Functions#
Whether the installed TRT-LLM’s chat choice model declares |
|
|
|
|
|
Render the chat template and splice in the on-policy prefix. |
|
The engine’s |
|
Reply to a |
|
Every token that ends a turn: configured stops, tokenizer EOS and generation-config EOS. |
|
Whether every sampling param the request pins equals profile’s value. |
|
|
|
Whether the prompt ends inside an open |
|
Build the TRT-LLM sampling params for one HTTP rollout request. |
|
Build a FastAPI application backed by llm ( |
|
Resolve the configured parser or infer it from the model. |
|
Body as a dict, honoring the orchestrator’s msgpack framing. |
|
Instantiate a TRT-LLM tool parser by registered name. |
|
Return a tool-call parser bound to a specific parser instance. |
|
Coerce chat-template output to a flat list[int]. |
|
Convert chat messages to token IDs via apply_chat_template (full retokenisation each turn). |
|
Return preserved and rendered token IDs for the on-policy prefix splice. |
|
Start the HTTP server in a daemon thread and return (thread, base_url, server). |
Data#
API#
- nemo_rl.models.generation.trtllm.trtllm_http_server.logger#
‘getLogger(…)’
- nemo_rl.models.generation.trtllm.trtllm_http_server._choice_declares_token_ids() bool#
Whether the installed TRT-LLM’s chat choice model declares
token_ids.Cached because it is consulted once per generated response, and imported lazily because this module is also used on the aggregated path where tensorrt_llm need not be importable.
- nemo_rl.models.generation.trtllm.trtllm_http_server._chat_completion_request_cls() type#
ChatCompletionRequestwhose assistanttool_callssurvive dumping.The OpenAI message types declare
tool_callsas anIterable, which validates into a lazyValidatorIterator. For an assistant message that carries bothreasoningandreasoning_content– what NeMo-Gym sends – the union resolves to TRT-LLM’sReasoningAssistantMessageandmodel_dumpthen emitstool_calls: [], so the prompt is rendered without the conversation’s earlier tool calls. Materializing the iterator right after validation keeps them. Deferred so importing this module does not require tensorrt_llm.
- nemo_rl.models.generation.trtllm.trtllm_http_server.normalize_chat_inputs(
- messages: list[dict[str, Any]],
- tools: list[dict[str, Any]] | None,
messagesandtoolsas TRT-LLM’sChatCompletionRequestdumps them.Every path that renders the chat template goes through here, so the engine answering Gym directly and the disagg route render the same prompt. Key order matters: templates serialize each tool verbatim (
tool | tojson), and validation reorders a tool’s keys to the model’s declaration order,{"type", "function"}– what the disagg server hands its engines and what vLLM renders – while Gym sends{"function", "type"}.
- async nemo_rl.models.generation.trtllm.trtllm_http_server.build_spliced_prompt_ids(
- messages: list[dict],
- tools: list[dict] | None,
- tokenizer: Any,
- model_config: Any,
- template_kwargs: dict[str, Any],
- eos_token_ids: collections.abc.Collection[int] | None = None,
- chat_template: str | None = None,
Render the chat template and splice in the on-policy prefix.
eos_token_idsis every token that can end a turn (see- Func:
resolve_eos_token_ids);Nonemeans onlytokenizer.eos_token_id.
The single source of truth for turning a conversation into engine prompt ids – shared by the engine adapter’s route and the disagg frontend’s tokenizer (phase-2
frontend_tokenize) so both produce IDENTICAL ids; a divergence between them would silently train on off-policy tokens.Raises
ValueErrorfor unparseable or multimodal messages. The tokenizer-heavy part runs in a thread: the HF fast tokenizer releases the GIL, so a 30k-token render stops serializing the caller’s event loop.
- nemo_rl.models.generation.trtllm.trtllm_http_server._TOKENIZE_SHADOW_RATE#
‘float(…)’
- nemo_rl.models.generation.trtllm.trtllm_http_server._parse_disaggregated_params(
- raw: Optional[dict[str, Any]],
The engine’s
DisaggregatedParamsplus the orchestrator’s b64 request.The body carries TRT-LLM’s wire
DisaggregatedParams; the engine takes the LLM-level one (opaque_state is bytes there, base64 on the wire), so it is converted with TRT-LLM’s own helper. The conversion copies only what the engine consumes, which dropsreturn_prompt_token_ids_b64– an orchestrator-to-context-worker instruction (gen_tokids_ctxbytes) that must therefore be read off the wire model before converting.- Returns:
(None, False)without disaggregated params, else the LLM-level params and whether the context leg should returnprompt_token_ids_b64instead of the int list.
- nemo_rl.models.generation.trtllm.trtllm_http_server._context_leg_response(
- model_name: str,
- prompt_token_ids: list[int],
- gen: Any,
- return_prompt_token_ids_b64: bool,
Reply to a
context_onlyrequest.Prefill materialised KV and at most one token; the disagg server only reads the handshake back off this response (plus the prompt token ids, so the generation server need not re-tokenize). Nothing here is user-visible, so the reasoning/tool/stop-token post-processing is skipped entirely.
return_prompt_token_ids_b64comes from :func:_parse_disaggregated_params.
- nemo_rl.models.generation.trtllm.trtllm_http_server.resolve_eos_token_ids(
- tokenizer: Any,
- stop_token_ids: collections.abc.Collection[int] | None = None,
- generation_eos_token_ids: Any = None,
Every token that ends a turn: configured stops, tokenizer EOS and generation-config EOS.
- nemo_rl.models.generation.trtllm.trtllm_http_server._request_matches_profile(
- body: dict[str, Any],
- profile: dict[str, Any],
Whether every sampling param the request pins equals profile’s value.
Params the request leaves unset are not evidence against a profile. This server samples from the profile it selects and never from the request, so an omitted field simply takes that profile’s value – unlike vLLM, where an unset
top_pis resolved from the model’sgeneration_config.jsonand therefore has to be rejected outright (seevllm_worker_async.py).- Parameters:
body – Decoded chat-completions request body.
profile – Sampling profile to test, keyed
temperature/top_p/top_k.
- Returns:
True when the request is compatible with profile.
- nemo_rl.models.generation.trtllm.trtllm_http_server._tokens_for_response_text(
- token_ids: list[int],
- stop_token_ids: collections.abc.Collection[int],
token_idswithout trailing stop tokens, as a new list.
- nemo_rl.models.generation.trtllm.trtllm_http_server._prompt_opens_reasoning(
- tokenizer: Any,
- token_ids: list[int],
Whether the prompt ends inside an open
<think>block.
- nemo_rl.models.generation.trtllm.trtllm_http_server._build_reasoning_parser(
- name: str,
- chat_template_kwargs: dict[str, Any],
- *,
- reasoning_at_start: bool = False,
- nemo_rl.models.generation.trtllm.trtllm_http_server._build_sampling_params(
- sampling_params_cls: Any,
- *,
- sampling_config: dict[str, Any],
- stop_token_ids: list[int] | None,
- max_tokens: int,
Build the TRT-LLM sampling params for one HTTP rollout request.
Mirrors the direct generate() path (
TrtllmAsyncGenerationWorkerImpl._build_sampling_params) so both paths sample from the same distribution for a given generation config.- Parameters:
sampling_params_cls –
tensorrt_llm.SamplingParams, injected so this helper stays importable and testable without the TRT-LLM runtime.sampling_config – NeMo-RL generation config (temperature / top_p / top_k).
stop_token_ids – Extra stop tokens from the generation config, if any.
max_tokens – Output cap for this request, already clamped to the context window.
- Returns:
A
SamplingParamsinstance to hand tollm.generate_async.
- nemo_rl.models.generation.trtllm.trtllm_http_server.create_app(
- llm: Any,
- tokenizer: Any,
- model_name: str,
- *,
- max_seq_len: int,
- sampling_config: dict[str, Any],
- val_sampling_config: dict[str, Any],
- stop_token_ids: list[int] | None = None,
- default_chat_template_kwargs: dict[str, Any] | None = None,
- tool_parser: str | None = None,
- reasoning_parser: str | None = None,
- chat_template: str | None = None,
Build a FastAPI application backed by llm (
tensorrt_llm.LLM).- Parameters:
llm – The
tensorrt_llm.LLMengine to serve.tokenizer – Tokenizer matching llm, used for prompt construction.
model_name – Model identifier echoed back on responses.
max_seq_len – Context window of the engine being fronted.
sampling_config – Train sampling profile, keyed
temperature/top_p/top_k.val_sampling_config – Validation sampling profile, same keys.
stop_token_ids – Extra stop tokens to trim from generations.
default_chat_template_kwargs – Server-side chat template defaults.
tool_parser – Registered TRT-LLM tool parser name, or None to infer.
reasoning_parser – Registered TRT-LLM reasoning parser name, or None.
- Returns:
The configured FastAPI application.
- nemo_rl.models.generation.trtllm.trtllm_http_server._resolve_tool_parser_name(
- configured_name: str | None,
- model_name: str,
Resolve the configured parser or infer it from the model.
- nemo_rl.models.generation.trtllm.trtllm_http_server._MSGPACK_REQUEST_HEADER#
‘x-trtllm-msgpack’
- async nemo_rl.models.generation.trtllm.trtllm_http_server._decode_request_body(
- request: fastapi.Request,
Body as a dict, honoring the orchestrator’s msgpack framing.
- nemo_rl.models.generation.trtllm.trtllm_http_server._build_tool_parser(name: str) Any#
Instantiate a TRT-LLM tool parser by registered name.
- nemo_rl.models.generation.trtllm.trtllm_http_server._make_parse_tool_calls(tool_parser_instance: Any) Any#
Return a tool-call parser bound to a specific parser instance.
- nemo_rl.models.generation.trtllm.trtllm_http_server._to_int_ids(enc: Any) list[int]#
Coerce chat-template output to a flat list[int].
- nemo_rl.models.generation.trtllm.trtllm_http_server._build_prompt_token_ids(
- messages: list[dict[str, Any]],
- tokenizer: Any,
- *,
- tools: list[dict[str, Any]] | None = None,
- default_template_kwargs: dict[str, Any] | None = None,
- chat_template: str | None = None,
Convert chat messages to token IDs via apply_chat_template (full retokenisation each turn).
Full retokenisation avoids the gen_token_ids double-counting bug (~4000 tok/turn explosion that exhausted context at turn ~32 when prefix accumulation was used).
- nemo_rl.models.generation.trtllm.trtllm_http_server._compute_splice_inputs(
- raw_messages: list[dict[str, Any]],
- conversation: list[dict[str, Any]],
- tokenizer: Any,
- tools: list[dict[str, Any]] | None,
- default_template_kwargs: dict[str, Any],
- chat_template: str | None = None,
Return preserved and rendered token IDs for the on-policy prefix splice.
- nemo_rl.models.generation.trtllm.trtllm_http_server.start_server(
- llm: Any,
- tokenizer: Any,
- model_name: str,
- *,
- max_seq_len: int,
- sampling_config: dict[str, Any],
- val_sampling_config: dict[str, Any],
- stop_token_ids: list[int] | None = None,
- host: str = '0.0.0.0',
- port: int = 0,
- default_chat_template_kwargs: dict[str, Any] | None = None,
- tool_parser: str | None = None,
- reasoning_parser: str | None = None,
- chat_template: str | None = None,
Start the HTTP server in a daemon thread and return (thread, base_url, server).
- Parameters:
llm – The
tensorrt_llm.LLMengine to serve.tokenizer – Tokenizer matching llm.
model_name – Model identifier echoed back on responses.
max_seq_len – Context window of the engine being fronted.
sampling_config – Train sampling profile.
val_sampling_config – Validation sampling profile.
stop_token_ids – Extra stop tokens to trim from generations.
host – Bind address.
port – Bind port; 0 picks a free one.
default_chat_template_kwargs – Server-side chat template defaults.
tool_parser – Registered TRT-LLM tool parser name, or None to infer.
reasoning_parser – Registered TRT-LLM reasoning parser name, or None.
- Returns:
Tuple of (server thread, base URL, uvicorn server).