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#

_choice_declares_token_ids

Whether the installed TRT-LLM’s chat choice model declares token_ids.

_chat_completion_request_cls

ChatCompletionRequest whose assistant tool_calls survive dumping.

normalize_chat_inputs

messages and tools as TRT-LLM’s ChatCompletionRequest dumps them.

build_spliced_prompt_ids

Render the chat template and splice in the on-policy prefix.

_parse_disaggregated_params

The engine’s DisaggregatedParams plus the orchestrator’s b64 request.

_context_leg_response

Reply to a context_only request.

resolve_eos_token_ids

Every token that ends a turn: configured stops, tokenizer EOS and generation-config EOS.

_request_matches_profile

Whether every sampling param the request pins equals profile’s value.

_tokens_for_response_text

token_ids without trailing stop tokens, as a new list.

_prompt_opens_reasoning

Whether the prompt ends inside an open <think> block.

_build_reasoning_parser

_build_sampling_params

Build the TRT-LLM sampling params for one HTTP rollout request.

create_app

Build a FastAPI application backed by llm (tensorrt_llm.LLM).

_resolve_tool_parser_name

Resolve the configured parser or infer it from the model.

_decode_request_body

Body as a dict, honoring the orchestrator’s msgpack framing.

_build_tool_parser

Instantiate a TRT-LLM tool parser by registered name.

_make_parse_tool_calls

Return a tool-call parser bound to a specific parser instance.

_to_int_ids

Coerce chat-template output to a flat list[int].

_build_prompt_token_ids

Convert chat messages to token IDs via apply_chat_template (full retokenisation each turn).

_compute_splice_inputs

Return preserved and rendered token IDs for the on-policy prefix splice.

start_server

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#

ChatCompletionRequest whose assistant tool_calls survive dumping.

The OpenAI message types declare tool_calls as an Iterable, which validates into a lazy ValidatorIterator. For an assistant message that carries both reasoning and reasoning_content – what NeMo-Gym sends – the union resolves to TRT-LLM’s ReasoningAssistantMessage and model_dump then emits tool_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,
) → tuple[list[dict[str, Any]], list[dict[str, Any]] | None]#

messages and tools as TRT-LLM’s ChatCompletionRequest dumps 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,
) → list[int]#

Render the chat template and splice in the on-policy prefix.

eos_token_ids is every token that can end a turn (see

Func:

resolve_eos_token_ids); None means only tokenizer.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 ValueError for 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]],
) → tuple[Any, bool]#

The engine’s DisaggregatedParams plus 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 drops return_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 return prompt_token_ids_b64 instead 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,
) → Any#

Reply to a context_only request.

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_b64 comes 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,
) → set[int]#

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],
) → bool#

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_p is resolved from the model’s generation_config.json and therefore has to be rejected outright (see vllm_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],
) → list[int]#

token_ids without trailing stop tokens, as a new list.

nemo_rl.models.generation.trtllm.trtllm_http_server._prompt_opens_reasoning(
tokenizer: Any,
token_ids: list[int],
) → bool#

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,
) → Any#
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,
) → Any#

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 SamplingParams instance to hand to llm.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,
) → fastapi.FastAPI#

Build a FastAPI application backed by llm (tensorrt_llm.LLM).

Parameters:
  • llm – The tensorrt_llm.LLM engine 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,
) → 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,
) → dict[str, Any]#

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,
) → list[int]#

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,
) → tuple[list[int], list[int]]#

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,
) → tuple[threading.Thread, str, Any]#

Start the HTTP server in a daemon thread and return (thread, base_url, server).

Parameters:
  • llm – The tensorrt_llm.LLM engine 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).