|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from typing import Any, Optional |
| 15 | + |
| 16 | +import ray |
| 17 | +import torch |
| 18 | +import zmq |
| 19 | + |
| 20 | +from nemo_rl.distributed.batched_data_dict import BatchedDataDict |
| 21 | +from nemo_rl.models.policy.interfaces import ReferenceLogprobOutputSpec |
| 22 | +from nemo_rl.utils.nsys import wrap_with_nvtx_name |
| 23 | + |
| 24 | + |
| 25 | +class AbstractPolicyWorker: |
| 26 | + """Base class for policy workers with shared functionality.""" |
| 27 | + |
| 28 | + def init_collective( |
| 29 | + self, ip: str, port: int, world_size: int, *, train_world_size: int |
| 30 | + ) -> None: |
| 31 | + """Initialize the collective communication. |
| 32 | +
|
| 33 | + Args: |
| 34 | + ip: IP address for the process group |
| 35 | + port: Port for the process group |
| 36 | + world_size: Total world size (train_world_size + inference_world_size) |
| 37 | + train_world_size: Number of training workers (used in inference cluster) |
| 38 | + """ |
| 39 | + from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator |
| 40 | + from vllm.distributed.utils import StatelessProcessGroup |
| 41 | + |
| 42 | + pg = StatelessProcessGroup.create( |
| 43 | + host=ip, port=port, rank=self.rank, world_size=world_size |
| 44 | + ) |
| 45 | + device = torch.cuda.current_device() |
| 46 | + self.model_update_group = PyNcclCommunicator(pg, device=device) |
| 47 | + |
| 48 | + def is_alive(self) -> bool: |
| 49 | + """Check if the worker is alive.""" |
| 50 | + return True |
| 51 | + |
| 52 | + def reset_peak_memory_stats(self) -> None: |
| 53 | + """Reset peak memory statistics.""" |
| 54 | + torch.cuda.reset_peak_memory_stats() |
| 55 | + |
| 56 | + def get_gpu_info(self) -> dict[str, Any]: |
| 57 | + """Return information about the GPU being used by this worker.""" |
| 58 | + from nemo_rl.models.policy.utils import get_gpu_info |
| 59 | + |
| 60 | + return get_gpu_info(self.model) |
| 61 | + |
| 62 | + def report_device_id(self) -> str: |
| 63 | + """Report the UUID of the current CUDA device using NVML. |
| 64 | +
|
| 65 | + Returns: |
| 66 | + str: UUID of the device in the format "GPU-xxxxx" |
| 67 | + """ |
| 68 | + from nemo_rl.utils.nvml import get_device_uuid |
| 69 | + |
| 70 | + # Get current device index from torch |
| 71 | + device_idx = torch.cuda.current_device() |
| 72 | + # Get device UUID using NVML |
| 73 | + return get_device_uuid(device_idx) |
| 74 | + |
| 75 | + def get_zmq_address(self) -> str: |
| 76 | + """Get the ZMQ address for the current device.""" |
| 77 | + return f"ipc:///tmp/{self.report_device_id()}.sock" |
| 78 | + |
| 79 | + def maybe_init_zmq(self) -> None: |
| 80 | + """Initialize the ZMQ socket if it doesn't exist.""" |
| 81 | + if not hasattr(self, "zmq_socket"): |
| 82 | + self.zmq_context = zmq.Context() |
| 83 | + self.zmq_socket = self.zmq_context.socket(zmq.REQ) |
| 84 | + self.zmq_socket.setsockopt( |
| 85 | + zmq.SNDTIMEO, 120000 |
| 86 | + ) # set timeout to 120 seconds |
| 87 | + self.zmq_socket.setsockopt( |
| 88 | + zmq.RCVTIMEO, 120000 |
| 89 | + ) # set timeout to 120 seconds |
| 90 | + self.zmq_socket.setsockopt(zmq.LINGER, 0) |
| 91 | + self.zmq_socket.bind(self.get_zmq_address()) |
| 92 | + |
| 93 | + def get_free_memory_bytes(self) -> int: |
| 94 | + """Get the available free memory.""" |
| 95 | + from nemo_rl.utils.nvml import get_free_memory_bytes |
| 96 | + |
| 97 | + device_idx = torch.cuda.current_device() |
| 98 | + return get_free_memory_bytes(device_idx) |
| 99 | + |
| 100 | + def shutdown(self) -> bool: |
| 101 | + """Shutdown the policy.""" |
| 102 | + try: |
| 103 | + # Clean up extension resources like ZMQ sockets |
| 104 | + if hasattr(self, "zmq_socket"): |
| 105 | + self.zmq_socket.close() |
| 106 | + self.zmq_context.term() |
| 107 | + return True |
| 108 | + except Exception: |
| 109 | + return False |
| 110 | + |
| 111 | + def start_gpu_profiling(self) -> None: |
| 112 | + """Start GPU profiling.""" |
| 113 | + torch.cuda.profiler.start() |
| 114 | + |
| 115 | + def stop_gpu_profiling(self) -> None: |
| 116 | + """Stop GPU profiling.""" |
| 117 | + torch.cuda.profiler.stop() |
| 118 | + |
| 119 | + def report_node_ip_and_gpu_id(self) -> tuple[str, int]: |
| 120 | + """Report the node IP and GPU ID of the current worker.""" |
| 121 | + ip = ray._private.services.get_node_ip_address() |
| 122 | + gpu_id = ray.get_gpu_ids()[0] |
| 123 | + return (ip, gpu_id) |
| 124 | + |
| 125 | + # Temporary fix, 'data' is a kwarg due to some sort of ray bug |
| 126 | + @wrap_with_nvtx_name("policy_worker/get_reference_policy_logprobs") |
| 127 | + def get_reference_policy_logprobs( |
| 128 | + self, |
| 129 | + *, |
| 130 | + data: BatchedDataDict[Any], |
| 131 | + micro_batch_size: Optional[int] = None, |
| 132 | + ) -> BatchedDataDict[ReferenceLogprobOutputSpec]: |
| 133 | + """Get the logprobs from the reference policy for a batch of data. |
| 134 | +
|
| 135 | + If micro_batch_size is provided, it will be used instead of the configured |
| 136 | + logprob_batch_size. |
| 137 | +
|
| 138 | + Returns: |
| 139 | + a BatchedDataDict with key "reference_logprobs" and shape [batch_size, sequence_length]. |
| 140 | + We use the convention that the logprob of the first token is 0 so that the sequence length is maintained. |
| 141 | + The logprob of input token i is specified at position i in the output logprobs tensor. |
| 142 | + """ |
| 143 | + with self.use_reference_model(): |
| 144 | + reference_logprobs = self.get_logprobs( |
| 145 | + data=data, micro_batch_size=micro_batch_size |
| 146 | + ) |
| 147 | + |
| 148 | + return_data = BatchedDataDict[ReferenceLogprobOutputSpec]() |
| 149 | + return_data["reference_logprobs"] = reference_logprobs["logprobs"].cpu() |
| 150 | + return return_data |
| 151 | + |
| 152 | + def finish_training(self, *args: Any, **kwargs: Any) -> None: |
| 153 | + # Placeholder implementation |
| 154 | + pass |
0 commit comments