nemo_rl.models.policy.utils#
Module Contents#
Classes#
IPC protocol constants for ZMQ weight streaming. |
Functions#
Return the quantized policy worker FQN if |
|
Resolve the appropriate model class for a given model name. |
|
Check if vLLM V1 engine is enabled. |
|
Return information about the GPU being used by this worker. |
|
Disable dynamo autotune_local_cache. |
|
Get runtime environment configuration for policy workers. |
|
Gets the default megatron checkpoint directory for initial HF -> Mcore conversion. |
|
Get IPC handle from a tensor. |
|
Lazy-alloc / grow |
|
Flatten teacher per-sample IPC handles into a global-batch-ordered list. |
|
Calculate aligned size for memory alignment. |
|
Shared implementation for streaming weights via IPC ZMQ with improved memory management. |
|
Rebuild a CUDA tensor from an IPC handle. |
|
Lazily create a per-engine Gloo subgroup and cache rank-only routing state. |
|
Flatten |
|
Stream FSDP weights to colocated SGLang engines via CUDA IPC over HTTP. |
Data#
API#
- nemo_rl.models.policy.utils.AUTOMODEL_FACTORY: Dict[str, Any]#
None
- class nemo_rl.models.policy.utils.IPCProtocol(*args, **kwds)#
Bases:
enum.EnumIPC protocol constants for ZMQ weight streaming.
Initialization
- COMPLETE#
‘complete’
- ACK#
‘ack’
- nemo_rl.models.policy.utils.POLICY_WORKER_OVERRIDES#
None
- nemo_rl.models.policy.utils.resolve_policy_worker_cls(default_cls: str, config: dict) str#
Return the quantized policy worker FQN if
quant_cfgis set, elsedefault_cls.Safe to call even when ModelOpt is not installed — returns
default_clsunchanged wheneverquant_cfgisNone, so the core policy path stays import-free of ModelOpt.
- nemo_rl.models.policy.utils.resolve_model_class(model_name: str) Any#
Resolve the appropriate model class for a given model name.
- nemo_rl.models.policy.utils.is_vllm_v1_engine_enabled() bool#
Check if vLLM V1 engine is enabled.
- Returns:
True if V1 engine is enabled, False otherwise (defaults to True if not set)
- Return type:
bool
- nemo_rl.models.policy.utils.get_gpu_info(model: torch.nn.Module) dict[str, Any]#
Return information about the GPU being used by this worker.
- nemo_rl.models.policy.utils.configure_dynamo_cache() None#
Disable dynamo autotune_local_cache.
Dynamo may fail at cached_autotune when there’s already a cache with different order of node_bundles. Disable autotune_local_cache as a workaround. See https://github.com/pytorch/pytorch/issues/153791 for more details.
- nemo_rl.models.policy.utils.get_runtime_env_for_policy_worker(
- policy_worker_name: str,
Get runtime environment configuration for policy workers.
Note: expandable_segments configuration is handled directly in the worker init methods to ensure proper GPU detection after CUDA initialization.
- nemo_rl.models.policy.utils.get_megatron_checkpoint_dir() str#
Gets the default megatron checkpoint directory for initial HF -> Mcore conversion.
Megatron initial checkpoint should be saved to a path available on all nodes. The directory used will take this order of precendence:
$NRL_MEGATRON_CHECKPOINT_DIR (if set)
$HF_HOME/nemo_rl (if HF_HOME is set)
~/.cache/huggingface/nemo_rl
HF_HOME is preferred since many users will also have that path mounted and it means one less directory to mount into your runtime environment.
- nemo_rl.models.policy.utils.get_handle_from_tensor(tensor: torch.Tensor) tuple[Any]#
Get IPC handle from a tensor.
- nemo_rl.models.policy.utils.ensure_teacher_ipc_buffer(
- storage: Optional[torch.Tensor],
- handle: Optional[tuple[Any, ...]],
- num_microbatches: int,
- batch_size: int,
- seq_len: int,
- vocab_size: int,
- dtype: torch.dtype,
- device: torch.device,
Lazy-alloc / grow
[N_mb, B, T, V]teacher-logits IPC storage.Returns the (possibly reallocated)
(storage, handle). Reallocates and re-exports the IPC handle whenever any dim of the requested shape exceeds the current storage, or dtype/device changed; otherwise the existing storage and cached handle are returned unchanged.
- nemo_rl.models.policy.utils.aggregate_per_sample_handles(
- worker_results: list[dict[str, Any]],
Flatten teacher per-sample IPC handles into a global-batch-ordered list.
Each worker returns
{"dp_rank": int, "per_sample_handles": list}where the handle list is in local sample order; the several workers sharing adp_rankare TP/CP replicas that each contribute one shard per sample. Concatenating samples insorted(dp_rank)order reproduces the original global sample order (rank 0 holds the firstgbs/dpsamples, rank 1 the next, …), so the result is a length-gbslist independent of the teacher’s DP degree. Elementiis{"teacher_shards": [shard, ...]}holding all TP×CP shards of global samplei.
- nemo_rl.models.policy.utils.calculate_aligned_size(size_bytes: int, alignment: int = 512) int#
Calculate aligned size for memory alignment.
- Parameters:
size_bytes (int) – Size in bytes to align
alignment (int) – Alignment boundary in bytes (default 512)
- Returns:
Aligned size in bytes(int).
- nemo_rl.models.policy.utils.stream_weights_via_ipc_zmq_impl(
- params_generator,
- buffer_size_bytes: int,
- zmq_socket,
- rank: int,
- worker_name: str,
Shared implementation for streaming weights via IPC ZMQ with improved memory management.
Uses ping-pong double buffering to enable overlapping communication while reusing buffers to reduce memory allocation overhead and improve stability.
- Parameters:
params_generator – Generator yielding (name, tensor) pairs
buffer_size_bytes – total size of buffer in bytes for batching parameters
zmq_socket – ZMQ socket for communication
rank – Worker rank for logging
worker_name – Name of the worker for logging
- nemo_rl.models.policy.utils.rebuild_cuda_tensor_from_ipc(
- cuda_ipc_handle: tuple,
- device_id: int,
Rebuild a CUDA tensor from an IPC handle.
- nemo_rl.models.policy.utils._ensure_ipc_topology(
- num_engines: int,
- num_gpus_per_engine: int,
- worker_state: dict,
Lazily create a per-engine Gloo subgroup and cache rank-only routing state.
Every FSDP rank must call
dist.new_groupfor every engine’s rank range (collective). Only the ranks inside a given range stashgather_srcandgather_groupintoworker_state. The engine handle itself is resolved at call time from the caller-providedrollout_engineslist so that post-recover actor swaps are picked up without cache invalidation.Note: callers must have already applied
monkey_patch_torch_reductionsonce during worker setup; this function no longer applies it.
- nemo_rl.models.policy.utils._flush_bucket(
- named_tensors,
- gather_src: int,
- gather_group,
- engine_url: str,
- weight_version: int,
- flattened_tensor_bucket_cls,
- multiprocessing_serializer_cls,
Flatten
named_tensorsper dtype, gather togather_src, and POST to the engine.
- nemo_rl.models.policy.utils.stream_weights_via_http_impl(
- params_generator: Iterable[tuple[str, torch.Tensor]],
- rollout_engine_urls: Iterable[str],
- num_gpus_per_engine: int,
- rank: int,
- world_size: int,
- worker_name: str,
- buffer_size_bytes: int,
- worker_state: dict,
Stream FSDP weights to colocated SGLang engines via CUDA IPC over HTTP.
- Parameters:
params_generator – Iterable yielding
(name, tensor)pairs to stream. Caller is responsible for any pre-processing (LoRA merge, HF adaptation, dtype cast).rollout_engine_urls –
http://host:portbase URLs of each engine’snode_rank=0SGLang HTTP server. One entry per engine, in TP rank-range order: engineiowns global ranks[i * num_gpus_per_engine, (i + 1) * num_gpus_per_engine).num_gpus_per_engine – TP size per SGLang engine.
rank – Global FSDP rank.
world_size – Global FSDP world size.
worker_name – Human label for logs.
buffer_size_bytes – Max bucket size in bytes.
worker_state – Mutable dict on the worker used to cache topology and weight version across refits.