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#
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.GenerationInterfaceTRT-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,
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_sizeGPUs. 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]]]],
Attach each engine’s prefill/decode role to the worker config.
RayWorkerBuilderhands 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_keyand each worker looks up its own entry, then reads that role’s engine config, which- Func:
resolve_role_overridesalready 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( ) 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.
generateandgenerate_asyncsend 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,
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’srun_rank_0_only_axesgate 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.Nonefor 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 hasnum_replicas * Fentries, replica-major – callers must not index it by shard when F > 1. An engine-per-URL list would instead havenum_enginesentries, which is no longerdp_size.
- _report_device_id() list[list[str]]#
- init_collective(
- ip: str,
- port: int,
- world_size: int,
- *,
- train_world_size: int,
- generate(
- data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.generation.interfaces.GenerationDatumSpec],
- greedy: bool = False,
- async generate_async(
- data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.generation.interfaces.GenerationDatumSpec],
- greedy: bool = False,
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,
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_prefixesare 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,
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,
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,
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,
- 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,
- prepare_refit_info(
- state_dict_info: Optional[dict[str, Any]],
- 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,
- 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_actioncontext: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#