{"file_name": "verl__checkpoint_engine__nccl_checkpoint_engine.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport asyncio\nimport logging\nimport os\nimport time\nfrom dataclasses import dataclass\nfrom typing import AsyncGenerator, Generator\nfrom unittest.mock import patch\n\nwith patch(\"importlib.metadata.distributions\", return_value=[]):\n import cupy as cp\n\nimport ray\nimport ray.util.collective as collective\nimport torch\nimport zmq\n\nfrom verl.checkpoint_engine.base import CheckpointEngine, CheckpointEngineRegistry, TensorMeta\nfrom verl.utils.net_utils import get_free_port, is_valid_ipv6_address\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(os.getenv(\"VERL_LOGGING_LEVEL\", \"WARN\"))\n\n\n@dataclass\nclass MasterMetadata:\n zmq_ip: str\n zmq_port: int\n\n\nclass BroadcastOperation:\n \"\"\"Async broadcast operation with NCCL in separate thread.\n\n Args:\n rank (int): The rank of the current process.\n group_name (str): The name of the NCCL process group.\n bucket (cp.ndarray | torch.Tensor): The tensor to broadcast.\n metadata (dict[str, TensorMeta]): The metadata of the tensor.\n socket (zmq.Socket): The zeromq socket to communicate with master.\n topic (str): The topic to subscribe.\n \"\"\"\n\n def __init__(\n self,\n rank: int,\n group_name: str,\n bucket: cp.ndarray | torch.Tensor,\n metadata: dict[str, TensorMeta],\n socket: zmq.Socket,\n topic: str,\n ) -> None:\n self.rank = rank\n self.group_name = group_name\n self.bucket = bucket\n self.metadata = metadata\n self.socket = socket\n self.topic = topic\n\n loop = asyncio.get_running_loop()\n self._task = loop.run_in_executor(None, self._run)\n\n def _run(self):\n # broadcast tensor meta via zeromq PUB/SUB\n if self.rank == 0:\n self.socket.send_string(self.topic, flags=zmq.SNDMORE)\n self.socket.send_pyobj(self.metadata)\n else:\n self.socket.recv_string()\n self.metadata = self.socket.recv_pyobj()\n\n # broadcast tensor via NCCL\n collective.broadcast(self.bucket, src_rank=0, group_name=self.group_name)\n\n async def wait_for_complete(self) -> dict[str, TensorMeta]:\n \"\"\"Wait for the broadcast operation to complete.\n\n Returns:\n dict[str, TensorMeta]: The bucket meta after broadcast.\n \"\"\"\n await self._task\n return self.metadata\n\n\n@CheckpointEngineRegistry.register(\"nccl\")\nclass NCCLCheckpointEngine(CheckpointEngine):\n \"\"\"NCCL checkpoint engine with collective communication.\n\n Args:\n bucket_size (int): Bucket size in bytes to transfer multiple weights at one time. Note that we use\n two buffer to send and recv weights at same time, so the device memory overhead is 2 * bucket_size.\n group_name (str): The name of the NCCL process group. Defaults to \"default\".\n rebuild_group (bool): Whether to rebuild the NCCL process group in each update. Defaults to False.\n is_master (bool): Whether the current process is the master process. Defaults to False.\n rollout_dtype (torch.dtype): The dtype of the weights received from rollout workers. Defaults to torch.bfloat16.\n \"\"\"\n\n def __init__(\n self,\n bucket_size: int,\n group_name: str = \"default\",\n rebuild_group: bool = False,\n is_master: bool = False,\n rollout_dtype: torch.dtype = torch.bfloat16,\n ) -> None:\n self.bucket_size = bucket_size\n self.group_name = group_name\n self.rebuild_group = rebuild_group\n self.rollout_dtype = rollout_dtype\n\n # start zeromq server for broadcasting bucket tensor metadata\n self.is_master = is_master\n self.topic = \"bucket_metadata\"\n if self.is_master:\n self._start_zmq_server()\n\n def prepare(self) -> MasterMetadata:\n # For master process, use cupy instead of torch to avoid memory register error\n # when `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`.\n if self.is_master:\n self.send_buf = cp.zeros(self.bucket_size, dtype=cp.uint8)\n self.recv_buf = cp.zeros(self.bucket_size, dtype=cp.uint8)\n else:\n self.send_buf = torch.zeros(self.bucket_size, dtype=torch.uint8, device=\"cuda\")\n self.recv_buf = torch.zeros(self.bucket_size, dtype=torch.uint8, device=\"cuda\")\n\n return MasterMetadata(zmq_ip=self.ip, zmq_port=self.listen_port) if self.is_master else None\n\n def finalize(self):\n \"\"\"Destroy the NCCL process group if rebuild_group is True.\"\"\"\n if self.rebuild_group:\n if self.rank >= 0:\n collective.destroy_collective_group(self.group_name)\n self.rank = None\n self.world_size = None\n\n self.send_buf = None\n self.recv_buf = None\n\n @classmethod\n def build_topology(cls, trainer_world_size: int, rollout_world_size: int, metadata: list[dict]):\n trainer_kwargs = {\n \"rank\": [0] + [-1] * (trainer_world_size - 1),\n \"world_size\": [rollout_world_size + 1] * trainer_world_size,\n \"master_metadata\": [metadata[0]] * trainer_world_size,\n }\n rollout_kwargs = {\n \"rank\": list(range(1, rollout_world_size + 1)),\n \"world_size\": [rollout_world_size + 1] * rollout_world_size,\n \"master_metadata\": [metadata[0]] * rollout_world_size,\n }\n return trainer_kwargs, rollout_kwargs\n\n def _start_zmq_server(self):\n self.ip = ray.util.get_node_ip_address().strip(\"[]\")\n self.listen_port, self.listen_sock = get_free_port(self.ip)\n\n context = zmq.Context()\n self.socket = context.socket(zmq.PUB)\n if is_valid_ipv6_address(self.ip):\n address = f\"tcp://[{self.ip}]:{self.listen_port}\"\n self.socket.setsockopt(zmq.IPV6, 1)\n else:\n address = f\"tcp://{self.ip}:{self.listen_port}\"\n\n self.socket.bind(address)\n\n def _connect_zmq_client(self, metadata: MasterMetadata):\n assert not self.is_master, \"Master process should not connect to other processes.\"\n context = zmq.Context()\n self.socket = context.socket(zmq.SUB)\n if is_valid_ipv6_address(metadata.zmq_ip):\n address = f\"tcp://[{metadata.zmq_ip}]:{metadata.zmq_port}\"\n self.socket.setsockopt(zmq.IPV6, 1)\n else:\n address = f\"tcp://{metadata.zmq_ip}:{metadata.zmq_port}\"\n\n self.socket.connect(address)\n self.socket.setsockopt_string(zmq.SUBSCRIBE, self.topic)\n\n def init_process_group(self, rank: int, world_size: int, master_metadata: MasterMetadata):\n \"\"\"Initialize the NCCL process group.\n\n Args:\n rank (int): The rank of the current process.\n world_size (int): The total number of processes.\n \"\"\"\n # For trainer workers other than rank 0, their rank should be -1.\n if rank < 0:\n self.rank = rank\n self.world_size = world_size\n return\n\n if self.rebuild_group or not collective.is_group_initialized(self.group_name):\n collective.init_collective_group(world_size, rank, \"nccl\", self.group_name)\n self.rank = rank\n self.world_size = world_size\n else:\n assert self.rank == rank, f\"rank {rank} is not equal to self.rank {self.rank}\"\n assert self.world_size == world_size, (\n f\"world_size {world_size} is not equal to self.world_size {self.world_size}\"\n )\n\n if self.rank > 0:\n self._connect_zmq_client(master_metadata)\n collective.barrier(self.group_name)\n\n logger.info(f\"init_process_group rank: {self.rank}, world_size: {self.world_size}\")\n\n @torch.no_grad()\n async def send_weights(self, weights: Generator[tuple[str, torch.Tensor], None, None]):\n \"\"\"Send the weights of the model.\n\n Args:\n weights: A generator that yields the name of the weight tensor and the tensor itself.\n \"\"\"\n assert self.rank <= 0, \"Trainer workers other than rank 0 should not send weights.\"\n\n # For trainer rank other than 0, consume weights without sending.\n if self.rank < 0:\n for name, weight in weights:\n pass\n return\n\n send_buf, recv_buf = self.send_buf, self.recv_buf\n broadcast_op = None\n\n start_time = time.time()\n bucket_meta: dict[str, TensorMeta] = {}\n offset = 0\n for name, weight in weights:\n # fill the tensor bucket\n if offset + weight.nbytes > self.bucket_size:\n torch.cuda.synchronize()\n\n # wait previous broadcast op finish\n if broadcast_op is not None:\n await broadcast_op.wait_for_complete()\n\n broadcast_op = BroadcastOperation(\n rank=self.rank,\n group_name=self.group_name,\n bucket=send_buf,\n metadata={\"bucket_meta\": bucket_meta, \"is_last\": False},\n socket=self.socket,\n topic=self.topic,\n )\n\n # swap send_buf and recv_buf\n send_buf, recv_buf = recv_buf, send_buf\n bucket_meta = {}\n offset = 0\n\n assert offset + weight.nbytes <= self.bucket_size, (\n f\"Weight {name}({weight.shape}, {weight.dtype}) is too large to fit in the bucket.\"\n )\n\n bucket_meta[name] = {\n \"name\": name,\n \"shape\": weight.shape,\n \"dtype\": weight.dtype,\n \"offset\": offset,\n }\n send_buf[offset : offset + weight.nbytes] = cp.asarray(weight.view(-1).view(torch.uint8))\n offset += weight.nbytes\n\n # broadcast last bucket\n torch.cuda.synchronize()\n if broadcast_op is not None:\n await broadcast_op.wait_for_complete()\n\n broadcast_op = BroadcastOperation(\n rank=self.rank,\n group_name=self.group_name,\n bucket=send_buf,\n metadata={\"bucket_meta\": bucket_meta, \"is_last\": True},\n socket=self.socket,\n topic=self.topic,\n )\n await broadcast_op.wait_for_complete()\n logger.info(f\"Rank {self.rank} send weights done, time cost: {time.time() - start_time:.2f}s\")\n\n @torch.no_grad()\n async def receive_weights(self) -> AsyncGenerator[tuple[str, torch.Tensor], None]:\n \"\"\"Receive the weights of the model.\n\n Yields:\n A tuple of the name of the weight tensor and the tensor itself.\n \"\"\"\n assert self.rank > 0, \"Rank 0 should not receive weights.\"\n send_buf, recv_buf = self.send_buf, self.recv_buf\n total_bytes, total_params = 0, 0\n\n # receive first bucket\n start_time = time.time()\n broadcast_op = BroadcastOperation(\n rank=self.rank,\n group_name=self.group_name,\n bucket=recv_buf,\n metadata=None,\n socket=self.socket,\n topic=self.topic,\n )\n metadata = await broadcast_op.wait_for_complete()\n total_bytes += self.bucket_size\n total_params += len(metadata[\"bucket_meta\"])\n\n # swap send_buf and recv_buf\n send_buf, recv_buf = recv_buf, send_buf\n while not metadata[\"is_last\"]:\n # 1. receive next bucket\n broadcast_op = BroadcastOperation(\n rank=self.rank,\n group_name=self.group_name,\n bucket=recv_buf,\n metadata=None,\n socket=self.socket,\n topic=self.topic,\n )\n\n # 2. yield tensor from send_buf\n for name, meta in metadata[\"bucket_meta\"].items():\n dtype, shape = meta[\"dtype\"], meta[\"shape\"]\n size = dtype.itemsize * shape.numel()\n tensor = send_buf[meta[\"offset\"] : meta[\"offset\"] + size].view(dtype=dtype).view(shape)\n yield name, tensor\n\n # 3. wait for next bucket broadcast finish\n metadata = await broadcast_op.wait_for_complete()\n total_bytes += self.bucket_size\n total_params += len(metadata[\"bucket_meta\"])\n\n # 4. swap send_buf and recv_buf\n torch.cuda.synchronize() # sync non-blocking copy\n send_buf, recv_buf = recv_buf, send_buf\n\n # yield tensor from send_buf\n for name, meta in metadata[\"bucket_meta\"].items():\n dtype, shape = meta[\"dtype\"], meta[\"shape\"]\n size = dtype.itemsize * shape.numel()\n tensor = send_buf[meta[\"offset\"] : meta[\"offset\"] + size].view(dtype=dtype).view(shape)\n yield name, tensor\n\n time_cost = time.time() - start_time\n bandwidth = total_bytes / time_cost / (1024 * 1024 * 1024)\n logger.info(\n f\"Rank {self.rank} receive weights done, total_params: {total_params}, \"\n f\"time cost: {time_cost:.2f}s, bandwidth: {bandwidth:.2f} GB/s\"\n )\n"} {"file_name": "verl__interactions__base.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023-2024 SGLang Team\n# Copyright 2025 ModelBest Inc. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, Optional\nfrom uuid import uuid4\n\n\nclass BaseInteraction:\n def __init__(self, config: dict[str, Any]):\n self.config = config\n self.name: str = config.get(\"name\", \"interaction_agent\") # More general agent default role name\n\n async def start_interaction(self, instance_id: Optional[str] = None, **kwargs) -> str:\n \"\"\"Create a tool instance.\n\n Args:\n instance_id: The instance id of the tool.\n\n Returns:\n The instance id of the tool.\n \"\"\"\n if instance_id is None:\n return str(uuid4())\n else:\n return instance_id\n\n async def generate_response(\n self, instance_id: str, messages: list[dict[str, Any]], **kwargs\n ) -> tuple[bool, str, float, dict[str, Any]]: # More clear response generation method\n \"\"\"\n Generates a response for the current turn of interaction.\n Returns a tuple containing:\n - should_terminate_sequence (bool): True if the interaction sequence should end.\n - response_content (str): The textual content of the response.\n - current_turn_score (float): The score for this specific turn/response.\n - additional_data (dict): Any extra information or metadata.\n \"\"\"\n should_terminate_sequence: bool = False # if True, end rollout\n response_content: str = \"Your current result seems acceptable.\"\n current_turn_score: float = 0.8\n additional_data: dict[str, Any] = {}\n return should_terminate_sequence, response_content, current_turn_score, additional_data\n\n async def calculate_score(self) -> float: # More clear score calculation method\n \"\"\"\n Calculates a score for the interaction,\n potentially considering aspects like partial exposure & in-context task switching.\n should be invoke at turn-level\n \"\"\"\n # ...implement the logic to calculate turn-level score...\n score = 0.0\n return score\n\n async def finalize_interaction(self) -> None: # More clear interaction end and resource release method\n \"\"\"\n Finalizes the interaction session and releases any associated state or resources.\n Simulates: release state\n \"\"\"\n # ...implement the logic to release state...\n pass\n"} {"file_name": "verl__models__llama__megatron__checkpoint_utils__llama_loader_depracated.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\n\nimport torch\nimport torch.distributed as dist\n\nfrom verl.utils.device import get_device_id, get_torch_device\n\n\ndef _megatron_calc_layer_map(config):\n \"\"\"Calculate the mapping of global layer_idx to local layer_idx\n Returns:\n layer_map (Dict: int -> tuple(int, int, int)):\n mapping from the global layer index to\n a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model)\n \"\"\"\n from megatron.core import mpu\n\n print(f\"get megatron data parallel size: {mpu.get_data_parallel_world_size()}\")\n\n pp_size = mpu.get_pipeline_model_parallel_world_size()\n virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n\n layer_map = dict()\n num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n for pp_rank_idx in range(pp_size):\n for virtual_pp_rank_idx in range(virtual_pp_size):\n layer_offset = (\n virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model\n )\n for layer_idx in range(num_layers_per_model):\n layer_map[layer_offset + layer_idx] = (\n pp_rank_idx,\n virtual_pp_rank_idx,\n layer_idx,\n )\n return layer_map\n\n\ndef load_state_dict_to_megatron_llama(\n state_dict, wrapped_models, config, params_dtype, is_value_model=False, tie_word_embeddings=False\n):\n \"\"\"Load merged state_dict to sharded Megatron module in training.\"\"\"\n from megatron.core import DistributedDataParallel as LocalDDP\n from megatron.core import mpu\n from megatron.core.transformer.module import Float16Module\n from torch.nn.parallel import DistributedDataParallel as torchDDP\n\n from verl.utils.logger import print_rank_0\n from verl.utils.megatron_utils import unwrap_model\n\n start_time = time.time()\n\n def _get_gpt_model(model):\n return model\n\n def broadcast_params(module):\n for param in module.parameters():\n torch.distributed.broadcast(\n param.data, src=mpu.get_data_parallel_src_rank(), group=mpu.get_data_parallel_group()\n )\n\n dp_rank = mpu.get_data_parallel_rank()\n pp_rank = mpu.get_pipeline_model_parallel_rank()\n pp_size = mpu.get_pipeline_model_parallel_world_size()\n virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n mp_group = mpu.get_model_parallel_group()\n\n if torch.distributed.get_rank() == 0:\n assert mp_group.rank() == 0, f\"mp_rank:[{mp_group.rank}] != 0 on rank #0\"\n assert pp_rank == 0, f\"pp_rank:[{pp_rank}] != 0 on rank #0\"\n assert dp_rank == 0, f\"dp_rank:[{dp_rank}] != 0 on rank #0\"\n\n if not isinstance(wrapped_models, list | tuple):\n wrapped_models = list(wrapped_models)\n\n assert len(wrapped_models) == virtual_pp_size\n num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers, (\n f\"num_layers_per_model: {num_layers_per_model} * pp_size: {pp_size} * virtual_pp_size \"\n f\"{virtual_pp_size} != config.num_hidden_layers: {config.num_hidden_layers}\"\n )\n\n models = [None] * len(wrapped_models)\n\n for i, wrapped_model in enumerate(wrapped_models):\n models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module))\n gpt_model_module = _get_gpt_model(models[i])\n assert len(gpt_model_module.model.layers) == num_layers_per_model\n\n def _broadcast_tensor(tensor, name) -> torch.Tensor:\n \"\"\"broadcast tensor from rank0 across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n if torch.distributed.get_rank() == 0:\n if name in state_dict:\n weight = state_dict[name]\n tensor_shape = weight.shape\n else:\n tensor_shape = None\n else:\n weight = None\n tensor_shape = None\n\n obj_list = [tensor_shape]\n dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n tensor_shape = obj_list[0]\n\n if tensor_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tensor:[{name}] not in state_dict, skip load\")\n return\n\n if tensor is None:\n tensor = torch.empty(\n tensor_shape,\n dtype=params_dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n if torch.distributed.get_rank() == 0:\n tensor.data.copy_(weight)\n dist.broadcast(tensor, src=0, group=mp_group)\n\n def _broadcast_tp_shard_tensor_vocab(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor:\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_rank = mpu.get_tensor_model_parallel_rank()\n tp_size = mpu.get_tensor_model_parallel_world_size()\n\n if torch.distributed.get_rank() == 0:\n if name in state_dict:\n full_weight = state_dict[name]\n\n if mutate_func is not None:\n full_weight = mutate_func(full_weight)\n tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim)\n chunk_shape = tensor_chunk[0].shape\n else:\n chunk_shape = None\n else:\n chunk_shape = None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n return\n\n if tensor is None:\n sync_tensor = torch.empty(\n chunk_shape,\n dtype=params_dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n else:\n assert tensor.shape == chunk_shape, (\n f\"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}\"\n )\n sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False)\n\n for i in range(tp_size):\n if torch.distributed.get_rank() == 0:\n sync_tensor.data.copy_(tensor_chunk[i])\n dist.broadcast(sync_tensor, src=0, group=mp_group)\n if (i == tp_rank) and (tensor is not None):\n tensor.data.copy_(sync_tensor)\n\n def _broadcast_tp_shard_tensor(tensor, name, chunk_dim=0, mutate_func=None) -> torch.Tensor:\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_rank = mpu.get_tensor_model_parallel_rank()\n tp_size = mpu.get_tensor_model_parallel_world_size()\n\n if torch.distributed.get_rank() == 0:\n if name in state_dict:\n full_weight = state_dict[name]\n if mutate_func is not None:\n full_weight = mutate_func(full_weight)\n tensor_chunk = torch.chunk(full_weight, tp_size, dim=chunk_dim)\n chunk_shape = tensor_chunk[0].shape\n else:\n chunk_shape = None\n else:\n chunk_shape = None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{name}] not in state_dict, skip loading\")\n return\n\n if tensor is None:\n sync_tensor = torch.empty(\n chunk_shape,\n dtype=params_dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n else:\n assert tensor.shape == chunk_shape, (\n f\"rank #{torch.distributed.get_rank()} tensor {name} shape {tensor.shape} != {chunk_shape}\"\n )\n sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False)\n\n for i in range(tp_size):\n if torch.distributed.get_rank() == 0:\n sync_tensor.data.copy_(tensor_chunk[i])\n dist.broadcast(sync_tensor, src=0, group=mp_group)\n if (i == tp_rank) and (tensor is not None):\n tensor.data.copy_(sync_tensor)\n\n def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name) -> torch.Tensor:\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_rank = mpu.get_tensor_model_parallel_rank()\n tp_size = mpu.get_tensor_model_parallel_world_size()\n\n if torch.distributed.get_rank() == 0:\n gate_weight = state_dict[gate_name]\n up_weight = state_dict[up_name]\n new_gate_up_weight = torch.empty(\n config.intermediate_size * 2, config.hidden_size, dtype=params_dtype, device=get_device_id()\n )\n for i in range(tp_size):\n intermediate_size_tp = config.intermediate_size // tp_size\n gate_weight_tp = gate_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp]\n up_weight_tp = up_weight[i * intermediate_size_tp : (i + 1) * intermediate_size_tp]\n new_gate_up_weight[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)].copy_(\n torch.cat([gate_weight_tp, up_weight_tp], dim=0)\n )\n\n tensor_chunk = torch.chunk(new_gate_up_weight, tp_size, dim=0)\n chunk_shape = tensor_chunk[0].shape\n else:\n chunk_shape = None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{gate_name, up_name}] not in state_dict, skip loading\")\n return\n\n if tensor is None:\n sync_tensor = torch.empty(\n chunk_shape,\n dtype=params_dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n else:\n assert tensor.shape == chunk_shape, (\n f\"rank #{torch.distributed.get_rank() == 0:} tensor {gate_name, up_name} shape \"\n f\"{tensor.shape} != {chunk_shape}\"\n )\n sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False)\n\n for i in range(tp_size):\n if torch.distributed.get_rank() == 0:\n sync_tensor.data.copy_(tensor_chunk[i])\n dist.broadcast(sync_tensor, src=0, group=mp_group)\n if (i == tp_rank) and (tensor is not None):\n tensor.data.copy_(sync_tensor)\n\n def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name) -> torch.Tensor:\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_rank = mpu.get_tensor_model_parallel_rank()\n tp_size = mpu.get_tensor_model_parallel_world_size()\n\n if torch.distributed.get_rank() == 0:\n assert q_name in state_dict and k_name in state_dict and v_name in state_dict\n full_weight_q = state_dict[q_name]\n full_weight_k = state_dict[k_name]\n full_weight_v = state_dict[v_name]\n\n hidden_size_per_head = config.hidden_size // config.num_attention_heads\n\n if config.num_key_value_heads >= tp_size:\n q_size_tp = config.hidden_size // tp_size\n kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size\n total_size = q_size_tp + 2 * kv_size_tp\n new_weight_qkv = torch.empty(\n total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id()\n )\n for i in range(tp_size):\n q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp]\n k_part = full_weight_k[i * kv_size_tp : (i + 1) * kv_size_tp]\n v_part = full_weight_v[i * kv_size_tp : (i + 1) * kv_size_tp]\n new_weight_qkv[i * total_size : (i + 1) * total_size].copy_(\n torch.cat([q_part, k_part, v_part], dim=0)\n )\n\n else:\n q_size_tp = config.hidden_size // tp_size\n kv_size_tp = hidden_size_per_head\n total_size = q_size_tp + 2 * kv_size_tp\n new_weight_qkv = torch.empty(\n total_size * tp_size, config.hidden_size, dtype=params_dtype, device=get_device_id()\n )\n for i in range(tp_size):\n q_part = full_weight_q[i * q_size_tp : (i + 1) * q_size_tp]\n start_idx = i * config.num_key_value_heads // tp_size * hidden_size_per_head\n end_idx = (i * config.num_key_value_heads // tp_size + 1) * hidden_size_per_head\n k_part = full_weight_k[start_idx:end_idx]\n v_part = full_weight_v[start_idx:end_idx]\n new_weight_qkv[i * total_size : (i + 1) * total_size].copy_(\n torch.cat([q_part, k_part, v_part], dim=0)\n )\n\n tensor_chunk = torch.chunk(new_weight_qkv, tp_size, dim=0)\n chunk_shape = tensor_chunk[0].shape\n else:\n chunk_shape = None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=0, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{q_name, k_name, v_name}] not in state_dict, skip loading\")\n return\n\n if tensor is None:\n sync_tensor = torch.empty(\n chunk_shape,\n dtype=params_dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n else:\n assert tensor.shape == chunk_shape, (\n f\"rank #{torch.distributed.get_rank()} tensor {q_name} shape {tensor.shape} != {chunk_shape}\"\n )\n sync_tensor = torch.empty_like(tensor, device=get_device_id(), requires_grad=False)\n\n for i in range(tp_size):\n if torch.distributed.get_rank() == 0:\n sync_tensor.data.copy_(tensor_chunk[i])\n dist.broadcast(sync_tensor, src=0, group=mp_group)\n if (i == tp_rank) and (tensor is not None):\n tensor.data.copy_(sync_tensor)\n\n if dp_rank == 0:\n # Embeddings\n # -------------------\n print_rank_0(\"loading embeddings...\")\n gpt_model_module = _get_gpt_model(models[0])\n embed_tokens_weight = None\n if pp_rank == 0:\n embed_tokens_weight = gpt_model_module.model.embed_tokens.weight\n _broadcast_tp_shard_tensor_vocab(embed_tokens_weight, \"model.embed_tokens.weight\")\n\n # Transformer layers\n # -------------------\n layer_map = _megatron_calc_layer_map(config)\n\n for layer in range(config.num_hidden_layers):\n print_rank_0(f\"loading layer #{layer}...\")\n layer_name = f\"model.layers.{layer}\"\n dst_pp_rank, dst_virtual_pp_rank, dst_layer_idx = layer_map[layer]\n\n gpt_model_module = _get_gpt_model(models[dst_virtual_pp_rank])\n sync_layer = gpt_model_module.model.layers[dst_layer_idx]\n\n _broadcast_tensor(\n sync_layer.input_layernorm.weight if dst_pp_rank == pp_rank else None,\n f\"{layer_name}.input_layernorm.weight\",\n )\n\n _broadcast_tp_shard_tensor_qkv(\n sync_layer.self_attn.qkv_proj.weight if dst_pp_rank == pp_rank else None,\n f\"{layer_name}.self_attn.q_proj.weight\",\n f\"{layer_name}.self_attn.k_proj.weight\",\n f\"{layer_name}.self_attn.v_proj.weight\",\n )\n\n _broadcast_tp_shard_tensor(\n sync_layer.self_attn.o_proj.weight if dst_pp_rank == pp_rank else None,\n f\"{layer_name}.self_attn.o_proj.weight\",\n chunk_dim=1,\n )\n\n _broadcast_tensor(\n sync_layer.post_attention_layernorm.weight if dst_pp_rank == pp_rank else None,\n f\"{layer_name}.post_attention_layernorm.weight\",\n )\n\n _broadcast_tp_shard_tensor_gate_up(\n sync_layer.mlp.gate_up_proj.weight if dst_pp_rank == pp_rank else None,\n f\"{layer_name}.mlp.gate_proj.weight\",\n f\"{layer_name}.mlp.up_proj.weight\",\n )\n\n _broadcast_tp_shard_tensor(\n sync_layer.mlp.down_proj.weight if dst_pp_rank == pp_rank else None,\n f\"{layer_name}.mlp.down_proj.weight\",\n chunk_dim=1,\n )\n # Final Layernorm\n # -------------------\n print_rank_0(\"loading final layernorm...\")\n gpt_model_module = _get_gpt_model(models[-1])\n _broadcast_tensor(\n getattr(gpt_model_module.model.norm, \"weight\", None),\n \"model.norm.weight\",\n )\n\n print_rank_0(\"loading lm_head...\")\n lm_head_weight = None\n if pp_rank + 1 == pp_size:\n lm_head_weight = gpt_model_module.lm_head.weight\n\n if is_value_model:\n if \"lm_head.weight\" in state_dict and state_dict[\"lm_head.weight\"].shape[0] == 1:\n _broadcast_tensor(lm_head_weight, \"lm_head.weight\")\n print_rank_0(\"load lm_head weight\")\n elif \"reward_head.weight\" in state_dict and state_dict[\"reward_head.weight\"].shape[0] == 1:\n _broadcast_tensor(lm_head_weight, \"reward_head.weight\")\n print_rank_0(\"load lm_head from value_head weight\")\n else:\n _broadcast_tensor(None, \"lm_head.weight\")\n print_rank_0(\"fail to match lm_head in value_model\")\n else:\n _broadcast_tp_shard_tensor(lm_head_weight, \"lm_head.weight\")\n dist.barrier()\n # Broadcast weights inside data parallel groups\n for wrapped_model in wrapped_models:\n broadcast_params(wrapped_model)\n\n get_torch_device().empty_cache()\n print_rank_0(f\"loading megatron ckpt done, time elapsed {time.time() - start_time}s\")\n"} {"file_name": "verl__models__mcore__bridge.py", "text": "# Copyright 2025 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ntry:\n from megatron.bridge import AutoBridge\n from megatron.bridge.models.conversion.param_mapping import AutoMapping\n from megatron.bridge.peft.canonical_lora import CanonicalLoRA\n from megatron.bridge.peft.dora import DoRA\n from megatron.bridge.peft.lora import LoRA, VLMLoRA\nexcept ImportError:\n # `pip install verl[mcore]` or\n print(\"Megatron-Bridge package not found. Please install Megatron-Bridge with `pip install megatron-bridge`\")\n raise\n\nimport torch\nfrom megatron.core import tensor_parallel\n\n\ndef _ensure_model_list(model):\n return model if isinstance(model, list) else [model]\n\n\nclass LinearForLastLayer(torch.nn.Linear):\n \"\"\"\n A custom linear layer implementation for the last layer of a model.\n\n This layer extends PyTorch's Linear module with functionality specifically designed\n for handling the final layer in transformer models with sequence parallelism.\n\n Attributes:\n sequence_parallel: Boolean indicating whether sequence parallelism is enabled\n \"\"\"\n\n def __init__(\n self,\n input_size,\n output_size,\n *,\n sequence_parallel: bool,\n ):\n \"\"\"\n Initializes the LinearForLastLayer.\n\n Args:\n input_size: The size of the input features\n output_size: The size of the output features\n sequence_parallel (bool): Whether sequence parallelism is enabled\n \"\"\"\n super().__init__(in_features=input_size, out_features=output_size, bias=False)\n self.sequence_parallel = sequence_parallel\n if self.sequence_parallel:\n self.weight.sequence_parallel = True\n\n def forward(\n self,\n input_,\n weight=None,\n runtime_gather_output=None,\n ):\n \"\"\"\n Forward pass for the linear layer.\n\n This method computes the linear transformation and handles sequence parallelism\n if enabled, gathering outputs from different sequence parallel regions.\n\n Args:\n input_: Input tensor\n weight: Placeholder for compatibility\n runtime_gather_output: Placeholder for compatibility\n\n Returns:\n tuple: (logits, None) where logits is the output of the linear transformation\n \"\"\"\n logits = super().forward(input_)\n logits = logits.float()\n if self.sequence_parallel:\n logits = tensor_parallel.gather_from_sequence_parallel_region(logits, tensor_parallel_output_grad=False)\n return logits, None\n\n\n# Make Megatron-Bridge AutoMapping treats the custom last layer as replicated.\nAutoMapping.register_module_type(\"LinearForLastLayer\", \"replicated\")\n\n\ndef make_value_model(hidden_size, sequence_parallel):\n \"\"\"Creates a pre-wrap hook that replace the output layer with a value head.\n\n Args:\n hidden_size (int): The hidden size of the model's transformer layers.\n sequence_parallel (bool): Whether sequence parallelism is enabled.\n\n Returns:\n A hook function that can be used as a `pre_wrap_hook` in Megatron-Bridge.\n The hook itself takes the model as input and prepares it for value head activation.\n \"\"\"\n\n from megatron.core import parallel_state\n\n def hook(model):\n model_post_process = []\n if (\n parallel_state.get_pipeline_model_parallel_world_size() > 1\n and parallel_state.get_virtual_pipeline_model_parallel_world_size() is not None\n ):\n for i in range(parallel_state.get_virtual_pipeline_model_parallel_world_size()):\n model_post_process.append(parallel_state.is_pipeline_last_stage(ignore_virtual=False, vp_stage=i))\n else:\n model_post_process.append(parallel_state.is_pipeline_last_stage())\n\n model_list = _ensure_model_list(model)\n assert len(model_post_process) == len(model_list), \"Model list length and post process list length must match.\"\n\n for index, model_chunk in enumerate(model_list):\n if not model_post_process[index]:\n continue\n\n model_chunk.output_layer = LinearForLastLayer(\n input_size=hidden_size,\n output_size=1,\n sequence_parallel=sequence_parallel,\n )\n\n return hook\n\n\ndef freeze_moe_router(model):\n \"\"\"Pre-wrap hook to freeze MoE router parameters.\n\n Args:\n model: List of MegatronModule instances or single module\n\n Returns:\n The model with frozen router parameters\n \"\"\"\n for model_chunk in _ensure_model_list(model):\n if hasattr(model_chunk, \"decoder\") and hasattr(model_chunk.decoder, \"layers\"):\n for layer in model_chunk.decoder.layers:\n if hasattr(layer.mlp, \"router\"):\n if hasattr(layer.mlp.router, \"weight\"):\n layer.mlp.router.weight.requires_grad = False\n if hasattr(layer.mlp.router, \"bias\"):\n layer.mlp.router.bias.requires_grad = False\n if hasattr(layer.mlp, \"shared_experts\"):\n if (\n hasattr(layer.mlp.shared_experts, \"gate_weight\")\n and layer.mlp.shared_experts.gate_weight is not None\n ):\n layer.mlp.shared_experts.gate_weight.requires_grad = False\n if (\n hasattr(layer.mlp.shared_experts, \"gate_bias\")\n and layer.mlp.shared_experts.gate_bias is not None\n ):\n layer.mlp.shared_experts.gate_bias.requires_grad = False\n\n return model\n\n\n__all__ = [\n \"AutoBridge\",\n \"make_value_model\",\n \"freeze_moe_router\",\n \"LoRA\",\n \"VLMLoRA\",\n \"DoRA\",\n \"CanonicalLoRA\",\n]\n"} {"file_name": "verl__models__mcore__qwen2_5_vl__attention.py", "text": "# Copyright 2025 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.\n# Copyright (c) 2024 Alibaba PAI Team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom megatron.core.transformer.attention import *\n\nfrom .rope_utils import apply_rotary_pos_emb_absolute\n\n\nclass Qwen2_5VLSelfAttention(SelfAttention):\n \"\"\"\n Overrides the SelfAttention class, the difference is that qwen2_5_vl uses apply_rotary_pos_emb_absolute\n instead of apply_rotary_pos_emb\n \"\"\"\n\n def forward(\n self,\n hidden_states: Tensor,\n attention_mask: Tensor,\n key_value_states: Optional[Tensor] = None,\n inference_context: Optional[BaseInferenceContext] = None,\n rotary_pos_emb: Optional[Union[Tensor, Tuple[Tensor, Tensor]]] = None,\n rotary_pos_cos: Optional[Tensor] = None,\n rotary_pos_sin: Optional[Tensor] = None,\n attention_bias: Optional[Tensor] = None,\n packed_seq_params: Optional[PackedSeqParams] = None,\n sequence_len_offset: Optional[int] = None,\n *,\n inference_params: Optional[BaseInferenceContext] = None,\n rotary_pos_cos_sin: Optional[Tensor] = None,\n ) -> Tuple[Tensor, Tensor]:\n \"\"\"\n Perform a forward pass through the attention module.\n\n Args:\n hidden_states (Tensor): Hidden states.\n attention_mask (Tensor): Attention mask.\n key_value_states (Optional[Tensor]): Key/value states (for cross attention).\n inference_context (Optional[BaseInferenceContext]): Inference context that manages\n KV cache.\n rotary_pos_emb (Optional[Union[Tensor, Tuple[Tensor, Tensor]]]): Rotary\n embedding tensor(s).\n rotary_pos_cos (Optional[Tensor]): Rotary embedding cosine.\n rotary_pos_sin (Optional[Tensor]): Rotary embedding sine.\n attention_bias (Optional[Tensor]): Attention bias.\n packed_seq_params (Optional[PackedSeqparams]): Parameters used for THD format.\n sequence_len_offset (Optional[int]): Sequence length offset used for\n inference CUDA graphs.\n\n Return:\n (Tuple[Tensor, Tensor]) Attention output and bias.\n\n \"\"\"\n\n inference_context = deprecate_inference_params(inference_context, inference_params)\n\n if inference_context and inference_context.is_dynamic_batching():\n assert flash_decode_and_prefill_kernel is not None, (\n \"Internal use only: install package `nvidia_chunked_flash_attn`.\"\n )\n\n # hidden_states: [sq, b, h]\n if self.config.flash_decode and not self.training and inference_context is not None:\n rotary_pos_emb = None\n else:\n assert rotary_pos_cos is None and rotary_pos_sin is None\n\n # For self attention we just duplicate the rotary_pos_emb if it isn't already\n if rotary_pos_emb is not None and not isinstance(rotary_pos_emb, tuple):\n rotary_pos_emb = (rotary_pos_emb,) * 2\n\n # =====================\n # Query, Key, and Value\n # =====================\n # Get the query, key and value tensors based on the type of attention -\n # self or cross attn.\n query, key, value = self.get_query_key_value_tensors(hidden_states, key_value_states)\n\n # ===================================================\n # Adjust key, value, and rotary_pos_emb for inference\n # ===================================================\n\n # This branch only runs in the decode phase of flash decoding and returns after the linear\n # projection. This conditional is not used in the prefill phase or non-flash-decoding cases.\n if (\n self.config.flash_decode\n and inference_context is not None\n and inference_context.is_decode_only()\n and not self.training\n and rotary_pos_cos is not None\n ):\n assert self.layer_number in inference_context.key_value_memory_dict\n assert inference_context.sequence_len_offset is not None\n inference_key_memory, inference_value_memory = inference_context.key_value_memory_dict[self.layer_number]\n output = self.flash_decode(\n sequence_len_offset=sequence_len_offset,\n query_layer=query,\n key_layer=key,\n value_layer=value,\n inference_key_memory=inference_key_memory,\n inference_value_memory=inference_value_memory,\n rotary_cos=rotary_pos_cos,\n rotary_sin=rotary_pos_sin,\n )\n out = output.transpose(0, 1).contiguous()\n context_layer = out.view(out.size(0), out.size(1), -1)\n output, bias = self.linear_proj(context_layer)\n return output, bias\n\n # Use latest mcore 0.13 API and forward-compatible with previous versions.\n outputs = self._adjust_key_value_for_inference(\n inference_context,\n query,\n key,\n value,\n rotary_pos_emb,\n rotary_pos_cos,\n rotary_pos_sin,\n sequence_len_offset,\n )\n\n query, key, value, rotary_pos_emb, attn_mask_type = outputs[:5]\n\n if packed_seq_params is not None:\n query = query.squeeze(1)\n key = key.squeeze(1)\n value = value.squeeze(1)\n\n # ================================================\n # relative positional embedding (rotary embedding)\n # ================================================\n if rotary_pos_emb is not None and not self.config.flash_decode:\n q_pos_emb, k_pos_emb = rotary_pos_emb\n\n if packed_seq_params is not None:\n if packed_seq_params.cu_seqlens_q_padded is not None:\n cu_seqlens_q = packed_seq_params.cu_seqlens_q_padded\n else:\n cu_seqlens_q = packed_seq_params.cu_seqlens_q\n if packed_seq_params.cu_seqlens_kv_padded is not None:\n cu_seqlens_kv = packed_seq_params.cu_seqlens_kv_padded\n else:\n cu_seqlens_kv = packed_seq_params.cu_seqlens_kv\n else:\n cu_seqlens_q = cu_seqlens_kv = None\n\n if q_pos_emb is not None:\n # TODO VIJAY: simplify\n if inference_context is None or inference_context.is_static_batching():\n query = apply_rotary_pos_emb_absolute(query, q_pos_emb, config=self.config, cu_seqlens=cu_seqlens_q)\n else:\n query = inference_context.apply_rotary_emb_query(query, q_pos_emb, self.config, cu_seqlens_q)\n if k_pos_emb is not None:\n key = apply_rotary_pos_emb_absolute(key, k_pos_emb, config=self.config, cu_seqlens=cu_seqlens_kv)\n\n # TODO, can apply positional embedding to value_layer so it has\n # absolute positional embedding.\n # otherwise, only relative positional embedding takes effect\n # value_layer = apply_rotary_pos_emb(value_layer, k_pos_emb)\n\n # ==================================\n # core attention computation\n # ==================================\n\n if self.checkpoint_core_attention and self.training:\n core_attn_out = self._checkpointed_attention_forward(\n query,\n key,\n value,\n attention_mask,\n attn_mask_type=attn_mask_type,\n attention_bias=attention_bias,\n packed_seq_params=packed_seq_params,\n )\n else:\n if inference_context is None or inference_context.is_static_batching():\n # Static batching attention kernel.\n core_attn_out = self.core_attention(\n query,\n key,\n value,\n attention_mask,\n attn_mask_type=attn_mask_type,\n attention_bias=attention_bias,\n packed_seq_params=packed_seq_params,\n )\n\n else:\n # Dynamic batching attention kernel.\n q, k, v = (query, key, value)\n cu_query_lengths, max_seqlen_q = inference_context.cu_query_lengths()\n cu_kv_lengths, max_seqlen_k = inference_context.cu_kv_lengths()\n\n core_attn_out = self.flash_decode_and_prefill(\n q, k, v, max_seqlen_q, max_seqlen_k, cu_query_lengths, cu_kv_lengths\n )\n core_attn_out = core_attn_out.squeeze(0).unsqueeze(1)\n core_attn_out = rearrange(core_attn_out, \"s b h d -> s b (h d)\")\n\n if packed_seq_params is not None and packed_seq_params.qkv_format == \"thd\":\n # reshape to same output shape as unpacked case\n # (t, np, hn) -> (t, b=1, h=np*hn)\n # t is the pack size = sum (sq_i)\n # note that batch is a dummy dimension in the packed case\n core_attn_out = core_attn_out.reshape(core_attn_out.size(0), 1, -1)\n\n # =================\n # Output. [sq, b, h]\n # =================\n\n output, bias = self.linear_proj(core_attn_out)\n\n return output, bias\n"} {"file_name": "verl__models__qwen2__megatron__checkpoint_utils__qwen2_saver.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\n\nimport torch\nimport torch.distributed as dist\nfrom megatron.core import mpu\nfrom megatron.core.distributed import DistributedDataParallel as LocalDDP\nfrom megatron.core.transformer.module import Float16Module\nfrom torch.nn.parallel import DistributedDataParallel as torchDDP\n\nfrom verl.utils.device import get_device_id, get_torch_device\nfrom verl.utils.logger import print_rank_0\nfrom verl.utils.megatron_utils import unwrap_model\n\n\ndef _megatron_calc_global_rank(tp_rank: int = 0, dp_rank: int = 0, pp_rank: int = 0):\n \"\"\"given TP,DP,PP rank to get the global rank.\"\"\"\n\n tp_size = mpu.get_tensor_model_parallel_world_size()\n dp_size = mpu.get_data_parallel_world_size()\n pp_size = mpu.get_pipeline_model_parallel_world_size()\n assert tp_size * dp_size * pp_size == torch.distributed.get_world_size(), (\n f\"{tp_size} x {dp_size} x {pp_size} != {torch.distributed.get_world_size()}\"\n )\n # We only support TP-DP-PP grouping, for correctness when resharding\n return (pp_rank * dp_size + dp_rank) * tp_size + tp_rank\n\n\ndef _megatron_calc_layer_map(config):\n \"\"\"Calculate the mapping of global layer_idx to local layer_idx\n Returns:\n layer_map (Dict: int -> tuple(int, int, int)):\n mapping from the global layer index to\n a tuple of (pp_rank, virtual_pp_rank, layer_idx inside model)\n \"\"\"\n from megatron.core import mpu\n\n pp_size = mpu.get_pipeline_model_parallel_world_size()\n virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n\n layer_map = dict()\n num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n for pp_rank_idx in range(pp_size):\n for virtual_pp_rank_idx in range(virtual_pp_size):\n layer_offset = (\n virtual_pp_rank_idx * (config.num_hidden_layers // virtual_pp_size) + pp_rank_idx * num_layers_per_model\n )\n for layer_idx in range(num_layers_per_model):\n layer_map[layer_offset + layer_idx] = (\n pp_rank_idx,\n virtual_pp_rank_idx,\n layer_idx,\n )\n return layer_map\n\n\ndef merge_megatron_ckpt_qwen2(wrapped_models, config, dtype, is_value_model=False, tie_word_embeddings=False):\n \"\"\"Merge sharded parameters of a Megatron module into a merged checkpoint.\n\n Args:\n wrapped_models (list of megatron.core.distributed.DistributedDataParallel):\n The local DDP wrapped megatron modules.\n config (str or None):\n HF config for model\n dtype: model params type\n is_value_model: if model is value model\n tie_word_embeddings: tie_word_embeddings\n Returns:\n state_dict (dict):\n The merged state_dict in rank 0, and an empty dictionary in other ranks.\n \"\"\"\n start_time = time.time()\n\n def _get_gpt_model(model):\n return model\n\n dp_rank = mpu.get_data_parallel_rank()\n pp_size = mpu.get_pipeline_model_parallel_world_size()\n pp_rank = mpu.get_pipeline_model_parallel_rank()\n virtual_pp_size = mpu.get_virtual_pipeline_model_parallel_world_size() or 1\n mp_group = mpu.get_model_parallel_group()\n\n if dist.get_rank() == 0:\n assert mp_group.rank() == 0, f\"mp_rank:[{mp_group.rank}] != 0 on rank #0\"\n assert pp_rank == 0, f\"pp_rank:[{pp_rank}] != 0 on rank #0\"\n assert dp_rank == 0, f\"dp_rank:[{dp_rank}] != 0 on rank #0\"\n\n if not isinstance(wrapped_models, list | tuple):\n wrapped_models = list(wrapped_models)\n\n assert len(wrapped_models) == virtual_pp_size\n num_layers_per_model = config.num_hidden_layers // pp_size // virtual_pp_size\n assert num_layers_per_model * pp_size * virtual_pp_size == config.num_hidden_layers\n\n models = [None] * len(wrapped_models)\n\n for i, wrapped_model in enumerate(wrapped_models):\n models[i] = unwrap_model(wrapped_model, (torchDDP, LocalDDP, Float16Module))\n assert len(models[i].model.layers) == num_layers_per_model, (\n \"len model layers {} not equal to num_layers_per_model {}\".format(\n len(models[i].model.layers), num_layers_per_model\n )\n )\n\n state_dict = dict()\n\n def _get_cpu_tensor(tensor: torch.Tensor):\n if tensor is None:\n return None\n if tensor.device == torch.device(\"cpu\"):\n return tensor.detach().clone()\n return tensor.detach().cpu()\n\n def _broadcast_tensor(tensor, name, src_pp_rank) -> torch.Tensor:\n \"\"\"broadcast tensor across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n if torch.distributed.get_rank() == src_rank:\n if tensor is None:\n weight = None\n tensor_shape = None\n else:\n weight = tensor\n tensor_shape = weight.shape\n else:\n weight = None\n tensor_shape = None\n\n obj_list = [tensor_shape]\n dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n tensor_shape = obj_list[0]\n\n if tensor_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tensor:[{name}] not exist, skip collect\")\n return\n\n if weight is None:\n weight = torch.empty(\n tensor_shape,\n dtype=dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n\n dist.broadcast(weight, src=src_rank, group=mp_group)\n\n if torch.distributed.get_rank() == 0:\n state_dict[name] = _get_cpu_tensor(weight)\n\n def _broadcast_tp_shard_tensor(tensor, name, src_pp_rank, concat_dim=0, mutate_func=None) -> torch.Tensor:\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_size = mpu.get_tensor_model_parallel_world_size()\n src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{name}] not exist, skip collecting\")\n return\n\n buffer_tensor = torch.empty(\n chunk_shape,\n dtype=dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n\n chunk_tensors = [None] * tp_size\n\n for i in range(tp_size):\n cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n if torch.distributed.get_rank() == 0:\n chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n if torch.distributed.get_rank() == 0:\n full_tensor = torch.concat(chunk_tensors, dim=concat_dim)\n if mutate_func is not None:\n full_tensor = mutate_func(full_tensor)\n state_dict[name] = full_tensor\n\n def _broadcast_tp_shard_tensor_gate_up(tensor, gate_name, up_name, src_pp_rank) -> torch.Tensor:\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_size = mpu.get_tensor_model_parallel_world_size()\n src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{gate_name, up_name}] not exist, skip collecting\")\n return\n\n buffer_tensor = torch.empty(\n chunk_shape,\n dtype=dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n\n chunk_tensors = [None] * tp_size\n\n for i in range(tp_size):\n cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n if torch.distributed.get_rank() == 0:\n chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n if torch.distributed.get_rank() == 0:\n full_tensor = torch.concat(chunk_tensors, dim=0)\n intermediate_size_tp = config.intermediate_size // tp_size\n gate_weight_list = []\n up_weight_list = []\n for i in range(tp_size):\n gate_up_weight_tp = full_tensor[intermediate_size_tp * 2 * i : intermediate_size_tp * 2 * (i + 1)]\n gate_weight_tp = gate_up_weight_tp[:intermediate_size_tp]\n up_weight_tp = gate_up_weight_tp[intermediate_size_tp:]\n gate_weight_list.append(gate_weight_tp)\n up_weight_list.append(up_weight_tp)\n\n state_dict[gate_name] = torch.cat(gate_weight_list, dim=0)\n state_dict[up_name] = torch.cat(up_weight_list, dim=0)\n\n def _broadcast_tp_shard_tensor_qkv(tensor, q_name, k_name, v_name, src_pp_rank):\n \"\"\"broadcast tensor in tp shards across mp_group\"\"\"\n nonlocal state_dict\n nonlocal mp_group\n tp_size = mpu.get_tensor_model_parallel_world_size()\n src_rank = _megatron_calc_global_rank(tp_rank=0, dp_rank=0, pp_rank=src_pp_rank)\n\n chunk_shape = tensor.shape if torch.distributed.get_rank() == src_rank else None\n\n obj_list = [chunk_shape]\n dist.broadcast_object_list(obj_list, src=src_rank, group=mp_group)\n chunk_shape = obj_list[0]\n if chunk_shape is None:\n # all or none ranks in the mp_group should reach here\n print_rank_0(f\"tp_shard tensor:[{q_name}] not exist, skip collecting\")\n return\n\n buffer_tensor = torch.empty(\n chunk_shape,\n dtype=dtype,\n device=get_device_id(),\n requires_grad=False,\n )\n\n chunk_tensors = [None] * tp_size\n\n for i in range(tp_size):\n cur_src_rank = _megatron_calc_global_rank(tp_rank=i, dp_rank=0, pp_rank=src_pp_rank)\n sync_tensor = tensor if torch.distributed.get_rank() == cur_src_rank else buffer_tensor\n dist.broadcast(sync_tensor, src=cur_src_rank, group=mp_group)\n\n if torch.distributed.get_rank() == 0:\n chunk_tensors[i] = _get_cpu_tensor(sync_tensor)\n\n if torch.distributed.get_rank() == 0:\n full_tensor = torch.concat(chunk_tensors, dim=0)\n q_weight_list = []\n k_weight_list = []\n v_weight_list = []\n hidden_size_per_head = config.hidden_size // config.num_attention_heads\n\n if config.num_key_value_heads >= tp_size:\n q_size_tp = config.hidden_size // tp_size\n kv_size_tp = hidden_size_per_head * config.num_key_value_heads // tp_size\n total_size = q_size_tp + 2 * kv_size_tp\n for i in range(tp_size):\n qkv_part = full_tensor[i * total_size : (i + 1) * total_size]\n q_part = qkv_part[:q_size_tp]\n k_part = qkv_part[q_size_tp : q_size_tp + kv_size_tp]\n v_part = qkv_part[q_size_tp + kv_size_tp : total_size]\n q_weight_list.append(q_part)\n k_weight_list.append(k_part)\n v_weight_list.append(v_part)\n else:\n q_size_tp = config.hidden_size // tp_size\n kv_size_tp = hidden_size_per_head\n total_size = q_size_tp + 2 * kv_size_tp\n for i in range(tp_size):\n qkv_part = full_tensor[i * total_size : (i + 1) * total_size]\n q_part = qkv_part[:q_size_tp]\n k_part = qkv_part[q_size_tp : q_size_tp + kv_size_tp]\n v_part = qkv_part[q_size_tp + kv_size_tp : total_size]\n q_weight_list.append(q_part)\n if i * config.num_key_value_heads % tp_size == 0:\n k_weight_list.append(k_part)\n v_weight_list.append(v_part)\n\n state_dict[q_name] = torch.cat(q_weight_list, dim=0)\n state_dict[k_name] = torch.cat(k_weight_list, dim=0)\n state_dict[v_name] = torch.cat(v_weight_list, dim=0)\n\n # empty cache before collecting weights\n get_torch_device().empty_cache()\n # Embeddings\n # -------------------\n if dp_rank == 0:\n # Embeddings\n # -------------------\n print_rank_0(\"collecting embeddings...\")\n gpt_model_module = _get_gpt_model(models[0])\n _broadcast_tp_shard_tensor(\n gpt_model_module.model.embed_tokens.weight if pp_rank == 0 else None,\n \"model.embed_tokens.weight\",\n src_pp_rank=0,\n )\n\n # Transformer layers\n # -------------------\n layer_map = _megatron_calc_layer_map(config)\n for layer in range(config.num_hidden_layers):\n print_rank_0(f\"collecting layer #{layer}...\")\n layer_name = f\"model.layers.{layer}\"\n src_pp_rank, src_virtual_pp_rank, src_layer_idx = layer_map[layer]\n\n gpt_model_module = _get_gpt_model(models[src_virtual_pp_rank])\n sync_layer = gpt_model_module.model.layers[src_layer_idx]\n\n _broadcast_tensor(\n sync_layer.input_layernorm.weight,\n f\"{layer_name}.input_layernorm.weight\",\n src_pp_rank=src_pp_rank,\n )\n\n _broadcast_tp_shard_tensor_qkv(\n sync_layer.self_attn.qkv_proj.weight,\n f\"{layer_name}.self_attn.q_proj.weight\",\n f\"{layer_name}.self_attn.k_proj.weight\",\n f\"{layer_name}.self_attn.v_proj.weight\",\n src_pp_rank=src_pp_rank,\n )\n\n _broadcast_tp_shard_tensor_qkv(\n sync_layer.self_attn.qkv_proj.bias,\n f\"{layer_name}.self_attn.q_proj.bias\",\n f\"{layer_name}.self_attn.k_proj.bias\",\n f\"{layer_name}.self_attn.v_proj.bias\",\n src_pp_rank=src_pp_rank,\n )\n\n _broadcast_tp_shard_tensor(\n sync_layer.self_attn.o_proj.weight,\n f\"{layer_name}.self_attn.o_proj.weight\",\n concat_dim=1,\n src_pp_rank=src_pp_rank,\n )\n\n _broadcast_tensor(\n sync_layer.post_attention_layernorm.weight,\n f\"{layer_name}.post_attention_layernorm.weight\",\n src_pp_rank=src_pp_rank,\n )\n\n _broadcast_tp_shard_tensor_gate_up(\n sync_layer.mlp.gate_up_proj.weight,\n f\"{layer_name}.mlp.gate_proj.weight\",\n f\"{layer_name}.mlp.up_proj.weight\",\n src_pp_rank=src_pp_rank,\n )\n\n _broadcast_tp_shard_tensor(\n sync_layer.mlp.down_proj.weight,\n f\"{layer_name}.mlp.down_proj.weight\",\n concat_dim=1,\n src_pp_rank=src_pp_rank,\n )\n\n # Final Layernorm\n # -------------------\n print_rank_0(\"collecting final layernorm...\")\n gpt_model_module = _get_gpt_model(models[-1])\n _broadcast_tensor(\n getattr(gpt_model_module.model.norm, \"weight\", None),\n \"model.norm.weight\",\n src_pp_rank=pp_size - 1,\n )\n\n if tie_word_embeddings:\n print_rank_0(\"tie word embedding skip load lm_head...\")\n else:\n print_rank_0(\"collecting lm_head...\")\n\n if is_value_model:\n _broadcast_tensor(\n gpt_model_module.lm_head.weight if pp_rank == pp_size - 1 else None,\n \"lm_head.weight\",\n src_pp_rank=pp_size - 1,\n )\n _broadcast_tensor(\n gpt_model_module.reward_head.weight\n if pp_rank == pp_size - 1 and getattr(gpt_model_module, \"reward_weight\", None) is not None\n else None,\n \"reward_head.weight\",\n src_pp_rank=pp_size - 1,\n )\n\n else:\n _broadcast_tp_shard_tensor(\n getattr(gpt_model_module.lm_head, \"weight\", None) if pp_rank == pp_size - 1 else None,\n \"lm_head.weight\",\n src_pp_rank=pp_size - 1,\n )\n\n dist.barrier()\n\n get_torch_device().empty_cache()\n if torch.distributed.get_rank() == 0:\n for k, v in state_dict.items():\n if dtype != v.dtype:\n state_dict[k] = v.to(dtype)\n\n print_rank_0(f\"merge megatron ckpt done, time elapsed {time.time() - start_time}s\")\n return state_dict\n"} {"file_name": "verl__models__qwen2__megatron__layers__parallel_decoder.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.\n#\n# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX\n# and OPT implementations in this library. It has been modified from its\n# original forms to accommodate minor architectural differences compared\n# to GPT-NeoX and OPT used by the Meta AI team that trained the model.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Optional\n\nimport torch\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers import Qwen2Config\n\nfrom verl.utils.megatron_utils import TransformerConfig, convert_config\n\nfrom .parallel_attention import ParallelQwen2Attention, ParallelQwen2AttentionRmPad\nfrom .parallel_mlp import ParallelQwen2MLP\nfrom .parallel_rmsnorm import ParallelQwen2RMSNorm\n\n\nclass ParallelQwen2DecoderLayer(nn.Module):\n def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, layer_idx: int):\n super().__init__()\n self.config: TransformerConfig = convert_config(config, megatron_config)\n self.layer_idx = layer_idx\n self.hidden_size = config.hidden_size\n self.self_attn = ParallelQwen2Attention(config=config, megatron_config=megatron_config)\n\n self.mlp = ParallelQwen2MLP(config, megatron_config=megatron_config)\n self.input_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n self.post_attention_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:\n \"\"\"\n Args:\n hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n attention_mask (`torch.FloatTensor`, *optional*): attention mask of size\n `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n returned tensors for more detail.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n (see `past_key_values`).\n past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states\n \"\"\"\n\n residual = hidden_states\n\n hidden_states = self.input_layernorm(hidden_states)\n\n # Note: sequence parallel is hidden inside ColumnParallelLinear\n # reduce scatter is hidden inside RowParallelLinear\n\n # Self Attention\n hidden_states = self.self_attn(\n hidden_states=hidden_states,\n attention_mask=attention_mask,\n position_ids=position_ids,\n )\n\n # TODO: add sequence parallel operator reduce_scatter here\n\n hidden_states = residual + hidden_states\n\n # Fully Connected\n residual = hidden_states\n hidden_states = self.post_attention_layernorm(hidden_states)\n\n # TODO: add sequence parallel operator all_gather here\n\n hidden_states = self.mlp(hidden_states)\n\n # TODO: add sequence parallel operator reduce_scatter here\n\n hidden_states = residual + hidden_states\n\n outputs = hidden_states\n\n return outputs\n\n\nclass ParallelQwen2DecoderLayerRmPad(nn.Module):\n def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig, layer_idx: int):\n super().__init__()\n self.config: TransformerConfig = convert_config(config, megatron_config)\n self.hidden_size = config.hidden_size\n self.layer_idx = layer_idx\n self.self_attn = ParallelQwen2AttentionRmPad(config=config, megatron_config=megatron_config)\n\n self.mlp = ParallelQwen2MLP(config, megatron_config=megatron_config)\n self.input_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n self.post_attention_layernorm = ParallelQwen2RMSNorm(config, megatron_config)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n position_ids: Optional[torch.LongTensor] = None,\n sequence_length: int = None,\n indices: torch.Tensor = None,\n cu_seqlens: int = None,\n max_seqlen_in_batch: int = None,\n ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:\n residual = hidden_states # (total_nnz // sp, 1, hidden_size)\n\n hidden_states = self.input_layernorm(hidden_states)\n\n # Self Attention\n # (total_nnz // sp, 1, hidden_size) -> all-gather (total_nnz, 1, hidden_size)\n # -> col + row -> reduce-scatter -> (total_nnz // sp, 1, hidden_size)\n hidden_states = self.self_attn(\n hidden_states=hidden_states,\n position_ids=position_ids,\n sequence_length=sequence_length,\n indices=indices,\n cu_seqlens=cu_seqlens,\n max_seqlen_in_batch=max_seqlen_in_batch,\n )\n\n hidden_states = residual + hidden_states\n\n # Fully Connected\n # shape changes same as attn\n residual = hidden_states\n hidden_states = self.post_attention_layernorm(hidden_states)\n hidden_states = self.mlp(hidden_states)\n hidden_states = residual + hidden_states\n\n outputs = hidden_states\n\n return outputs\n"} {"file_name": "verl__models__qwen2__megatron__layers__parallel_linear.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright 2023 The vLLM team.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/linear.py\n\n\nfrom megatron.core import tensor_parallel\n\n\nclass QKVParallelLinear(tensor_parallel.ColumnParallelLinear):\n def __init__(\n self,\n input_size,\n num_heads,\n num_key_value_heads,\n head_dim,\n *,\n bias=True,\n gather_output=True,\n skip_bias_add=False,\n **kwargs,\n ):\n # Keep input parameters, and already restrict the head numbers\n self.input_size = input_size\n self.q_output_size = num_heads * head_dim\n self.kv_output_size = num_key_value_heads * head_dim\n self.head_dim = head_dim\n self.gather_output = gather_output\n self.skip_bias_add = skip_bias_add\n\n input_size = self.input_size\n output_size = (num_heads + 2 * num_key_value_heads) * self.head_dim\n\n super().__init__(\n input_size=input_size,\n output_size=output_size,\n bias=bias,\n gather_output=gather_output,\n skip_bias_add=skip_bias_add,\n **kwargs,\n )\n\n\nclass MergedColumnParallelLinear(tensor_parallel.ColumnParallelLinear):\n def __init__(\n self,\n input_size,\n gate_ouput_size,\n up_output_size,\n *,\n bias=True,\n gather_output=True,\n skip_bias_add=False,\n **kwargs,\n ):\n # Keep input parameters, and already restrict the head numbers\n self.input_size = input_size\n self.output_size = gate_ouput_size + up_output_size\n self.gather_output = gather_output\n self.skip_bias_add = skip_bias_add\n\n super().__init__(\n input_size=self.input_size,\n output_size=self.output_size,\n bias=bias,\n gather_output=gather_output,\n skip_bias_add=skip_bias_add,\n **kwargs,\n )\n"} {"file_name": "verl__models__qwen2__megatron__layers__parallel_rmsnorm.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numbers\n\nimport torch\nfrom apex.normalization.fused_layer_norm import fused_rms_norm_affine\nfrom megatron.core import ModelParallelConfig\nfrom torch import nn\nfrom transformers import Qwen2Config\n\nfrom verl.utils.megatron import sequence_parallel as sp_utils\n\n\nclass ParallelQwen2RMSNorm(nn.Module):\n def __init__(self, config: Qwen2Config, megatron_config: ModelParallelConfig):\n \"\"\"\n Qwen2RMSNorm is equivalent to T5LayerNorm\n \"\"\"\n super().__init__()\n if isinstance(config.hidden_size, numbers.Integral):\n normalized_shape = (config.hidden_size,)\n self.normalized_shape = torch.Size(normalized_shape)\n self.weight = nn.Parameter(torch.ones(self.normalized_shape))\n self.variance_epsilon = config.rms_norm_eps\n\n if megatron_config.sequence_parallel:\n sp_utils.mark_parameter_as_sequence_parallel(self.weight)\n\n def forward(self, hidden_states):\n return fused_rms_norm_affine(\n input=hidden_states,\n weight=self.weight,\n normalized_shape=self.normalized_shape,\n eps=self.variance_epsilon,\n memory_efficient=True,\n )\n"} {"file_name": "verl__protocol.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nImplement base data transfer protocol between any two functions, modules.\nWe can subclass Protocol to define more detailed batch info with specific keys\n\"\"\"\n\nimport contextlib\nimport copy\nimport logging\nimport math\nimport os\nimport pickle\nfrom dataclasses import dataclass, field\nfrom typing import Any, Callable, Optional\n\nimport numpy as np\nimport ray\nimport tensordict\nimport torch\nimport torch.distributed\nfrom packaging import version\nfrom packaging.version import parse as parse_version\nfrom tensordict import TensorDict\nfrom torch.utils.data import DataLoader\n\nfrom verl.utils.device import get_device_id, get_torch_device\nfrom verl.utils.py_functional import union_two_dict\nfrom verl.utils.torch_functional import allgather_dict_tensors\n\n__all__ = [\"DataProto\", \"union_tensor_dict\"]\n\nwith contextlib.suppress(Exception):\n tensordict.set_lazy_legacy(False).set()\n if parse_version(tensordict.__version__) < parse_version(\"0.10.0\"):\n tensordict.set_list_to_stack(True).set()\n\n\nclass _DataProtoConfigMeta(type):\n _config = {}\n\n auto_padding_key = \"_verl_auto_padding\"\n\n @property\n def auto_padding(cls):\n enabled_by_env = os.getenv(\"VERL_AUTO_PADDING\", \"FALSE\").upper() in [\"TRUE\", \"1\"]\n return enabled_by_env or cls._config.get(cls.auto_padding_key, False)\n\n @auto_padding.setter\n def auto_padding(cls, enabled: bool):\n assert isinstance(enabled, bool), f\"enabled must be a boolean, got {enabled} as {type(enabled)}\"\n cls._config[cls.auto_padding_key] = enabled\n\n\nclass DataProtoConfig(metaclass=_DataProtoConfigMeta):\n pass\n\n\n_padding_size_key = \"_padding_size_key_x123d\"\n\n\ndef pad_dataproto_to_divisor(data: \"DataProto\", size_divisor: int):\n \"\"\"Pad a DataProto to size divisible by size_divisor\n\n Args:\n size_divisor (int): size divisor\n\n Returns:\n data: (DataProto): the padded DataProto\n pad_size (int)\n \"\"\"\n assert isinstance(data, DataProto), \"data must be a DataProto\"\n if len(data) % size_divisor != 0:\n pad_size = size_divisor - len(data) % size_divisor\n padding_protos = []\n remaining_pad = pad_size\n while remaining_pad > 0:\n take_size = min(remaining_pad, len(data))\n padding_protos.append(data[:take_size])\n remaining_pad -= take_size\n data_padded = DataProto.concat([data] + padding_protos)\n else:\n if len(data) == 0:\n logging.warning(\"padding a DataProto with no item, no changed made\")\n pad_size = 0\n data_padded = data\n return data_padded, pad_size\n\n\ndef unpad_dataproto(data: \"DataProto\", pad_size):\n \"\"\"Unpad the data proto with pad_size. i.e. `data[:-pad_size]`\"\"\"\n if pad_size != 0:\n data = data[:-pad_size]\n return data\n\n\ndef union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict:\n \"\"\"Union two tensordicts.\"\"\"\n assert tensor_dict1.batch_size == tensor_dict2.batch_size, (\n f\"Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}\"\n )\n for key in tensor_dict2.keys():\n if key not in tensor_dict1.keys():\n tensor_dict1[key] = tensor_dict2[key]\n else:\n assert tensor_dict1[key].equal(tensor_dict2[key]), (\n f\"{key} in tensor_dict1 and tensor_dict2 are not the same object\"\n )\n\n return tensor_dict1\n\n\ndef _array_equal(array1: np.ndarray, array2: np.ndarray, visited: set[int]) -> bool:\n \"\"\"\n Recursively compares two NumPy arrays for strict equality, with special\n handling for object-dtype arrays, NaN values, and circular references.\n This function assumes that the two arguments provided are NumPy arrays.\n\n Args:\n array1: The first NumPy array.\n array2: The second NumPy array.\n\n Returns:\n True if the arrays' dtypes, shapes, and all elements are equal.\n \"\"\"\n # Check dtype and shape first, as this is the fastest failure path.\n if array1.dtype != array2.dtype or array1.shape != array2.shape:\n return False\n\n # For non-object dtypes, use NumPy's implementation with equal_nan=True.\n if array1.dtype != \"object\":\n return np.array_equal(array1, array2, equal_nan=True)\n\n # For object-dtype arrays, we must recursively compare each element.\n # We delegate to _deep_equal to handle elements, as they could be any\n # type, including other nested arrays or NaNs.\n return all(_deep_equal(x, y, visited) for x, y in zip(array1.flat, array2.flat, strict=False))\n\n\ndef _deep_equal(a: Any, b: Any, visited: set[int]) -> bool:\n \"\"\"\n Recursively performs a deep comparison between two Python objects.\n - Handles NaN values correctly (NaN == NaN evaluates to True).\n - Handling circular references.\n - Dispatches to _array_equal if both objects are NumPy arrays.\n - Otherwise, uses standard '==' comparison.\n \"\"\"\n if type(a) is not type(b):\n return False\n\n # If we have seen this object ID before on this path, it's a cycle.\n # Since we already know the types match, we can safely assume this part\n # of the structure is equal.\n obj_id = id(a)\n if obj_id in visited:\n return True\n\n visited.add(obj_id)\n\n # Perform the specific comparison based on type\n result = False\n if isinstance(a, float) and math.isnan(a) and math.isnan(b):\n result = True\n elif isinstance(a, np.ndarray):\n # We know b is also an ndarray due to the initial type check\n result = _array_equal(a, b, visited)\n else:\n # Standard equality for all other types\n result = a == b\n\n # Clean up the visited set on the way out of the recursion\n visited.remove(obj_id)\n return result\n\n\ndef union_numpy_dict(tensor_dict1: dict[str, np.ndarray], tensor_dict2: dict[str, np.ndarray]) -> dict[str, np.ndarray]:\n for key, val in tensor_dict2.items():\n if key in tensor_dict1:\n assert isinstance(tensor_dict2[key], np.ndarray)\n assert isinstance(tensor_dict1[key], np.ndarray)\n # to properly deal with nan and object type\n assert _deep_equal(tensor_dict1[key], tensor_dict2[key], visited=set()), (\n f\"`{key}` in tensor_dict1 and tensor_dict2 are not the same object.\"\n )\n tensor_dict1[key] = val\n\n return tensor_dict1\n\n\ndef list_of_dict_to_dict_of_list(list_of_dict: list[dict]):\n if len(list_of_dict) == 0:\n return {}\n keys = list_of_dict[0].keys()\n output = {key: [] for key in keys}\n for data in list_of_dict:\n for key, item in data.items():\n assert key in output\n output[key].append(item)\n return output\n\n\ndef fold_batch_dim(data: \"DataProto\", new_batch_size):\n \"\"\"\n Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx]\n \"\"\"\n batch_size = data.batch.batch_size[0]\n\n assert batch_size % new_batch_size == 0\n\n tensor: TensorDict = data.batch\n non_tensor = data.non_tensor_batch\n\n tensor = tensor.view(new_batch_size, -1)\n tensor.auto_batch_size_(batch_dims=1)\n\n for key, val in non_tensor.items():\n non_tensor[key] = np.reshape(val, newshape=(new_batch_size, -1, *val.shape[1:]))\n\n return type(data)(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info)\n\n\ndef unfold_batch_dim(data: \"DataProto\", batch_dims=2):\n \"\"\"\n Unfold the first n dims as new batch dim\n \"\"\"\n tensor: TensorDict = data.batch\n non_tensor = data.non_tensor_batch\n tensor.auto_batch_size_(batch_dims=batch_dims)\n tensor = tensor.view(-1)\n\n batch_size = tensor.batch_size[0]\n\n non_tensor_new = {}\n\n for key, val in non_tensor.items():\n non_tensor_new[key] = np.reshape(val, newshape=(batch_size, *val.shape[batch_dims:]))\n\n return type(data)(batch=tensor, non_tensor_batch=non_tensor_new, meta_info=data.meta_info)\n\n\ndef serialize_single_tensor(obj: torch.Tensor) -> tuple[str, tuple[int, ...], int | memoryview]:\n data = obj.flatten().contiguous().view(torch.uint8).numpy()\n dtype = str(obj.dtype).removeprefix(\"torch.\")\n return dtype, obj.shape, data\n\n\ndef serialize_tensordict(batch: TensorDict) -> tuple[tuple[int, ...], Optional[str], dict[str, tuple[str, Any]]]:\n encoded_items: dict[str, tuple[Any]] = {}\n for k, v in batch.items():\n if not v.is_nested:\n encoded_items[k] = serialize_single_tensor(v)\n else:\n layout = str(v.layout).removeprefix(\"torch.\")\n data = [serialize_single_tensor(tensor) for tensor in v.unbind()]\n encoded_items[k] = (layout, data)\n\n batch_size = tuple(batch.batch_size)\n device = str(batch.device) if batch.device is not None else None\n return batch_size, device, encoded_items\n\n\ndef deserialize_single_tensor(arr: Any) -> torch.Tensor:\n dtype, shape, data = arr\n\n torch_dtype = getattr(torch, dtype)\n assert isinstance(torch_dtype, torch.dtype)\n\n buffer = bytearray(data)\n # Create uint8 array\n arr = torch.frombuffer(buffer, dtype=torch.uint8)\n # Convert back to proper shape & type\n return arr.view(torch_dtype).view(shape)\n\n\ndef deserialize_tensordict(arr: Any) -> TensorDict:\n batch_size, device, encoded_items = arr\n decoded_items: dict[str, Any] = {}\n\n for k, v in encoded_items.items():\n if len(v) == 3:\n # decode single tensor\n decoded_items[k] = deserialize_single_tensor(v)\n elif len(v) == 2:\n # decode nested tensor\n layout, data = v\n torch_layout = getattr(torch, layout)\n decoded_items[k] = torch.nested.as_nested_tensor(\n [deserialize_single_tensor(tensor) for tensor in data], layout=torch_layout\n )\n else:\n raise ValueError(f\"Invalid tensor encoding format, expected length 2 or 3, got {len(v)}\")\n\n return TensorDict(source=decoded_items, batch_size=batch_size, device=device)\n\n\ndef collate_fn(x: list[\"DataProtoItem\"]):\n batch = []\n non_tensor_batch = []\n for data in x:\n batch.append(data.batch)\n non_tensor_batch.append(data.non_tensor_batch)\n batch = torch.stack(batch).contiguous()\n non_tensor_batch = list_of_dict_to_dict_of_list(non_tensor_batch)\n for key, val in non_tensor_batch.items():\n non_tensor_batch[key] = np.array(val, dtype=object)\n return DataProto(batch=batch, non_tensor_batch=non_tensor_batch)\n\n\n@dataclass\nclass DataProtoItem:\n # TODO(zhangchi.usc1992) add consistency check\n batch: TensorDict = None\n non_tensor_batch: dict = field(default_factory=dict)\n meta_info: dict = field(default_factory=dict)\n\n\n@dataclass\nclass DataProto:\n \"\"\"\n A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions.\n It contains a batch (TensorDict) and a meta_info (Dict). The batch is a TensorDict https://pytorch.org/tensordict/.\n TensorDict allows you to manipulate a dictionary of Tensors like a single Tensor. Ideally, the tensors with the\n same batch size should be put inside batch.\n \"\"\"\n\n batch: TensorDict = None\n non_tensor_batch: dict = field(default_factory=dict)\n meta_info: dict = field(default_factory=dict)\n\n def __post_init__(self):\n # perform necessary checking\n self.check_consistency()\n\n def __len__(self):\n if self.batch is not None:\n return self.batch.batch_size[0]\n elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0:\n random_key = list(self.non_tensor_batch.keys())[0]\n return self.non_tensor_batch[random_key].shape[0]\n else:\n return 0\n\n def __getitem__(self, item):\n \"\"\"\n Enhanced indexing for DataProto objects.\n\n Args:\n item: Can be one of:\n - int: A single index\n - slice: A slice object (start:stop:step)\n - list: A list of indices\n - numpy.ndarray: An array of indices\n - torch.Tensor: A tensor of indices\n\n Returns:\n DataProto: For all indexing types except single integers\n DataProtoItem: Only for single integer indices\n \"\"\"\n # Case 1: Slice object - use the slice method\n if isinstance(item, slice):\n return self.slice(item.start, item.stop, item.step)\n\n # Case 2: List, numpy array, or torch tensor - use sel_idxs\n elif isinstance(item, list | np.ndarray | torch.Tensor):\n return self.select_idxs(item)\n\n # Case 3: Single integer - return DataProtoItem for backward compatibility\n elif isinstance(item, int | np.integer):\n tensor_data = self.batch[item] if self.batch is not None else None\n non_tensor_data = {key: val[item] for key, val in self.non_tensor_batch.items()}\n return DataProtoItem(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info)\n\n # # Case 4: Unsupported type\n else:\n raise TypeError(f\"Indexing with {type(item)} is not supported\")\n\n def __getstate__(self):\n if version.parse(tensordict.__version__) >= version.parse(\"0.5.0\") and self.batch is not None:\n # Check if batch is empty to avoid torch.cat error in consolidate\n if len(self.batch.keys()) > 0:\n batch = self.batch.contiguous().consolidate()\n else:\n batch = self.batch\n else:\n batch = self.batch\n\n if os.getenv(\"VERL_DATAPROTO_SERIALIZATION_METHOD\") == \"numpy\":\n if batch is not None:\n batch = serialize_tensordict(self.batch)\n\n return (\n batch,\n self.non_tensor_batch,\n self.meta_info,\n )\n else:\n import io\n\n buffer = io.BytesIO()\n torch.save(batch, buffer)\n buffer_bytes = buffer.getvalue()\n return buffer_bytes, self.non_tensor_batch, self.meta_info\n\n def __setstate__(self, data):\n batch_deserialized_bytes, non_tensor_batch, meta_info = data\n\n if os.getenv(\"VERL_DATAPROTO_SERIALIZATION_METHOD\") == \"numpy\":\n if batch_deserialized_bytes is not None:\n self.batch = deserialize_tensordict(batch_deserialized_bytes)\n else:\n self.batch = None\n else:\n import io\n\n batch_deserialized = io.BytesIO(initial_bytes=batch_deserialized_bytes)\n batch = torch.load(\n batch_deserialized,\n weights_only=False,\n map_location=\"cpu\" if not get_torch_device().is_available() else None,\n )\n self.batch = batch\n\n self.non_tensor_batch = non_tensor_batch\n self.meta_info = meta_info\n\n def save_to_disk(self, filepath):\n with open(filepath, \"wb\") as f:\n pickle.dump(self, f)\n\n @staticmethod\n def load_from_disk(filepath) -> \"DataProto\":\n with open(filepath, \"rb\") as f:\n data = pickle.load(f)\n return data\n\n def print_size(self, prefix=\"\"):\n size_of_tensordict = 0\n if self.batch is not None:\n for _, tensor in self.batch.items():\n size_of_tensordict += tensor.element_size() * tensor.numel()\n size_of_numpy_array = 0\n for _, numpy_array in self.non_tensor_batch.items():\n size_of_numpy_array += numpy_array.nbytes\n\n size_of_numpy_array /= 1024**3\n size_of_tensordict /= 1024**3\n\n message = f\"Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB\"\n\n if prefix:\n message = f\"{prefix}, \" + message\n print(message)\n\n def check_consistency(self):\n \"\"\"Check the consistency of the DataProto. Mainly for batch and non_tensor_batch\n We expose this function as a public one so that user can call themselves directly\n \"\"\"\n if self.batch is not None:\n assert len(self.batch.batch_size) == 1, \"only support num_batch_dims=1\"\n\n if self.non_tensor_batch is not None:\n for key, val in self.non_tensor_batch.items():\n assert isinstance(val, np.ndarray)\n\n if self.batch is not None and self.non_tensor_batch is not None and len(self.non_tensor_batch) != 0:\n # TODO: we can actually lift this restriction if needed\n assert len(self.batch.batch_size) == 1, \"only support num_batch_dims=1 when non_tensor_batch is not empty.\"\n\n batch_size = self.batch.batch_size[0]\n for key, val in self.non_tensor_batch.items():\n assert isinstance(val, np.ndarray), (\n f\"data in the non_tensor_batch must be a numpy.array with dtype=object, but for \"\n f\"{key=}, got {type(val)=}\"\n )\n assert val.shape[0] == batch_size, (\n f\"key {key} length {len(val)} is not equal to batch size {batch_size}\"\n )\n\n @classmethod\n def from_single_dict(cls, data: dict[str, torch.Tensor | np.ndarray], meta_info=None, auto_padding=False):\n \"\"\"Create a DataProto from a dict of tensors and non_tensors\"\"\"\n tensors = {}\n non_tensors = {}\n\n for key, val in data.items():\n if isinstance(val, torch.Tensor):\n tensors[key] = val\n elif isinstance(val, np.ndarray):\n non_tensors[key] = val\n else:\n raise ValueError(f\"Unsupported type in data {type(val)}\")\n\n return cls.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info, auto_padding=auto_padding)\n\n @classmethod\n def from_dict(\n cls,\n tensors: Optional[dict[str, torch.Tensor]] = None,\n non_tensors=None,\n meta_info=None,\n num_batch_dims=1,\n auto_padding=False,\n ):\n \"\"\"Create a DataProto from a dict of tensors. This assumes that\n 1. All the tensor in tensors have the same dim0\n 2. Only dim0 is the batch dim\n \"\"\"\n\n assert num_batch_dims > 0, \"num_batch_dims must be greater than zero\"\n if non_tensors is not None:\n assert num_batch_dims == 1, \"only support num_batch_dims=1 when non_tensors is not None.\"\n\n if tensors is None:\n tensors = {}\n if meta_info is None:\n meta_info = {}\n if non_tensors is None:\n non_tensors = {}\n\n assert isinstance(non_tensors, dict)\n\n # get and check batch size\n batch_size = None\n pivot_key = None\n for key, tensor in tensors.items():\n if batch_size is None:\n batch_size = tensor.shape[:num_batch_dims]\n pivot_key = key\n else:\n current_batch = tensor.shape[:num_batch_dims]\n assert batch_size == current_batch, (\n f\"Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. \"\n f\"Got {pivot_key} has {batch_size}, {key} has {current_batch}\"\n )\n\n for key, val in non_tensors.items():\n if not isinstance(val, np.ndarray):\n non_tensors[key] = np.array(val, dtype=object)\n\n tensor_dict = TensorDict(source=tensors, batch_size=batch_size) if tensors else None\n if auto_padding:\n meta_info[DataProtoConfig.auto_padding_key] = True\n return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info)\n\n @classmethod\n def from_tensordict(\n cls,\n tensor_dict: TensorDict = None,\n meta_info=None,\n num_batch_dims=1,\n ):\n \"\"\"Create a DataProto from a TensorDict. This assumes that\n 1. All the tensor in tensor_dict have the same dim0\n 2. Only dim0 is the batch dim\n \"\"\"\n assert version.parse(tensordict.__version__) >= version.parse(\"0.10.0\"), (\n \"Build DataProto from TensorDict at least requires tensordict version 0.10.0\"\n )\n from tensordict import NonTensorData, NonTensorStack\n\n assert num_batch_dims > 0, \"num_batch_dims must be greater than zero\"\n if not all(isinstance(val, torch.Tensor) for val in tensor_dict.values()):\n assert num_batch_dims == 1, \"only support num_batch_dims=1 when tensor_dict contains non tensor data.\"\n\n if meta_info is None:\n meta_info = {}\n batch = {}\n non_tensor_batch = {}\n batch_size = None\n for key, val in tensor_dict.items():\n if isinstance(val, torch.Tensor):\n batch[key] = val\n if batch_size is None:\n batch_size = val.shape[:num_batch_dims]\n elif isinstance(val, NonTensorStack):\n non_tensor_batch[key] = np.array([elem.data for elem in val], dtype=object)\n elif isinstance(val, NonTensorData):\n meta_info[key] = val.data\n\n return cls(\n batch=TensorDict(batch, batch_size=batch_size),\n non_tensor_batch=non_tensor_batch,\n meta_info=meta_info,\n )\n\n def to(self, device) -> \"DataProto\":\n \"\"\"move the batch to device\n\n Args:\n device (torch.device, str): torch device\n\n Returns:\n DataProto: the current DataProto\n\n \"\"\"\n if self.batch is not None:\n self.batch = self.batch.to(device)\n return self\n\n def select(self, batch_keys=None, non_tensor_batch_keys=None, meta_info_keys=None, deepcopy=False) -> \"DataProto\":\n \"\"\"Select a subset of the DataProto via batch_keys and meta_info_keys\n\n Args:\n batch_keys (list, optional): a list of strings indicating the keys in batch to select\n meta_info_keys (list, optional): a list of keys indicating the meta info to select\n\n Returns:\n DataProto: the DataProto with the selected batch_keys and meta_info_keys\n \"\"\"\n # TODO (zhangchi.usc1992) whether to copy\n if batch_keys is not None:\n batch_keys = tuple(batch_keys)\n sub_batch = self.batch.select(*batch_keys)\n else:\n sub_batch = self.batch\n\n if non_tensor_batch_keys is not None:\n non_tensor_batch = {key: val for key, val in self.non_tensor_batch.items() if key in non_tensor_batch_keys}\n else:\n non_tensor_batch = self.non_tensor_batch\n\n if deepcopy:\n non_tensor_batch = copy.deepcopy(non_tensor_batch)\n\n if meta_info_keys is not None:\n sub_meta_info = {key: val for key, val in self.meta_info.items() if key in meta_info_keys}\n else:\n sub_meta_info = self.meta_info\n\n if deepcopy:\n sub_meta_info = copy.deepcopy(sub_meta_info)\n\n return type(self)(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info)\n\n def select_idxs(self, idxs):\n \"\"\"\n Select specific indices from the DataProto.\n\n Args:\n idxs (torch.Tensor or numpy.ndarray or list): Indices to select\n\n Returns:\n DataProto: A new DataProto containing only the selected indices\n \"\"\"\n if isinstance(idxs, list):\n idxs = torch.tensor(idxs)\n if idxs.dtype != torch.bool:\n idxs = idxs.type(torch.int32)\n\n if isinstance(idxs, np.ndarray):\n idxs_np = idxs\n idxs_torch = torch.from_numpy(idxs)\n else: # torch.Tensor\n idxs_torch = idxs\n idxs_np = idxs.detach().cpu().numpy()\n\n batch_size = int(idxs_np.sum()) if idxs_np.dtype == bool else idxs_np.shape[0]\n\n if self.batch is not None:\n # Use TensorDict's built-in indexing capabilities\n selected_batch = TensorDict(\n source={key: tensor[idxs_torch] for key, tensor in self.batch.items()},\n batch_size=(batch_size,),\n device=self.batch.device,\n )\n else:\n selected_batch = None\n\n selected_non_tensor = {}\n for key, val in self.non_tensor_batch.items():\n selected_non_tensor[key] = val[idxs_np]\n\n return type(self)(batch=selected_batch, non_tensor_batch=selected_non_tensor, meta_info=self.meta_info)\n\n def slice(self, start=None, end=None, step=None):\n \"\"\"\n Slice the DataProto and return a new DataProto object.\n This is an improved version of direct slicing which returns a DataProtoItem.\n\n Args:\n start (int, optional): Start index. Defaults to None (start from beginning).\n end (int, optional): End index (exclusive). Defaults to None (go to end).\n step (int, optional): Step size. Defaults to None (step=1).\n\n Returns:\n DataProto: A new DataProto containing the sliced data\n\n Examples:\n # Using the slice method directly\n sliced_data = data_proto.slice(10, 20)\n\n # Using enhanced indexing (returns DataProto)\n sliced_data = data_proto[10:20]\n sliced_data = data_proto[::2] # Every other element\n\n # Using list indexing (returns DataProto)\n indices = [1, 5, 10]\n selected_data = data_proto[indices]\n\n # Single index still returns DataProtoItem\n single_item = data_proto[5]\n \"\"\"\n # Create a slice object\n slice_obj = slice(start, end, step)\n\n # Handle the batch data\n if self.batch is not None:\n # Use TensorDict's built-in slicing capabilities\n sliced_batch = self.batch[slice_obj]\n else:\n sliced_batch = None\n\n # Handle the non-tensor batch data\n sliced_non_tensor = {}\n for key, val in self.non_tensor_batch.items():\n sliced_non_tensor[key] = val[slice_obj]\n\n # Return a new DataProto object\n return type(self)(batch=sliced_batch, non_tensor_batch=sliced_non_tensor, meta_info=self.meta_info)\n\n def pop(self, batch_keys=None, non_tensor_batch_keys=None, meta_info_keys=None) -> \"DataProto\":\n \"\"\"Pop a subset of the DataProto via `batch_keys` and `meta_info_keys`\n\n Args:\n batch_keys (list, optional): a list of strings indicating the keys in batch to pop\n meta_info_keys (list, optional): a list of keys indicating the meta info to pop\n\n Returns:\n DataProto: the DataProto with the poped batch_keys and meta_info_keys\n \"\"\"\n if batch_keys is None:\n batch_keys = []\n if meta_info_keys is None:\n meta_info_keys = []\n if non_tensor_batch_keys is None:\n non_tensor_batch_keys = []\n\n tensors = {}\n # tensor batch\n for key in batch_keys:\n assert key in self.batch.keys()\n tensors[key] = self.batch.pop(key)\n non_tensors = {}\n # non tensor batch\n for key in non_tensor_batch_keys:\n assert key in self.non_tensor_batch.keys()\n non_tensors[key] = self.non_tensor_batch.pop(key)\n meta_info = {}\n for key in meta_info_keys:\n assert key in self.meta_info.keys()\n meta_info[key] = self.meta_info.pop(key)\n return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)\n\n def rename(self, old_keys=None, new_keys=None) -> \"DataProto\":\n \"\"\"\n Note that this function only rename the key in the batch\n \"\"\"\n\n def validate_input(keys):\n if keys is not None:\n if isinstance(keys, str):\n keys = [keys]\n elif isinstance(keys, list):\n pass\n else:\n raise TypeError(f\"keys must be a list or a string, but got {type(keys)}\")\n return keys\n\n old_keys = validate_input(old_keys)\n new_keys = validate_input(new_keys)\n\n if len(new_keys) != len(old_keys):\n raise ValueError(\n f\"new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}\"\n )\n\n self.batch.rename_key_(tuple(old_keys), tuple(new_keys))\n\n return self\n\n def union(self, other: \"DataProto\") -> \"DataProto\":\n \"\"\"Union with another DataProto. Union batch and meta_info separately.\n Throw an error if\n\n - there are conflict keys in batch and they are not equal\n - the batch size of two data batch is not the same\n - there are conflict keys in meta_info and they are not the same.\n\n Args:\n other (DataProto): another DataProto to union\n\n Returns:\n DataProto: the DataProto after union\n \"\"\"\n self.batch = union_tensor_dict(self.batch, other.batch)\n self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch)\n self.meta_info = union_two_dict(self.meta_info, other.meta_info)\n return self\n\n def make_iterator(self, mini_batch_size, epochs, seed=None, dataloader_kwargs=None):\n r\"\"\"Make an iterator from the DataProto. This is built upon that TensorDict can be used as a normal Pytorch\n dataset. See https://pytorch.org/tensordict/stable/tutorials/data_fashion for more details.\n\n\n Args:\n mini_batch_size (int): mini-batch size when iterating the dataset. We require that\n ``batch.batch_size[0] % mini_batch_size == 0``.\n epochs (int): number of epochs when iterating the dataset.\n dataloader_kwargs (Any): internally, it returns a DataLoader over the batch. The\n dataloader_kwargs is the kwargs passed to the DataLoader.\n\n Returns:\n Iterator: an iterator that yields a mini-batch data at a time. The total number of iteration\n steps is ``self.batch.batch_size * epochs // mini_batch_size``\n \"\"\"\n assert self.batch.batch_size[0] % mini_batch_size == 0, f\"{self.batch.batch_size[0]} % {mini_batch_size} != 0\"\n # we can directly create a dataloader from TensorDict\n if dataloader_kwargs is None:\n dataloader_kwargs = {}\n\n if seed is not None:\n generator = torch.Generator()\n generator.manual_seed(seed)\n else:\n generator = None\n\n assert isinstance(dataloader_kwargs, dict)\n train_dataloader = DataLoader(\n dataset=self, batch_size=mini_batch_size, collate_fn=collate_fn, generator=generator, **dataloader_kwargs\n )\n\n def get_data():\n for _ in range(epochs):\n for d in train_dataloader:\n d.meta_info = self.meta_info\n yield d\n\n return iter(get_data())\n\n def is_padding_enabled(self):\n \"\"\"\n Check if padding is enabled for the DataProto.\n Returns:\n bool: True if padding is enabled, False otherwise.\n \"\"\"\n dataproto_specific_padding = self.meta_info.get(DataProtoConfig.auto_padding_key, False)\n return dataproto_specific_padding or DataProtoConfig.auto_padding\n\n def padding(self, padding_size, padding_candidate=\"\"):\n \"\"\"Pad the DataProto by concating with padding_candidate.repeat(padding_size)\n\n Args:\n padding_size (int): the number of repeated padding_candidate\n padding_candidate: the item to be repeated and appended to the DataProto, only supporting [\"first\", \"last\"]\n \"\"\"\n if padding_size == 0:\n return\n padding_candidate = self.select_idxs([0 if padding_candidate == \"first\" else len(self) - 1])\n padding_part = padding_candidate.repeat(padding_size)\n padded_dp = DataProto.concat([self, padding_part])\n self.batch = padded_dp.batch\n self.non_tensor_batch = padded_dp.non_tensor_batch\n\n def chunk(self, chunks: int) -> list[\"DataProto\"]:\n \"\"\"Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split.\n\n Args:\n chunks (int): the number of chunks to split on dim=0\n\n Returns:\n List[DataProto]: a list of DataProto after splitting\n \"\"\"\n if not self.is_padding_enabled():\n assert len(self) % chunks == 0, (\n f\"only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}.\"\n )\n\n bsz_in_batch = None\n if self.batch is not None:\n batch_lst = self.batch.chunk(chunks=chunks, dim=0)\n bsz_in_batch = np.array([batch.batch_size[0] for batch in batch_lst])\n chunk_indices = np.cumsum(bsz_in_batch)[:-1]\n else:\n batch_lst = [None for _ in range(chunks)]\n\n non_tensor_batch_lst = [{} for _ in range(chunks)]\n for key, val in self.non_tensor_batch.items():\n assert isinstance(val, np.ndarray)\n if bsz_in_batch is not None:\n non_tensor_lst = np.array_split(val, chunk_indices.tolist())\n else:\n non_tensor_lst = np.array_split(val, chunks)\n assert len(non_tensor_lst) == chunks\n for i in range(chunks):\n non_tensor_batch_lst[i][key] = non_tensor_lst[i]\n\n output = []\n for i in range(chunks):\n output.append(\n type(self)(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info)\n )\n\n return output\n\n def split(self, split_size: int) -> list[\"DataProto\"]:\n \"\"\"Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split.\n\n Args:\n split_size (int): the size of each split\n\n Returns:\n List[DataProto]: a list of DataProto after splitting\n \"\"\"\n return [self[i : i + split_size] for i in range(0, len(self), split_size)]\n\n @staticmethod\n def concat(data: list[\"DataProto\"]) -> \"DataProto\":\n \"\"\"Concat a list of DataProto. The batch is concatenated among dim=0.\n The meta_info is merged, with special handling for metrics from different workers.\n\n Args:\n data (List[DataProto]): list of DataProto\n\n Returns:\n DataProto: concatenated DataProto\n \"\"\"\n batch_lst = []\n for batch in data:\n batch_lst.append(batch.batch)\n new_batch = torch.cat(batch_lst, dim=0) if batch_lst[0] is not None else None\n\n non_tensor_batch = list_of_dict_to_dict_of_list(list_of_dict=[d.non_tensor_batch for d in data])\n for key, val in non_tensor_batch.items():\n non_tensor_batch[key] = np.concatenate(val, axis=0)\n\n # Merge meta_info with special handling for metrics\n merged_meta_info = {}\n if data:\n # Merge non-metric meta_info and aggregate metrics from all workers.\n all_metrics = []\n for d in data:\n for k, v in d.meta_info.items():\n if k == \"metrics\":\n if v is not None:\n if isinstance(v, list):\n all_metrics.extend(v)\n else:\n all_metrics.append(v)\n else:\n if k in merged_meta_info:\n # Ensure consistency for overlapping non-metric keys\n assert merged_meta_info[k] == v, f\"Conflicting values for meta_info key '{k}'\"\n else:\n merged_meta_info[k] = v\n\n # Flatten list of dicts to dict of lists for consistent metrics structure\n if all_metrics:\n merged_meta_info[\"metrics\"] = list_of_dict_to_dict_of_list(all_metrics)\n\n cls = type(data[0]) if len(data) > 0 else DataProto\n return cls(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=merged_meta_info)\n\n def reorder(self, indices):\n \"\"\"\n Note that this operation is in-place\n \"\"\"\n indices_np = indices.detach().numpy()\n self.batch = self.batch[indices]\n self.non_tensor_batch = {key: val[indices_np] for key, val in self.non_tensor_batch.items()}\n\n def repeat(self, repeat_times=2, interleave=True):\n \"\"\"\n Repeat the batch data a specified number of times.\n\n Args:\n repeat_times (int): Number of times to repeat the data.\n interleave (bool): Whether to interleave the repeated data.\n\n Returns:\n DataProto: A new DataProto with repeated data.\n \"\"\"\n if self.batch is not None:\n if interleave:\n # Interleave the data\n repeated_tensors = {\n key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items()\n }\n else:\n # Stack the data\n repeated_tensors = {\n key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:])\n for key, tensor in self.batch.items()\n }\n\n repeated_batch = TensorDict(\n source=repeated_tensors,\n batch_size=(self.batch.batch_size[0] * repeat_times,),\n )\n else:\n repeated_batch = None\n\n repeated_non_tensor_batch = {}\n for key, val in self.non_tensor_batch.items():\n if interleave:\n repeated_non_tensor_batch[key] = np.repeat(val, repeat_times, axis=0)\n else:\n repeated_non_tensor_batch[key] = np.tile(val, (repeat_times,) + (1,) * (val.ndim - 1))\n\n return type(self)(\n batch=repeated_batch,\n non_tensor_batch=repeated_non_tensor_batch,\n meta_info=self.meta_info,\n )\n\n def unfold_column_chunks(self, n_split: int, split_keys: Optional[list[str]] = None):\n \"\"\"Split along the second dim into `n_split`, unfold it to the first dim (batch dim)\n Useful in passing grouped tensors that doesn't want to be shuffled in dataset.\n keys not in split_keys are repeated to match the shape\n Note that if the `split_keys` is not provided, it will repeat all the keys in the second dim.\n \"\"\"\n if self.batch is not None:\n unfolded_batch = {}\n for key in self.batch.keys():\n if key in split_keys if split_keys is not None else False:\n shape = list(self.batch[key].shape)\n shape[0] = self.batch[key].shape[0] * n_split\n shape[1] = self.batch[key].shape[1] // n_split\n unfolded_batch[key] = self.batch[key].reshape(*shape)\n else:\n unfolded_batch[key] = torch.repeat_interleave(self.batch[key], n_split, dim=0)\n # locate the `unfolded_batch` as a TensorDict on the same device as the original batch\n unfolded_batch = TensorDict(\n source=unfolded_batch, batch_size=(self.batch.batch_size[0] * n_split,), device=self.batch.device\n )\n else:\n unfolded_batch = None\n\n repeated_non_tensor_batch = {}\n for key, val in self.non_tensor_batch.items():\n if key in split_keys:\n shape = list(val.shape)\n shape[0] = val.shape[0] * n_split\n shape[1] = val.shape[1] // n_split\n repeated_non_tensor_batch[key] = val.reshape(*shape)\n else:\n repeated_non_tensor_batch[key] = np.repeat(val, n_split, axis=0)\n\n return type(self)(\n batch=unfolded_batch,\n non_tensor_batch=repeated_non_tensor_batch,\n meta_info=self.meta_info,\n )\n\n def sample_level_repeat(self, repeat_times):\n \"\"\"\n Repeat each row of the batch data a specified number of times.\n\n Args:\n repeat_times (torch.tensor, list, tuple, ndarray): Number of times to repeat the data.\n\n Returns:\n DataProto: A new DataProto with repeated data.\n \"\"\"\n if isinstance(repeat_times, tuple):\n repeat_times = list(repeat_times)\n elif isinstance(repeat_times, torch.Tensor):\n assert len(repeat_times.shape) == 1\n repeat_times = repeat_times.tolist()\n elif isinstance(repeat_times, np.ndarray):\n assert len(repeat_times.shape) == 1\n repeat_times = repeat_times.tolist()\n else:\n assert isinstance(repeat_times, list), (\n f\"repeat_times type must be in [list, torch.Tensor, np.ndarray, tuple], got {type(repeat_times)}\"\n )\n repeat_times = torch.tensor(repeat_times)\n\n if self.batch is not None:\n # Interleave the data\n repeated_tensors = {\n key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items()\n }\n\n repeated_batch = TensorDict(\n source=repeated_tensors,\n batch_size=(repeat_times.sum().item(),),\n device=self.batch.device,\n )\n else:\n repeated_batch = None\n\n repeated_non_tensor_batch = {}\n for key, val in self.non_tensor_batch.items():\n repeated_non_tensor_batch[key] = np.repeat(val, repeat_times, axis=0)\n\n return type(self)(\n batch=repeated_batch,\n non_tensor_batch=repeated_non_tensor_batch,\n meta_info=self.meta_info,\n )\n\n def to_tensordict(self) -> TensorDict:\n \"\"\"Convert this DataProto to TensorDict. Note that this requires tensordict version at least 0.10\n\n Returns:\n\n \"\"\"\n assert parse_version(tensordict.__version__) >= parse_version(\"0.10\"), (\n \"Convert DataProto to TensorDict at least requires tensordict version 0.10\"\n )\n tensor_batch = self.batch.to_dict()\n non_tensor_batch = self.non_tensor_batch\n\n from tensordict.tensorclass import NonTensorData, NonTensorStack\n\n from verl.utils import tensordict_utils as tu\n\n common_keys = set(tensor_batch.keys()) & set(non_tensor_batch.keys())\n assert len(common_keys) == 0, f\"tensor_batch and non_tensor_batch have common keys {common_keys}\"\n\n for key, val in non_tensor_batch.items():\n assert isinstance(val, np.ndarray)\n # Convert to NonTensorStack instead of plain list to handle nested structures\n tensor_batch[key] = NonTensorStack.from_list([NonTensorData(item) for item in val])\n output = tu.get_tensordict(tensor_dict=tensor_batch, non_tensor_dict=self.meta_info)\n return output\n\n def get_data_info(self) -> str:\n \"\"\"Return formatted information about stored data with nested type details.\n\n Returns:\n str: Formatted string showing tensor details and recursive metadata types\n \"\"\"\n info = [\"batch\"]\n\n for key, tensor in self.batch.items():\n if hasattr(tensor, \"shape\") and hasattr(tensor, \"dtype\") and hasattr(tensor, \"device\"):\n info.append(f\" {key}: {tuple(tensor.shape)} ({tensor.dtype}) {tensor.device}\")\n elif hasattr(tensor, \"shape\") and hasattr(tensor, \"dtype\"):\n info.append(f\" {key}: {tuple(tensor.shape)} ({tensor.dtype})\")\n else:\n info.append(f\" {key}: {type(tensor).__name__}\")\n\n info.append(\"non_tensor_batch\")\n for key, array in self.non_tensor_batch.items():\n info.append(f\" {key}: ndarray{array.shape} ({array.dtype})\")\n\n info.append(\"meta_info\")\n for k, v in self.meta_info.items():\n type_info = self._get_type_info(v)\n info.append(f\" {k}: {type_info}\")\n\n return \"\\n\".join(info)\n\n def _get_type_info(self, value):\n \"\"\"Recursively get type information for nested structures\"\"\"\n if isinstance(value, list):\n elem_types = {self._get_type_info(v) for v in value[:3]}\n return f\"list[{'|'.join(elem_types) if elem_types else '...'}]\"\n if isinstance(value, tuple):\n elem_types = [self._get_type_info(v) for v in value]\n return f\"tuple({', '.join(elem_types)})\"\n if isinstance(value, dict):\n if not value:\n return \"dict\"\n k, v = next(iter(value.items()))\n return f\"dict[{self._get_type_info(k)}: {self._get_type_info(v)}]\"\n if isinstance(value, np.ndarray):\n return f\"ndarray{value.shape} ({value.dtype})\"\n return type(value).__name__\n\n\n@dataclass\nclass DataProtoFuture:\n \"\"\"\n DataProtoFuture aims to eliminate actual data fetching on driver. By doing so, the driver doesn't have to wait\n for data so that asynchronous execution becomes possible.\n DataProtoFuture contains a list of futures from another WorkerGroup of size world_size.\n - collect_fn is a Callable that reduces the list of futures to a DataProto\n - dispatch_fn is a Callable that partitions the DataProto into a list of DataProto of size world_size\n and then select\n\n Potential issue: we can optimize dispatch_fn(collect_fn) such that only needed data is fetched on destination\n - DataProtoFuture only supports directly passing from the output of a method to another input. You can't perform any\n operation on the DataProtoFuture in driver.\n \"\"\"\n\n collect_fn: Callable\n futures: list[ray.ObjectRef]\n dispatch_fn: Callable = None\n\n @staticmethod\n def concat(data: list[ray.ObjectRef]) -> \"DataProtoFuture\":\n output = DataProtoFuture(collect_fn=DataProto.concat, futures=data)\n return output\n\n def chunk(self, chunks: int) -> list[\"DataProtoFuture\"]:\n from functools import partial\n\n arg_future_lst = []\n for i in range(chunks):\n # note that we can't directly pass i and chunks\n def dispatch_fn(x, i, chunks):\n return x.chunk(chunks=chunks)[i]\n\n arg_future = DataProtoFuture(\n collect_fn=self.collect_fn, dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks), futures=self.futures\n )\n arg_future_lst.append(arg_future)\n return arg_future_lst\n\n def get(self):\n output = ray.get(self.futures) # dp_size.\n for o in output:\n assert isinstance(o, DataProto | TensorDict)\n\n if isinstance(output[0], DataProto):\n output = DataProto.concat(output) # select dp, concat\n elif isinstance(output[0], TensorDict):\n from verl.utils.tensordict_utils import concat_tensordict\n\n output = concat_tensordict(output)\n else:\n raise TypeError(f\"Unknown type {type(o[0])} in DataProtoFuture\")\n\n if self.dispatch_fn is not None:\n output = self.dispatch_fn(output) # split in batch dim, select using dp\n return output\n\n\ndef all_gather_data_proto(data: DataProto, process_group):\n # Note that this is an inplace operator just like torch.distributed.all_gather\n group_size = torch.distributed.get_world_size(group=process_group)\n assert isinstance(data, DataProto)\n prev_device = data.batch.device\n data = data.to(get_device_id())\n data.batch = allgather_dict_tensors(data.batch.contiguous(), size=group_size, group=process_group, dim=0)\n data = data.to(prev_device)\n # all gather non_tensor_batch\n all_non_tensor_batch = [None for _ in range(group_size)]\n torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=process_group)\n data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch}\n"} {"file_name": "verl__single_controller__base__worker_group.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nthe class of WorkerGroup\n\"\"\"\n\nimport logging\nimport signal\nimport threading\nimport time\nfrom typing import Any, Callable\n\nfrom .decorator import MAGIC_ATTR, Dispatch, get_predefined_dispatch_fn, get_predefined_execute_fn\n\n\nclass ResourcePool:\n \"\"\"\n Manages a pool of resources across multiple nodes, tracking process counts and GPU allocations.\n The class provides methods to calculate world size, local world sizes, and local ranks\n across all nodes in the pool.\n \"\"\"\n\n def __init__(self, process_on_nodes=None, max_colocate_count: int = 10, n_gpus_per_node=8) -> None:\n \"\"\"Initialize the ResourcePool with node processes and GPU configuration.\n\n Args:\n process_on_nodes (List[int], optional): List of process counts per node. Defaults to empty list.\n max_colocate_count (int, optional): Maximum number of processes that can be colocated. Defaults to 10.\n n_gpus_per_node (int, optional): Number of GPUs available per node. Defaults to 8.\n \"\"\"\n if process_on_nodes is None:\n process_on_nodes = []\n self._store = process_on_nodes\n self.max_colocate_count = max_colocate_count\n self.n_gpus_per_node = n_gpus_per_node # this is left for future huawei GPU that contains 16 GPUs per node\n\n def add_node(self, process_count):\n self._store.append(process_count)\n\n @property\n def world_size(self):\n \"\"\"Total number of processes across all nodes in the pool.\"\"\"\n return sum(self._store)\n\n def __call__(self) -> Any:\n return self._store\n\n @property\n def store(self):\n return self._store\n\n def local_world_size_list(self) -> list[int]:\n \"\"\"Returns a flat list where each process has its local world size.\"\"\"\n nested_local_world_size_list = [\n [local_world_size for _ in range(local_world_size)] for local_world_size in self._store\n ]\n return [item for row in nested_local_world_size_list for item in row]\n\n def local_rank_list(self) -> list[int]:\n \"\"\"Returns a flat list of local ranks for all processes across all nodes.\"\"\"\n nested_local_rank_list = [[i for i in range(local_world_size)] for local_world_size in self._store]\n return [item for row in nested_local_rank_list for item in row]\n\n\nclass ClassWithInitArgs:\n \"\"\"\n Wrapper class that stores constructor arguments for deferred instantiation.\n This class is particularly useful for remote class instantiation where\n the actual construction needs to happen at a different time or location.\n \"\"\"\n\n def __init__(self, cls, *args, **kwargs) -> None:\n \"\"\"Initialize the ClassWithInitArgs instance.\n\n Args:\n cls: The class to be instantiated later\n *args: Positional arguments for the class constructor\n **kwargs: Keyword arguments for the class constructor\n \"\"\"\n self.cls = cls\n self.args = args\n self.kwargs = kwargs\n\n self.fused_worker_used = False\n\n def __call__(self) -> Any:\n \"\"\"Instantiate the stored class with the stored arguments.\"\"\"\n return self.cls(*self.args, **self.kwargs)\n\n\ndef check_workers_alive(workers: list, is_alive: Callable, gap_time: float = 1) -> None:\n \"\"\"Continuously monitors worker processes and raises SIGABRT if any worker dies.\n\n Args:\n workers (List):\n List of worker objects to monitor\n is_alive (Callable):\n Function to check if a worker is alive\n gap_time (float):\n Time interval between checks\n \"\"\"\n import time\n\n while True:\n for worker in workers:\n if not is_alive(worker):\n logging.warning(f\"worker {worker} is not alive sending signal to main thread\")\n signal.raise_signal(signal.SIGABRT)\n time.sleep(gap_time)\n\n\nclass WorkerGroup:\n \"\"\"\n Base class for managing a group of workers in a distributed system.\n The class provides methods for worker management, aliveness checking, and method binding.\n \"\"\"\n\n fused_worker_execute_fn_name = \"_fuw_execute\"\n\n def __init__(self, resource_pool: ResourcePool, **kwargs) -> None:\n self._is_init_with_detached_workers = resource_pool is None\n\n self.fused_worker_used = False\n\n if resource_pool is not None:\n # handle the case when WorkGroup is attached to an existing one\n self._procecss_dispatch_config = resource_pool()\n else:\n self._procecss_dispatch_config = None\n\n self._workers = []\n self._worker_names = []\n\n self._dispatch_info = {}\n self._collect_info = {}\n\n self._master_addr = None\n self._master_port = None\n\n self._checker_thread: threading.Thread = None\n\n def _is_worker_alive(self, worker):\n \"\"\"Check if a worker is alive. Must be implemented by derived classes.\"\"\"\n raise NotImplementedError(\"WorkerGroup._is_worker_alive called, should be implemented in derived class.\")\n\n def _block_until_all_workers_alive(self) -> None:\n \"\"\"Blocks until all workers in the group are alive.\"\"\"\n while True:\n all_state = [self._is_worker_alive(worker) for worker in self._workers]\n if False in all_state:\n time.sleep(1)\n else:\n break\n\n def start_worker_aliveness_check(self, every_n_seconds=1) -> None:\n \"\"\"Starts a background thread to monitor worker aliveness.\n\n Args:\n every_n_seconds (int): Interval between aliveness checks\n \"\"\"\n # before starting checking worker aliveness, make sure all workers are already alive\n self._block_until_all_workers_alive()\n\n self._checker_thread = threading.Thread(\n target=check_workers_alive, args=(self._workers, self._is_worker_alive, every_n_seconds)\n )\n self._checker_thread.start()\n\n @property\n def world_size(self):\n \"\"\"Number of workers in the group.\"\"\"\n return len(self._workers)\n\n def _bind_worker_method(self, user_defined_cls, func_generator):\n \"\"\"Binds worker methods to the WorkerGroup based on registered attributes.\n\n Args:\n user_defined_cls (type): The class containing methods to bind\n func_generator (Callable): Function that generates the bound method\n\n Returns:\n List[str]: List of method names that were successfully bound\n \"\"\"\n method_names = []\n for method_name in dir(user_defined_cls):\n try:\n method = getattr(user_defined_cls, method_name)\n assert callable(method), f\"{method_name} in {user_defined_cls} is not callable\"\n except Exception:\n # if it is a property, it will fail because Class doesn't have instance property\n continue\n\n if hasattr(method, MAGIC_ATTR):\n # this method is decorated by register\n attribute = getattr(method, MAGIC_ATTR)\n assert isinstance(attribute, dict), f\"attribute must be a dictionary. Got {type(attribute)}\"\n assert \"dispatch_mode\" in attribute, \"attribute must contain dispatch_mode in its key\"\n\n dispatch_mode = attribute[\"dispatch_mode\"]\n execute_mode = attribute[\"execute_mode\"]\n blocking = attribute[\"blocking\"]\n\n # get dispatch fn\n if isinstance(dispatch_mode, Dispatch):\n # get default dispatch fn\n fn = get_predefined_dispatch_fn(dispatch_mode=dispatch_mode)\n dispatch_fn = fn[\"dispatch_fn\"]\n collect_fn = fn[\"collect_fn\"]\n else:\n assert isinstance(dispatch_mode, dict)\n assert \"dispatch_fn\" in dispatch_mode\n assert \"collect_fn\" in dispatch_mode\n dispatch_fn = dispatch_mode[\"dispatch_fn\"]\n collect_fn = dispatch_mode[\"collect_fn\"]\n\n # get execute_fn_name\n execute_mode = get_predefined_execute_fn(execute_mode=execute_mode)\n wg_execute_fn_name = execute_mode[\"execute_fn_name\"]\n\n # get execute_fn from string\n try:\n execute_fn = getattr(self, wg_execute_fn_name)\n assert callable(execute_fn), \"execute_fn must be callable\"\n except Exception:\n print(f\"execute_fn {wg_execute_fn_name} is invalid\")\n raise\n\n # bind a new method to the RayWorkerGroup\n func = func_generator(\n self,\n method_name,\n dispatch_fn=dispatch_fn,\n collect_fn=collect_fn,\n execute_fn=execute_fn,\n blocking=blocking,\n )\n\n try:\n setattr(self, method_name, func)\n method_names.append(method_name)\n except Exception as e:\n raise ValueError(f\"Fail to set method_name {method_name}\") from e\n\n return method_names\n"} {"file_name": "verl__trainer__ppo__reward.py", "text": "# Copyright 2025 Individual Contributor: Thibaut Barroyer\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import annotations\n\nimport inspect\nimport multiprocessing\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Any, Optional, cast\n\nfrom verl import DataProto\nfrom verl.utils.reward_score import default_compute_score\n\nif TYPE_CHECKING:\n from omegaconf import DictConfig\n\n from verl.experimental.reward_loop.reward_manager.base import RawRewardFn, RewardManagerBase\n from verl.trainer.config.config import ModuleConfig\n from verl.workers.config.reward import RewardManagerConfig\n\n\ndef _call_with_kwargs(raw_fn, extra_kwargs, *args, **kwargs):\n \"\"\"Calls `raw_fn` by merging `extra_kwargs` into call-time `kwargs`, with `extra_kwargs` taking precedence.\n\n This function is used to merge additional keyword arguments with the original function's arguments.\n \"\"\"\n merged_kwargs = {**kwargs, **extra_kwargs}\n return raw_fn(*args, **merged_kwargs)\n\n\nasync def _call_with_kwargs_async(raw_fn, extra_kwargs, *args, **kwargs):\n \"\"\"Calls `raw_fn` by merging `extra_kwargs` into call-time `kwargs`, with `extra_kwargs` taking precedence.\n\n This function is used to merge additional keyword arguments with the original function's arguments.\n \"\"\"\n merged_kwargs = {**kwargs, **extra_kwargs}\n return await raw_fn(*args, **merged_kwargs)\n\n\ndef get_custom_reward_fn(config: DictConfig) -> Optional[RawRewardFn]:\n \"\"\"Load and return a custom reward function from external file.\n\n Dynamically imports a reward function from a specified file path and wraps\n it with additional keyword arguments from the configuration.\n\n Args:\n config (dict): Configuration dictionary containing custom_reward_function\n settings with 'path', 'name', and 'reward_kwargs' fields.\n\n Returns:\n callable or None: Wrapped reward function with merged kwargs, or None\n if no custom reward function is configured.\n\n Raises:\n FileNotFoundError: If the specified reward function file doesn't exist.\n RuntimeError: If there's an error loading the module from file.\n AttributeError: If the specified function name isn't found in the module.\n \"\"\"\n\n reward_fn_config = config.reward.get(\"custom_reward_function\") or {}\n module_path = reward_fn_config.get(\"path\")\n if not module_path:\n return None\n\n fn_name = reward_fn_config.get(\"name\")\n assert fn_name is not None\n\n from verl.utils.import_utils import load_extern_object\n\n raw_fn = load_extern_object(module_path=module_path, object_name=fn_name)\n\n reward_kwargs = dict(reward_fn_config.get(\"reward_kwargs\", {}))\n if not inspect.iscoroutinefunction(raw_fn):\n return partial(_call_with_kwargs, raw_fn, reward_kwargs)\n else:\n return partial(_call_with_kwargs_async, raw_fn, reward_kwargs)\n\n\ndef load_reward_manager(config: DictConfig, tokenizer: Any, **reward_kwargs: Any) -> RewardManagerBase:\n \"\"\"\n Load and initialize a reward manager based on the configuration.\n\n Args:\n config: PPO trainer configuration object containing reward_model fields.\n tokenizer: Tokenizer object used for processing text.\n **reward_kwargs: Additional keyword arguments for the reward manager.\n\n Returns:\n An instance of the specified reward manager class.\n \"\"\"\n\n # Try to get a custom reward function based on the configuration\n # user defined reward manager can be registered in custom_reward_fn\n compute_score = get_custom_reward_fn(config)\n final_compute_score = compute_score\n\n reward_manager_cfg: RewardManagerConfig = config.reward.reward_manager\n reward_manager_cls: type[RewardManagerBase]\n if reward_manager_cfg.source == \"register\":\n from verl.experimental.reward_loop.reward_manager import get_reward_manager_cls\n\n reward_manager_cls = get_reward_manager_cls(reward_manager_cfg.name)\n elif reward_manager_cfg.source == \"importlib\":\n from verl.utils.import_utils import load_extern_object\n\n module_cfg: ModuleConfig | None = reward_manager_cfg.module\n assert module_cfg is not None and module_cfg.path is not None, (\n f\"Module path is required when {reward_manager_cfg.source=}, but got {module_cfg=}\"\n )\n reward_manager_cls_name = reward_manager_cfg.name\n reward_manager_cls = cast(\n \"type[RewardManagerBase]\",\n load_extern_object(module_path=module_cfg.path, object_name=reward_manager_cls_name),\n )\n\n if compute_score is None:\n sandbox_config = config.reward.get(\"sandbox_fusion\")\n sandbox_url = sandbox_config.get(\"url\") if sandbox_config else None\n memory_limit_mb = sandbox_config.get(\"memory_limit_mb\", 1024) if sandbox_config else 1024\n if sandbox_url:\n sandbox_manager = multiprocessing.Manager()\n # Create a semaphore to control concurrent access to the sandbox\n _concurrent_semaphore = sandbox_manager.Semaphore(sandbox_config.get(\"max_concurrent\", 64))\n final_compute_score = partial(\n default_compute_score,\n sandbox_fusion_url=sandbox_url,\n concurrent_semaphore=_concurrent_semaphore,\n memory_limit_mb=memory_limit_mb,\n )\n else:\n final_compute_score = default_compute_score\n\n # Instantiate and return the reward manager with the specified parameters\n return reward_manager_cls(\n config=config,\n tokenizer=tokenizer,\n compute_score=final_compute_score,\n **reward_kwargs,\n )\n\n\ndef extract_reward(batch: DataProto):\n \"\"\"\n Extract reward tensor and extra info from batch data.\n \"\"\"\n reward_tensor = batch.batch[\"rm_scores\"]\n reward_extra_keys = batch.meta_info.get(\"reward_extra_keys\", [])\n reward_extra_infos_dict = {key: batch.non_tensor_batch[key] for key in reward_extra_keys}\n return reward_tensor, reward_extra_infos_dict\n"} {"file_name": "verl__utils__import_utils.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nUtilities to check if packages are available.\nWe assume package availability won't change during runtime.\n\"\"\"\n\nimport importlib\nimport importlib.util\nimport os\nimport warnings\nfrom functools import cache, wraps\nfrom typing import Optional\n\n\n@cache\ndef is_megatron_core_available():\n try:\n mcore_spec = importlib.util.find_spec(\"megatron.core\")\n except ModuleNotFoundError:\n mcore_spec = None\n return mcore_spec is not None\n\n\n@cache\ndef is_vllm_available():\n try:\n vllm_spec = importlib.util.find_spec(\"vllm\")\n except ModuleNotFoundError:\n vllm_spec = None\n return vllm_spec is not None\n\n\n@cache\ndef is_sglang_available():\n try:\n sglang_spec = importlib.util.find_spec(\"sglang\")\n except ModuleNotFoundError:\n sglang_spec = None\n return sglang_spec is not None\n\n\n@cache\ndef is_nvtx_available():\n try:\n nvtx_spec = importlib.util.find_spec(\"nvtx\")\n except ModuleNotFoundError:\n nvtx_spec = None\n return nvtx_spec is not None\n\n\n@cache\ndef is_trl_available():\n try:\n trl_spec = importlib.util.find_spec(\"trl\")\n except ModuleNotFoundError:\n trl_spec = None\n return trl_spec is not None\n\n\ndef import_external_libs(external_libs=None):\n if external_libs is None:\n return\n if not isinstance(external_libs, list):\n external_libs = [external_libs]\n import importlib\n\n for external_lib in external_libs:\n importlib.import_module(external_lib)\n\n\nPKG_PATH_PREFIX = \"pkg://\"\nFILE_PATH_PREFIX = \"file://\"\n\n\ndef load_module(module_path: str, module_name: Optional[str] = None) -> object:\n \"\"\"Load a module from a path.\n\n Args:\n module_path (str):\n The path to the module. Either\n - `pkg_path`, e.g.,\n - \"pkg://verl.utils.dataset.rl_dataset\"\n - \"pkg://verl/utils/dataset/rl_dataset\"\n - or `file_path` (absolute or relative), e.g.,\n - \"file://verl/utils/dataset/rl_dataset.py\"\n - \"/path/to/verl/utils/dataset/rl_dataset.py\"\n module_name (str, optional):\n The name of the module to added to ``sys.modules``. If not provided, the module will not be added,\n thus will not be cached and directly ``import``able.\n \"\"\"\n if not module_path:\n return None\n\n if module_path.startswith(PKG_PATH_PREFIX):\n module_name = module_path[len(PKG_PATH_PREFIX) :].replace(\"/\", \".\")\n module = importlib.import_module(module_name)\n\n else:\n if module_path.startswith(FILE_PATH_PREFIX):\n module_path = module_path[len(FILE_PATH_PREFIX) :]\n\n if not os.path.exists(module_path):\n raise FileNotFoundError(f\"Custom module file not found: {module_path=}\")\n\n # Use the provided module_name for the spec, or derive a unique name to avoid collisions.\n spec_name = module_name or f\"custom_module_{hash(os.path.abspath(module_path))}\"\n spec = importlib.util.spec_from_file_location(spec_name, module_path)\n if spec is None or spec.loader is None:\n raise ImportError(f\"Could not load module from {module_path=}\")\n\n module = importlib.util.module_from_spec(spec)\n try:\n spec.loader.exec_module(module)\n except Exception as e:\n raise RuntimeError(f\"Error loading module from {module_path=}\") from e\n\n if module_name is not None:\n import sys\n\n # Avoid overwriting an existing module with a different object.\n if module_name in sys.modules and sys.modules[module_name] is not module:\n raise RuntimeError(\n f\"Module name '{module_name}' already in `sys.modules` and points to a different module.\"\n )\n sys.modules[module_name] = module\n\n return module\n\n\ndef _get_qualified_name(func):\n \"\"\"Get full qualified name including module and class (if any).\"\"\"\n module = func.__module__\n qualname = func.__qualname__\n return f\"{module}.{qualname}\"\n\n\ndef deprecated(replacement: str = \"\"):\n \"\"\"Decorator to mark functions or classes as deprecated.\"\"\"\n\n def decorator(obj):\n qualified_name = _get_qualified_name(obj)\n\n if isinstance(obj, type):\n original_init = obj.__init__\n\n @wraps(original_init)\n def wrapped_init(self, *args, **kwargs):\n msg = f\"Warning: Class '{qualified_name}' is deprecated.\"\n if replacement:\n msg += f\" Please use '{replacement}' instead.\"\n warnings.warn(msg, category=FutureWarning, stacklevel=2)\n return original_init(self, *args, **kwargs)\n\n obj.__init__ = wrapped_init\n return obj\n\n else:\n\n @wraps(obj)\n def wrapped(*args, **kwargs):\n msg = f\"Warning: Function '{qualified_name}' is deprecated.\"\n if replacement:\n msg += f\" Please use '{replacement}' instead.\"\n warnings.warn(msg, category=FutureWarning, stacklevel=2)\n return obj(*args, **kwargs)\n\n return wrapped\n\n return decorator\n\n\ndef load_extern_object(module_path: str, object_name: str) -> object:\n \"\"\"Load an object from a module path.\n\n Args:\n module_path (str): See :func:`load_module`.\n object_name (str):\n The name of the object to load with ``getattr(module, object_name)``.\n \"\"\"\n module = load_module(module_path)\n\n if not hasattr(module, object_name):\n raise AttributeError(f\"Object not found in module: {object_name=}, {module_path=}.\")\n\n return getattr(module, object_name)\n\n\ndef load_class_from_fqn(fqn: str, description: str = \"class\") -> type:\n \"\"\"Load a class from its fully qualified name.\n\n Args:\n fqn: Fully qualified class name (e.g., 'mypackage.module.ClassName').\n description: Description for error messages (e.g., 'AgentLoopManager').\n\n Returns:\n The loaded class.\n\n Raises:\n ValueError: If fqn format is invalid (missing dot separator).\n ImportError: If the module cannot be imported.\n AttributeError: If the class is not found in the module.\n\n Example:\n >>> cls = load_class_from_fqn(\"verl.experimental.agent_loop.AgentLoopManager\")\n >>> instance = cls(config=config, ...)\n \"\"\"\n if \".\" not in fqn:\n raise ValueError(\n f\"Invalid {description} '{fqn}'. Expected fully qualified class name (e.g., 'mypackage.module.ClassName').\"\n )\n try:\n module_path, class_name = fqn.rsplit(\".\", 1)\n module = importlib.import_module(module_path)\n return getattr(module, class_name)\n except ImportError as e:\n raise ImportError(f\"Failed to import module '{module_path}' for {description}: {e}\") from e\n except AttributeError as e:\n raise AttributeError(f\"Class '{class_name}' not found in module '{module_path}': {e}\") from e\n\n\n@deprecated(replacement=\"load_module(file_path); getattr(module, type_name)\")\ndef load_extern_type(file_path: str, type_name: str) -> type:\n \"\"\"DEPRECATED. Directly use `load_extern_object` instead.\"\"\"\n return load_extern_object(file_path, type_name)\n"} {"file_name": "verl__utils__logging_utils.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport os\n\nimport torch\n\n\ndef set_basic_config(level):\n \"\"\"\n This function sets the global logging format and level. It will be called when import verl\n \"\"\"\n logging.basicConfig(format=\"%(levelname)s:%(asctime)s:%(message)s\", level=level)\n\n\ndef log_to_file(string):\n print(string)\n if os.path.isdir(\"logs\"):\n with open(f\"logs/log_{torch.distributed.get_rank()}\", \"a+\") as f:\n f.write(string + \"\\n\")\n"} {"file_name": "verl__utils__megatron__optimizer.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nfrom megatron.core.optimizer import OptimizerConfig\nfrom megatron.core.optimizer import get_megatron_optimizer as get_megatron_optimizer_native\nfrom megatron.core.optimizer_param_scheduler import OptimizerParamScheduler\n\nfrom verl.utils.logger import print_rank_0\n\n\ndef init_megatron_optim_config(\n optim_config: dict, use_distributed_optimizer: bool = True, fp16: bool = False\n) -> OptimizerConfig:\n optim_args = {\n \"optimizer\": optim_config.optimizer,\n \"lr\": optim_config.lr,\n \"min_lr\": optim_config.min_lr,\n \"clip_grad\": optim_config.clip_grad,\n \"weight_decay\": optim_config.weight_decay,\n \"use_distributed_optimizer\": use_distributed_optimizer,\n }\n if fp16:\n optim_args.update(\n {\n \"bf16\": False,\n \"fp16\": True,\n \"params_dtype\": torch.float16,\n \"initial_loss_scale\": 32768,\n \"min_loss_scale\": 1,\n \"use_precision_aware_optimizer\": True,\n \"store_param_remainders\": False,\n }\n )\n else: # bf16 mode\n optim_args.update(\n {\n \"bf16\": True,\n \"params_dtype\": torch.bfloat16,\n }\n )\n override_config = optim_config.get(\"override_optimizer_config\", {})\n if override_config:\n for k, v in override_config.items():\n optim_args[k] = v\n\n print_rank_0(f\"optimizer config after override: {optim_args}\")\n\n config = OptimizerConfig(**optim_args)\n return config\n\n\ndef get_megatron_optimizer(\n model,\n config: OptimizerConfig,\n):\n # Base optimizer.\n return get_megatron_optimizer_native(\n config=config,\n model_chunks=model,\n )\n\n\ndef get_megatron_optimizer_param_scheduler(\n optimizer,\n config,\n):\n \"\"\"\n Get the optimizer parameter scheduler for Megatron.\n \"\"\"\n lr_decay_steps = config.lr_decay_steps\n lr_warmup_steps = config.lr_warmup_steps\n if config.get(\"lr_decay_steps\", None) is None:\n lr_decay_steps = config.total_training_steps\n wsd_decay_steps = None\n if config.get(\"lr_wsd_decay_steps\", None) is not None:\n wsd_decay_steps = config.lr_wsd_decay_steps\n if config.get(\"lr_warmup_steps_ratio\", None) is not None and (\n config.get(\"lr_warmup_steps\", None) is None or config.lr_warmup_steps <= 0\n ):\n lr_warmup_steps = int(config.lr_warmup_steps_ratio * lr_decay_steps)\n\n opt_param_scheduler = OptimizerParamScheduler(\n optimizer,\n init_lr=config.lr_warmup_init,\n max_lr=config.lr,\n min_lr=config.min_lr,\n lr_warmup_steps=lr_warmup_steps,\n lr_decay_steps=lr_decay_steps,\n lr_decay_style=config.lr_decay_style,\n start_wd=config.weight_decay,\n end_wd=config.weight_decay,\n wd_incr_steps=config.total_training_steps,\n wd_incr_style=config.weight_decay_incr_style,\n use_checkpoint_opt_param_scheduler=config.use_checkpoint_opt_param_scheduler,\n override_opt_param_scheduler=(not config.use_checkpoint_opt_param_scheduler),\n wsd_decay_steps=wsd_decay_steps,\n lr_wsd_decay_style=config.lr_wsd_decay_style,\n )\n\n return opt_param_scheduler\n\n\ndef get_megatron_last_lr(optimizer):\n \"\"\"\n Get the last learning rate from the optimizer parameter scheduler.\n \"\"\"\n return optimizer.param_groups[0][\"lr\"]\n"} {"file_name": "verl__utils__memory_utils.py", "text": "# Copyright 2025 Bytedance Ltd. and/or its affiliates\n# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport inspect\nimport logging\nimport os\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport torch\n\nfrom verl.utils.device import get_torch_device, is_cuda_available\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv(\"VERL_LOGGING_LEVEL\", \"WARN\"))\n\n\ndef aggressive_empty_cache(force_sync: bool = True, max_retries: int = 3) -> None:\n \"\"\"\n More aggressive GPU memory cleanup function, tries to release PyTorch reserved\n but unallocated memory.\n\n Args:\n force_sync: Whether to force device synchronization\n max_retries: Maximum number of retries\n \"\"\"\n device = get_torch_device()\n if not device.is_available():\n return\n\n for attempt in range(max_retries):\n # Record memory status before cleanup\n before_reserved = device.memory_reserved()\n before_allocated = device.memory_allocated()\n\n # Run garbage collection\n gc.collect()\n\n # Clear PyTorch cache\n device.empty_cache()\n\n # Force synchronization (optional)\n if force_sync:\n device.synchronize()\n\n # Record memory status after cleanup\n after_reserved = device.memory_reserved()\n after_allocated = device.memory_allocated()\n\n # Calculate freed memory\n reserved_freed = before_reserved - after_reserved\n allocated_freed = before_allocated - after_allocated\n\n logger.info(\n f\"Memory cleanup attempt {attempt + 1}: Freed {reserved_freed / 1024**3:.2f} GB reserved, \"\n f\"{allocated_freed / 1024**3:.2f} GB allocated\"\n )\n\n # Stop retrying if little memory was freed\n if reserved_freed < 1024**3: # less than 1GB\n break\n\n\ndef reset_memory_stats() -> None:\n \"\"\"Reset GPU memory statistics\"\"\"\n if get_torch_device().is_available():\n device = get_torch_device()\n device.reset_peak_memory_stats()\n device.reset_accumulated_memory_stats()\n\n\ndef get_memory_info() -> dict:\n \"\"\"Get detailed GPU memory information\"\"\"\n if not get_torch_device().is_available():\n return {}\n\n device = get_torch_device()\n device_id = device.current_device()\n\n return {\n \"total_memory_gb\": device.get_device_properties(device_id).total_memory / 1024**3,\n \"reserved_memory_gb\": device.memory_reserved() / 1024**3,\n \"allocated_memory_gb\": device.memory_allocated() / 1024**3,\n \"cached_memory_gb\": (device.memory_reserved() - device.memory_allocated()) / 1024**3,\n \"max_memory_allocated_gb\": device.max_memory_allocated() / 1024**3,\n \"max_memory_reserved_gb\": device.max_memory_reserved() / 1024**3,\n }\n\n\ndef log_memory_usage(stage: str = \"current\") -> None:\n \"\"\"Log GPU memory usage\"\"\"\n if not get_torch_device().is_available():\n return\n\n info = get_memory_info()\n logger.info(\n f\"Memory usage [{stage}]: \"\n f\"Total: {info['total_memory_gb']:.2f} GB, \"\n f\"Allocated: {info['allocated_memory_gb']:.2f} GB, \"\n f\"Reserved: {info['reserved_memory_gb']:.2f} GB, \"\n f\"Cached: {info['cached_memory_gb']:.2f} GB\"\n )\n\n\ndef optimize_memory_for_inference() -> None:\n \"\"\"Optimize GPU memory usage for inference\"\"\"\n if not get_torch_device().is_available():\n return\n\n # Set a more aggressive memory allocation policy\n get_torch_device().set_per_process_memory_fraction(0.95) # Use 95% of GPU memory\n\n # Clear cache\n aggressive_empty_cache(force_sync=True)\n\n logger.info(\"Optimized GPU memory usage for inference\")\n\n\ndef optimize_memory_for_training() -> None:\n \"\"\"Optimize GPU memory usage for training\"\"\"\n if not get_torch_device().is_available():\n return\n\n # Set a moderate memory allocation policy\n get_torch_device().set_per_process_memory_fraction(0.9) # Use 90% of GPU memory\n\n # Clear cache\n aggressive_empty_cache(force_sync=False)\n\n logger.info(\"Optimized GPU memory usage for training\")\n\n\ndef enable_memory_visualize(\n trace_alloc_max_entries: int = 200_000,\n stack_depth: int = 32,\n context: str = \"all\",\n stacks: str = \"all\",\n devices=None,\n record_context: bool = True,\n):\n \"\"\"\n Enables memory history recording for CUDA allocations. This function\n should be called before any large-scale CUDA allocations. For DDP or\n multi-process setups, it must be called on each rank.\n\n Args:\n trace_alloc_max_entries (int): Maximum number of allocation entries\n to record.\n stack_depth (int): The depth of the call stack to capture for each\n allocation. (Supported by some PyTorch versions).\n context (str): The type of memory events to record.\n 'alloc': records only allocation events.\n 'state': records memory state changes.\n 'all': records both.\n stacks (str): The type of call stacks to record.\n 'python': records Python stacks.\n 'cpp': records C++ stacks (available in some versions).\n 'all': records both.\n devices (Union[int, list[int], None]): The device for which to enable\n memory history. `None` enables it for the current default device.\n record_context (bool): Whether to record context information for\n allocations. Required by older PyTorch versions.\n \"\"\"\n # Memory history recording is CUDA-specific functionality\n if not is_cuda_available:\n logger.warning(\"[memory_visualize] Memory history recording is only available on CUDA devices\")\n return\n\n f = get_torch_device().memory._record_memory_history\n params = set(inspect.signature(f).parameters.keys())\n\n def _one_call(dev_kw=None):\n kwargs = {}\n if \"context\" in params:\n kwargs[\"context\"] = context\n if \"stacks\" in params:\n kwargs[\"stacks\"] = stacks\n if \"max_entries\" in params:\n kwargs[\"max_entries\"] = trace_alloc_max_entries\n elif \"trace_alloc_max_entries\" in params:\n kwargs[\"trace_alloc_max_entries\"] = trace_alloc_max_entries\n if \"stack_depth\" in params:\n kwargs[\"stack_depth\"] = stack_depth\n if dev_kw is not None:\n if \"device\" in params:\n kwargs[\"device\"] = dev_kw\n elif \"devices\" in params:\n kwargs[\"devices\"] = dev_kw if isinstance(dev_kw, list) else [dev_kw]\n if \"record_context\" in params:\n kwargs[\"record_context\"] = record_context\n\n try:\n f(**kwargs)\n return \"native\", kwargs\n except TypeError:\n try:\n if \"trace_alloc_max_entries\" in params and \"record_context\" in params:\n f(enabled=True, trace_alloc_max_entries=trace_alloc_max_entries, record_context=True)\n return \"legacy\", {\n \"enabled\": True,\n \"trace_alloc_max_entries\": trace_alloc_max_entries,\n \"record_context\": True,\n }\n else:\n f(enabled=True)\n return \"legacy-min\", {\"enabled\": True}\n except Exception:\n raise\n\n if devices is None or isinstance(devices, str | int | torch.device):\n mode, used = _one_call(devices if devices is not None else None)\n else:\n mode, used = \"multi-device\", {}\n for d in list(devices):\n _mode, _used = _one_call(d)\n used[f\"dev{d}\"] = _used\n\n device = get_torch_device()\n if device.is_available():\n device.reset_peak_memory_stats()\n device.synchronize()\n\n rank = int(os.environ.get(\"RANK\", \"0\") or 0)\n logger.info(f\"[memory_visualize][rank {rank}] recording enabled ({mode}); args={used}\")\n\n\nclass MemorySnapshotSampler:\n \"\"\"\n A utility class that dumps GPU memory snapshots.\n This is useful for monitoring memory usage over a long-running process.\n\n The dumped files can be visualized with https://docs.pytorch.org/memory_viz\n\n Args:\n out_dir (str): The directory where the snapshots will be saved.\n tag (str): A tag for the snapshot filenames.\n \"\"\"\n\n def __init__(self, out_dir: str = \"./mem_snapshots\", tag: str = \"periodic\"):\n self.out_dir = out_dir\n self.tag = tag\n\n def dump_memory_snapshot(self, out_dir: str = \"./mem_snapshots\", tag: str = \"snapshot\", sub_dir: str = None):\n \"\"\"\n Generates a memory snapshot and saves it as a pickle file in a specified directory.\n The files are organized by timestamp in subdirectories, with all ranks' files\n placed in the same timestamp subdirectory.\n\n Args:\n out_dir (str): The directory where the snapshot file will be saved.\n The directory is created if it does not exist.\n tag (str): A string tag to prepend to the filename for easier identification.\n sub_dir (str): A subdirectory to place the snapshot file in.\n \"\"\"\n if sub_dir is None:\n timestamp = datetime.now().strftime(\"%Y%m%d-%H%M\")\n out_path = Path(out_dir) / timestamp\n else:\n out_path = Path(out_dir) / sub_dir\n out_path.mkdir(parents=True, exist_ok=True)\n\n # get the GPU rank on the current process\n rank = os.environ.get(\"RANK\", \"0\")\n pid = os.getpid()\n # todo(chenyang): check wether we need to sync all ranks before dump\n fname = f\"{tag}_rank{rank}_pid{pid}.pickle\"\n path = out_path / fname\n\n device = get_torch_device()\n if not device.is_available():\n logger.warning(\"[memory_visualize] is only available on CUDA devices.\")\n return\n try:\n device.synchronize()\n # Memory snapshot is CUDA-specific functionality\n device.memory._dump_snapshot(str(path))\n logger.info(f\"[memory_visualize] dumped: {path}\")\n except Exception as e:\n logger.info(f\"[memory_visualize][warn] dump failed: {e}\")\n"} {"file_name": "verl__utils__transformers_compat.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nCompatibility utilities for different versions of transformers library.\n\"\"\"\n\nimport importlib.metadata\nfrom functools import lru_cache\nfrom typing import Optional\n\nfrom packaging import version\n\n# Handle version compatibility for flash_attn_supports_top_left_mask\n# This function was added in newer versions of transformers\ntry:\n from transformers.modeling_flash_attention_utils import flash_attn_supports_top_left_mask\nexcept ImportError:\n # For older versions of transformers that don't have this function\n # Default to False as a safe fallback for older versions\n def flash_attn_supports_top_left_mask():\n \"\"\"Fallback implementation for older transformers versions.\n Returns False to disable features that require this function.\n \"\"\"\n return False\n\n\n@lru_cache\ndef is_transformers_version_in_range(min_version: Optional[str] = None, max_version: Optional[str] = None) -> bool:\n try:\n # Get the installed version of the transformers library\n transformers_version_str = importlib.metadata.version(\"transformers\")\n except importlib.metadata.PackageNotFoundError as e:\n raise ModuleNotFoundError(\"The `transformers` package is not installed.\") from e\n\n transformers_version = version.parse(transformers_version_str)\n\n lower_bound_check = True\n if min_version is not None:\n lower_bound_check = version.parse(min_version) <= transformers_version\n\n upper_bound_check = True\n if max_version is not None:\n upper_bound_check = transformers_version <= version.parse(max_version)\n\n return lower_bound_check and upper_bound_check\n"} {"file_name": "verl__workers__config__actor.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom dataclasses import dataclass, field\nfrom typing import Any, Optional\n\nfrom omegaconf import MISSING\n\nfrom verl.base_config import BaseConfig\nfrom verl.trainer.config import CheckpointConfig\nfrom verl.utils.profiler.config import ProfilerConfig\nfrom verl.utils.qat import QATConfig\n\nfrom .engine import FSDPEngineConfig, McoreEngineConfig, VeOmniEngineConfig\nfrom .model import HFModelConfig\nfrom .optimizer import OptimizerConfig\n\n__all__ = [\n \"PolicyLossConfig\",\n \"RouterReplayConfig\",\n \"ActorConfig\",\n \"FSDPActorConfig\",\n \"McoreActorConfig\",\n \"VeOmniActorConfig\",\n \"QATConfig\",\n]\n\n\n@dataclass\nclass RouterReplayConfig(BaseConfig):\n \"\"\"Configuration for router replay in MoE models.\n\n This configuration controls the routing behavior for Mixture of Experts (MoE) models,\n allowing for deterministic training through route recording and replay.\n\n Args:\n mode (str): Router replay mode. Options: 'disabled', 'R2', 'R3'.\n - 'disabled': No router replay functionality\n - 'R2': Use Router Replay routing strategy\n - 'R3': Use Rollout Router Replay routing strategy\n record_file (Optional[str]): File path to save recorded routing decisions.\n Required when mode is 'record', 'R2', or 'R3'.\n replay_file (Optional[str]): File path to load recorded routing decisions for replay.\n Required when mode is 'replay'.\n \"\"\"\n\n mode: str = \"disabled\"\n record_file: Optional[str] = None\n replay_file: Optional[str] = None\n\n def __post_init__(self):\n \"\"\"Validate router replay configuration.\"\"\"\n valid_modes = [\"disabled\", \"R2\", \"R3\"]\n if self.mode not in valid_modes:\n raise ValueError(f\"Invalid router_replay mode: {self.mode}. Must be one of {valid_modes}\")\n\n\n@dataclass\nclass PolicyLossConfig(BaseConfig):\n \"\"\"Configuration for policy loss computation.\n\n The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config.\n\n Args:\n loss_mode (str): Loss function mode. Options: 'vanilla', 'clip-cov', 'kl-cov', 'gpg'.\n clip_cov_ratio (float): Ratio of tokens to be clipped for clip-cov loss.\n clip_cov_lb (float): Lower bound for clip-cov loss.\n clip_cov_ub (float): Upper bound for clip-cov loss.\n kl_cov_ratio (float): Ratio of tokens to be applied KL penalty for kl-cov loss.\n ppo_kl_coef (float): KL divergence penalty coefficient.\n \"\"\"\n\n loss_mode: str = \"vanilla\"\n clip_cov_ratio: float = 0.0002\n clip_cov_lb: float = 1.0\n clip_cov_ub: float = 5.0\n kl_cov_ratio: float = 0.0002\n ppo_kl_coef: float = 0.1\n\n\n@dataclass\nclass ActorConfig(BaseConfig):\n \"\"\"Configuration for actor model training.\n\n The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config.\n\n Args:\n strategy (str): Training strategy. Must be specified.\n ppo_mini_batch_size (int): Mini-batch size for PPO training.\n ppo_micro_batch_size (Optional[int]): Micro-batch size for PPO training.\n If None, uses ppo_micro_batch_size_per_gpu.\n ppo_micro_batch_size_per_gpu (Optional[int]): Micro-batch size per GPU for PPO training.\n use_dynamic_bsz (bool): Whether to use dynamic batch sizing.\n ppo_max_token_len_per_gpu (int): Maximum token length per GPU for PPO training.\n clip_ratio (float): PPO clipping ratio for policy loss.\n clip_ratio_low (float): Lower bound for PPO clipping ratio.\n clip_ratio_high (float): Upper bound for PPO clipping ratio.\n policy_loss (PolicyLossConfig): Configuration for policy loss computation.\n clip_ratio_c (float): Clipping ratio for critic loss.\n loss_agg_mode (str): Loss aggregation mode. Options: 'token-mean', 'sample-mean'.\n loss_scale_factor (Optional[int]): Scale factor for 'seq-mean-token-sum-norm' loss aggregation mode.\n If None, uses response_length. Set to a constant to ensure consistent normalization.\n entropy_coeff (float): Entropy coefficient for regularization.\n tau_pos (float): Positive tau for SAPO smoothing (>= 1.0 keeps rewards stable).\n tau_neg (float): Negative tau for SAPO smoothing (> tau_pos for asymmetry).\n use_kl_loss (bool): Whether to use KL divergence loss.\n use_torch_compile (bool): Whether to use torch.compile for optimization.\n kl_loss_coef (float): KL divergence loss coefficient.\n kl_loss_type (str): Type of KL loss to use.\n ppo_epochs (int): Number of PPO epochs per training step.\n shuffle (bool): Whether to shuffle data during training.\n checkpoint (CheckpointConfig): Configuration for checkpointing.\n optim (OptimizerConfig): Configuration for optimizer.\n use_fused_kernels (bool): Whether to use custom fused kernels (e.g., FlashAttention, fused MLP).\n data_loader_seed (int): Seed for data loader. If None, uses global seed.\n router_replay (RouterReplayConfig): Configuration for router replay in MoE models.\n \"\"\"\n\n _mutable_fields = BaseConfig._mutable_fields | {\n \"ppo_mini_batch_size\",\n \"ppo_micro_batch_size\",\n \"ppo_micro_batch_size_per_gpu\",\n \"ppo_infer_micro_batch_size_per_gpu\",\n \"engine\",\n \"model_config\",\n }\n\n strategy: str = MISSING\n ppo_mini_batch_size: int = 256\n ppo_micro_batch_size: Optional[int] = None # deprecate\n ppo_micro_batch_size_per_gpu: Optional[int] = None\n ppo_infer_micro_batch_size_per_gpu: Optional[int] = None\n use_dynamic_bsz: bool = False\n ppo_max_token_len_per_gpu: int = 16384\n ppo_infer_max_token_len_per_gpu: int = 16384\n clip_ratio: float = 0.2\n clip_ratio_low: float = 0.2\n clip_ratio_high: float = 0.2\n freeze_vision_tower: bool = False\n policy_loss: PolicyLossConfig = field(default_factory=PolicyLossConfig)\n clip_ratio_c: float = 3.0\n loss_agg_mode: str = \"token-mean\"\n loss_scale_factor: Optional[int] = None\n entropy_coeff: float = 0\n tau_pos: float = 1.0\n tau_neg: float = 1.05\n calculate_entropy: bool = False\n use_kl_loss: bool = False\n # Whether to enable PrefixGrouper-based shared-prefix forward\n use_prefix_grouper: bool = False\n use_torch_compile: bool = True\n kl_loss_coef: float = 0.001\n kl_loss_type: str = \"low_var_kl\"\n ppo_epochs: int = 1\n shuffle: bool = False\n data_loader_seed: int = 1\n checkpoint: CheckpointConfig = field(default_factory=CheckpointConfig)\n optim: OptimizerConfig = field(default_factory=OptimizerConfig)\n use_fused_kernels: bool = False\n profiler: ProfilerConfig = field(default_factory=ProfilerConfig)\n engine: BaseConfig = field(default_factory=BaseConfig)\n rollout_n: int = MISSING # must be override by sampling config\n model_config: HFModelConfig = field(default_factory=BaseConfig)\n router_replay: RouterReplayConfig = field(default_factory=RouterReplayConfig)\n\n # Store global batch info for loss aggregation:\n # dp_size: data parallel size\n # batch_num_tokens: number of valid tokens in global batch\n # global_batch_size: global batch size\n global_batch_info: dict = field(default_factory=dict)\n\n def __post_init__(self):\n \"\"\"Validate actor configuration parameters.\"\"\"\n assert self.strategy != MISSING\n assert self.rollout_n != MISSING\n if not self.use_dynamic_bsz:\n if self.ppo_micro_batch_size is not None and self.ppo_micro_batch_size_per_gpu is not None:\n raise ValueError(\n \"[actor] You have set both 'actor.ppo_micro_batch_size' AND 'actor.ppo_micro_batch_size_per_gpu'. \"\n \"Please remove 'actor.ppo_micro_batch_size' because only '*_ppo_micro_batch_size_per_gpu' is \"\n \"supported (the former is deprecated).\"\n )\n else:\n assert not (self.ppo_micro_batch_size is None and self.ppo_micro_batch_size_per_gpu is None), (\n \"[actor] Please set at least one of 'actor.ppo_micro_batch_size' or \"\n \"'actor.ppo_micro_batch_size_per_gpu' if use_dynamic_bsz is not enabled.\"\n )\n\n valid_loss_agg_modes = [\n \"token-mean\",\n \"seq-mean-token-sum\",\n \"seq-mean-token-mean\",\n \"seq-mean-token-sum-norm\",\n ]\n if self.loss_agg_mode not in valid_loss_agg_modes:\n raise ValueError(f\"Invalid loss_agg_mode: {self.loss_agg_mode}\")\n\n def validate(self, n_gpus: int, train_batch_size: int, model_config: dict = None):\n \"\"\"Validate actor configuration with runtime parameters.\"\"\"\n if not self.use_dynamic_bsz:\n if train_batch_size < self.ppo_mini_batch_size:\n raise ValueError(\n f\"train_batch_size ({train_batch_size}) must be >= \"\n f\"actor.ppo_mini_batch_size ({self.ppo_mini_batch_size})\"\n )\n\n sp_size = getattr(self, \"ulysses_sequence_parallel_size\", 1)\n if self.ppo_micro_batch_size is not None:\n if self.ppo_mini_batch_size % self.ppo_micro_batch_size != 0:\n raise ValueError(\n f\"ppo_mini_batch_size ({self.ppo_mini_batch_size}) must be divisible by \"\n f\"ppo_micro_batch_size ({self.ppo_micro_batch_size})\"\n )\n if self.ppo_micro_batch_size * sp_size < n_gpus:\n raise ValueError(\n f\"ppo_micro_batch_size ({self.ppo_micro_batch_size}) * \"\n f\"ulysses_sequence_parallel_size ({sp_size}) must be >= n_gpus ({n_gpus})\"\n )\n\n @staticmethod\n def _check_mutually_exclusive(mbs, mbs_per_gpu, name: str):\n \"\"\"Validate mutually exclusive micro batch size configuration options.\"\"\"\n param = \"ppo_micro_batch_size\"\n param_per_gpu = f\"{param}_per_gpu\"\n\n if mbs is None and mbs_per_gpu is None:\n raise ValueError(f\"[{name}] Please set at least one of '{name}.{param}' or '{name}.{param_per_gpu}'.\")\n\n if mbs is not None and mbs_per_gpu is not None:\n raise ValueError(\n f\"[{name}] You have set both '{name}.{param}' AND '{name}.{param_per_gpu}'. Please remove \"\n f\"'{name}.{param}' because only '*_{param_per_gpu}' is supported (the former is deprecated).\"\n )\n\n\n@dataclass\nclass McoreActorConfig(ActorConfig):\n \"\"\"Configuration for Megatron actor models.\n\n The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config.\n\n Args:\n strategy (str): Training strategy set to 'megatron' for Megatron parallelism.\n load_weight (bool): Whether to load model weights from checkpoint.\n megatron (dict[str, Any]): Configuration for Megatron parallelism settings.\n profile (dict[str, Any]): Configuration for profiling settings.\n \"\"\"\n\n strategy: str = \"megatron\"\n load_weight: bool = True\n megatron: McoreEngineConfig = field(default_factory=McoreEngineConfig)\n profile: dict[str, Any] = field(default_factory=dict)\n use_rollout_log_probs: bool = False\n\n def __post_init__(self):\n \"\"\"Validate FSDP actor configuration parameters.\"\"\"\n super().__post_init__()\n self.engine = self.megatron\n\n\n@dataclass\nclass FSDPActorConfig(ActorConfig):\n \"\"\"Configuration for FSDP actor models.\n\n The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config.\n\n Args:\n strategy (str): Training strategy set to 'fsdp' for Fully Sharded Data Parallel.\n grad_clip (float): Gradient clipping threshold.\n ulysses_sequence_parallel_size (int): [DEPRECATED] Ulysses sequence parallel size for long sequences.\n entropy_from_logits_with_chunking (bool): Whether to compute entropy from logits\n with chunking for memory efficiency.\n entropy_checkpointing (bool): Whether to use gradient checkpointing for entropy computation.\n fsdp_config (dict[str, Any]): Configuration for FSDP settings.\n use_remove_padding (bool): Whether to remove padding tokens in inputs during training\n \"\"\"\n\n strategy: str = \"fsdp\"\n grad_clip: float = 1.0\n ulysses_sequence_parallel_size: int = 1\n entropy_from_logits_with_chunking: bool = False\n entropy_checkpointing: bool = False\n fsdp_config: FSDPEngineConfig = field(default_factory=FSDPEngineConfig)\n use_remove_padding: bool = False\n use_rollout_log_probs: bool = False\n calculate_sum_pi_squared: bool = False\n sum_pi_squared_checkpointing: bool = False\n qat: QATConfig = field(default_factory=QATConfig)\n\n def __post_init__(self):\n \"\"\"Validate FSDP actor configuration parameters.\"\"\"\n super().__post_init__()\n self.engine = self.fsdp_config\n\n # backward compatibility\n if self.ulysses_sequence_parallel_size > 1:\n self.fsdp_config.ulysses_sequence_parallel_size = self.ulysses_sequence_parallel_size\n\n def validate(self, n_gpus: int, train_batch_size: int, model_config: dict = None):\n \"\"\"Validate FSDP actor configuration with runtime parameters.\"\"\"\n super().validate(n_gpus, train_batch_size, model_config)\n\n if self.strategy in {\"fsdp\", \"fsdp2\"} and self.ulysses_sequence_parallel_size > 1:\n if model_config and not model_config.get(\"use_remove_padding\", False):\n raise ValueError(\n \"When using sequence parallelism for actor/ref policy, you must enable `use_remove_padding`.\"\n )\n\n\n@dataclass\nclass VeOmniActorConfig(ActorConfig):\n \"\"\"Configuration for VeOmni actor models.\n\n The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config.\n\n Args:\n strategy (str): Training strategy set to 'veomni' for VeOmni parallelism.\n veomni (dict[str, Any]): Configuration for VeOmni settings.\n use_remove_padding (bool): Whether to remove padding tokens in inputs during training\n \"\"\"\n\n strategy: str = \"veomni\"\n veomni: VeOmniEngineConfig = field(default_factory=VeOmniEngineConfig)\n use_remove_padding: bool = False\n use_rollout_log_probs: bool = False\n\n def __post_init__(self):\n \"\"\"Validate VeOmni actor configuration parameters.\"\"\"\n super().__post_init__()\n self.engine = self.veomni\n"} {"file_name": "verl__workers__critic__dp_critic.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nImplement a multiprocess PPOCritic\n\"\"\"\n\nimport logging\nimport os\n\nimport torch\nimport torch.distributed\nfrom torch import nn, optim\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP\n\nfrom verl import DataProto\nfrom verl.trainer.ppo import core_algos\nfrom verl.utils.attention_utils import index_first_axis, pad_input, rearrange, unpad_input\nfrom verl.utils.device import get_device_id, get_device_name\nfrom verl.utils.fsdp_utils import FSDPModule, fsdp2_clip_grad_norm_\nfrom verl.utils.profiler import GPUMemoryLogger\nfrom verl.utils.py_functional import append_to_dict\nfrom verl.utils.seqlen_balancing import prepare_dynamic_batch, restore_dynamic_batch\nfrom verl.utils.torch_functional import masked_mean\nfrom verl.utils.ulysses import gather_outputs_and_unpad, ulysses_pad_and_slice_inputs\nfrom verl.workers.critic import BasePPOCritic\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(os.getenv(\"VERL_LOGGING_LEVEL\", \"WARN\"))\n\n\nclass DataParallelPPOCritic(BasePPOCritic):\n def __init__(self, config, critic_module: nn.Module, critic_optimizer: optim.Optimizer):\n super().__init__(config=config)\n self.critic_module = critic_module\n self.critic_optimizer = critic_optimizer\n self.use_remove_padding = self.config.model.get(\"use_remove_padding\", False)\n print(f\"Critic use_remove_padding={self.use_remove_padding}\")\n\n self.ulysses_sequence_parallel_size = self.config.get(\"ulysses_sequence_parallel_size\", 1)\n self.device_name = get_device_name()\n\n def _forward_micro_batch(self, micro_batch):\n response_length = micro_batch[\"responses\"].size(-1)\n multi_modal_inputs = {}\n if \"multi_modal_inputs\" in micro_batch.keys():\n from verl.utils.model import extract_multi_modal_inputs\n\n multi_modal_inputs = extract_multi_modal_inputs(micro_batch[\"multi_modal_inputs\"])\n\n with torch.autocast(device_type=self.device_name, dtype=torch.bfloat16):\n input_ids = micro_batch[\"input_ids\"]\n batch, seqlen = input_ids.shape\n attention_mask = micro_batch[\"attention_mask\"]\n position_ids = micro_batch[\"position_ids\"]\n if position_ids.dim() == 3: # qwen2vl mrope\n position_ids = position_ids.transpose(0, 1)\n\n if self.use_remove_padding:\n input_ids_rmpad, indices, *_ = unpad_input(\n input_ids.unsqueeze(-1), attention_mask\n ) # input_ids_rmpad (total_nnz, ...)\n input_ids_rmpad = input_ids_rmpad.transpose(0, 1) # (1, total_nnz)\n\n # unpad the position_ids to align the rotary\n if position_ids.dim() == 3:\n position_ids_rmpad = (\n index_first_axis(rearrange(position_ids, \"c b s ... -> (b s) c ...\"), indices)\n .transpose(0, 1)\n .unsqueeze(1)\n ) # (4, bsz, seqlen) -> (4, 1, bsz * seqlen)\n else:\n position_ids_rmpad = index_first_axis(\n rearrange(position_ids.unsqueeze(-1), \"b s ... -> (b s) ...\"), indices\n ).transpose(0, 1)\n\n # pad and slice the inputs if sp > 1\n if self.ulysses_sequence_parallel_size > 1:\n input_ids_rmpad, position_ids_rmpad, pad_size = ulysses_pad_and_slice_inputs(\n input_ids_rmpad, position_ids_rmpad, sp_size=self.ulysses_sequence_parallel_size\n )\n\n # only pass input_ids and position_ids to enable flash_attn_varlen\n output = self.critic_module(\n input_ids=input_ids_rmpad,\n attention_mask=None,\n position_ids=position_ids_rmpad,\n **multi_modal_inputs,\n use_cache=False,\n ) # prevent model thinks we are generating\n\n if hasattr(self.critic_module, \"v_head\"):\n # For trl.AutoModelForCausalLMWithValueHead\n values_rmpad = output[2].squeeze(0).unsqueeze(-1)\n else:\n values_rmpad = output.logits\n values_rmpad = values_rmpad.squeeze(0) # (total_nnz)\n\n # gather output if sp > 1\n if self.ulysses_sequence_parallel_size > 1:\n values_rmpad = gather_outputs_and_unpad(\n values_rmpad, gather_dim=0, unpad_dim=0, padding_size=pad_size\n )\n\n # pad it back\n values = pad_input(values_rmpad, indices=indices, batch=batch, seqlen=seqlen).squeeze(-1)\n values = values[:, -response_length - 1 : -1]\n else:\n output = self.critic_module(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n **multi_modal_inputs,\n use_cache=False,\n ) # prevent model thinks we are generating\n if hasattr(self.critic_module, \"v_head\"):\n # For trl.AutoModelForCausalLMWithValueHead\n values = output[2]\n else:\n values = output.logits\n values = values[:, -response_length - 1 : -1].squeeze(-1)\n return values\n\n def _optimizer_step(self):\n assert self.config.grad_clip is not None\n\n if isinstance(self.critic_module, FSDP):\n grad_norm = self.critic_module.clip_grad_norm_(self.config.grad_clip)\n elif isinstance(self.critic_module, FSDPModule):\n grad_norm = fsdp2_clip_grad_norm_(self.critic_module.parameters(), max_norm=self.config.grad_clip)\n else:\n grad_norm = torch.nn.utils.clip_grad_norm_(self.critic_module.parameters(), max_norm=self.config.grad_clip)\n\n # if grad_norm is not finite, skip the update\n if not torch.isfinite(grad_norm):\n print(f\"WARN: grad_norm is not finite: {grad_norm}\")\n self.critic_optimizer.zero_grad()\n else:\n self.critic_optimizer.step()\n return grad_norm\n\n @GPUMemoryLogger(role=\"dp critic\", logger=logger)\n def compute_values(self, data: DataProto) -> torch.Tensor:\n self.critic_module.eval()\n micro_batch_size = data.meta_info[\"micro_batch_size\"]\n use_dynamic_bsz = data.meta_info[\"use_dynamic_bsz\"]\n has_multi_modal_inputs = \"multi_modal_inputs\" in data.non_tensor_batch.keys()\n select_keys = (\n [\"responses\", \"input_ids\", \"response_mask\", \"attention_mask\", \"position_ids\"]\n if \"response_mask\" in data.batch\n else [\"responses\", \"input_ids\", \"attention_mask\", \"position_ids\"]\n )\n non_tensor_select_keys = [\"multi_modal_inputs\"] if has_multi_modal_inputs else []\n\n data = data.select(batch_keys=select_keys, non_tensor_batch_keys=non_tensor_select_keys)\n\n if use_dynamic_bsz:\n max_token_len = data.meta_info[\"max_token_len\"] * self.ulysses_sequence_parallel_size\n micro_batches, batch_idx_list = prepare_dynamic_batch(data, max_token_len=max_token_len)\n else:\n micro_batches = data.split(micro_batch_size)\n\n values_lst = []\n for micro_batch in micro_batches:\n micro_batch = micro_batch.to(get_device_id())\n model_inputs = {**micro_batch.batch, **micro_batch.non_tensor_batch}\n with torch.no_grad():\n values = self._forward_micro_batch(model_inputs)\n values_lst.append(values)\n values = torch.concat(values_lst, dim=0)\n\n if use_dynamic_bsz:\n values = restore_dynamic_batch(values, batch_idx_list)\n\n if \"response_mask\" in data.batch:\n response_mask = data.batch[\"response_mask\"]\n response_mask = response_mask.to(values.device)\n values = values * response_mask # Only action tokens have values\n return values\n\n @GPUMemoryLogger(role=\"dp critic\", logger=logger)\n def update_critic(self, data: DataProto):\n # make sure we are in training mode\n self.critic_module.train()\n metrics = {\n \"critic/vf_loss\": 0.0,\n }\n\n select_keys = [\"input_ids\", \"responses\", \"response_mask\", \"attention_mask\", \"position_ids\", \"values\", \"returns\"]\n has_multi_modal_inputs = \"multi_modal_inputs\" in data.non_tensor_batch.keys()\n non_tensor_select_keys = [\"multi_modal_inputs\"] if has_multi_modal_inputs else []\n\n data = data.select(batch_keys=select_keys, non_tensor_batch_keys=non_tensor_select_keys)\n\n # Split to make minibatch iterator for updating the actor\n # See PPO paper for details. https://arxiv.org/abs/1707.06347\n mini_batches = data.split(self.config.ppo_mini_batch_size)\n\n for _ in range(self.config.ppo_epochs):\n for batch_idx, mini_batch in enumerate(mini_batches):\n if self.config.use_dynamic_bsz:\n max_token_len = self.config.ppo_max_token_len_per_gpu * self.ulysses_sequence_parallel_size\n micro_batches, _ = prepare_dynamic_batch(mini_batch, max_token_len=max_token_len)\n else:\n self.gradient_accumulation = (\n self.config.ppo_mini_batch_size // self.config.ppo_micro_batch_size_per_gpu\n )\n micro_batches = mini_batch.split(self.config.ppo_micro_batch_size_per_gpu)\n\n self.critic_optimizer.zero_grad()\n\n for micro_batch in micro_batches:\n micro_batch = micro_batch.to(get_device_id())\n micro_batch_metrics = {}\n model_inputs = {**micro_batch.batch, **micro_batch.non_tensor_batch}\n response_mask = model_inputs[\"response_mask\"]\n values = model_inputs[\"values\"]\n returns = model_inputs[\"returns\"]\n\n vpreds = self._forward_micro_batch(model_inputs)\n vf_loss, vf_clipfrac = core_algos.compute_value_loss(\n vpreds=vpreds,\n values=values,\n returns=returns,\n response_mask=response_mask,\n cliprange_value=self.config.cliprange_value,\n loss_agg_mode=self.config.loss_agg_mode,\n )\n if self.config.use_dynamic_bsz:\n # relative to the dynamic bsz\n loss_scale_factor = response_mask.shape[0] / self.config.ppo_mini_batch_size\n loss = vf_loss * loss_scale_factor\n else:\n loss_scale_factor = 1 / self.gradient_accumulation\n loss = vf_loss * loss_scale_factor\n\n loss.backward()\n\n micro_batch_metrics.update(\n {\n \"critic/vf_clipfrac\": vf_clipfrac.detach().item(),\n \"critic/vpred_mean\": masked_mean(vpreds, response_mask).detach().item(),\n }\n )\n\n metrics[\"critic/vf_loss\"] += vf_loss.detach().item() * loss_scale_factor\n append_to_dict(metrics, micro_batch_metrics)\n\n grad_norm = self._optimizer_step()\n mini_batch_metrics = {\"critic/grad_norm\": grad_norm.detach().item()}\n append_to_dict(metrics, mini_batch_metrics)\n self.critic_optimizer.zero_grad()\n return metrics\n"} {"file_name": "verl__workers__rollout__sglang_rollout__http_server_engine.py", "text": "# Copyright 2025 z.ai\n# Copyright 2023-2024 SGLang Team\n# Copyright 2025 ModelBest Inc. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# This file is adapted from multiple sources:\n# 1. THUDM/slime project\n# Original source: https://github.com/THUDM/slime/blob/main/slime/backends/sglang_utils/http_server_engine.py\n# Copyright 2025 z.ai\n# Licensed under the Apache License, Version 2.0\n# 2. SGLang project\n# Original source: https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/entrypoints/http_server_engine.py\n# Copyright 2023-2024 SGLang Team\n# Licensed under the Apache License, Version 2.0\n#\n# Modifications made by z.ai and ModelBest Inc. include but are not limited to:\n# - Enhanced error handling and retry logic\n# - Added async support with connection pooling\n# - Extended functionality for distributed weight updates\n# - Improved logging and monitoring capabilities\n# - Additional configuration options and optimizations\n\n\"\"\"HTTP Server Engine Adapter for SGLang.\n\nThis module provides HTTP-based adapters for SGLang engines, allowing communication\nwith SGLang servers through HTTP requests instead of direct engine calls.\n\nClasses:\n HttpServerAdapter: Synchronous HTTP adapter for SGLang engines\n AsyncHttpServerAdapter: Asynchronous HTTP adapter for SGLang engines\n\nFunctions:\n launch_server_process: Launch and initialize an SGLang HTTP server process\n\"\"\"\n\nimport asyncio\nimport logging\nimport multiprocessing\nimport os\nimport time\nfrom contextlib import asynccontextmanager\nfrom typing import Any, Callable, Optional\n\nimport aiohttp\nimport requests\nfrom sglang.srt.entrypoints.EngineBase import EngineBase\nfrom sglang.srt.entrypoints.http_server import launch_server\nfrom sglang.srt.managers.io_struct import (\n UpdateWeightsFromTensorReqInput,\n)\nfrom sglang.srt.server_args import ServerArgs\nfrom sglang.srt.utils import kill_process_tree\n\n# Configure logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(os.getenv(\"VERL_LOGGING_LEVEL\", \"WARN\"))\n\n# Default configuration constants\nDEFAULT_TIMEOUT = 60.0\nDEFAULT_MAX_ATTEMPTS = 3\nDEFAULT_RETRY_DELAY = 2.0\nDEFAULT_MAX_CONNECTIONS = 2000\nDEFAULT_MAX_WAIT_TIME = 300.0\n\n\ndef _read_response(response: requests.Response):\n if response.status_code == 204 or not response.content:\n return {}\n try:\n return response.json()\n except ValueError:\n return {\n \"content_type\": response.headers.get(\"Content-Type\", \"\"),\n \"text\": response.text,\n }\n\n\nasync def _read_async_response(resp: aiohttp.ClientResponse) -> dict[str, Any]:\n if resp.status == 204 or (resp.content_length == 0):\n return {}\n\n try:\n return await resp.json(content_type=None)\n except Exception:\n try:\n text = await resp.text()\n except Exception:\n return {}\n return {\n \"content_type\": (resp.headers.get(\"Content-Type\") or \"\"),\n \"text\": text,\n }\n\n\ndef launch_server_process(\n server_args: ServerArgs,\n timeout: float = DEFAULT_TIMEOUT,\n max_wait_time=DEFAULT_MAX_WAIT_TIME,\n first_rank_in_node=False,\n) -> multiprocessing.Process:\n \"\"\"Launch an SGLang HTTP server process and wait for it to be ready.\n\n This function starts a new process running an SGLang HTTP server, then waits\n for the server to become ready by polling its health endpoints. It ensures\n the server is fully operational before returning.\n\n Args:\n server_args (ServerArgs): Server configuration arguments including host, port, and other settings\n timeout (float, optional): Timeout for individual HTTP requests during health checks.\n Defaults to DEFAULT_TIMEOUT.\n\n Returns:\n multiprocessing.Process: The launched multiprocessing.Process instance\n\n Raises:\n RuntimeError: If the server process terminates unexpectedly during startup or cache flush\n TimeoutError: If server fails to become ready within reasonable time (300 seconds)\n requests.RequestException: If health check requests fail repeatedly\n\n Note:\n This function will return immediately for non-master nodes (node_rank != 0),\n but the process will still be started and returned.\n This is for consistency; except for the process obtained by node_rank = 0,\n other processes have no actual effect.\n \"\"\"\n p = multiprocessing.Process(target=launch_server, args=(server_args,))\n if server_args.node_rank != 0 or not first_rank_in_node:\n logger.info(f\"Server process started with PID {p.pid} for node rank {server_args.node_rank}\", flush=True)\n return p\n\n p.start()\n\n base_url = server_args.url()\n headers = {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Authorization\": f\"Bearer {server_args.api_key}\",\n }\n\n # Health check with overall timeout\n start_time = time.time()\n\n with requests.Session() as session:\n while time.time() - start_time < max_wait_time:\n if not p.is_alive():\n raise RuntimeError(\"Server process terminated unexpectedly during startup\")\n\n try:\n if server_args.is_embedding:\n response = session.get(f\"{base_url}/health\", headers=headers, timeout=timeout)\n else:\n response = session.get(f\"{base_url}/health_generate\", headers=headers, timeout=timeout)\n if response.status_code == 200:\n break\n except requests.RequestException as e:\n logger.debug(f\"Health check failed: {e}\")\n\n time.sleep(2)\n else:\n p.terminate()\n logger.error(f\"Server in {base_url} failed to become healthy within timeout period\")\n raise TimeoutError(\"Server failed to become healthy within timeout period\")\n\n # Ensure cache is ready\n while time.time() - start_time < max_wait_time:\n if not p.is_alive():\n raise RuntimeError(\"Server process terminated unexpectedly during cache flush\")\n\n try:\n response = session.get(f\"{base_url}/flush_cache\", headers=headers, timeout=timeout)\n if response.status_code == 200:\n break\n except requests.RequestException as e:\n logger.debug(f\"Cache flush check failed: {e}\")\n\n time.sleep(2)\n else:\n p.terminate()\n raise TimeoutError(\"Server cache flush failed within timeout period\")\n\n return p\n\n\nclass HttpServerAdapter(EngineBase):\n \"\"\"HTTP-based adapter for SGLang engines.\n\n This adapter allows interaction with SGLang engines through HTTP requests\n instead of direct engine calls. It launches an HTTP server process and\n provides methods to communicate with it via REST API calls.\n\n You can use this class to launch a server from a HttpServerAdapter instance.\n We recommend using this class only when you need to use http server.\n Otherwise, you can use Engine directly.\n\n Attributes:\n router_ip (Optional[str]): IP address of the router for worker registration\n router_port (Optional[int]): Port of the router for worker registration\n server_args (ServerArgs): Server configuration arguments\n node_rank (int): Rank of this node in distributed setup\n process (multiprocessing.Process): The launched server process\n timeout (float): HTTP request timeout in seconds\n max_attempts (int): Maximum number of attempts for requests\n retry_delay (float): Base delay between retries in seconds\n \"\"\"\n\n def __init__(\n self,\n router_ip: Optional[str] = None,\n router_port: Optional[int] = None,\n timeout: float = DEFAULT_TIMEOUT,\n max_attempts: int = DEFAULT_MAX_ATTEMPTS,\n retry_delay: float = DEFAULT_RETRY_DELAY,\n first_rank_in_node: bool = False,\n max_start_wait_time: float = DEFAULT_MAX_WAIT_TIME,\n launch_server: bool = True,\n **kwargs: Any,\n ) -> None:\n \"\"\"Initialize the HTTP server engine adapter.\n\n Args:\n router_ip (Optional[str], optional): IP address of router for worker registration.\n Defaults to None.\n router_port (Optional[int], optional): Port of router for worker registration.\n Defaults to None.\n timeout (float, optional): HTTP request timeout in seconds.\n Defaults to DEFAULT_TIMEOUT.\n max_attempts (int, optional): Maximum number of retry attempts for failed requests.\n Defaults to DEFAULT_MAX_ATTEMPTS.\n retry_delay (float, optional): Base delay between retries in seconds.\n Defaults to DEFAULT_RETRY_DELAY.\n launch_server (bool, optional): Whether to launch the server process.\n Defaults to True.\n **kwargs (Any): Additional arguments passed to ServerArgs\n\n Note:\n TODO: @ChangyiYang Enable SGLang router for this http server engine\n If both router_ip and router_port are provided and this is the master node\n (node_rank == 0), the adapter will automatically register with the router.\n \"\"\"\n self.router_ip: Optional[str] = router_ip\n self.router_port: Optional[int] = router_port\n self.timeout: float = timeout\n self.max_attempts: int = max_attempts\n self.retry_delay: float = retry_delay\n self.server_args: ServerArgs = ServerArgs(**kwargs)\n self.node_rank: int = self.server_args.node_rank\n self.max_start_wait_time: float = max_start_wait_time\n\n logger.info(\n f\"Launch HttpServerAdapter at: {self.server_args.host}:{self.server_args.port} with {first_rank_in_node}\"\n )\n if launch_server:\n self.process: multiprocessing.Process = launch_server_process(\n self.server_args, self.timeout, self.max_start_wait_time, first_rank_in_node\n )\n\n if self.node_rank == 0 and self.router_ip and self.router_port:\n self._register_with_router()\n\n def _register_with_router(self) -> None:\n \"\"\"Register worker with router with error handling.\n\n This method attempts to register the current worker with a router service.\n If registration fails, it logs an error but does not raise an exception,\n allowing the server to continue operating without router integration.\n\n Raises:\n Does not raise exceptions - all errors are logged and handled gracefully.\n \"\"\"\n try:\n url = f\"http://{self.router_ip}:{self.router_port}/add_worker\"\n params = {\"url\": f\"http://{self.server_args.host}:{self.server_args.port}\"}\n response = requests.post(url, params=params, timeout=self.timeout)\n response.raise_for_status()\n logger.info(\"Successfully registered with router\")\n except Exception as e:\n logger.error(f\"Failed to register with router: {e}\")\n # Don't raise here - server can still work without router\n\n def _make_request(\n self,\n endpoint: str,\n payload: Optional[dict[str, Any]] = None,\n method: str = \"POST\",\n timeout: float = DEFAULT_TIMEOUT,\n only_master: bool = True,\n ) -> dict[str, Any]:\n \"\"\"Make a HTTP request with retry logic and consistent error handling.\n\n Args:\n endpoint (str): The API endpoint to call (without leading slash)\n payload (Optional[Dict[str, Any]], optional): The JSON payload to send.\n Defaults to empty dict if None.\n method (str, optional): HTTP method to use. Defaults to \"POST\".\n\n Returns:\n Dict[str, Any]: The JSON response from the server\n\n Raises:\n requests.HTTPError: If the HTTP request fails with a client/server error\n RuntimeError: If all retry attempts are exhausted\n\n Note:\n - For non-master nodes (node_rank != 0), returns empty dict immediately\n - Uses exponential backoff for retries\n - Logs warnings for timeout and connection errors, errors for HTTP errors\n \"\"\"\n if only_master and self.node_rank != 0:\n return {}\n\n url = f\"http://{self.server_args.host}:{self.server_args.port}/{endpoint}\"\n\n for attempt in range(self.max_attempts):\n try:\n if method.upper() == \"GET\":\n response = requests.get(url, timeout=self.timeout)\n else:\n response = requests.post(url, json=payload or {}, timeout=self.timeout)\n\n response.raise_for_status()\n return _read_response(response)\n\n except requests.exceptions.Timeout:\n logger.warning(f\"Request to {endpoint} timed out (attempt {attempt + 1})\")\n except requests.exceptions.ConnectionError:\n logger.warning(f\"Connection error for {endpoint} (attempt {attempt + 1})\")\n except requests.exceptions.HTTPError as e:\n logger.error(f\"HTTP error for {endpoint}: {e}\")\n raise\n except Exception as e:\n logger.error(f\"Unexpected error for {endpoint}: {e}\")\n if attempt == self.max_attempts - 1:\n raise\n\n if attempt < self.max_attempts - 1:\n time.sleep(self.retry_delay * (2**attempt))\n\n raise RuntimeError(f\"Failed to complete request to {endpoint} after {self.max_attempts} attempts\")\n\n def update_weights_from_tensor(self, req: UpdateWeightsFromTensorReqInput) -> dict[str, Any]:\n \"\"\"Update model weights from tensor data.\n\n The HTTP server will only post meta data, and the real weights will be\n copied directly from GPUs.\n\n Args:\n serialized_named_tensors (List[str]): List of serialized tensor data\n load_format (Optional[str], optional): Format specification for loading weights.\n Defaults to None.\n flush_cache (bool, optional): Whether to flush cache after updating weights.\n Defaults to False.\n\n Returns:\n Dict[str, Any]: Server response containing update status\n\n Note:\n The model should be on GPUs rather than CPU for this functionality to work properly.\n If you encounter issues, ensure your model is loaded on GPU devices rather than CPU.\n \"\"\"\n import base64\n\n named_tensors = req.serialized_named_tensors\n load_format = req.load_format\n flush_cache = req.flush_cache\n\n if named_tensors:\n serialized_named_tensors = [\n base64.b64encode(named_tensor).decode(\"utf-8\") for named_tensor in named_tensors\n ]\n else:\n serialized_named_tensors = []\n\n return self._make_request(\n \"update_weights_from_tensor\",\n {\n \"serialized_named_tensors\": serialized_named_tensors,\n \"load_format\": load_format,\n \"flush_cache\": flush_cache,\n },\n )\n\n def shutdown(self) -> None:\n \"\"\"Shutdown the HTTP server and clean up resources.\n\n This method performs the following cleanup operations:\n 1. Unregisters the worker from the router (if configured)\n 2. Terminates the server process tree\n\n All operations are performed with error handling to ensure graceful shutdown\n even if individual steps fail.\n\n Note:\n This method should be called when the adapter is no longer needed\n to ensure proper cleanup of resources and processes.\n \"\"\"\n # Unregister from router\n if self.router_ip and self.router_port:\n try:\n url = f\"http://{self.router_ip}:{self.router_port}/remove_worker\"\n params = {\"url\": f\"http://{self.server_args.host}:{self.server_args.port}\"}\n requests.post(url, params=params, timeout=5.0) # Short timeout for shutdown\n logger.info(\"Successfully unregistered from router\")\n except Exception as e:\n logger.warning(f\"Failed to unregister from router: {e}\")\n\n # Kill server process\n if hasattr(self, \"process\") and self.process is not None:\n try:\n kill_process_tree(self.process.pid)\n logger.info(\"Server process terminated\")\n except Exception as e:\n logger.error(f\"Failed to terminate server process: {e}\")\n\n def generate(\n self,\n prompt: Optional[str] = None,\n sampling_params: Optional[dict[str, Any]] = None,\n input_ids: Optional[list[int]] = None,\n image_data: Optional[Any] = None,\n return_logprob: bool = False,\n logprob_start_len: Optional[int] = None,\n top_logprobs_num: Optional[int] = None,\n token_ids_logprob: Optional[list[int]] = None,\n lora_path: Optional[str] = None,\n custom_logit_processor: Optional[Callable] = None,\n ) -> dict[str, Any]:\n \"\"\"Generate text using the SGLang server.\n\n Args:\n prompt (Optional[str], optional): Text prompt for generation. Defaults to None.\n sampling_params (Optional[Dict[str, Any]], optional): Parameters controlling\n text generation sampling. Defaults to None.\n input_ids (Optional[List[int]], optional): Alternative to prompt, direct token IDs input.\n Defaults to None.\n image_data (Optional[Any], optional): Image data for multimodal generation.\n Defaults to None.\n return_logprob (bool, optional): Whether to return log probabilities.\n Defaults to False.\n logprob_start_len (Optional[int], optional): Starting length for log probability calculation.\n Defaults to None.\n top_logprobs_num (Optional[int], optional): Number of top log probabilities to return.\n Defaults to None.\n token_ids_logprob (Optional[List[int]], optional): Specific token IDs for\n log probability calculation. Defaults to None.\n lora_path (Optional[str], optional): Path to LoRA adapter weights. Defaults to None.\n custom_logit_processor (Optional[Callable], optional): Custom logit processing function.\n Defaults to None.\n\n Returns:\n Dict[str, Any]: Generated text and associated metadata from the server\n\n Note:\n Either prompt or input_ids should be provided, but not both.\n The response format depends on the server configuration and parameters.\n \"\"\"\n payload = {\n \"text\": prompt,\n \"sampling_params\": sampling_params,\n \"input_ids\": input_ids,\n \"image_data\": image_data,\n \"return_logprob\": return_logprob,\n \"logprob_start_len\": logprob_start_len,\n \"top_logprobs_num\": top_logprobs_num,\n \"token_ids_logprob\": token_ids_logprob,\n \"lora_path\": lora_path,\n \"custom_logit_processor\": custom_logit_processor,\n }\n # Filter out None values\n payload = {k: v for k, v in payload.items() if v is not None}\n\n return self._make_request(\"generate\", payload, only_master=False)\n\n def reward_score(\n self,\n prompt: Optional[str] = None,\n input_ids: Optional[list[int]] = None,\n image_data: Optional[Any] = None,\n lora_path: Optional[str] = None,\n ) -> dict[str, Any]:\n assert self.server_args.is_embedding, \"Score is only supported for embedding models\"\n payload = {\n \"text\": prompt,\n \"input_ids\": input_ids,\n \"image_data\": image_data,\n \"lora_path\": lora_path,\n }\n # Filter out None values\n payload = {k: v for k, v in payload.items() if v is not None}\n\n return self._make_request(\"classify\", payload, only_master=False)\n\n def flush_cache(self) -> dict[str, Any]:\n \"\"\"Flush the cache of the server.\n\n This method repeatedly attempts to flush the server cache until successful.\n The flush operation will not return status 200 when there are pending requests.\n\n Returns:\n Dict[str, Any]: Server response indicating cache flush status.\n For non-master nodes, returns empty dict.\n\n Note:\n Uses retry logic with limited attempts (max_attempts * 2) to avoid infinite loops.\n Each retry includes a delay to allow pending requests to complete.\n \"\"\"\n if self.node_rank != 0:\n return {}\n\n # Use retry logic with limited attempts to avoid infinite loops\n for attempt in range(self.max_attempts * 2): # Allow more retries for cache flush\n try:\n response = requests.get(\n f\"http://{self.server_args.host}:{self.server_args.port}/flush_cache\", timeout=self.timeout\n )\n if response.status_code == 200:\n return _read_response(response)\n except Exception as e:\n logger.warning(f\"Error flushing cache (attempt {attempt + 1}): {e}\")\n\n time.sleep(self.retry_delay)\n\n logger.error(\"Failed to flush cache after maximum attempts\")\n return {}\n\n def release_memory_occupation(self, tags: Optional[list[str]] = None) -> dict[str, Any]:\n \"\"\"Release GPU memory occupation temporarily.\n\n Args:\n tags (Optional[List[str]], optional): List of tags to specify which memory to release.\n If None, releases all memory. Defaults to None. [\"weights\", \"kv_cache\"]\n\n Returns:\n Dict[str, Any]: Server response indicating memory release status\n \"\"\"\n return self._make_request(\"release_memory_occupation\", {\"tags\": tags})\n\n def resume_memory_occupation(self, tags: Optional[list[str]] = None) -> dict[str, Any]:\n \"\"\"Resume GPU memory occupation.\n\n Args:\n tags (Optional[List[str]], optional): List of tags to specify which memory to resume.\n If None, resumes all memory. Defaults to None. [\"weights\", \"kv_cache\"]\n\n Returns:\n Dict[str, Any]: Server response indicating memory resume status\n \"\"\"\n return self._make_request(\"resume_memory_occupation\", {\"tags\": tags})\n\n def abort_request(self, rid: str = \"\", abort_all: bool = False) -> dict[str, Any]:\n \"\"\"Abort a request.\n\n Args:\n rid (str): The ID of the request to abort\n abort_all (bool, optional): Whether to abort all requests. Defaults to False.\n\n Returns:\n Dict[str, Any]: Server response indicating abort status\n \"\"\"\n return self._make_request(\"abort_request\", {\"rid\": rid, \"abort_all\": abort_all})\n\n\nclass AsyncHttpServerAdapter(HttpServerAdapter):\n \"\"\"Asynchronous HTTP-based adapter for SGLang engines.\n\n This class inherits from HttpServerAdapter and adds async capabilities\n for non-blocking HTTP requests to the SGLang server. It provides the same\n functionality as the synchronous version but with async/await support.\n\n The async adapter is useful when you need to make multiple concurrent requests\n or integrate with async frameworks. It uses aiohttp for efficient async HTTP\n communication and maintains connection pooling for better performance.\n\n Attributes:\n max_connections (int): Maximum number of connections in the connection pool\n \"\"\"\n\n def __init__(\n self,\n router_ip: Optional[str] = None,\n router_port: Optional[int] = None,\n timeout: float = DEFAULT_TIMEOUT,\n max_attempts: int = DEFAULT_MAX_ATTEMPTS,\n retry_delay: float = DEFAULT_RETRY_DELAY,\n max_connections: int = DEFAULT_MAX_CONNECTIONS,\n first_rank_in_node: bool = False,\n launch_server: bool = True,\n **kwargs: Any,\n ) -> None:\n \"\"\"Initialize the async HTTP server engine adapter.\n\n Args:\n router_ip (Optional[str], optional): IP address of router for worker registration.\n Defaults to None.\n router_port (Optional[int], optional): Port of router for worker registration.\n Defaults to None.\n timeout (float, optional): HTTP request timeout in seconds.\n Defaults to DEFAULT_TIMEOUT.\n max_attempts (int, optional): Maximum number of retry attempts for failed requests.\n Defaults to DEFAULT_MAX_ATTEMPTS.\n retry_delay (float, optional): Base delay between retries in seconds.\n Defaults to DEFAULT_RETRY_DELAY.\n max_connections (int, optional): Maximum number of connections in the connection pool.\n Defaults to DEFAULT_MAX_CONNECTIONS.\n launch_server (bool, optional): Whether to launch the server process.\n Defaults to True.\n **kwargs (Any): Additional arguments passed to ServerArgs\n \"\"\"\n super().__init__(\n router_ip,\n router_port,\n timeout,\n max_attempts,\n retry_delay,\n first_rank_in_node,\n launch_server=launch_server,\n **kwargs,\n )\n self.max_connections: int = max_connections\n\n @asynccontextmanager\n async def _get_session(self) -> aiohttp.ClientSession:\n \"\"\"Context manager for safe session access with proper connection pooling.\n\n Yields:\n aiohttp.ClientSession: Session instance for making HTTP requests\n\n Note:\n This method creates a new session for each request to avoid resource competition\n while still maintaining proper connection pooling through the shared connector.\n \"\"\"\n # Create a new session for each request to avoid resource competition\n connector = aiohttp.TCPConnector(\n limit=self.max_connections,\n limit_per_host=self.max_connections // 4,\n ttl_dns_cache=300,\n use_dns_cache=True,\n )\n timeout = aiohttp.ClientTimeout(total=self.timeout)\n session = aiohttp.ClientSession(connector=connector, timeout=timeout)\n\n try:\n yield session\n finally:\n # Always close the session to free up resources\n if not session.closed:\n await session.close()\n\n async def _make_async_request(\n self,\n endpoint: str,\n payload: Optional[dict[str, Any]] = None,\n method: str = \"POST\",\n timeout: float = DEFAULT_TIMEOUT,\n only_master: bool = True,\n ) -> dict[str, Any]:\n \"\"\"Make an async HTTP request with retry logic and consistent error handling.\n\n Args:\n endpoint (str): The API endpoint to call (without leading slash)\n payload (Optional[Dict[str, Any]], optional): The JSON payload to send.\n Defaults to empty dict if None.\n method (str, optional): HTTP method to use. Defaults to \"POST\".\n\n Returns:\n Dict[str, Any]: The JSON response from the server\n\n Raises:\n aiohttp.ClientResponseError: If the HTTP request fails with a client/server error\n RuntimeError: If all retry attempts are exhausted\n\n Note:\n - For non-master nodes (node_rank != 0), returns empty dict immediately\n - Uses exponential backoff for retries\n - Logs warnings for timeout and connection errors, errors for HTTP errors\n \"\"\"\n if only_master and self.node_rank != 0:\n return {}\n\n url = f\"http://{self.server_args.host}:{self.server_args.port}/{endpoint}\"\n\n for attempt in range(self.max_attempts):\n try:\n async with self._get_session() as session:\n if method.upper() == \"GET\":\n async with session.get(url, timeout=timeout) as response:\n response.raise_for_status()\n return await _read_async_response(response)\n else:\n async with session.post(url, json=payload or {}, timeout=timeout) as response:\n response.raise_for_status()\n return await _read_async_response(response)\n\n except asyncio.TimeoutError:\n logger.warning(f\"Async request to {endpoint} timed out (attempt {attempt + 1})\")\n except aiohttp.ClientConnectorError:\n logger.warning(f\"Connection error for {endpoint} (attempt {attempt + 1})\")\n except aiohttp.ClientResponseError as e:\n logger.error(f\"HTTP error for {endpoint}: {e}\")\n raise\n except Exception as e:\n logger.error(f\"Unexpected error for {endpoint}: {e}\")\n if attempt == self.max_attempts - 1:\n raise\n\n if attempt < self.max_attempts - 1:\n await asyncio.sleep(self.retry_delay * (2**attempt))\n\n raise RuntimeError(f\"Failed to complete async request to {endpoint} after {self.max_attempts} attempts\")\n\n async def release_memory_occupation(self, tags: Optional[list[str]] = None) -> dict[str, Any]:\n \"\"\"Release GPU memory occupation temporarily (async version).\n\n Args:\n tags (Optional[List[str]], optional): List of tags to specify which memory to release.\n If None, releases all memory. Defaults to None. [\"weights\", \"kv_cache\"]\n\n Returns:\n Dict[str, Any]: Server response indicating memory release status\n \"\"\"\n return await self._make_async_request(\"release_memory_occupation\", {\"tags\": tags})\n\n async def resume_memory_occupation(self, tags: Optional[list[str]] = None) -> dict[str, Any]:\n \"\"\"Resume GPU memory occupation (async version).\n\n Similar to AsyncEngine, this method handles first-time weight reloading\n by calling release_memory_occupation if needed.\n\n Args:\n tags (Optional[List[str]], optional): List of tags to specify which memory to resume.\n If None, resumes all memory. Defaults to None. [\"weights\", \"kv_cache\"]\n\n Returns:\n Dict[str, Any]: Server response indicating memory resume status\n \"\"\"\n return await self._make_async_request(\"resume_memory_occupation\", {\"tags\": tags})\n\n async def update_weights_from_tensor(\n self,\n req: UpdateWeightsFromTensorReqInput,\n ) -> dict[str, Any]:\n \"\"\"Update model weights from tensor data asynchronously.\n\n Args:\n serialized_named_tensors (List[str]): List of serialized tensor data\n load_format (Optional[str], optional): Format specification for loading weights.\n Defaults to None.\n flush_cache (bool, optional): Whether to flush cache after updating weights.\n Defaults to True.\n\n Returns:\n Dict[str, Any]: Server response containing update status\n \"\"\"\n import base64\n\n named_tensors = req.serialized_named_tensors\n load_format = req.load_format\n flush_cache = req.flush_cache\n\n serialized_named_tensors = [base64.b64encode(named_tensor).decode(\"utf-8\") for named_tensor in named_tensors]\n return await self._make_async_request(\n \"update_weights_from_tensor\",\n {\n \"serialized_named_tensors\": serialized_named_tensors,\n \"load_format\": load_format,\n \"flush_cache\": flush_cache,\n },\n )\n\n async def flush_cache(self) -> dict[str, Any]:\n \"\"\"Flush the cache of the server asynchronously.\n\n Similar to the sync version, this method retries until the cache\n is successfully flushed. It uses async sleep between retries.\n\n Returns:\n Dict[str, Any]: Server response indicating cache flush status.\n For non-master nodes, returns empty dict.\n\n Note:\n Uses retry logic with limited attempts (max_attempts * 4) to avoid infinite loops.\n Each retry includes an async delay to allow pending requests to complete.\n \"\"\"\n if self.node_rank != 0:\n return {}\n\n # Use retry logic with limited attempts to avoid infinite loops\n for attempt in range(self.max_attempts * 4): # Allow more retries for cache flush\n try:\n async with self._get_session() as session:\n url = f\"http://{self.server_args.host}:{self.server_args.port}/flush_cache\"\n async with session.get(url) as response:\n if response.status == 200:\n return await _read_async_response(response)\n except Exception as e:\n logger.warning(f\"Error flushing cache (attempt {attempt + 1}): {e}\")\n\n await asyncio.sleep(self.retry_delay)\n\n logger.error(\"Failed to flush cache after maximum attempts\")\n return {}\n\n async def generate(\n self,\n prompt: Optional[str] = None,\n sampling_params: Optional[dict[str, Any]] = None,\n input_ids: Optional[list[int]] = None,\n image_data: Optional[Any] = None,\n return_logprob: bool = False,\n logprob_start_len: Optional[int] = None,\n top_logprobs_num: Optional[int] = None,\n token_ids_logprob: Optional[list[int]] = None,\n lora_path: Optional[str] = None,\n custom_logit_processor: Optional[Callable] = None,\n ) -> dict[str, Any]:\n \"\"\"Generate text using the SGLang server asynchronously.\"\"\"\n logger.info(\"generate() started\")\n\n payload = {\n \"text\": prompt,\n \"sampling_params\": sampling_params,\n \"input_ids\": input_ids,\n \"image_data\": image_data,\n \"return_logprob\": return_logprob,\n \"logprob_start_len\": logprob_start_len,\n \"top_logprobs_num\": top_logprobs_num,\n \"token_ids_logprob\": token_ids_logprob,\n \"lora_path\": lora_path,\n \"custom_logit_processor\": custom_logit_processor,\n }\n\n # Filter out None values\n payload = {k: v for k, v in payload.items() if v is not None}\n\n # Send request\n response = await self._make_async_request(\"generate\", payload, timeout=self.timeout, only_master=False)\n\n return response\n\n async def async_generate(\n self,\n prompt: Optional[str] = None,\n sampling_params: Optional[dict[str, Any]] = None,\n input_ids: Optional[list[int]] = None,\n image_data: Optional[Any] = None,\n return_logprob: bool = False,\n logprob_start_len: Optional[int] = None,\n top_logprobs_num: Optional[int] = None,\n token_ids_logprob: Optional[list[int]] = None,\n lora_path: Optional[str] = None,\n custom_logit_processor: Optional[Callable] = None,\n ) -> dict[str, Any]:\n \"\"\"Async generate method that mirrors AsyncEngine.async_generate interface.\n\n This method provides compatibility with AsyncEngine's async_generate method\n by forwarding the call to the generate method. It ensures API consistency\n between direct engine usage and HTTP-based engine usage.\n\n Args:\n prompt (Optional[str], optional): Text prompt for generation. Defaults to None.\n sampling_params (Optional[Dict[str, Any]], optional): Parameters controlling\n text generation sampling. Defaults to None.\n input_ids (Optional[List[int]], optional): Alternative to prompt, direct token IDs input.\n Defaults to None.\n image_data (Optional[Any], optional): Image data for multimodal generation.\n Defaults to None.\n return_logprob (bool, optional): Whether to return log probabilities.\n Defaults to False.\n logprob_start_len (Optional[int], optional): Starting length for log probability calculation.\n Defaults to None.\n top_logprobs_num (Optional[int], optional): Number of top log probabilities to return.\n Defaults to None.\n token_ids_logprob (Optional[List[int]], optional): Specific token IDs for\n log probability calculation. Defaults to None.\n lora_path (Optional[str], optional): Path to LoRA adapter weights. Defaults to None.\n custom_logit_processor (Optional[Callable], optional): Custom logit processing function.\n Defaults to None.\n\n Returns:\n Dict[str, Any]: Generated text and associated metadata from the server\n\n Note:\n This method is provided for API compatibility with AsyncEngine.\n It forwards all calls to the generate method.\n \"\"\"\n return await self.generate(\n prompt=prompt,\n sampling_params=sampling_params,\n input_ids=input_ids,\n image_data=image_data,\n return_logprob=return_logprob,\n logprob_start_len=logprob_start_len,\n top_logprobs_num=top_logprobs_num,\n token_ids_logprob=token_ids_logprob,\n lora_path=lora_path,\n custom_logit_processor=custom_logit_processor,\n )\n\n async def reward_score(\n self,\n prompt: Optional[str] = None,\n input_ids: Optional[list[int]] = None,\n image_data: Optional[Any] = None,\n lora_path: Optional[str] = None,\n ) -> dict[str, Any]:\n logger.info(\"reward_score() started\")\n payload = {\n \"text\": prompt,\n \"input_ids\": input_ids,\n \"image_data\": image_data,\n \"lora_path\": lora_path,\n }\n # Filter out None values\n payload = {k: v for k, v in payload.items() if v is not None}\n\n # Send request\n response = await self._make_async_request(\"classify\", payload, timeout=self.timeout, only_master=False)\n\n return response\n\n async def async_reward_score(\n self,\n prompt: Optional[str] = None,\n input_ids: Optional[list[int]] = None,\n image_data: Optional[Any] = None,\n lora_path: Optional[str] = None,\n ) -> dict[str, Any]:\n return await self.reward_score(\n prompt=prompt,\n input_ids=input_ids,\n image_data=image_data,\n lora_path=lora_path,\n )\n\n async def abort_request(self, rid: str = \"\", abort_all: bool = False) -> dict[str, Any]:\n \"\"\"Abort a request asynchronously.\n\n Args:\n rid (str): The ID of the request to abort\n abort_all (bool, optional): Whether to abort all requests. Defaults to False.\n\n Returns:\n Dict[str, Any]: Server response indicating abort status\n \"\"\"\n return await self._make_async_request(\"abort_request\", {\"rid\": rid, \"abort_all\": abort_all})\n"} {"file_name": "verl__workers__rollout__tokenizer.py", "text": "# Copyright 2024 Bytedance Ltd. and/or its affiliates\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThe base tokenizer class, required for any hybrid engine based rollout or inference with vLLM.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\nimport torch\n\n__all__ = [\"HybridEngineBaseTokenizer\"]\n\n\nclass HybridEngineBaseTokenizer(ABC):\n \"\"\"the tokenizer property and function name should align with HF's to meet vllm requirement\"\"\"\n\n @property\n @abstractmethod\n def vocab_size(self):\n \"\"\"\n `int`: Size of the base vocabulary (without the added tokens).\n \"\"\"\n pass\n\n @property\n @abstractmethod\n def pad_token_id(self):\n \"\"\"\n `Optional[int]`: Id of the padding token in the vocabulary. Returns `None` if the token has not been set.\n \"\"\"\n pass\n\n @property\n @abstractmethod\n def eos_token_id(self):\n \"\"\"\n `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been\n set.\n \"\"\"\n pass\n\n @property\n @abstractmethod\n def all_special_ids(self) -> list[int]:\n \"\"\"\n `List[int]`: List the ids of the special tokens(`''`, `''`, etc.) mapped to class attributes.\n \"\"\"\n pass\n\n @property\n @abstractmethod\n def all_special_tokens(self) -> list[str]:\n \"\"\"\n `List[str]`: A list of the unique special tokens (`''`, `''`, ..., etc.).\n\n Convert tokens of `tokenizers.AddedToken` type to string.\n \"\"\"\n pass\n\n @abstractmethod\n def encode(self, text):\n \"\"\"\n Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary.\n\n Args:\n text (`str`, `List[str]` or `List[int]`):\n The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the\n `tokenize` method) or a list of integers.\n\n text_pair (`str`, `List[str]` or `List[int]`, *optional*):\n Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using\n the `tokenize` method) or a list of integers.\n \"\"\"\n pass\n\n @abstractmethod\n def decode(\n self,\n token_ids: int | list[int] | np.ndarray | torch.Tensor,\n skip_special_tokens: bool = False,\n clean_up_tokenization_spaces: bool = None,\n **kwargs,\n ) -> str:\n \"\"\"\n Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\n tokens and clean up tokenization spaces.\n\n Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\n Args:\n token_ids (`Union[int, List[int], np.ndarray, torch.Tensor]`):\n List of tokenized input ids. Can be obtained using the `__call__` method.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n clean_up_tokenization_spaces (`bool`, *optional*):\n Whether or not to clean up the tokenization spaces. If `None`, will default to\n `self.clean_up_tokenization_spaces`.\n kwargs (additional keyword arguments, *optional*):\n Will be passed to the underlying model specific decode method.\n\n Returns:\n `str`: The decoded sentence.\n \"\"\"\n pass\n\n @abstractmethod\n def convert_ids_to_tokens(self, ids: int | list[int], skip_special_tokens: bool = False) -> str | list[str]:\n \"\"\"\n Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and\n added tokens.\n\n Args:\n ids (`int` or `List[int]`):\n The token id (or token ids) to convert to tokens.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n\n Returns:\n `str` or `List[str]`: The decoded token(s).\n \"\"\"\n pass\n\n @abstractmethod\n def get_added_vocab(self) -> dict[str, int]:\n \"\"\"\n Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from\n the fast call because for now we always add the tokens even if they are already in the vocabulary. This is\n something we should change.\n\n Returns:\n `Dict[str, int]`: The added tokens.\n \"\"\"\n pass\n\n @abstractmethod\n def convert_tokens_to_string(self, tokens: list[str]) -> str:\n \"\"\"\n Converts a sequence of tokens in a single string. The most simple way to do it is `\" \".join(tokens)` but we\n often want to remove sub-word tokenization artifacts at the same time.\n\n Args:\n tokens (`List[str]`): The token to join in a string.\n\n Returns:\n `str`: The joined tokens.\n \"\"\"\n pass\n\n @property\n def is_fast(self):\n return False\n"}