nemo_rl.models.generation.trtllm.trtllm_generation#

GenerationInterface implementation backed by TRT-LLM.

Non-colocated: separate train / inference GPU sets, NCCL broadcast for weight sync. Colocated: shares GPUs with the policy and uses sleep/wakeup to time-multiplex GPU memory between training and inference phases.

Module Contents#

Classes#

TrtllmGeneration

TRT-LLM generation backend (requires trtllm_cfg.async_engine=true).

API#

class nemo_rl.models.generation.trtllm.trtllm_generation.TrtllmGeneration(
cluster: nemo_rl.distributed.virtual_cluster.RayVirtualCluster,
config: nemo_rl.models.generation.trtllm.config.TrtllmConfig,
name_prefix: str = 'trtllm_policy',
workers_per_node: Optional[Union[int, list[int]]] = None,
)#

Bases: nemo_rl.models.generation.interfaces.GenerationInterface

TRT-LLM generation backend (requires trtllm_cfg.async_engine=true).

Initialization

static init_cluster_placement_groups(
cluster: nemo_rl.distributed.virtual_cluster.RayVirtualCluster,
config: nemo_rl.models.generation.trtllm.config.TrtllmConfig,
) → None#

Pre-initialize placement groups matching TRT-LLM’s topology.

_plan_engines(world_size: int) → tuple[list[str], list[int], int]#

Per-engine (role, width), in engine order.

Without disaggregation every engine is an aggregated engine of tensor_parallel_size GPUs. Under disaggregation each replica contributes its prefill engines followed by its decode engines:

[prefill_width x M, decode_width x K,   prefill_width x M, ...]
 \_________ replica 0 __________/  \____ replica 1 ...

The replica count is derived, not configured: it follows from the cluster size, the same way the DP-shard count does without disaggregation. Same-role engines stay contiguous so each role’s GPUs are adjacent.

_config_with_engine_roles(
node_bundle_indices: Optional[list[tuple[int, list[int]]]],
) → nemo_rl.models.generation.trtllm.config.TrtllmConfig#

Attach each engine’s prefill/decode role to the worker config.

RayWorkerBuilder hands every worker the same config, and a worker cannot tell its role from its TP width – both roles may share one. So the driver attaches a map keyed by :meth:_engine_key and each worker looks up its own entry, then reads that role’s engine config, which

Func:

resolve_role_overrides already resolved.

The role is per request in TRT-LLM, so an engine does not strictly need to know it; it is recorded because the engine’s config and its cache transceiver are chosen from it.

static _engine_key(pg_idx: int, local_bundle_indices: list[int]) → str#

Stable id for the engine occupying these bundles.

Both sides of the worker boundary compute this from the same (pg_idx, local_bundle_indices) tuple, so the worker can look up its own role without the driver needing per-worker init kwargs. Keying on the tuple rather than deriving a global ordinal keeps it correct for both the unified-PG and per-node-PG layouts, whose local bundle indices mean different things.

_get_tied_worker_bundle_indices(
cluster: nemo_rl.distributed.virtual_cluster.RayVirtualCluster,
) → list[tuple[int, list[int]]]#

Calculate bundle indices for tensor-parallel worker groups.

Handles both unified placement groups (cross-node model parallelism) and per-node placement groups (node-local model parallelism). For unified PGs, bundles are reordered by physical node before slicing so each TP group stays as node-local as possible.

Bundles are consumed engine by engine following self._engine_tps, so engines of differing width (PD disaggregation with asymmetric TP) each get exactly their own number of bundles.

_assert_direct_dispatch_allowed() → None#

Reject the direct engine-dispatch path while PD is enabled.

generate and generate_async send requests straight to the DP leader engines, bypassing the disagg servers, so the rollout would run without disaggregation. PD is only wired for the HTTP / NeMo-Gym path.

_start_disagg_servers() → list[Optional[str]]#

Start one disagg server per replica and return their URLs.

Every engine already runs its own HTTP server; an address is the only thing a disagg server is given about one. This slices the engine list into replicas, hands each disagg server its two address pools, and collects the single URL it exposes. Those URLs are what NeMo-Gym sees.

Starting a server is not idempotent, so a second call returns the URLs of the servers already running instead of doubling them.

_run_on_engines(
method_name: str,
per_engine: Optional[dict[str, list[Any]]] = None,
**common: Any,
) → list[ray.ObjectRef]#

Fan out to each engine’s model owner, one call per engine.

Dispatches by :attr:_engine_owner_indices, computed once from the bundle split. Neither the sharding grid’s run_rank_0_only_axes gate nor the worker group’s DP-leader list is used: the grid cannot model engines of differing width, and the DP leaders are one worker per replica, which under disaggregation skips every engine but the replica’s first. This keeps one source of truth for who owns an engine.

Parameters:
  • per_engine – kwargs whose value is a per-engine list, in engine order.

  • **common – kwargs passed unchanged to every engine.

_report_engine_addrs() → list[Optional[dict[str, Any]]]#

Collect {host, port, node_id} from every engine’s HTTP server.

None for an engine whose server never started. The node id is what lets the replica’s disagg server be pinned beside its engines.

_report_dp_openai_server_base_urls() → list[Optional[str]]#

OpenAI-compatible base URLs, grouped by DP shard in shard order.

A shard’s entry point is not always an engine: under disaggregation the caller must talk to the replica’s disagg server, which routes prefill and decode itself. Without disaggregation this is one URL per DP shard. With it, each replica (shard) contributes its num_frontend_workers (F) disagg servers, so the list has num_replicas * F entries, replica-major – callers must not index it by shard when F > 1. An engine-per-URL list would instead have num_engines entries, which is no longer dp_size.

_report_device_id() → list[list[str]]#
init_collective(
ip: str,
port: int,
world_size: int,
*,
train_world_size: int,
) → list[ray.ObjectRef]#
generate(
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.generation.interfaces.GenerationDatumSpec],
greedy: bool = False,
) → nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.generation.interfaces.GenerationOutputSpec]#
async generate_async(
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.generation.interfaces.GenerationDatumSpec],
greedy: bool = False,
) → AsyncGenerator[tuple[int, nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.generation.interfaces.GenerationOutputSpec]], None]#

Yield a single-sample generation result.

Called by run_async_multi_turn_rollout, which dispatches one sample at a time per coroutine. The async worker’s max_concurrency lets multiple in-flight Ray calls share the same AsyncLLM, which batches them internally via asyncio.gather.

prepare_for_generation(
*args: Any,
**kwargs: Any,
) → bool#

Wake inference workers up. No-op for non-colocated.

finish_generation(*args: Any, **kwargs: Any) → bool#

Sleep workers (colocated) or reset prefix cache (non-colocated).

get_nccl_reshard_layouts() → list[dict[str, Any]]#

Destination layouts, engines in engine order within each.

rank_prefixes are the engines’ first ranks inside the layout’s rollout block (cumulative TP widths), which is where they sit in the layout’s bulk communicator after that stage’s train ranks.

_run_on_engine_subset(
method_name: str,
engine_indices: list[int],
per_engine: Optional[dict[str, list[Any]]] = None,
**common: Any,
) → list[ray.ObjectRef]#

Fan out to the given engines’ model owners, one call per engine.

Parameters:
  • engine_indices – engines to call, in call order.

  • per_engine – kwargs whose value is a list aligned with engine_indices.

  • **common – kwargs passed unchanged to every selected engine.

set_refit_membership(membership: Any) → None#

Check the refit fleet covers every replica.

TRT-LLM replicas cannot drop out of a refit today; a membership that excludes a shard is rejected rather than silently loading a subset.

rebuild_collective(
membership: Any,
ip: str,
port: int,
) → list[ray.ObjectRef]#

Rebuild model_update_group over the full fleet (see set_refit_membership).

init_nccl_reshard_comm_group(
layout_index: int,
pp_ips: list[str],
pp_ports: list[int],
pp_size: int,
train_ranks_per_stage: int,
sub_world_size: int,
) → list[ray.ObjectRef]#

Join one layout’s per-PP-stage bulk communicators (all its engines).

rebuild_nccl_reshard_comm_group(
membership: Any,
pp_ips: list[str],
pp_ports: list[int],
pp_size: int,
train_ranks_per_stage: int,
sub_world_size: int,
layout_index: int = 0,
) → list[ray.ObjectRef]#
prepare_nccl_reshard_refit_info(refit_infos: list[dict]) → None#

One refit plan per layout, in layout order.

nccl_reshard_refit(
refit_timeout_s: Optional[float] = None,
) → list[ray.ObjectRef]#
prepare_refit_info(
state_dict_info: Optional[dict[str, Any]],
) → Optional[list[str]]#
start_gpu_profiling() → None#

Grpo profiling protocol: start nsys capture on the GPU workers.

stop_gpu_profiling() → None#

Grpo profiling protocol: stop nsys capture on the GPU workers.

update_weights_from_collective(
refit_timeout_s: Optional[float] = None,
) → list[ray.ObjectRef]#
update_weights_via_ipc_zmq() → list[ray.ObjectRef]#

Receive weights via CUDA-IPC + ZMQ (colocated mode).

invalidate_kv_cache() → bool#

No-op for TRT-LLM: KV-cache invalidation happens inside the refit path.

For async RL correctness, KV/prefix-cache invalidation must happen in the same engine step boundary as the weight update — otherwise in-flight requests forward several decode steps with new weights × old KV, opening a race window.

TRT-LLM avoids this by performing the invalidation inside the refit function itself, under the same control_action context:

  • NcclExtension.update_weights_from_collective (NCCL path)

  • NcclExtension.update_weights_via_ipc_zmq (IPC-ZMQ path)

clear_logger_metrics() → None#

No-op: TRT-LLM rollout telemetry is not yet wired up.

vLLM overrides this (vllm_generation.py) to reset AsyncLLM iteration stats (rollout throughput, KV-cache utilization, in-flight batch counters). TRT-LLM has no equivalent plumbing yet, so this stays a no-op rather than inheriting silently — making the gap explicit.

TODO: fetch AsyncLLM iteration stats from the TRT-LLM workers and clear them here, mirroring clear_vllm_logger_metrics.

get_logger_metrics() → dict[str, Any]#

Return empty metrics: TRT-LLM rollout telemetry is not yet wired up.

See :meth:clear_logger_metrics. Returning {} explicitly documents that rollout observability metrics (present for vLLM) are absent for TRT-LLM runs, rather than letting them silently disappear via the inherited no-op default.

TODO: surface AsyncLLM iteration stats here, mirroring get_vllm_logger_metrics.

shutdown() → bool#
__del__() → None#