nemo_rl.models.value.workers.megatron_value_worker#

Module Contents#

Classes#

_ValueTrainStep

MegatronValueWorkerImpl

Megatron-Core based value function worker for PPO.

MegatronValueWorker

Functions#

_report_multimodal_input_once

Emit one rank-zero marker proving that media reached the value worker.

_value_head_parent

Return the module and state-dict path that own a chunk’s language head.

_install_value_head_load_skip

Install hide_loss_modules for the actual scalar-head state-dict path.

make_value_head_hook

Build a pre-wrap scalar-head hook for both GPT and VLM model layouts.

_unpack_value_sequences

Unpack packed (and CP-sharded) per-token values back to [B, S].

_value_loss_prepare_fn

Prepare the value-head output for MseValueLossFn (LossPostProcessor prepare_fn).

Data#

API#

nemo_rl.models.value.workers.megatron_value_worker.TokenizerType#

‘TypeVar(…)’

class nemo_rl.models.value.workers.megatron_value_worker._ValueTrainStep#
loss_fn: nemo_rl.algorithms.loss.interfaces.LossFunction#

None

gbs: int#

None

mbs: int#

None

counts: torch.Tensor#

None

grad_sync_func: Any#

None

no_sync_func: Any#

None

finalize_model_grads_func: Any#

None

metrics: list[dict[str, Any]]#

‘field(…)’

num_microbatches: int#

0

num_chunks: int#

0

failed: bool#

False

nemo_rl.models.value.workers.megatron_value_worker._report_multimodal_input_once(
worker: Any,
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[Any],
) → None#

Emit one rank-zero marker proving that media reached the value worker.

nemo_rl.models.value.workers.megatron_value_worker._value_head_parent(
chunk: megatron.core.transformer.MegatronModule,
) → tuple[Any, str]#

Return the module and state-dict path that own a chunk’s language head.

Plain GPT models expose output_layer directly. Megatron-Bridge VLM wrappers (including Qwen2.5-VL) keep the causal-LM head under language_model.output_layer; installing a top-level head on those wrappers leaves the real vocabulary head active and makes the critic emit logits instead of scalar values.

nemo_rl.models.value.workers.megatron_value_worker._install_value_head_load_skip(
chunk: megatron.core.transformer.MegatronModule,
output_layer_path: str,
) → None#

Install hide_loss_modules for the actual scalar-head state-dict path.

The freshly-initialized value head is never in a base checkpoint, so Megatron-Bridge enters this context during finetune loads (and HF->Megatron conversion) to skip it. Resume loads run with finetune=False, so the trained head is restored normally.

nemo_rl.models.value.workers.megatron_value_worker.make_value_head_hook(hidden_size: int, sequence_parallel: bool)#

Build a pre-wrap scalar-head hook for both GPT and VLM model layouts.

nemo_rl.models.value.workers.megatron_value_worker._unpack_value_sequences(
values: torch.Tensor,
cu_seqlens_padded: torch.Tensor | nemo_rl.utils.sequence_lengths.CpuIntTuple,
unpacked_seqlen: int,
cp_group: Optional[torch.distributed.ProcessGroup] = None,
) → torch.Tensor#

Unpack packed (and CP-sharded) per-token values back to [B, S].

values is the value head output for a packed microbatch, shape [1, T // CP] (SP/TP already gathered inside the head). For each sequence delimited by cu_seqlens_padded (indices into the full, non-CP-adjusted packed layout) the local CP shard is all-gathered to the full sequence, then shifted right by one so values[t] = V(state before token t) — matching the unpacked path.

nemo_rl.models.value.workers.megatron_value_worker._value_loss_prepare_fn(
logits: torch.Tensor,
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[Any],
loss_fn: Optional[nemo_rl.algorithms.loss.interfaces.LossFunction] = None,
vocab_parallel_rank: Optional[int] = None,
vocab_parallel_group: Optional[torch.distributed.ProcessGroup] = None,
context_parallel_group: Optional[torch.distributed.ProcessGroup] = None,
) → tuple[dict[str, torch.Tensor], nemo_rl.distributed.batched_data_dict.BatchedDataDict[Any]]#

Prepare the value-head output for MseValueLossFn (LossPostProcessor prepare_fn).

All-gather across CP (packed only — CP requires packing), shift right by one so values[t] = V(state before token t), then truncate to data["returns"].

class nemo_rl.models.value.workers.megatron_value_worker.MegatronValueWorkerImpl(
config: nemo_rl.models.value.config.ValueConfig,
tokenizer: nemo_rl.models.value.workers.megatron_value_worker.TokenizerType,
weights_path: Optional[str] = None,
optimizer_path: Optional[str] = None,
init_optimizer: bool = True,
*,
worker_sharding_annotations: nemo_rl.distributed.named_sharding.NamedSharding,
**kwargs: Any,
)#

Bases: nemo_rl.models.megatron.manual_gc.ManualGCMixin, nemo_rl.data_plane.worker_mixin.TQWorkerMixin, nemo_rl.models.policy.workers.base_policy_worker.AbstractPolicyWorker

Megatron-Core based value function worker for PPO.

This worker wraps a Megatron-Core GPT model backbone with a value head (Linear: hidden_size -> 1) to predict per-token state values.

Supports:

  • Tensor parallelism (TP)

  • Pipeline parallelism (PP)

  • Context parallelism (CP)

  • Sequence packing

  • Activation checkpointing

  • FP8 quantization

  • MoE models

Initialization

Initialize the MegatronValueWorker.

Parameters:
  • config – Value model configuration.

  • tokenizer – HuggingFace tokenizer.

  • weights_path – Path to load finetuned weights from (optional).

  • optimizer_path – Path to load optimizer state from (optional).

  • init_optimizer – Whether to initialize the optimizer.

  • worker_sharding_annotations – Sharding topology for distributed training.

__repr__()#
_local_coords() → dict[str, int]#

Axis to local-rank mapping. Deliberate copy of MegatronPolicyWorkerImpl.

_get_replica_group() → Optional[Any]#

Replica group = TP x CP x PP siblings within this DP rank.

Deliberate copy of MegatronPolicyWorkerImpl._get_replica_group; see there for why it is never gated on CP > 1 and why new_group has to be called collectively.

static configure_worker(
num_gpus: int | float,
bundle_indices: Optional[tuple[int, list[int]]] = None,
num_gpus_per_node: Optional[int] = None,
) → tuple[dict[str, Any], dict[str, str], dict[str, Any], dict[str, Any]]#

Worker-controlled Ray actor configuration.

Mirrors MegatronPolicyWorker to ensure NVLS communication functions correctly.

Parameters:
  • num_gpus – Original GPU allocation for this worker based on the placement group

  • bundle_indices – Tuple of (node_idx, local_bundle_indices) for this server

  • num_gpus_per_node – Per-node GPU count (unused here; part of the shared configure_worker contract).

Returns:

  • ‘resources’: Resource allocation (e.g., num_gpus)

  • ’env_vars’: Environment variables for this worker

  • ’init_kwargs’: Parameters to pass to init of the worker

  • ’runtime_env’: Additional runtime_env options (e.g., nsight config)

Return type:

tuple with complete worker configuration

enable_forward_pre_hook()#
disable_forward_pre_hook(param_sync=True)#
train(
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict,
loss_fn: nemo_rl.algorithms.loss.interfaces.LossFunction,
eval_mode: bool = False,
gbs: Optional[int] = None,
mbs: Optional[int] = None,
) → dict[str, Any]#

Train the value function on a batch of data with a given loss function.

Parameters:
  • data –

    BatchedDataDict containing training data with keys:

    • input_ids, input_lengths, token_mask, sample_mask, returns

  • loss_fn – Value loss function (e.g., MseValueLossFn).

  • eval_mode – If True, run forward only without parameter updates.

  • gbs – Global batch size override.

  • mbs – Micro batch size override.

Returns:

Dictionary with training metrics (global_loss, grad_norm, etc.)

_assert_train_step_open() → nemo_rl.models.value.workers.megatron_value_worker._ValueTrainStep#
_restore_train_hooks(
state: nemo_rl.models.value.workers.megatron_value_worker._ValueTrainStep,
) → None#
begin_train_step(
loss_fn: nemo_rl.algorithms.loss.interfaces.LossFunction,
gbs: Optional[int] = None,
mbs: Optional[int] = None,
) → None#

Open one optimizer step; subsequent chunks accumulate unreduced gradients.

train_microbatch(
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[Any],
) → None#

Accumulate one DP shard without stepping or synchronizing gradients.

finish_train_step() → dict[str, Any]#

Finalize one complete global batch and return the usual value metrics.

abort_train_step() → None#

Discard uncommitted gradients. Idempotent; cannot undo an optimizer step.

get_values(
data: nemo_rl.distributed.batched_data_dict.BatchedDataDict[Any],
micro_batch_size: Optional[int] = None,
) → nemo_rl.distributed.batched_data_dict.BatchedDataDict[nemo_rl.models.value.interfaces.ValueOutputSpec]#

Get per-token value predictions for a batch of data.

Parameters:
  • data – BatchedDataDict containing input_ids and input_lengths.

  • micro_batch_size – Override for inference micro batch size.

Returns:

BatchedDataDict with “values” key of shape [batch_size, seq_length].

prepare_for_training() → None#

Move model and optimizer to CUDA for training.

prepare_for_inference()#

Prepare model for value inference.

move_model(
model: torch.nn.Module,
device: str,
move_params: bool = True,
move_grads: bool = True,
) → torch.nn.Module#

Move model parameters and gradient buffers to the specified device.

move_optimizer(device: str)#

Move optimizer state to the specified device.

save_checkpoint(
weights_path: str,
optimizer_path: Optional[str] = None,
tokenizer_path: Optional[str] = None,
**kwargs,
)#

Save a checkpoint of the value model.

The value head is the model’s output_layer and is saved as part of the normal Megatron dist-checkpoint — no separate value-head sidecar.

abstractmethod load_checkpoint(
weights_path: str,
optimizer_path: Optional[str] = None,
)#

Load a checkpoint for the value model.

finish_inference() → None#

Offload model params to CPU after inference.

finish_training() → None#

Offload model, gradients, and optimizer to CPU after training.

class nemo_rl.models.value.workers.megatron_value_worker.MegatronValueWorker(
config: nemo_rl.models.value.config.ValueConfig,
tokenizer: nemo_rl.models.value.workers.megatron_value_worker.TokenizerType,
weights_path: Optional[str] = None,
optimizer_path: Optional[str] = None,
init_optimizer: bool = True,
*,
worker_sharding_annotations: nemo_rl.distributed.named_sharding.NamedSharding,
**kwargs: Any,
)#

Bases: nemo_rl.models.value.workers.megatron_value_worker.MegatronValueWorkerImpl