before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
actor_rollout_ref.rollout.top_k=${top_k}
actor_rollout_ref.rollout.val_kwargs.temperature=${temperature}
actor_rollout_ref.rollout.val_kwargs.top_p=${val_top_p}
actor_rollout_ref.rollout.val_kwargs.top_k=${top_k}
actor_rollout_ref.rollout.val_kwargs.do_sample=True
actor_rollout_ref.rollout.val_k... | `trainer.device` param will be automatically determined on Ascend NPU, maybe this param is not required? | actor_rollout_ref.rollout.val_kwargs.temperature=${temperature}
actor_rollout_ref.rollout.val_kwargs.top_p=${val_top_p}
actor_rollout_ref.rollout.val_kwargs.top_k=${top_k}
actor_rollout_ref.rollout.val_kwargs.do_sample=True
actor_rollout_ref.rollout.val_kwargs.n=1
actor_rollout_ref.rollout.enabl... | @@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+set -xeuo pipefail
+
+# Test script for one_step_off_policy E2E regression testing
+# This script runs one_step_off_policy with FSDP2
+# to ensure the asynchronous training mechanism works correctly
+
+NUM_GPUS=${NUM_GPUS:-8}
+ACTOR_STRATEGY="fsdp2"
+
+# Download model if not exi... | tests/special_npu/run_one_step_off_policy.sh | 26 | Shell | 0.5 | question | 104 | 51 | 51 | false | [ci] test: add one step off policy test cases for npu | 4,485 | volcengine/verl | 16,907 | Python | FightingZhen | ji-huazhong |
trainer.project_name='verl-test'
trainer.experiment_name="${exp_name}"
trainer.val_before_train=True
trainer.test_freq=-1
trainer.save_freq=-1
trainer.total_epochs=2
trainer.total_training_steps=2
trainer.resume_mode=disable
trainer.nnodes=1
trainer.n_gpus_per_node=${n_npus_train... | Now `ACTOR_STRATEGY` is only used for some prints, can we set this param with `$ACTOR_STRATEGY`? | trainer.experiment_name="${exp_name}"
trainer.val_before_train=True
trainer.test_freq=-1
trainer.save_freq=-1
trainer.total_epochs=2
trainer.total_training_steps=2
trainer.resume_mode=disable
trainer.nnodes=1
trainer.n_gpus_per_node=${n_npus_training}
rollout.nnodes=1
rollout... | @@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+set -xeuo pipefail
+
+# Test script for one_step_off_policy E2E regression testing
+# This script runs one_step_off_policy with FSDP2
+# to ensure the asynchronous training mechanism works correctly
+
+NUM_GPUS=${NUM_GPUS:-8}
+ACTOR_STRATEGY="fsdp2"
+
+# Download model if not exi... | tests/special_npu/run_one_step_off_policy.sh | 26 | Shell | 0.429 | question | 97 | 42 | 41 | false | [ci] test: add one step off policy test cases for npu | 4,485 | volcengine/verl | 16,907 | Python | FightingZhen | ji-huazhong |
#!/usr/bin/env bash
set -xeuo pipefail
# Test script for one_step_off_policy E2E regression testing
# This script runs one_step_off_policy with FSDP2
# to ensure the asynchronous training mechanism works correctly
NUM_GPUS=${NUM_GPUS:-8}
ACTOR_STRATEGY="fsdp2"
# Download model if not exists
MODEL_ID=${MODEL_ID:-Qwen... | looks not necessary, can we remove it ? | #!/usr/bin/env bash
set -xeuo pipefail
# Test script for one_step_off_policy E2E regression testing
# This script runs one_step_off_policy with FSDP2
# to ensure the asynchronous training mechanism works correctly
ACTOR_STRATEGY="fsdp2"
# Download model if not exists
MODEL_ID=${MODEL_ID:-Qwen/Qwen2.5-0.5B-Instruct}
... | @@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+set -xeuo pipefail
+
+# Test script for one_step_off_policy E2E regression testing
+# This script runs one_step_off_policy with FSDP2
+# to ensure the asynchronous training mechanism works correctly
+
+NUM_GPUS=${NUM_GPUS:-8} | tests/special_npu/run_one_step_off_policy.sh | 8 | Shell | 0.143 | question | 39 | 33 | 33 | false | [ci] test: add one step off policy test cases for npu | 4,485 | volcengine/verl | 16,907 | Python | FightingZhen | ji-huazhong |
train_sampler: Optional[Sampler] = None,
device_name=None,
):
# assert get_torch_device().is_available(), 'cuda must be available on driver'
self.tokenizer = tokenizer
self.processor = processor
self.config = config
self.reward_fn = reward_fn
self.val... | Please throw a deprecated warning when train.device is not None. | device_name=None,
):
# assert get_torch_device().is_available(), 'cuda must be available on driver'
self.tokenizer = tokenizer
self.processor = processor
self.config = config
self.reward_fn = reward_fn
self.val_reward_fn = val_reward_fn
self.hybrid_e... | @@ -371,7 +372,7 @@ def __init__(
self.ray_worker_group_cls = ray_worker_group_cls
self.validation_generations_logger = ValidationGenerationsLogger()
self.async_rollout_mode = False
- self.device_name = device_name if device_name else self.config.trainer.device
+ self.device_nam... | recipe/spin/spin_trainer.py | 26 | Python | 0.214 | suggestion | 64 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
sglang_spec = importlib.util.find_spec("sglang")
except ModuleNotFoundError:
sglang_spec = None
return sglang_spec is not None
@cache
def is_nvtx_available():
try:
nvtx_spec = importlib.util.find_spec("nvtx")
except ModuleNotFoundError:
nvtx_spec = None
return nvtx_... | ```suggestion
def is_torch_npu_available():
``` | sglang_spec = importlib.util.find_spec("sglang")
except ModuleNotFoundError:
sglang_spec = None
return sglang_spec is not None
@cache
def is_nvtx_available():
try:
nvtx_spec = importlib.util.find_spec("nvtx")
except ModuleNotFoundError:
nvtx_spec = None
return nvtx_... | @@ -69,6 +69,15 @@ def is_trl_available():
return trl_spec is not None
+@cache
+def is_torch_npu_pkg_available(): | verl/utils/import_utils.py | 26 | Python | 0.429 | suggestion | 47 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
from tensordict import NonTensorData
from torch.utils.data import Dataset, Sampler
from torchdata.stateful_dataloader import StatefulDataLoader
from tqdm import tqdm
from verl import DataProto
from verl.experimental.dataset.sampler import AbstractCurriculumSampler
from verl.protocol import pad_dataproto_to_divisor, un... | ```suggestion
from verl.utils.import_utils import is_torch_npu_available
``` | from tensordict import NonTensorData
from torch.utils.data import Dataset, Sampler
from torchdata.stateful_dataloader import StatefulDataLoader
from tqdm import tqdm
from verl import DataProto
from verl.experimental.dataset.sampler import AbstractCurriculumSampler
from verl.protocol import pad_dataproto_to_divisor, un... | @@ -57,6 +57,7 @@
from verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path, should_save_ckpt_esi
from verl.utils.config import omega_conf_to_dataclass
from verl.utils.debug import marked_timer
+from verl.utils.import_utils import is_torch_npu_pkg_available | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.571 | suggestion | 76 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
"""
# Store the tokenizer for text processing
self.tokenizer = tokenizer
self.processor = processor
self.config = config
self.reward_fn = reward_fn
self.val_reward_fn = val_reward_fn
self.hybrid_engine = config.actor_rollout_ref.hybrid_engine
ass... | ```suggestion
if is_torch_npu_available():
``` |
# Store the tokenizer for text processing
self.tokenizer = tokenizer
self.processor = processor
self.config = config
self.reward_fn = reward_fn
self.val_reward_fn = val_reward_fn
self.hybrid_engine = config.actor_rollout_ref.hybrid_engine
assert self.hyb... | @@ -332,6 +333,10 @@ def __init__(
self.use_critic = need_critic(self.config)
self.ray_worker_group_cls = ray_worker_group_cls
self.device_name = device_name if device_name else self.config.trainer.device
+
+ if is_torch_npu_pkg_available(): | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.571 | suggestion | 54 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | ```suggestion
from verl.utils.import_utils import is_torch_npu_available
``` | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | @@ -20,6 +20,8 @@
import os
+from verl.utils.import_utils import is_torch_npu_pkg_available | verl/trainer/fsdp_sft_trainer.py | 23 | Python | 0.571 | suggestion | 76 | 48 | 48 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
# Set sequence parallel size
self.config.ulysses_sequence_parallel_size = getattr(self.config, "ulysses_sequence_parallel_size", 1)
self.use_remove_padding = getattr(self.config, "use_remove_padding", False)
if self.device_mesh.get_rank() == 0:
print(f"Using sequence parallel... | ```suggestion
self.device_name = self.config.trainer.device if not is_torch_npu_available() else "npu"
``` |
# normalize dp size
self._normalize_config_bsz()
# Set sequence parallel size
self.config.ulysses_sequence_parallel_size = getattr(self.config, "ulysses_sequence_parallel_size", 1)
self.use_remove_padding = getattr(self.config, "use_remove_padding", False)
if self.devic... | @@ -132,7 +134,8 @@ def __init__(
if self.device_mesh.get_rank() == 0:
print(self.config)
- self.device_name = self.config.trainer.device
+
+ self.device_name = self.config.trainer.device if not is_torch_npu_pkg_available() else "npu" | verl/trainer/fsdp_sft_trainer.py | 26 | Python | 0.714 | suggestion | 114 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | ```suggestion
from verl.utils.import_utils import is_torch_npu_available
``` | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | @@ -18,6 +18,8 @@
from tensordict.tensorclass import NonTensorData
+from verl.utils.import_utils import is_torch_npu_pkg_available | verl/trainer/sft_trainer.py | 21 | Python | 0.571 | suggestion | 76 | 46 | 46 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
class SFTTrainer:
def __init__(
self,
config,
):
self.config = config
self.rank = torch.distributed.get_rank()
self._build_config()
self._build_dataset()
self._build_engine()
self._build_dataloader()
self._init_engine()
self... | ```suggestion
self.device_name = self.config.trainer.device if not is_torch_npu_available() else "npu"
``` | class SFTTrainer:
def __init__(
self,
config,
):
self.config = config
self.rank = torch.distributed.get_rank()
self._build_config()
self._build_dataset()
self._build_engine()
self._build_dataloader()
self._init_engine()
self._... | @@ -68,7 +70,7 @@ def __init__(
# Initialize resume-related variables
self.resume_global_step = self.ckpt_handler.load_checkpoint()
- self.device_name = self.config.trainer.device
+ self.device_name = self.config.trainer.device if not is_torch_npu_pkg_available() else "npu" | verl/trainer/sft_trainer.py | 26 | Python | 0.714 | suggestion | 114 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | ```suggestion
from verl.utils.import_utils import is_torch_npu_available
``` | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | @@ -18,6 +18,8 @@
from tensordict.tensorclass import NonTensorData
+from verl.utils.import_utils import is_torch_npu_pkg_available | verl/trainer/sft_trainer_ray.py | 21 | Python | 0.571 | suggestion | 76 | 46 | 46 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
from verl.utils.logger import log_with_rank
from verl.utils.tracking import Tracking
from verl.workers.engine_workers import TrainingWorker
logger = logging.getLogger(__file__)
logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN"))
class SFTTrainer:
def __init__(
self,
config,
):
... | ```suggestion
self.device_name = self.config.trainer.device if not is_torch_npu_available() else "npu"
``` | from verl.workers.engine_workers import TrainingWorker
logger = logging.getLogger(__file__)
logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN"))
class SFTTrainer:
def __init__(
self,
config,
):
self.config = config
self._build_config()
self._build_dataset()
... | @@ -62,7 +64,7 @@ def __init__(
# Initialize resume-related variables
self.resume_global_step = self.ckpt_handler.load_checkpoint()
- self.device_name = self.config.trainer.device
+ self.device_name = self.config.trainer.device if not is_torch_npu_pkg_available() else "npu" | verl/trainer/sft_trainer_ray.py | 26 | Python | 0.714 | suggestion | 114 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
**kwargs,
) -> None:
"""Initialize a RayWorkerGroup.
Args:
resource_pool: Resource pool for worker allocation
ray_cls_with_init: Class with initialization arguments for workers
bin_pack: Whether to use strict bin packing for resource allocation
... | ```suggestion
self.device_name = kwargs.get("device_name", "cuda") if not is_torch_npu_available() else "npu"
``` | ) -> None:
"""Initialize a RayWorkerGroup.
Args:
resource_pool: Resource pool for worker allocation
ray_cls_with_init: Class with initialization arguments for workers
bin_pack: Whether to use strict bin packing for resource allocation
name_prefix: Pre... | @@ -372,7 +373,7 @@ def __init__(
# if a WorkerGroup is spawned from Colocate WorkerGroup, this indicates which sub-class is binded to
# this WorkerGroup.
self.sub_cls_name = ""
- self.device_name = kwargs.get("device_name", "cuda")
+ self.device_name = kwargs.get("device_name",... | verl/single_controller/ray/base.py | 26 | Python | 0.714 | suggestion | 121 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Li... | ```suggestion
from verl.utils.import_utils import is_torch_npu_available
``` | # You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Li... | @@ -27,6 +27,7 @@
from verl.protocol import DataProto, _padding_size_key
from verl.single_controller.base import ClassWithInitArgs, ResourcePool, Worker, WorkerGroup
from verl.single_controller.base.decorator import MAGIC_ATTR, Dispatch
+from verl.utils.import_utils import is_torch_npu_pkg_available | verl/single_controller/ray/base.py | 26 | Python | 0.571 | suggestion | 76 | 51 | 51 | false | [hardware] feat: Auto set device_name to npu for Ascend NPU | 4,489 | volcengine/verl | 16,907 | Python | ji-huazhong | FightingZhen |
# This is a special dispatch mode for vllm ExternalRayDistributedExecutor
Dispatch.register("DIRECT_ROLLOUT_METHOD")
class Execute(DynamicEnum):
"""Enum class defining different execution modes for distributed computation.
These modes control how a function should be executed across different ranks
... | Please move this function to verl/utils/tensordict_utils and add a test. Thanks! | Dispatch.register("DIRECT_ROLLOUT_METHOD")
class Execute(DynamicEnum):
"""Enum class defining different execution modes for distributed computation.
These modes control how a function should be executed across different ranks
in a distributed system.
"""
_registry = {}
_next_value = 0
... | @@ -72,20 +72,48 @@ def init_predefined_execute_mode():
init_predefined_execute_mode()
+def _chunk_tensordict(td: TensorDict, chunks: int) -> list[TensorDict]: | verl/single_controller/base/decorator.py | 26 | Python | 0.286 | refactor | 80 | 51 | 51 | false | [trainer] fix: model engine vlm multi_modal_inputs to NonTensorStack | 4,492 | volcengine/verl | 16,907 | Python | vermouth1992 | wuxibin89 |
# Compute importance sampling ratio: π_θ / π_θ_old
negative_approx_kl = log_prob - old_log_prob
# Clamp for numerical stability
negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0)
ratio = torch.exp(negative_approx_kl)
ppo_kl = verl_F.masked_mean(-negative_approx_kl, respons... | `**config.global_batch_info` should be passed into agg_loss, see other policy loss implementation. | loss_agg_mode: str = "token-mean",
config: Optional[DictConfig | ActorConfig] = None,
rollout_is_weights: torch.Tensor | None = None,
) -> tuple[torch.Tensor, dict[str, Any]]:
"""
Compute the clipped policy objective and related metrics for CISPO.
See https://arxiv.org/pdf/2506.13585 for more d... | @@ -1380,6 +1380,65 @@ def compute_policy_loss_geo_mean(
return pg_loss, pg_metrics
+@register_policy_loss("cispo")
+def compute_policy_loss_cispo(
+ old_log_prob: torch.Tensor,
+ log_prob: torch.Tensor,
+ advantages: torch.Tensor,
+ response_mask: torch.Tensor,
+ loss_agg_mode: str = "token-mea... | verl/trainer/ppo/core_algos.py | 26 | Python | 0.429 | performance | 98 | 51 | 51 | false | [algo] feat: add cispo | 4,508 | volcengine/verl | 16,907 | Python | wuxibin89 | xvlincaigou |
for _ in range(self.config.ppo_epochs):
for batch_idx, mini_batch in enumerate(mini_batches):
if self.config.use_dynamic_bsz:
max_token_len = self.config.ppo_max_token_len_per_gpu * self.ulysses_sequence_parallel_size
micro_batches, _ = prepare... | dp_size = world_size/ulysses_sequence_parallel_size in FSDP | for _ in range(self.config.ppo_epochs):
for batch_idx, mini_batch in enumerate(mini_batches):
if self.config.use_dynamic_bsz:
max_token_len = self.config.ppo_max_token_len_per_gpu * self.ulysses_sequence_parallel_size
micro_batches, _ = prepare... | @@ -456,6 +456,10 @@ def update_policy(self, data: DataProto):
entropy_coeff = self.config.entropy_coeff
loss_agg_mode = self.config.loss_agg_mode
+ # Populate global_batch_info for loss aggregation
+ self.config.global_batch_info["dp_siz... | verl/workers/actor/dp_actor.py | 26 | Python | 0.214 | suggestion | 59 | 51 | 51 | false | [algo] fix: Add seq mean mask denominator option | 4,510 | volcengine/verl | 16,907 | Python | ISEEKYAN | szrlee |
if post_process_fn is None:
pass
# metrics["logits"] = output
else:
stats = post_process_fn(output, data)
metrics.update(stats)
if not calculate_entropy:
return torch.tenso... | should be `megatron.core.parallel_state.get_data_parallel_world_size()` | if post_process_fn is None:
pass
# metrics["logits"] = output
else:
stats = post_process_fn(output, data)
metrics.update(stats)
if not calculate_entropy:
return torch.tenso... | @@ -480,6 +480,10 @@ def loss_func(output, data, meta_info):
entropy_coeff = self.config.entropy_coeff
loss_agg_mode = self.config.loss_agg_mode
+ # Populate global_batch_info for loss aggregation
+ self.config.global_batch_info["dp_size"] = data.get("dp... | verl/workers/actor/megatron_actor.py | 26 | Python | 0.429 | suggestion | 71 | 51 | 51 | false | [algo] fix: Add seq mean mask denominator option | 4,510 | volcengine/verl | 16,907 | Python | ISEEKYAN | szrlee |
def agg_loss(
loss_mat: torch.Tensor,
loss_mask: torch.Tensor,
loss_agg_mode: str,
dp_size: int = 1,
batch_num_tokens: Optional[int] = None,
global_batch_size: Optional[int] = None,
loss_scale_factor: Optional[int] = None,
):
"""
Aggregate the loss across global batch to ensure the l... | is it possible that we remove the dp_size from the algorithm loss function? | def agg_loss(
loss_mat: torch.Tensor,
loss_mask: torch.Tensor,
loss_agg_mode: str,
dp_size: int = 1,
batch_num_tokens: Optional[int] = None,
global_batch_size: Optional[int] = None,
loss_scale_factor: Optional[int] = None,
):
"""
Aggregate the loss across global batch to ensure the l... | @@ -785,11 +785,14 @@ def agg_loss(
- FSDP: the loss is directly used for backward.
- Megatron: the loss should be scaled by `num_microbatches` and `cp_size` for pp schedule.
+ # TODO: Consider the numerical stability?
+
Args:
loss_mat: micro batch loss matrix, (bs, response_length)
... | verl/trainer/ppo/core_algos.py | 26 | Python | 0.286 | question | 75 | 51 | 51 | false | [algo] fix: Add seq mean mask denominator option | 4,510 | volcengine/verl | 16,907 | Python | ISEEKYAN | szrlee |
config=self.config,
rollout_is_weights=rollout_is_weights,
)
micro_batch_metrics.update(pg_metrics)
# Skip if using pure rollout correction mode (metrics already in pg_metrics)
rollout_log_pr... | `global_batch_info` should only be passed in new model engine: https://github.com/volcengine/verl/blob/main/verl/workers/engine_workers.py
For legacy engine `fsdp_workers.py` and `megatron_workers.py`, we should not pass it. |
# Skip if using pure rollout correction mode (metrics already in pg_metrics)
rollout_log_prob = model_inputs.get("rollout_log_probs", None)
if loss_mode != "rollout_correction" and rollout_log_prob is not None:
# Compute metrics using ... | @@ -516,7 +520,12 @@ def update_policy(self, data: DataProto):
policy_loss = pg_loss
if calculate_entropy and entropy is not None:
- entropy_agg = agg_loss(loss_mat=entropy, loss_mask=response_mask, loss_agg_mode=loss_agg_mode)
+ ... | verl/workers/actor/dp_actor.py | 26 | Python | 0.643 | performance | 227 | 51 | 51 | false | [algo] fix: Add seq mean mask denominator option | 4,510 | volcengine/verl | 16,907 | Python | wuxibin89 | szrlee |
loss_agg_mode: method to aggregate the loss matrix into a scalar
dp_size: data parallel size
batch_num_tokens: number of valid tokens in global batch
global_batch_size: global batch size
loss_scale_factor: scale factor for "seq-mean-token-sum-norm" mode. If None, uses loss_mask.s... | The `seq_denominator` is not right, should be `global_batch_size / dp_size` | # TODO: Consider the numerical stability?
Args:
loss_mat: micro batch loss matrix, (bs, response_length)
loss_mask: micro batch loss mask, (bs, response_length)
loss_agg_mode: method to aggregate the loss matrix into a scalar
dp_size: data parallel size. When appling manual aggr... | @@ -799,30 +805,39 @@ def agg_loss(
loss: `a scalar torch.Tensor`
aggregated loss
"""
+ # NOTE: `masked_sum` is more robust than multiplying the `mask`.
if loss_agg_mode == "token-mean":
if batch_num_tokens is None:
batch_num_tokens = loss_mask.sum()
los... | verl/trainer/ppo/core_algos.py | 26 | Python | 0.429 | performance | 75 | 51 | 51 | false | [algo] fix: Add seq mean mask denominator option | 4,510 | volcengine/verl | 16,907 | Python | wuxibin89 | szrlee |
Returns:
dict[str, Any]: Dictionary containing:
- aborted_count: Number of requests aborted
- request_ids: List of aborted request IDs
"""
try:
# Take an atomic snapshot to avoid race conditions with the vLLM engine thread
requ... | We should always reset_prefix_cache when abort request? | - aborted_count: Number of requests aborted
- request_ids: List of aborted request IDs
"""
try:
# Take an atomic snapshot to avoid race conditions with the vLLM engine thread
request_states_snapshot = list(self.engine.output_processor.request_state... | @@ -552,14 +552,19 @@ async def abort_all_requests(self) -> dict[str, Any]:
self.engine.output_processor.abort_requests(request_ids)
await self.engine.engine_core.abort_requests_async(request_ids)
+ # Try to reset prefix cache to ensure clean state | verl/workers/rollout/vllm_rollout/vllm_async_server.py | 26 | Python | 0.286 | performance | 55 | 51 | 51 | false | [vllm, rollout] feat: support reset prefix cache after abort | 4,519 | volcengine/verl | 16,907 | Python | wuxibin89 | PeterSH6 |
return {"aborted_count": 0, "request_ids": []}
# For each request, create an abort output and put it to its queue
# This allows the generator to receive the aborted result
from vllm.v1.engine import FinishReason
for _, req_state in request_states_snapsho... | When will we want to abort single request? | # This allows the generator to receive the aborted result
from vllm.v1.engine import FinishReason
for _, req_state in request_states_snapshot:
request_output = req_state.make_request_output(
[], pooling_output=None, finish_reason=FinishReason.ABOR... | @@ -552,14 +552,19 @@ async def abort_all_requests(self) -> dict[str, Any]:
self.engine.output_processor.abort_requests(request_ids)
await self.engine.engine_core.abort_requests_async(request_ids)
+ # Try to reset prefix cache to ensure clean state
+ if reset_prefix_cac... | verl/workers/rollout/vllm_rollout/vllm_async_server.py | 26 | Python | 0.071 | question | 42 | 51 | 51 | false | [vllm, rollout] feat: support reset prefix cache after abort | 4,519 | volcengine/verl | 16,907 | Python | wuxibin89 | PeterSH6 |
logger.info(f"enable_sleep_mode: {self.config.enable_sleep_mode}")
if not self.config.enable_sleep_mode:
from verl.utils.device import set_expandable_segments
set_expandable_segments(True)
quantization = self.config.quantization
if quantization is not None:
... | We can disable sleep mode in standalone:
```python
"enable_sleep_mode": self.rollout_mode != RolloutMode.STANDALONE
``` | logger.info(f"enable_sleep_mode: {self.config.enable_sleep_mode}")
if not self.config.enable_sleep_mode:
from verl.utils.device import set_expandable_segments
set_expandable_segments(True)
quantization = self.config.quantization
if quantization is not None:
... | @@ -279,7 +285,7 @@ async def launch_server(self, master_address: str = None, master_port: int = Non
"enable_chunked_prefill": self.config.enable_chunked_prefill,
"max_num_batched_tokens": self.config.max_num_batched_tokens,
"enable_prefix_caching": self.config.enable_prefix_cachi... | verl/workers/rollout/vllm_rollout/vllm_async_server.py | 26 | Python | 0.714 | suggestion | 122 | 51 | 51 | false | [rollout,vllm] feat: disable sleep mode in fully-async mode | 4,521 | volcengine/verl | 16,907 | Python | wuxibin89 | chenjiaoAngel |
if str(Role.RefPolicy) in all_wg:
self.ref_policy_wg = all_wg[str(Role.RefPolicy)]
self.ref_policy_wg.init_model()
else:
# Model engine: ActorRolloutRefWorker
assert str(Role.ActorRolloutRef) in all_wg, f"{all_wg.keys()=}"
... | Please move this to a util function | if str(Role.RefPolicy) in all_wg:
self.ref_policy_wg = all_wg[str(Role.RefPolicy)]
self.ref_policy_wg.init_model()
else:
# Model engine: ActorRolloutRefWorker
assert str(Role.ActorRolloutRef) in all_wg, f"{all_wg.keys()=}"
... | @@ -847,7 +848,30 @@ def init_workers(self):
# create async rollout manager and request scheduler
self.async_rollout_mode = False
if self.config.actor_rollout_ref.rollout.mode == "async":
- from verl.experimental.agent_loop import AgentLoopManager
+ # Support custom Agen... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.143 | refactor | 35 | 51 | 51 | false | [rollout, trainer] feat: extend agent loop for custom implementations | 4,548 | volcengine/verl | 16,907 | Python | wuxibin89 | JoyboyBrian |
return system_prompt, generate_prompt
# =============================================================================
# Tokenization utility functions
# These functions are extracted from ToolAgentLoop for reusability in external
# projects like remote rollout servers.
# ==========================================... | It's a bit redundant here, we can safely pass `tools=None` to processor.apply_chat_template? | # Copyright 2025 Bytedance Ltd. and/or its affiliates
import logging
import os
from jinja2 import TemplateError
logger = logging.getLogger(__name__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
def initialize_system_prompt(tokenizer, **apply_chat_template_kwargs) -> list[int]:
"""
Initialize sys... | @@ -40,3 +41,84 @@ def extract_system_prompt_and_generation(tokenizer):
generate_prompt = token3[len(token1) :]
return system_prompt, generate_prompt
+
+
+# =============================================================================
+# Tokenization utility functions
+# These functions are extracted from T... | verl/utils/chat_template.py | 26 | Python | 0.357 | question | 92 | 51 | 43 | false | [rollout, trainer] feat: extend agent loop for custom implementations | 4,548 | volcengine/verl | 16,907 | Python | wuxibin89 | JoyboyBrian |
size_divisor = (
self.actor_rollout_wg.world_size
if not self.async_rollout_mode
else self.config.actor_rollout_ref.rollout.agent.num_workers
)
test_gen_batch_padded, pad_size = pad_dataproto_to_divisor(test_gen_batch, size_divisor)
... | We better move reward calculation to a separate function and reuse it in both `fit` and `_validate` | batch_keys_to_pop = ["input_ids", "attention_mask", "position_ids"]
non_tensor_batch_keys_to_pop = set(batch.non_tensor_batch.keys()) - reward_model_keys
gen_batch = batch.pop(
batch_keys=batch_keys_to_pop,
non_tensor_batch_keys=list(non_tensor_batch_keys_to_pop),
... | @@ -616,17 +616,41 @@ def _validate(self):
test_batch.meta_info["validate"] = True
# evaluate using reward_function
- if self.val_reward_fn is None:
- raise ValueError("val_reward_fn must be provided for validation.")
- result = self.val_reward_fn(test_ba... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.429 | suggestion | 99 | 51 | 51 | false | [reward] feat: Optimize reward computation when use_reward_loop=True | 4,581 | volcengine/verl | 16,907 | Python | wuxibin89 | none0663 |
if self.should_save_model:
# Save adapter-only checkpoint if PEFT is enabled
if self.peft_cls is not None:
from verl.utils.megatron_peft_utils import save_adapter_checkpoint
adapter_ckpt_path = os.path.join(local_path, "adapter_checkpoint")
... | recommend to modify like this:
```
import inspect
extended_args = {}
if "distributed_filesystem" in inspect.signature(self.bridge.save_weights):
extended_args["distributed_filesystem"] = True
extended_args["memory_efficient"] = True
self.bridge.save_weights(self.model, hf_ckpt_path, **extended_args)
``` |
if self.should_save_model:
# Save adapter-only checkpoint if PEFT is enabled
if self.peft_cls is not None:
from verl.utils.megatron_peft_utils import save_adapter_checkpoint
adapter_ckpt_path = os.path.join(local_path, "adapter_checkpoint")
... | @@ -500,7 +500,7 @@ def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: i
hf_ckpt_path = get_hf_model_checkpoint_path(local_path)
if self.vanilla_bridge:
self.bridge.save_weights( | verl/utils/checkpoint/megatron_checkpoint_manager.py | 26 | Python | 0.929 | performance | 313 | 51 | 51 | false | [megatron] feat: use yaml to manage mbridge args | 4,584 | volcengine/verl | 16,907 | Python | ISEEKYAN | Kite0011 |
delattr(self.transformer_config, k)
transformer_config_dict = asdict(self.transformer_config)
for k in backup:
setattr(self.transformer_config, k, backup[k])
to_convert_types = {torch.dtype: str, AttnBackend: str}
... | it could be more precise with code like:
```
mbridge_config = getattr(self.checkpoint_config, "mbridge_config", None) or {}
args = {}
if xxx in inspect.signature(self.bridge.save_weights)):
args[xxx] = getattr(mbridge_config, xxx, True)
```
BTW, why to use `str` to wrap the `inspect.signature`? | delattr(self.transformer_config, k)
transformer_config_dict = asdict(self.transformer_config)
for k in backup:
setattr(self.transformer_config, k, backup[k])
to_convert_types = {torch.dtype: str, AttnBackend: str}
... | @@ -571,9 +577,14 @@ def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: i
if self.bridge is not None:
hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path)
if self.vanilla_bridge:
- self.bridge.save_weights(
- ... | verl/utils/checkpoint/megatron_checkpoint_manager.py | 26 | Python | 0.857 | question | 300 | 51 | 51 | false | [megatron] feat: use yaml to manage mbridge args | 4,584 | volcengine/verl | 16,907 | Python | ISEEKYAN | Kite0011 |
if self.peft_cls is not None:
from verl.utils.megatron_peft_utils import save_adapter_checkpoint
adapter_ckpt_path = os.path.join(local_path, "adapter_checkpoint")
# Save adapter weights only (much smaller than full model)
save_adapter_checkp... | I wonder if this for loop would also parse `model` and `hf_ckpt_path` and give default value of True for them @Kite0011 | if self.peft_cls is not None:
from verl.utils.megatron_peft_utils import save_adapter_checkpoint
adapter_ckpt_path = os.path.join(local_path, "adapter_checkpoint")
# Save adapter weights only (much smaller than full model)
save_adapter_checkp... | @@ -499,9 +500,11 @@ def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: i
log_with_rank(f"Saving HF model checkpoint to {local_path} with bridge", rank=self.rank, logger=logger)
hf_ckpt_path = get_hf_model_checkpoint_path(local_path)
if self... | verl/utils/checkpoint/megatron_checkpoint_manager.py | 26 | Python | 0.5 | suggestion | 120 | 51 | 51 | false | [megatron] feat: use yaml to manage mbridge args | 4,584 | volcengine/verl | 16,907 | Python | ISEEKYAN | Kite0011 |
For standalone actor or rollout, use ActorWorker or BaseRollout respectively.
NOTE: ActorRolloutRefWorker no longer support spmd mode and run native server mode.
"""
def __init__(self, config: DictConfig, role: str, **kwargs):
Worker.__init__(self)
self.config = config
self.rol... | This exception branch can be deleted for clean code due to above role judgement in line 357 | For standalone actor or rollout, use ActorWorker or BaseRollout respectively.
NOTE: ActorRolloutRefWorker no longer support spmd mode and run native server mode.
"""
def __init__(self, config: DictConfig, role: str, **kwargs):
Worker.__init__(self)
self.config = config
self.rol... | @@ -354,6 +354,33 @@ def __init__(self, config: DictConfig, role: str, **kwargs):
self.actor: TrainingWorker = None
self.ref: TrainingWorker = None
self.rollout: BaseRollout = None
+ assert self.role in ["actor", "rollout", "ref", "actor_rollout", "actor_rollout_ref"]
+ self._is... | verl/workers/engine_workers.py | 26 | Python | 0.357 | suggestion | 91 | 51 | 51 | false | [worker] fix: Add profiler initialization for ActorRolloutRefWorker in engine_worker | 4,586 | volcengine/verl | 16,907 | Python | FightingZhen | pqhgit |
args: List of arguments passed to the function. Should contain a Worker instance
as the first argument when using lazy compute mode.
Returns:
bool: True if data collection is needed, False otherwise.
Note:
Only checks worker attributes when dispatch_mode is a dict with 'co... | It's too tricky to get collect info here, we better add a function to base Worker. | collect_fn for lazy compute optimization.
args: List of arguments passed to the function. Should contain a Worker instance
as the first argument when using lazy compute mode.
Returns:
bool: True if data collection is needed, False otherwise.
Note:
Onl... | @@ -144,7 +147,83 @@ def _update_batchmeta_with_output(output: DataProto, batchmeta: "BatchMeta", fun
return updated_batch_meta
-def tqbridge(put_data: bool = True):
+def _compute_need_collect(dispatch_mode: "dict | Dispatch", args: list) -> bool:
+ """Compute whether data collection is needed for the curre... | verl/utils/transferqueue_utils.py | 26 | Python | 0.286 | suggestion | 82 | 51 | 51 | false | [data] feat: TransferQueue - remove redundant data collect for both TQ and DataProto | 4,618 | volcengine/verl | 16,907 | Python | wuxibin89 | 0oshowero0 |
@ray.remote
class TestAllGatherActorV2(Worker):
def __init__(self, size) -> None:
super().__init__()
self.size = size
torch.distributed.init_process_group()
self.tensor = torch.zeros(size=(self.size,), dtype=torch.int64, device=get_device_name())
self.tensor += self.rank
... | Why set 100 here? same as follows ~ |
@ray.remote
class TestAllGatherActorV2(Worker):
def __init__(self, size) -> None:
super().__init__()
self.size = size
torch.distributed.init_process_group()
self.tensor = torch.zeros(size=(self.size,), dtype=torch.int64, device=get_device_name())
self.tensor += self.rank
... | @@ -68,13 +69,15 @@ def test_all_gather_torch():
"""
In this test, we instantiate 4 GPUs in a group and test the all_gather
"""
- ray.init()
+ ray.init(num_cpus=100) | tests/single_controller/test_worker_group_torch.py | 26 | Python | 0.071 | question | 35 | 51 | 51 | false | [ci] feat: add npu unit test | 4,626 | volcengine/verl | 16,907 | Python | FightingZhen | yyyy2000 |
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
impo... | Not advised, should consider is_cuda_available or is_npu_available. For cuda, should keep existing logic, for NPU, use `unpad_input` in `verl.utils.npu_flash_attn_utils` | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
impo... | @@ -26,15 +26,15 @@
from verl.utils.activation_offload import enable_activation_offloading
from verl.utils.checkpoint.fsdp_checkpoint_manager import FSDPCheckpointManager
+from verl.utils.device import get_device_name, get_nccl_backend, get_torch_device
from verl.utils.fsdp_utils import MixedPrecisionPolicy, apply... | tests/utils/test_activation_offload.py | 26 | Python | 0.571 | suggestion | 169 | 51 | 51 | false | [ci] feat: add npu unit test | 4,626 | volcengine/verl | 16,907 | Python | FightingZhen | yyyy2000 |
)
self.lm_head = nn.Linear(hidden_size, vocab_size)
def forward(self, input_ids, attention_mask=None, position_ids=None, use_cache=False, **kwargs):
batch_size, seq_len = input_ids.shape
embeddings = self.embedding(input_ids)
hidden_states = self.transformer(embeddings)
... | replace `torch.cuda.is_available()` with `is_cuda_available` | )
self.lm_head = nn.Linear(hidden_size, vocab_size)
def forward(self, input_ids, attention_mask=None, position_ids=None, use_cache=False, **kwargs):
batch_size, seq_len = input_ids.shape
embeddings = self.embedding(input_ids)
hidden_states = self.transformer(embeddings)
... | @@ -59,15 +60,18 @@ def setUpClass(cls):
"""Set up distributed environment"""
if not torch.distributed.is_initialized():
torch.distributed.init_process_group(
- backend="nccl" if torch.cuda.is_available() else "gloo", init_method="env://"
+ backend=get_nccl_b... | tests/workers/actor/test_special_dp_actor.py | 26 | Python | 0.429 | suggestion | 60 | 51 | 51 | false | [ci] feat: add npu unit test | 4,626 | volcengine/verl | 16,907 | Python | FightingZhen | yyyy2000 |
print("NOTICE: You have both enabled in-reward kl and kl loss.")
# critic
if use_critic:
critic_config = omega_conf_to_dataclass(config.critic)
critic_config.validate(n_gpus, config.data.train_batch_size)
if config.data.get("val_batch_size", None) is not None:
print(
... | when would lora_rank be less than 0? | print("NOTICE: You have both enabled in-reward kl and kl loss.")
# critic
if use_critic:
critic_config = omega_conf_to_dataclass(config.critic)
critic_config.validate(n_gpus, config.data.train_batch_size)
if config.data.get("val_batch_size", None) is not None:
print(
... | @@ -199,7 +199,13 @@ def check_mutually_exclusive(mbs, mbs_per_gpu, name: str):
)
# check LoRA rank in vLLM
- if config.actor_rollout_ref.model.get("lora_rank", 0) > 0 and config.actor_rollout_ref.rollout.name == "vllm":
- assert config.actor_rollout_ref.model.lora_rank <= 512, "LoRA rank in v... | verl/utils/config.py | 26 | Python | 0.071 | question | 36 | 32 | 34 | false | [megatron] feat: LoRA adapter only refit (TensorLoRARequest) | 4,632 | volcengine/verl | 16,907 | Python | ISEEKYAN | HollowMan6 |
if use_critic:
critic_config = omega_conf_to_dataclass(config.critic)
critic_config.validate(n_gpus, config.data.train_batch_size)
if config.data.get("val_batch_size", None) is not None:
print(
"WARNING: val_batch_size is deprecated."
+ " Validation datasets are ... | is it possible to use a number from vllm, instead of a hardcode 512? such as something like `assert lora_rank < vllm.xxx.xxx.max_lora_rank` | if use_critic:
critic_config = omega_conf_to_dataclass(config.critic)
critic_config.validate(n_gpus, config.data.train_batch_size)
if config.data.get("val_batch_size", None) is not None:
print(
"WARNING: val_batch_size is deprecated."
+ " Validation datasets are ... | @@ -199,7 +199,13 @@ def check_mutually_exclusive(mbs, mbs_per_gpu, name: str):
)
# check LoRA rank in vLLM
- if config.actor_rollout_ref.model.get("lora_rank", 0) > 0 and config.actor_rollout_ref.rollout.name == "vllm":
- assert config.actor_rollout_ref.model.lora_rank <= 512, "LoRA rank in v... | verl/utils/config.py | 26 | Python | 0.571 | suggestion | 139 | 29 | 31 | false | [megatron] feat: LoRA adapter only refit (TensorLoRARequest) | 4,632 | volcengine/verl | 16,907 | Python | ISEEKYAN | HollowMan6 |
omega_profiler_config = config.ref.get("profiler", {})
else:
raise ValueError(
f"Invalid role {self.role}, should be one of "
"['actor', 'rollout', 'ref', 'actor_rollout', 'actor_rollout_ref']"
)
# omega_profiler_config is DictConfig
... | is the `base_sync_done` an indicator of sync of only lora weights or the whole weights? I am not sure, this is ambiguous | else:
raise ValueError(
f"Invalid role {self.role}, should be one of "
"['actor', 'rollout', 'ref', 'actor_rollout', 'actor_rollout_ref']"
)
# omega_profiler_config is DictConfig
# profiler_config is a ProfilerConfig dataclass
profi... | @@ -345,6 +346,10 @@ def __init__(self, config: DictConfig, role: str, **kwargs):
self._is_offload_grad = False
self._is_offload_optimizer = False
+ # Initialize LoRA-related attributes (will be updated in _build_rollout if needed)
+ self.base_sync_done = False | verl/workers/megatron_workers.py | 26 | Python | 0.5 | suggestion | 120 | 51 | 51 | false | [megatron] feat: LoRA adapter only refit (TensorLoRARequest) | 4,632 | volcengine/verl | 16,907 | Python | ISEEKYAN | HollowMan6 |
hdfs_io.makedirs(hdfs_path, exist_ok=True)
hdfs_io.copy(src=hf_model_ckpt_path, dst=hdfs_path, dirs_exist_ok=True)
log_with_rank(
f"HDFS checkpoint uploaded to {hdfs_path}",
rank=self.rank,
... | Add some necessary blank lines to improve read convenience |
hdfs_io.makedirs(hdfs_path, exist_ok=True)
hdfs_io.copy(src=hf_model_ckpt_path, dst=hdfs_path, dirs_exist_ok=True)
log_with_rank(
f"HDFS checkpoint uploaded to {hdfs_path}",
rank=self.rank,
... | @@ -634,18 +637,39 @@ def finalize_save_fn():
f"Dist checkpointing save completed for {dist_checkpoint_path}", rank=self.rank, logger=logger
)
if self.rank == 0:
- local_latest_checkpointed_iteration = os.path.join(
- os.path.dirname(os.path.d... | verl/utils/checkpoint/megatron_checkpoint_manager.py | 26 | Python | 0.214 | style | 58 | 51 | 51 | false | [megatron] fix: megatron async save ckpt fix | 4,638 | volcengine/verl | 16,907 | Python | FightingZhen | Leem-Li |
nodes = api.list_nodes()
for node in nodes:
if node.is_head_node:
head_node = node
break
current_node_id = ray.get_runtime_context().get_node_id()
if head_node is not None and head_node.node_id == current_node_id:
... | Could there be a scenario of multi-process concurrent writing here? | return
head_node = None
nodes = api.list_nodes()
for node in nodes:
if node.is_head_node:
head_node = node
break
current_node_id = ray.get_runtime_context().get_node_id()
ray_local_world... | @@ -634,18 +637,39 @@ def finalize_save_fn():
f"Dist checkpointing save completed for {dist_checkpoint_path}", rank=self.rank, logger=logger
)
if self.rank == 0:
- local_latest_checkpointed_iteration = os.path.join(
- os.path.dirname(os.path.d... | verl/utils/checkpoint/megatron_checkpoint_manager.py | 26 | Python | 0.286 | question | 67 | 34 | 50 | false | [megatron] fix: megatron async save ckpt fix | 4,638 | volcengine/verl | 16,907 | Python | FightingZhen | Leem-Li |
"""Reorder the data on single controller such that each dp rank gets similar total tokens"""
attention_mask = batch.batch["attention_mask"]
batch_size = attention_mask.shape[0]
global_seqlen_lst = batch.batch["attention_mask"].view(batch_size, -1).sum(-1) # (train_batch_size,)
w... | Could you encapsulate this into a function? | """Get data parallel size from worker group dispatch info.
This method retrieves the data parallel size by querying the dispatch info
for the specified role. The dispatch info is cached for subsequent calls.
Args:
worker_group: The worker group to query dispatch info from.
... | @@ -1090,23 +1090,32 @@ def _balance_batch(self, batch: DataProto, metrics, logging_prefix="global_seqle
batch_size = attention_mask.shape[0]
global_seqlen_lst = batch.batch["attention_mask"].view(batch_size, -1).sum(-1) # (train_batch_size,)
workload_lst = calculate_workload(global_seqlen_l... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.143 | question | 43 | 51 | 51 | false | [trainer] fix: use dp_size instead of world_size in _balance_batch | 4,697 | volcengine/verl | 16,907 | Python | vermouth1992 | yurekami |
"""
self.config = config
self.worker_group = worker_group
self.reward_model_manager = None
self.reward_router_address = None
if self.config.reward_model.enable and self.config.reward_model.enable_resource_pool:
from verl.experimental.reward_loop import RewardM... | Add some comments to explain this | batch=batch,
non_tensor_batch=non_tensor_batch,
)
result = await self.reward_loop_worker.compute_score.remote(data)
output.reward_score = result["reward_score"]
output.extra_fields["reward_extra_info"] = result["reward_extra_info"]
def... | @@ -739,11 +739,17 @@ def __init__(
self.sleep()
def _initialize_llm_servers(self):
- rollout_world_size = (
- self.config.actor_rollout_ref.rollout.tensor_model_parallel_size
- * self.config.actor_rollout_ref.rollout.data_parallel_size
- * self.config.actor_r... | verl/experimental/agent_loop/agent_loop.py | 26 | Python | 0.071 | suggestion | 33 | 51 | 51 | false | [sglang] fix: sglang TP+DP support / port bug | 4,715 | volcengine/verl | 16,907 | Python | FightingZhen | hustmf |
_GlobalState,
_launch_subprocesses,
app,
set_global_state,
)
from sglang.srt.managers.io_struct import (
GenerateReqInput,
ReleaseMemoryOccupationReqInput,
ResumeMemoryOccupationReqInput,
)
from sglang.srt.managers.tokenizer_manager import ServerStatus
from verl.single_controller.ray import... | suggest rename this variable to `visible_devices_keyword` | ServerArgs,
_GlobalState,
_launch_subprocesses,
app,
set_global_state,
)
from sglang.srt.managers.io_struct import (
GenerateReqInput,
ReleaseMemoryOccupationReqInput,
ResumeMemoryOccupationReqInput,
)
from sglang.srt.managers.tokenizer_manager import ServerStatus
from verl.single_contr... | @@ -48,6 +51,8 @@
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
+device_keyword = get_visible_devices_keyword() | verl/workers/rollout/sglang_rollout/async_sglang_server.py | 26 | Python | 0.429 | suggestion | 57 | 51 | 51 | false | [sglang] fix: sglang TP+DP support / port bug | 4,715 | volcengine/verl | 16,907 | Python | FightingZhen | hustmf |
vLLM:
```
vllm serve --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-start-rank 0 ...
vllm serve --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-start-rank 8 ...
```
Args:
replica_rank: int, rank of this rollout replica.
config: RolloutC... | Same here, add some comments to explain this. | vLLM:
```
vllm serve --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-start-rank 0 ...
vllm serve --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-start-rank 8 ...
```
Args:
replica_rank: int, rank of this rollout replica.
config: RolloutC... | @@ -92,16 +92,20 @@ def __init__(
self.config = omega_conf_to_dataclass(config)
self.model_config: HFModelConfig = model_config
- self.world_size = (
- self.config.tensor_model_parallel_size
- * self.config.data_parallel_size
- * self.config.pipeline_model_par... | verl/workers/rollout/replica.py | 26 | Python | 0.071 | suggestion | 45 | 51 | 51 | false | [sglang] fix: sglang TP+DP support / port bug | 4,715 | volcengine/verl | 16,907 | Python | FightingZhen | hustmf |
num_warmup_steps=num_warmup_steps,
num_training_steps=total_steps,
min_lr_ratio=min_lr_ratio,
num_cycles=num_cycles,
)
else:
raise NotImplementedError(f"LR scheduler type {lr_scheduler_type} is no... | SPMD mode will be removed soon, if you want to keep it, please add some comments to explain this. | total_steps = optim_config.get("total_training_steps", 0)
num_warmup_steps = int(optim_config.get("lr_warmup_steps", -1))
lr_scheduler_type = optim_config.get("lr_scheduler_type", "constant")
min_lr_ratio = optim_config.get("min_lr_ratio", 0.0)
num_cycles = op... | @@ -603,7 +594,10 @@ def _build_rollout(self, trust_remote_code=False):
self.model_config = model_config
# 2. build rollout device mesh
- infer_tp = self.config.rollout.tensor_model_parallel_size * self.config.rollout.data_parallel_size
+ if self.config.rollout.name == "sglang":
+ ... | verl/workers/fsdp_workers.py | 26 | Python | 0.286 | suggestion | 97 | 51 | 51 | false | [sglang] fix: sglang TP+DP support / port bug | 4,715 | volcengine/verl | 16,907 | Python | FightingZhen | hustmf |
self.checkpoint_manager = FSDPCheckpointManager(
model=self.actor_module_fsdp,
optimizer=None,
lr_scheduler=None,
processing_class=self.processor if self.processor is not None else self.tokenizer,
checkpoint_config=checkpoint_co... | this extra branch can be removed | self.checkpoint_manager = FSDPCheckpointManager(
model=self.actor_module_fsdp,
optimizer=None,
lr_scheduler=None,
processing_class=self.processor if self.processor is not None else self.tokenizer,
checkpoint_config=checkpoint_co... | @@ -919,7 +919,15 @@ def update_actor(self, data: DataProto):
metrics = self.actor.update_policy(data=data)
delta_time = timer.last
global_num_tokens = data.meta_info["global_token_num"]
- estimated_flops, promised_flops = self.flops_counter.estimate_flops(global_nu... | verl/workers/fsdp_workers.py | 26 | Python | 0.143 | suggestion | 32 | 51 | 51 | false | [perf] feat: Add MFU for Qwen3-VL dense | 4,753 | volcengine/verl | 16,907 | Python | tardis-key | zhihaofang1017 |
self.checkpoint_manager = FSDPCheckpointManager(
model=self.actor_module_fsdp,
optimizer=None,
lr_scheduler=None,
processing_class=self.processor if self.processor is not None else self.tokenizer,
checkpoint_config=checkpoint_co... | Is this adaptation required in engine_worker? | self.checkpoint_manager = FSDPCheckpointManager(
model=self.actor_module_fsdp,
optimizer=None,
lr_scheduler=None,
processing_class=self.processor if self.processor is not None else self.tokenizer,
checkpoint_config=checkpoint_co... | @@ -919,7 +919,15 @@ def update_actor(self, data: DataProto):
metrics = self.actor.update_policy(data=data)
delta_time = timer.last
global_num_tokens = data.meta_info["global_token_num"]
- estimated_flops, promised_flops = self.flops_counter.estimate_flops(global_nu... | verl/workers/fsdp_workers.py | 26 | Python | 0.071 | question | 45 | 51 | 51 | false | [perf] feat: Add MFU for Qwen3-VL dense | 4,753 | volcengine/verl | 16,907 | Python | tardis-key | zhihaofang1017 |
"seed_oss": _estimate_qwen2_flops,
"apertus": _estimate_apertus_flops,
"glm4v": _estimate_qwen2_flops,
"gpt_oss": _estimate_gpt_oss_flops,
}
class FlopsCounter:
"""
Used to count mfu during training loop
Example:
flops_counter = FlopsCounter(config)
flops_achieved, flops_p... | unifying config usage, nice job! | "seed_oss": _estimate_qwen2_flops,
"apertus": _estimate_apertus_flops,
"glm4v": _estimate_qwen2_flops,
"gpt_oss": _estimate_gpt_oss_flops,
}
class FlopsCounter:
"""
Used to count mfu during training loop
Example:
flops_counter = FlopsCounter(config)
flops_achieved, flops_p... | @@ -429,10 +522,10 @@ def __init__(self, config: PretrainedConfig):
f"zero."
)
- self.config = getattr(config, "text_config", config)
+ self.config = config | verl/utils/flops_counter.py | 26 | Python | 0.071 | suggestion | 32 | 46 | 51 | false | [perf] feat: Add MFU for Qwen3-VL dense | 4,753 | volcengine/verl | 16,907 | Python | tardis-key | zhihaofang1017 |
return messages
def __getitem__(self, item):
"""For rollout, apply_chat_template has been moved to AgentLoop, so we only return raw_prompt here."""
row_dict: dict = self.dataframe[item]
row_dict["raw_prompt"] = self._build_messages(row_dict)
# TODO(wuxibin): We still need a... | We should not process_vision_info in `RLDataset` since it run in single-controller's dataloader, which will be a bottleneck for large scale multi-modal dataset. https://github.com/volcengine/verl/pull/4759 | return messages
def __getitem__(self, item):
"""For rollout, apply_chat_template has been moved to AgentLoop, so we only return raw_prompt here."""
row_dict: dict = self.dataframe[item]
row_dict["raw_prompt"] = self._build_messages(row_dict)
# TODO(wuxibin): We still need a... | @@ -354,6 +354,16 @@ def __getitem__(self, item):
row_dict["index"] = index
row_dict["tools_kwargs"] = tools_kwargs
row_dict["interaction_kwargs"] = interaction_kwargs
+
+ from qwen_vl_utils import process_vision_info
+ images, videos = process_vision_info(row_dict["raw_prompt"]... | verl/utils/dataset/rl_dataset.py | 26 | Python | 0.643 | performance | 205 | 51 | 51 | false | [perf] feat: Add MFU for Qwen3-VL dense | 4,753 | volcengine/verl | 16,907 | Python | wuxibin89 | zhihaofang1017 |
keys_to_pop.update(rm_scores.batch.keys())
batch.pop(batch_keys=list(keys_to_pop))
batch.batch["reward_baselines"] = reward_baseline_tensor
del rm_scores, gen_baseline_batch, gen_baseline_output
... | There's two problem here:
1. we should also count `video_grid_thw`
2. `images_seqlens` is pretty big: O(#samples) * O(#frames), meta_info is replicated and dispatched to all workers, we should keep it small. Better calculate `images_seqlens` and `seqlen_square_sum` ahead. | keys_to_pop.update(rm_scores.batch.keys())
batch.pop(batch_keys=list(keys_to_pop))
batch.batch["reward_baselines"] = reward_baseline_tensor
del rm_scores, gen_baseline_batch, gen_baseline_output
... | @@ -1415,7 +1415,13 @@ def fit(self):
# compute global_valid tokens
batch.meta_info["global_token_num"] = torch.sum(batch.batch["attention_mask"], dim=-1).tolist()
-
+ # get images_seqlens
+ images_seqlens_all = []
+ ... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.643 | suggestion | 274 | 51 | 51 | false | [perf] feat: Add MFU for Qwen3-VL dense | 4,753 | volcengine/verl | 16,907 | Python | wuxibin89 | zhihaofang1017 |
Expandable segments can help avoid out-of-memory (OOM) errors by allowing
the memory allocator to expand existing memory segments rather than
allocating new ones.
Args:
enable: If True, enable expandable segments. If False, disable them.
Note:
This function only has an effect when ... | In case the input configuration is set to CPU, we intend to retain the existing implementation as-is. | Expandable segments can help avoid out-of-memory (OOM) errors by allowing
the memory allocator to expand existing memory segments rather than
allocating new ones.
Args:
enable: If True, enable expandable segments. If False, disable them.
Note:
This function only has an effect when ... | @@ -127,25 +127,25 @@ def set_expandable_segments(enable: bool) -> None:
torch.cuda.memory._set_allocator_settings(f"expandable_segments:{enable}")
-def auto_set_ascend_device_name(config) -> None:
- """Automatically configure device name for Ascend NPU environments.
+def auto_set_device(config) -> None... | verl/utils/device.py | 26 | Python | 0.357 | suggestion | 101 | 51 | 51 | false | [trainer] feat: enable ray-based sft trainer on ascend npu | 4,764 | volcengine/verl | 16,907 | Python | ji-huazhong | ji-huazhong |
{"loss": 2.0, "accuracy": 0.8, "max_reward": 8.0, "min_error": 0.05}
"""
for key, val in metrics.items():
if isinstance(val, Metric):
metrics[key] = val.aggregate()
elif "max" in key:
metrics[key] = np.max(val)
elif "min" in key:
metrics[key] =... | Could you also add a unit test for this. | {"loss": 2.0, "accuracy": 0.8, "max_reward": 8.0, "min_error": 0.05}
"""
for key, val in metrics.items():
if isinstance(val, Metric):
metrics[key] = val.aggregate()
elif "max" in key:
metrics[key] = np.max(val)
elif "min" in key:
metrics[key] =... | @@ -45,10 +47,84 @@ def reduce_metrics(metrics: dict[str, list[Any]]) -> dict[str, Any]:
{"loss": 2.0, "accuracy": 0.8, "max_reward": 8.0, "min_error": 0.05}
"""
for key, val in metrics.items():
- if "max" in key:
+ if isinstance(val, Metric):
+ metrics[key] = val.aggregate()... | verl/utils/metric/utils.py | 26 | Python | 0.143 | nitpick | 40 | 51 | 51 | false | [worker, training_utils] fix: Engine Metric Aggregation | 4,778 | volcengine/verl | 16,907 | Python | wuxibin89 | JacobHelwig |
VLLM_LORA_NAME,
VLLM_LORA_PATH,
get_vllm_max_lora_rank,
)
_VLLM_VERSION = version.parse(vllm.__version__)
if _VLLM_VERSION > version.parse("0.11.0"):
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.utils.network_utils import get_tcp_uri
if _VLLM_VERSION == version.parse... | Following environment variables seems strongly related to vLLM, how about renaming this class name to `VLLMEnvsCopyToWorkers` ? | )
from verl.workers.rollout.vllm_rollout import vLLMAsyncRollout
from verl.workers.rollout.vllm_rollout.utils import (
VLLM_LORA_INT_ID,
VLLM_LORA_NAME,
VLLM_LORA_PATH,
get_vllm_max_lora_rank,
)
_VLLM_VERSION = version.parse(vllm.__version__)
if _VLLM_VERSION > version.parse("0.11.0"):
from vllm.u... | @@ -77,6 +78,17 @@
logger.setLevel(logging.INFO)
+class EnvsCopyToWorkers: | verl/workers/rollout/vllm_rollout/vllm_async_server.py | 26 | Python | 0.5 | question | 127 | 51 | 51 | false | [rollout, vllm] fix: accuracy issue in verl serve mode + vllm-ascend + dp + ep + tp scenarios | 4,783 | volcengine/verl | 16,907 | Python | FightingZhen | leo-pony |
self.engine.ulysses_sharding_manager.__enter__()
self.engine.module.train()
def __exit__(self, exc_type, exc_value, traceback):
assert isinstance(self.engine, VeOmniEngine)
self.engine.ulysses_sharding_manager.__exit__(exc_type, exc_value, traceback)
self.engine.optimizer_ze... | ```suggestion
class OmniSequenceShardCollator:
``` | assert isinstance(self.engine, VeOmniEngine)
self.engine.ulysses_sharding_manager.__exit__(exc_type, exc_value, traceback)
self.engine.optimizer_zero_grad()
super().__exit__(exc_type, exc_value, traceback)
@dataclass
class OmniSequenceShardCollator:
"""
Data collator to chunk i... | @@ -333,6 +334,55 @@ def __exit__(self, exc_type, exc_value, traceback):
super().__exit__(exc_type, exc_value, traceback)
+@dataclass
+class DataCollator(ABC):
+ """
+ Used in dataloader as a collate_fn.
+ """
+
+ @abstractmethod
+ def __call__(self, features: Sequence[dict[str, Any]]) -> di... | verl/workers/engine/veomni/transformer_impl.py | 26 | Python | 0.571 | suggestion | 50 | 51 | 51 | false | [trainer] feat: VeOmniEngine supports qwen3_vl ulysses | 4,806 | volcengine/verl | 16,907 | Python | ji-huazhong | A1waysBeenHere |
Dispatch.register("DIRECT_ROLLOUT_METHOD")
class Execute(DynamicEnum):
"""Enum class defining different execution modes for distributed computation.
These modes control how a function should be executed across different ranks
in a distributed system.
"""
_registry = {}
_next_value = 0
... | Will this `contiguous` drop NonTensorStack? | Dispatch.register("DIRECT_ROLLOUT_METHOD")
class Execute(DynamicEnum):
"""Enum class defining different execution modes for distributed computation.
These modes control how a function should be executed across different ranks
in a distributed system.
"""
_registry = {}
_next_value = 0
... | @@ -71,6 +71,10 @@ def init_predefined_execute_mode():
init_predefined_execute_mode()
+def _consolidate_tuple_td(chunked_arg):
+ return tuple(val.contiguous().consolidate() for val in chunked_arg) | verl/single_controller/base/decorator.py | 26 | Python | 0.214 | question | 43 | 51 | 51 | false | [misc] feat: consolidate tensordict before dispatch | 4,830 | volcengine/verl | 16,907 | Python | wuxibin89 | vermouth1992 |
self.actor.save_checkpoint(local_path, hdfs_path, global_step, max_ckpt_to_keep)
@register(dispatch_mode=Dispatch.DIRECT_ROLLOUT_METHOD)
async def sleep(self):
"""Context switch from rollout mode to trainer mode."""
if self.config.rollout.free_cache_engine:
log_gpu_memory_us... | @JacobHelwig Megatron engine `get_per_tensor_param` doesn't accept layered_summon and base_sync_done, please fix it.
https://github.com/volcengine/verl/blob/main/verl/workers/engine/megatron/transformer_impl.py#L539 | self.actor.save_checkpoint(local_path, hdfs_path, global_step, max_ckpt_to_keep)
@register(dispatch_mode=Dispatch.DIRECT_ROLLOUT_METHOD)
async def sleep(self):
"""Context switch from rollout mode to trainer mode."""
if self.config.rollout.free_cache_engine:
log_gpu_memory_us... | @@ -563,7 +563,10 @@ async def wake_up(self):
set_expandable_segments(False)
# 1. get per tensor generator from engine, this will load model to gpu
- per_tensor_param, peft_config = self.actor.engine.get_per_tensor_param()
+ per_tensor_param, peft_config = self.actor.engine.get_per_ten... | verl/workers/engine_workers.py | 26 | Python | 0.571 | suggestion | 216 | 51 | 51 | false | [fsdp, megatron] fix: Engine Rollout Worker LoRA Parameter Update | 4,836 | volcengine/verl | 16,907 | Python | wuxibin89 | JacobHelwig |
def mapping_string_to_attn_backend(args: dict) -> dict:
if "attention_backend" in args and isinstance(args["attention_backend"], str):
from megatron.core.transformer.enums import AttnBackend
args["attention_backend"] = AttnBackend[args["attention_backend"]]
return args
def get_megatron_module_... | ref model should not be save checkpoint? | # Copyright 2024 Bytedance Ltd. and/or its affiliates
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
# Copyright 2023-2024 SGLang Team
# Copyright 2025 ModelBest Inc. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | @@ -1228,3 +1228,28 @@ def mapping_string_to_attn_backend(args: dict) -> dict:
args["attention_backend"] = AttnBackend[args["attention_backend"]]
return args
+
+def get_megatron_module_device(models: list[Any]) -> str:
+ if not models:
+ return 'cpu'
+
+ model_chunk = models[0]
+ if isi... | verl/utils/megatron_utils.py | 26 | Python | 0.143 | question | 40 | 31 | 1,249 | false | [ckpt] fix: Megatron save ckpt after validation | 4,841 | volcengine/verl | 16,907 | Python | wuxibin89 | wdl339 |
"global_batch_size": self.global_batch_size,
"pad_mode": self.config.data.pad_mode,
"pad_token_id": self.model_config.tokenizer.pad_token_id,
}
train_time = 0
total_tokens = 0
for epoch in range(start_epoch, self.config.trainer.total_epochs):
... | Great catch! Could you modify batch_seqlens to batch_seqlens_ntd and assign to data instead of using batch_seqlens.data? Thanks! | "global_batch_size": self.global_batch_size,
"pad_mode": self.config.data.pad_mode,
"pad_token_id": self.model_config.tokenizer.pad_token_id,
}
train_time = 0
total_tokens = 0
for epoch in range(start_epoch, self.config.trainer.total_epochs):
... | verl/trainer/sft_trainer.py | 26 | Python | 0.429 | performance | 128 | 51 | 51 | false | fix(sft_trainer): Fix global_tokens and total_tokens metrics always showing 0.0 | 4,854 | volcengine/verl | 16,907 | Python | vermouth1992 | khazic | |
"""Call contiguous on a tensor dict. The contiguous function of tensordict lib will make NonTensorStack.
This function will always return a new tensordict
Args:
data: The input tensordict
Returns:
a tensordict that is contiguous
"""
tensor_dict = {}
non_tensor_dict = {}
... | should be a public function without `maybe_fix_3d_position_ids` | """Call contiguous on a tensor dict. The contiguous function of tensordict lib will make NonTensorStack.
This function will always return a new tensordict
Args:
data: The input tensordict
Returns:
a tensordict that is contiguous
"""
tensor_dict = {}
non_tensor_dict = {}
... | @@ -840,3 +840,10 @@ def contiguous(data: TensorDict) -> TensorDict:
tensor_dict[key] = val.contiguous()
return get_tensordict(tensor_dict=tensor_dict, non_tensor_dict=non_tensor_dict)
+
+def _maybe_fix_3d_position_ids(data: TensorDict): | verl/utils/tensordict_utils.py | 26 | Python | 0.429 | suggestion | 63 | 31 | 33 | false | [misc] fix: fix 3d position_ids for train_mini_batch | 4,860 | volcengine/verl | 16,907 | Python | wuxibin89 | wdl339 |
self.processed_sample_count = 0
# we start from step 1
self.global_steps = 1
self.idle_start_time = None
self.version_start_time = None
# Concurrency control
# Modified by self.pause() or self._should_pause_generation()
self.paused = False
self.ru... | Why do we need more than 1 thread in this case ? Aren't we only making single validate call during validation ?
On high end GPU nodes there are > 100s of CPU core and this will essentially create 100s of unused threads and take memory 100*8MB.
| self.total_generated_samples = 0
self.staleness_samples = 0
self.dropped_stale_samples = 0
self.processed_sample_count = 0
# we start from step 1
self.global_steps = 1
self.idle_start_time = None
self.version_start_time = None
# Concurrency contro... | @@ -168,6 +171,12 @@ def __init__(
self.active_tasks = set()
self.cancel_queue = asyncio.Queue()
+ cpu_cores = multiprocessing.cpu_count()
+ # cpu case use cpu_cores; io case use cpu_cores*2
+ self.validate_executor = ThreadPoolExecutor(max_workers=cpu_cores) | verl/experimental/fully_async_policy/fully_async_rollouter.py | 26 | Python | 0.643 | question | 247 | 51 | 51 | false | [rollout] feat: use rollout and validate parallel process | 4,863 | volcengine/verl | 16,907 | Python | bhks | chenjiaoAngel |
self.version_start_time = time.time()
async def save_checkpoint(self, local_global_step_folder: str):
# WARNING!: Due to the asynchronous nature, there are some in-flight samples
# (pending/cancel/result queue and message queue).
# Therefore, directly saving the state of the dat... | Here we are only making call to validate method once. | and self.current_param_version > 0
) # don't test here in the initial parameter sync
or (validate and self.val_reward_fn is not None)
)
print(
f"[FullyAsyncRollouter] need_validate: {need_validate},"
f"parallel_... | @@ -245,22 +254,71 @@ async def update_param_version(
f",reset staleness_samples to: {self.staleness_samples}"
f",idle_ratio: {idle_ratio}"
)
- val_metrics = None
- if (
- self.val_reward_fn is not None
- and self.config.... | verl/experimental/fully_async_policy/fully_async_rollouter.py | 26 | Python | 0.214 | suggestion | 54 | 51 | 51 | false | [rollout] feat: use rollout and validate parallel process | 4,863 | volcengine/verl | 16,907 | Python | bhks | chenjiaoAngel |
# When concatenating image and video datasets, pop will return None for image or video sample
images = example.pop(self.image_key, None) or []
videos = example.pop(self.video_key, None) or []
image_offset, video_offset = 0, 0
for message in messages:
if not images an... | It's not right here, image may be a PIL.Image or dict. For example, https://huggingface.co/datasets/hiyouga/geometry3k, the image is a PIL.Image. | # When concatenating image and video datasets, pop will return None for image or video sample
images = example.pop(self.image_key, None) or []
videos = example.pop(self.video_key, None) or []
image_offset, video_offset = 0, 0
for message in messages:
if not images an... | @@ -319,11 +320,11 @@ def _build_messages(self, example: dict):
image = image.convert("RGB")
elif isinstance(image, dict) and "bytes" in image:
image["image"] = Image.open(BytesIO(image["bytes"]))
- content_list.append({"type": "i... | verl/utils/dataset/rl_dataset.py | 26 | Python | 0.357 | suggestion | 145 | 51 | 51 | false | [data] fix: build_messages for multi-modal data | 4,864 | volcengine/verl | 16,907 | Python | wuxibin89 | ccilery |
if get_optimizer_pre_hook is not None:
optimizer_pre_hook = get_optimizer_pre_hook(
self.module, module_config, self.engine_config.data_parallel_mode
)
self.optimizer.register_step_pre_hook(optimizer_pre_hook)
self.lr_scheduler = build_lr_scheduler(
... | It looks like there are two separate print statements for displaying GPU memory usage. Can they be combined into one? | optimizer,
train_steps=optim_config.total_training_steps,
lr=optim_config.lr,
lr_min=optim_config.lr_min,
lr_decay_style=optim_config.lr_scheduler_type,
lr_decay_ratio=optim_config.lr_decay_ratio,
lr_warmup_ratio=optim_config.lr_warmup_... | @@ -121,69 +117,100 @@ def __init__(
def initialize(self):
"""
- Build the model, optimizer, and learning rate scheduler under FSDP.
+ Build the model, optimizer, and learning rate scheduler under VeOmni.
Applies device, dtype, and precision configurations, including mixed preci... | verl/workers/engine/veomni/transformer_impl.py | 26 | Python | 0.5 | question | 117 | 51 | 51 | false | [veomni] refactor: minor refactoring to ensure veomni engine compatibility with forward_only mode | 4,889 | volcengine/verl | 16,907 | Python | FightingZhen | ji-huazhong |
# Log to each configured logger
self.validation_generations_logger.log(self.config.trainer.logger, samples, self.global_steps)
def _compute_or_extract_reward(
self,
batch: DataProto,
reward_fn=None,
reward_for_val: bool = False,
sum_reward: bool = False,
... | Add descriptions for `reward_extra_infos` |
# Log to each configured logger
self.validation_generations_logger.log(self.config.trainer.logger, samples, self.global_steps)
def _compute_or_extract_reward(
self,
batch: DataProto,
reward_fn=None,
reward_for_val: bool = False,
sum_reward: bool = False,
... | @@ -551,49 +551,40 @@ def _compute_or_extract_reward(
Args:
batch: DataProto containing the batch data
reward_fn: Reward function to use if rm_scores doesn't exist (for training/validation)
- return_dict: Whether to return dict format with reward_extra_info (for validation)... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.214 | suggestion | 41 | 51 | 51 | false | [data] feat: TransferQueue - Unify the return of reward | 4,902 | volcengine/verl | 16,907 | Python | 0oshowero0 | walterchenchn |
# When rm_scores already exists, extract it directly (format conversion only)
if "rm_scores" in batch.batch.keys():
reward_tensor = batch.batch["rm_scores"]
if sum_reward:
reward_tensor = reward_tensor.sum(dim=-1)
if not reward_for_val and sum_reward:... | unify with `reward_extra_info_dict`? | if "rm_scores" in batch.batch.keys():
reward_tensor = batch.batch["rm_scores"]
if sum_reward:
reward_tensor = reward_tensor.sum(dim=-1)
if not reward_for_val and sum_reward:
return reward_tensor
reward_extra_keys = batch.meta_info... | @@ -551,49 +551,40 @@ def _compute_or_extract_reward(
Args:
batch: DataProto containing the batch data
reward_fn: Reward function to use if rm_scores doesn't exist (for training/validation)
- return_dict: Whether to return dict format with reward_extra_info (for validation)... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.214 | question | 36 | 51 | 51 | false | [data] feat: TransferQueue - Unify the return of reward | 4,902 | volcengine/verl | 16,907 | Python | 0oshowero0 | walterchenchn |
# Copyright 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | Given the significant differences between the implementations of fsdp1+ep and fsdp2+ep in Veomni, I will prioritize completing the functional verification of rl based on fsdp2. | # Copyright 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | @@ -0,0 +1,98 @@
+# Copyright 2025 Bytedance Ltd. and/or its affiliates
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless r... | verl/utils/veomni_utils.py | 25 | Python | 0.357 | suggestion | 176 | 50 | 50 | false | [veomni] feat: support offloading/loading the veomni model/optimizer | 4,916 | volcengine/verl | 16,907 | Python | ji-huazhong | ji-huazhong |
token_ids = final_res.outputs[0].token_ids
log_probs = None
if sampling_params.logprobs is not None:
log_probs = [logprobs[token_ids[i]].logprob for i, logprobs in enumerate(final_res.outputs[0].logprobs)]
routed_experts = None
if self.config.enable_rollout_routing_r... | This is equivalent to `num_preempted=num_preempted`? | token_ids = final_res.outputs[0].token_ids
log_probs = None
if sampling_params.logprobs is not None:
log_probs = [logprobs[token_ids[i]].logprob for i, logprobs in enumerate(final_res.outputs[0].logprobs)]
routed_experts = None
if self.config.enable_rollout_routing_r... | @@ -550,8 +550,14 @@ async def generate(
else:
stop_reason = finish_reason # for more stop reason in the future
+ num_preempted = final_res.outputs[0].get("num_preempted", None)
+
return TokenOutput(
- token_ids=token_ids, log_probs=log_probs, routed_experts=routed_ex... | verl/workers/rollout/vllm_rollout/vllm_async_server.py | 26 | Python | 0.357 | question | 52 | 51 | 51 | false | [rollout,mbridge] feat: add metrics for rollout num preempted and fix mbrideg freeze moe | 4,956 | volcengine/verl | 16,907 | Python | vermouth1992 | RobotGF |
self.training_client = TrainingWorker(config=config)
self.training_client.set_loss_fn(loss_fn=self.loss_fn)
# Note that in SPMD world, this abstraction has to break
self.engine = self.training_client.engine
def _init_engine(self):
# patch optimizer config
if self.co... | move this func to megatron impl |
self.training_client = TrainingWorker(config=config)
self.training_client.set_loss_fn(loss_fn=self.loss_fn)
# Note that in SPMD world, this abstraction has to break
self.engine = self.training_client.engine
def _init_engine(self):
# patch optimizer config
if self.co... | @@ -149,7 +155,9 @@ def _init_engine(self):
if self.test_freq == "after_each_epoch":
self.test_freq = self.steps_per_epoch
+ self.training_client.check_engine_config() | verl/trainer/sft_trainer.py | 26 | Python | 0.143 | refactor | 32 | 51 | 51 | false | [megatron] feat: Support MTP training in SFT | 4,981 | volcengine/verl | 16,907 | Python | ArronHZG | arvyanh |
assert config.no_sync_func is None, (
"When overlap_grad_reduce is True, config.no_sync_func must be None; "
"a custom no_sync_func is not supported when overlapping grad-reduce"
)
config.no_sync_func = [model_chunk.no_sync for model_chunk in model]
... | reuse get_megatron_mtp_loss in verl rl process | return offset
def register_megatron_training_hooks(model: list[torch.nn.Module], optimizer):
from megatron.core.distributed import finalize_model_grads
from megatron.core.utils import get_model_config
try:
from megatron.core.distributed.fsdp.mcore_fsdp_adapter import FullyShardedDataParallel ... | @@ -1242,6 +1243,28 @@ def mapping_string_to_attn_backend(args: dict) -> dict:
return args
+def get_megatron_mtp_loss(output, n_micro_batch): | verl/utils/megatron_utils.py | 26 | Python | 0.143 | suggestion | 47 | 51 | 51 | false | [megatron] feat: Support MTP training in SFT | 4,981 | volcengine/verl | 16,907 | Python | ArronHZG | arvyanh |
return optimizer
def _build_lr_scheduler(self):
from verl.utils.megatron.optimizer import get_megatron_optimizer_param_scheduler
optimizer_scheduler = get_megatron_optimizer_param_scheduler(
optimizer=self.optimizer, config=self.optimizer_config
)
return optimiz... | I advise to move this function to another place to keep the model engine implementation clean | self.optimizer_config,
use_distributed_optimizer=self.engine_config.use_distributed_optimizer,
fp16=self.param_dtype == torch.float16,
)
optimizer = get_megatron_optimizer(model=self.module, config=optim_config_megatron)
register_megatron_training_hooks(self.m... | @@ -262,7 +263,44 @@ def is_mp_src_rank_with_outputs(self):
and mpu.get_context_parallel_rank() == 0
)
+ def check_mtp_config(self): | verl/workers/engine/megatron/transformer_impl.py | 26 | Python | 0.286 | refactor | 93 | 51 | 51 | false | [megatron] feat: Support MTP training in SFT | 4,981 | volcengine/verl | 16,907 | Python | ISEEKYAN | arvyanh |
#!/usr/bin/env bash
set -xeuo pipefail
export RAY_DEDUP_LOGS=0
export HYDRA_FULL_ERROR=1
#TASK_QUEUE_ENABLE,下发优化,图模式设置为1,非图模式设置为2
export TASK_QUEUE_ENABLE=1
export HCCL_ASYNC_ERROR_HANDLING=0
export HCCL_EXEC_TIMEOUT=3600
export HCCL_CONNECT_TIMEOUT=3600
export CPU_AFFINITY_CONF=1
export LD_PRELOAD=/usr/local/lib/li... | The project and experiment names, including the format of parameter configurations, can be uniformly modified with reference to the ascend_training_configuration_guide.md | #!/usr/bin/env bash
set -xeuo pipefail
mkdir -p logs
ulimit -n 32768
## Basic Environment Settings
export RAY_DEDUP_LOGS=0
export HYDRA_FULL_ERROR=1
export TASK_QUEUE_ENABLE=1
export HCCL_EXEC_TIMEOUT=3600
export HCCL_CONNECT_TIMEOUT=3600
export HCCL_ASYNC_ERROR_HANDLING=0
export CPU_AFFINITY_CONF=1
export VLLM_USE_V1... | @@ -0,0 +1,149 @@
+#!/usr/bin/env bash
+set -xeuo pipefail
+
+export RAY_DEDUP_LOGS=0
+export HYDRA_FULL_ERROR=1
+#TASK_QUEUE_ENABLE,下发优化,图模式设置为1,非图模式设置为2
+export TASK_QUEUE_ENABLE=1
+export HCCL_ASYNC_ERROR_HANDLING=0
+export HCCL_EXEC_TIMEOUT=3600
+export HCCL_CONNECT_TIMEOUT=3600
+export CPU_AFFINITY_CONF=1
+expor... | examples/gspo_trainer/run_qwen3_32b_gspo_npu.sh | 21 | Shell | 0.357 | style | 170 | 46 | 46 | false | [doc] feat: add npu gspo practice | 4,988 | volcengine/verl | 16,907 | Python | psyloy | wucong25 |
context_parallel_size: int = 1
ulysses_parallel_size: int = 1
data_parallel_mode: Literal["ddp", "fsdp1", "fsdp2"] = "fsdp"
seed: int = 42
full_determinism: bool = False
mixed_precision: bool = False
init_device: str = "meta"
enable_full_shard: bool = False
ckpt_manager: Literal["dcp... | Please document the supported fields for both interfaces to improve clarity. | reshard_after_forward: bool = True
forward_prefetch: bool = False
use_orig_params: bool = False
entropy_from_logits_with_chunking: bool = False
use_torch_compile: bool = True
entropy_checkpointing: bool = False
strategy: str = "veomni"
data_parallel_size: int = 1
data_parallel_replic... | @@ -256,8 +256,8 @@ class VeOmniEngineConfig(EngineConfig):
load_checkpoint_path: Optional[str] = None
enable_fsdp_offload: bool = False
enable_reentrant: bool = False
- attn_implementation: Optional[Literal["eager", "sdpa", "flash_attention_2", "native-sparse"]] = "flash_attention_2"
- moe_impleme... | verl/workers/config/engine.py | 26 | Python | 0.214 | suggestion | 76 | 32 | 45 | false | [veomni] refactor: no long check the attn_implementation/moe_implementation in VeOmniEngineConfig | 5,019 | volcengine/verl | 16,907 | Python | ji-huazhong | A1waysBeenHere |
and self.profiler_controller.check_this_rank()
and self.profiler_controller.is_discrete_mode()
and not self._auto_stop_profiling
):
await self.tokenizer_manager.stop_profile()
_rollout_worker_actor_cls = ray.remote(ServerAdapter)
class SGLangReplica(RolloutRep... | If auto_stop_profiling is always True, it seems that stop_profile will never execute? Please verify the logic related to auto_stop_profiling | "'num_hidden_layers' or 'num_experts_per_tok'. This feature requires an MoE model "
"configuration that defines these attributes."
)
routed_experts = extract_routed_experts_from_meta_info(output).reshape(
-1, hf_conf... | @@ -389,26 +389,81 @@ async def generate(
return TokenOutput(token_ids=token_ids, log_probs=log_probs, routed_experts=routed_experts)
+ def _profile_args(self, **kwargs) -> dict[str, Any]:
+ global_step = kwargs.pop("global_step", 0)
+ config = self.profiler_controller.tool_config
+ ... | verl/workers/rollout/sglang_rollout/async_sglang_server.py | 26 | Python | 0.357 | suggestion | 140 | 51 | 51 | false | [rollout, perf, cfg] fix: Add global step info and support more profile control params for rollout profiling (sglang backend) | 5,025 | volcengine/verl | 16,907 | Python | tardis-key | bithighrr |
)
else:
token_ids = output["output_ids"]
log_probs = None
routed_experts = None
if self.config.enable_rollout_routing_replay:
if self.config.skip_tokenizer_init:
routed_experts = output.get("meta_info", {}).get("routed_experts", No... | **Keep Profiler Logic Cohesive**: The profiler logic seems to be scattered across the main workflow. It would be better to encapsulate it to keep the main execution path clean and cohesive. Avoid adding too much profiling-specific code directly into the core rollout logic |
async def wake_up(self):
if self.rollout_mode == RolloutMode.HYBRID:
# Call all workers to switch between trainer mode and rollout mode.
await asyncio.gather(*[worker.wake_up.remote() for worker in self.workers])
elif self.rollout_mode == RolloutMode.COLOCATED:
#... | @@ -389,26 +389,81 @@ async def generate(
return TokenOutput(token_ids=token_ids, log_probs=log_probs, routed_experts=routed_experts)
+ def _profile_args(self, **kwargs) -> dict[str, Any]: | verl/workers/rollout/sglang_rollout/async_sglang_server.py | 26 | Python | 0.5 | suggestion | 272 | 51 | 51 | false | [rollout, perf, cfg] fix: Add global step info and support more profile control params for rollout profiling (sglang backend) | 5,025 | volcengine/verl | 16,907 | Python | mengchengTang | bithighrr |
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1
actor_rollout_ref.rollout.log_prob_use_dynamic_bsz=${use_dynamic_bsz}
# Memory Management
actor_rollout_ref.rollout.gpu_memory_utilization=${gpu_memory_utilization}
actor_rollout_ref.rollout.tensor_model_parallel_size=${gen_tp}
actor_... | ```suggestion
```
verl now supports automatic device configuration, so no longer need to explicitly set trainer.device='npu'.
| # Log Probability Inference
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1
actor_rollout_ref.rollout.log_prob_use_dynamic_bsz=${use_dynamic_bsz}
# Memory Management
actor_rollout_ref.rollout.gpu_memory_utilization=${gpu_memory_utilization}
actor_rollout_ref.rollout.tensor_model_pa... | @@ -0,0 +1,182 @@
+#!/bin/bash
+set -xeuo pipefail
+mkdir -p logs
+
+# Project Configuration
+project_name='GRPO-Qwen2.5-32B-BASE-SGLang'
+exp_name='GRPO-Qwen2.5-32B-BASE-FSDP-SGLang'
+
+# Necessary env
+export HCCL_CONNECT_TIMEOUT=1500
+export HCCL_HOST_SOCKET_PORT_RANGE=60000-60050
+export HCCL_NPU_SOCKET_PORT_RANGE=... | examples/grpo_trainer/run_qwen2-32b_sglang_fsdp_npu.sh | 26 | Shell | 0.714 | suggestion | 127 | 49 | 49 | false | [sglang] feat: add NPU GRPO training scripts for Qwen2.5-32B (FSDP/SGLang backends) | 5,062 | volcengine/verl | 16,907 | Python | ji-huazhong | xiazhahe |
OmegaConf.select(self.config.global_profiler.global_tool_config.nsys, "worker_nsight_options")
)
wg_kwargs["device_name"] = self.device_name
for resource_pool, class_dict in self.resource_pool_to_cls.items():
worker_dict_cls = create_colocated_worker_cls(... | Should we always use reward_loop? | self.critic_wg.init_model()
if self.use_reference_policy and not self.ref_in_actor:
if str(Role.RefPolicy) in all_wg:
self.ref_policy_wg = all_wg[str(Role.RefPolicy)]
self.ref_policy_wg.init_model()
else:
# Model engine: Ac... | @@ -893,6 +867,19 @@ def init_workers(self):
if self.ref_in_actor:
self.ref_policy_wg = self.actor_rollout_wg
+ # create reward loop manager
+ if self.use_reward_loop: | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.143 | question | 33 | 51 | 51 | false | [reward] feat: split reward loop manager and agent loop manager | 5,134 | volcengine/verl | 16,907 | Python | wuxibin89 | yyDing1 |
peft_model = getattr(self.actor_module_fsdp, "_fsdp_wrapped_module", self.actor_module_fsdp)
if hasattr(peft_model, "peft_config"): # LoRA
peft_config = peft_model.peft_config.get("default", None)
params = collect_lora_params(
module=self.actor_module_fsdp,
... | Could you update this for `megatron_workers.py` and `engine_workers.py` as well?
BTW I'm not sure if this flag is still reliable these days, it can easily be broken and we also need to be careful about this: https://github.com/verl-project/verl/pull/1464 https://github.com/verl-project/verl/pull/3442 | peft_model = getattr(self.actor_module_fsdp, "_fsdp_wrapped_module", self.actor_module_fsdp)
if hasattr(peft_model, "peft_config"): # LoRA
peft_config = peft_model.peft_config.get("default", None)
params = collect_lora_params(
module=self.actor_module_fsdp,
... | @@ -705,7 +705,11 @@ async def rollout_mode(self):
# When sleep_level=2, base model weights are destroyed during each sleep cycle.
# separately collect and update LoRA weights and base model weights through their respective interfaces.
# Here: params contains LoRA weights, base_model_params c... | verl/workers/fsdp_workers.py | 26 | Python | 0.643 | bug | 304 | 51 | 51 | false | [worker] feat: Avoid redundant base weight sync when engine doesn't sleep | 5,147 | volcengine/verl | 16,907 | Python | HollowMan6 | JohnConnor123 |
import numpy as np
import torch
import torch.distributed
from megatron.core import dist_checkpointing, mpu, tensor_parallel
from megatron.core.dist_checkpointing.mapping import ShardedObject
from megatron.core.transformer.enums import AttnBackend
from packaging import version
from transformers import GenerationConfig
... | it is better to name it directly to indicate the version is >=0.14, not just '0.14'. Because when mcore==0.15, the `mcore_014==True` is confusing.
A better name might be `mcore_post_014`, `mcore_version_ge_014` or some longer name | import numpy as np
import torch
import torch.distributed
from megatron.core import dist_checkpointing, mpu, tensor_parallel
from megatron.core.dist_checkpointing.mapping import ShardedObject
from megatron.core.transformer.enums import AttnBackend
from packaging import version
from transformers import GenerationConfig
... | @@ -43,6 +45,7 @@
# Setup logging
logger = logging.getLogger(__file__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO"))
+mcore_014 = version.parse(megatron.core.__version__) >= version.parse("0.14.0") | verl/utils/checkpoint/megatron_checkpoint_manager.py | 26 | Python | 0.643 | suggestion | 231 | 51 | 51 | false | [megatron] fix: checkpoints uses `fully_reshardable` by default when supported | 5,154 | volcengine/verl | 16,907 | Python | ISEEKYAN | HollowMan6 |
sampling_params.setdefault(
"repetition_penalty",
self.config.get("repetition_penalty", 1.0),
)
sampling_params.pop("logprobs", None)
return_logprob = True
from sglang.srt.managers.io_struct import GenerateReqInput
request = GenerateReqInput(
... | is sglang supporting video_data now? |
sampling_params.setdefault(
"repetition_penalty",
self.config.get("repetition_penalty", 1.0),
)
sampling_params.pop("logprobs", None)
return_logprob = True
from sglang.srt.managers.io_struct import GenerateReqInput
if video_data is not None and ... | @@ -91,6 +92,8 @@ async def _generate_step(
sampling_params=sampling_params,
return_logprob=return_logprob,
image_data=image_data,
+ # TODO: support video input for sglang
+ # video_data=video_data, | verl/experimental/fully_async_policy/sglang_rollout/sglang_async_server.py | 26 | Python | 0.071 | question | 36 | 51 | 51 | false | [vllm] fix: handle multimodal inputs correctly in full async mode | 5,160 | volcengine/verl | 16,907 | Python | ISEEKYAN | Silas-11 |
sampling_params.setdefault(
"repetition_penalty",
self.config.get("repetition_penalty", 1.0),
)
sampling_params.pop("logprobs", None)
return_logprob = True
from sglang.srt.managers.io_struct import GenerateReqInput
request = GenerateReqInput(
... | we'd better give a warning since we pass the video_data but are not using it |
sampling_params.setdefault(
"repetition_penalty",
self.config.get("repetition_penalty", 1.0),
)
sampling_params.pop("logprobs", None)
return_logprob = True
from sglang.srt.managers.io_struct import GenerateReqInput
if video_data is not None and ... | @@ -91,6 +92,8 @@ async def _generate_step(
sampling_params=sampling_params,
return_logprob=return_logprob,
image_data=image_data,
+ # TODO: support video input for sglang
+ # video_data=video_data, | verl/experimental/fully_async_policy/sglang_rollout/sglang_async_server.py | 26 | Python | 0.286 | suggestion | 76 | 51 | 51 | false | [vllm] fix: handle multimodal inputs correctly in full async mode | 5,160 | volcengine/verl | 16,907 | Python | ISEEKYAN | Silas-11 |
# limitations under the License.
import logging
import os
from contextlib import nullcontext
from functools import partial
from itertools import chain
import torch
from codetiming import Timer
from omegaconf import DictConfig, open_dict
from tensordict import NonTensorData, TensorDict
from torch.distributed.device_mes... | Can we move this into megatron transformer_impl? | # limitations under the License.
import functools
import logging
import os
from contextlib import nullcontext
from functools import partial
from itertools import chain
import torch
from codetiming import Timer
from omegaconf import DictConfig, open_dict
from tensordict import NonTensorData, TensorDict
from torch.distr... | @@ -35,6 +35,7 @@
from verl.utils.device import get_device_name, set_expandable_segments
from verl.utils.distributed import initialize_global_process_group_ray
from verl.utils.flops_counter import FlopsCounter
+from verl.utils.megatron.router_replay_patch import RouterReplay, RouterReplayAction, apply_router_replay_... | verl/workers/engine_workers.py | 26 | Python | 0.143 | refactor | 48 | 51 | 51 | false | [algo] feat: support rollout router replay in MegatronEngine | 5,185 | volcengine/verl | 16,907 | Python | vermouth1992 | xhx1022 |
if "response_mask" not in batch.batch.keys():
batch.batch["response_mask"] = compute_response_mask(batch)
# Balance the number of valid tokens across DP ranks.
# NOTE: This usually changes the order of data in the `batch`,
... | we better move all reward compute into a single function
```
with marked_timer("reward", timing_raw, color="yellow"):
reward_tensor, reward_extra_infos_dict = self._compute_reward(...)
``` | del rm_scores, gen_baseline_batch, gen_baseline_output
# repeat to align with repeated responses in rollout
batch = batch.repeat(repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True)
batch = batch.union(gen_batch_ou... | @@ -1458,22 +1463,23 @@ def fit(self):
with marked_timer("reward", timing_raw, color="yellow"):
# compute reward model score
if self.use_rm and "rm_scores" not in batch.batch.keys(): | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.786 | suggestion | 192 | 51 | 51 | false | [reward] refactor: migrate all reward managers to the new asynchronous reward manager | 5,189 | volcengine/verl | 16,907 | Python | wuxibin89 | yyDing1 |
batch = TensorDict(
{
"prompts": prompts, # [1, prompt_length]
"responses": responses, # [1, response_length]
"attention_mask": attention_mask, # [1, prompt_length + response_length]
"input_ids": input_ids, #... | "kwargs" parameter is a bit odd here, explicit maybe better. | batch = TensorDict(
{
"prompts": prompts, # [1, prompt_length]
"responses": responses, # [1, response_length]
"attention_mask": attention_mask, # [1, prompt_length + response_length]
"input_ids": input_ids, #... | @@ -717,7 +717,7 @@ async def _compute_score(self, output, prompts, responses, attention_mask, input
output.reward_score = result["reward_score"]
output.extra_fields["reward_extra_info"] = result["reward_extra_info"]
- def _postprocess(self, inputs: list[_InternalAgentLoopOutput]) -> Data... | verl/experimental/agent_loop/agent_loop.py | 26 | Python | 0.286 | suggestion | 60 | 51 | 51 | false | [reward] fix: preserve input non_tensor_batch in AgentLoopManager when reward_loop_worker_handles is None | 5,195 | volcengine/verl | 16,907 | Python | yyDing1 | none0663 |
{
"prompts": prompt_ids, # [bsz, prompt_length]
"responses": response_ids, # [bsz, response_length]
"response_mask": response_mask, # [bsz, response_length]
"input_ids": input_ids, # [bsz, prompt_length + response_length]
"a... | Can we explicitly define what goes into `non_tensor_batch`? For example, specifying fields like "data_sources" might make things clearer. | if inputs[0].routed_experts is not None:
optional_outputs["routed_experts"] = torch.cat([input.routed_experts for input in inputs], dim=0)
batch = TensorDict(
{
"prompts": prompt_ids, # [bsz, prompt_length]
"responses": response_ids, # [bsz, res... | @@ -757,6 +757,8 @@ def _postprocess(self, inputs: list[_InternalAgentLoopOutput]) -> DataProto:
non_tensor_batch = {
"__num_turns__": np.array([input.num_turns for input in inputs], dtype=np.int32),
}
+ if self.reward_loop_worker_handles is None and kwargs:
+ non_tensor... | verl/experimental/agent_loop/agent_loop.py | 26 | Python | 0.5 | performance | 137 | 51 | 51 | false | [reward] fix: preserve input non_tensor_batch in AgentLoopManager when reward_loop_worker_handles is None | 5,195 | volcengine/verl | 16,907 | Python | yyDing1 | none0663 |
# Handle different transformers versions for Vision2Seq models
import transformers
from packaging import version
if version.parse(transformers.__version__) >= version.parse("4.54.0"):
# transformers >= 4.54.0 uses A... | Infer from model structure doesn't sound like a reliable approach, and it can introduce security risks. Actually, there's already a specialized field for user to pass wether they want to trust remote code or not. https://github.com/verl-project/verl/blob/a8d5bf9d2164de9558447e014a8cbe380c72a44e/verl/workers/config/mode... |
auto_model_cls = AutoModelForCausalLM
elif "ForConditionalGeneration" in model_config.architectures[0]:
# Handle different transformers versions for Vision2Seq models
import transformers
from packaging import version
... | @@ -333,7 +333,16 @@ def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: i
raise NotImplementedError(f"Unknown architecture {model_config['architectures']}")
with init_empty_weights():
- save_model = auto_model_cls.from_config(model_c... | verl/utils/checkpoint/fsdp_checkpoint_manager.py | 26 | Python | 0.786 | security | 439 | 51 | 51 | false | [fsdp] fix: Support trust_remote_code during FSDP HugginFace checkpoint save | 5,200 | volcengine/verl | 16,907 | Python | HollowMan6 | thvasilo |
auto_model_cls = AutoModelForCausalLM
elif "ForConditionalGeneration" in model_config.architectures[0]:
# Handle different transformers versions for Vision2Seq models
import transformers
from packaging import version
... | I don't think this is needed as in any case, when user specifies to `trust_remote_code`, we can just directly pass it to the call (set to `True`) even if model doesn't require it. This can make the code logic more simplified and less error-prone. | auto_model_cls = AutoModelForCausalLM
elif "ForConditionalGeneration" in model_config.architectures[0]:
# Handle different transformers versions for Vision2Seq models
import transformers
from packaging import version
... | @@ -333,7 +336,16 @@ def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: i
raise NotImplementedError(f"Unknown architecture {model_config['architectures']}")
with init_empty_weights():
- save_model = auto_model_cls.from_config(model_c... | verl/utils/checkpoint/fsdp_checkpoint_manager.py | 26 | Python | 0.786 | suggestion | 246 | 51 | 51 | false | [fsdp] fix: Support trust_remote_code during FSDP HugginFace checkpoint save | 5,200 | volcengine/verl | 16,907 | Python | HollowMan6 | thvasilo |
if self.use_rm and not self.use_reward_loop:
raise RuntimeError("Reward model worker group is not supported, please set use_reward_loop=True")
# initialize WorkerGroup
# NOTE: if you want to use a different resource pool for each role, which can support different parallel size,
... | We don't need to pass the config to the trainer, just provide the API so that it is configurable based on actual use case. |
if self.use_rm and not self.use_reward_loop:
raise RuntimeError("Reward model worker group is not supported, please set use_reward_loop=True")
# initialize WorkerGroup
# NOTE: if you want to use a different resource pool for each role, which can support different parallel size,
... | @@ -829,6 +829,7 @@ def init_workers(self):
OmegaConf.select(self.config.global_profiler.global_tool_config.nsys, "worker_nsight_options")
)
wg_kwargs["device_name"] = self.device_name
+ wg_kwargs["master_port_range"] = self.config.trainer.get("master_port_range", N... | verl/trainer/ppo/ray_trainer.py | 26 | Python | 0.429 | suggestion | 122 | 51 | 51 | false | [ray,trainer] feat: add master port range configuration for port range | 5,201 | volcengine/verl | 16,907 | Python | vermouth1992 | RobotGF |
torch.distributed.all_reduce(
loss, op=torch.distributed.ReduceOp.AVG, group=self.engine.get_data_parallel_group()
)
loss = loss.item()
# For grad_norm, we do not perform all reduce because it is already been done when clipping grad
grad_norm = metrics.pop("grad_norm... | make sure it works if images_seqlens = None | torch.distributed.all_reduce(
loss, op=torch.distributed.ReduceOp.AVG, group=self.engine.get_data_parallel_group()
)
loss = loss.item()
# For grad_norm, we do not perform all reduce because it is already been done when clipping grad
grad_norm = metrics.pop("grad_norm... | @@ -187,7 +187,9 @@ def _postprocess_output(self, output, *, global_token_num, delta_time, forward_o
final_metrics[k] = sum(flatten_v) / len(flatten_v)
# compute mfu
if global_token_num is not None:
- estimated_flops, promised_flops = self.flops_counter.estimate_flops(globa... | verl/workers/engine_workers.py | 26 | Python | 0.071 | suggestion | 43 | 51 | 51 | false | [perf] feat: add images_seqlens on mfu calculation for engine_worker | 5,207 | volcengine/verl | 16,907 | Python | tardis-key | alwaysyiyu |
def rms_norm_forward_npu(self, x):
"""NPU optimized implementation for RMSNorm."""
if x.dtype != self.weight.dtype:
x = x.to(self.weight.dtype)
return torch_npu.npu_rms_norm(x, self.weight, epsilon=self.variance_epsilon)[0]
def silu_forward_npu(self, hidden_state):
"""NPU optimized... | Looks like `rms_norm_forward_npu` can be directly reused. | logger = logging.get_logger(__name__)
def rms_norm_forward_npu(self, x):
"""NPU optimized implementation for RMSNorm."""
if x.dtype != self.weight.dtype:
x = x.to(self.weight.dtype)
return torch_npu.npu_rms_norm(x, self.weight, epsilon=self.variance_epsilon)[0]
def silu_forward_npu(sel... | @@ -53,6 +54,34 @@ def apply_rotary_pos_emb_npu(q, k, cos, sin, position_ids=None, unsqueeze_dim=1)
return q_embed.to(q.dtype), k_embed.to(k.dtype)
+def qwen3_next_rms_norm_forward_npu(self, x):
| verl/models/transformers/npu_patch.py | 26 | Python | 0.429 | suggestion | 57 | 51 | 51 | false | [fsdp] feat: add script for qwen3next training on npu platform | 5,236 | volcengine/verl | 16,907 | Python | zheliuyu | zjchenn |
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
... | Better move this to `verl/experimental/reward_loop` | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
... | @@ -31,6 +31,51 @@
from verl.utils.import_utils import load_extern_object
+def migrate_legacy_reward_impl(config): | verl/trainer/main_ppo.py | 26 | Python | 0.429 | refactor | 51 | 51 | 51 | false | [reward] fix: backward compatibility with old reward config | 5,287 | volcengine/verl | 16,907 | Python | wuxibin89 | yyDing1 |
ipaddress.IPv6Address(address)
return True
except ValueError:
return False
def get_free_port(address: str, random_seed: int | None = None) -> int:
family = socket.AF_INET6 if is_valid_ipv6_address(address) else socket.AF_INET
# When a seed is provided, use it to deterministically ... | The open sock will be closed when return, then other process may choose the same port. | # Copyright 2023-2024 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | @@ -70,15 +71,26 @@ def is_valid_ipv6_address(address: str) -> bool:
return False
-def get_free_port(address: str) -> tuple[int, socket.socket]:
- family = socket.AF_INET
- if is_valid_ipv6_address(address):
- family = socket.AF_INET6
+def get_free_port(address: str, random_seed: int | None = ... | verl/utils/net_utils.py | 26 | Python | 0.214 | suggestion | 86 | 30 | 92 | false | [ci] fix: occasional CI failures caused by sglang server port conflicts | 5,310 | volcengine/verl | 16,907 | Python | wuxibin89 | pengwu22 |
import uvicorn
from fastapi import FastAPI
from verl.utils.net_utils import get_free_port
logger = logging.getLogger(__file__)
def get_max_position_embeddings(hf_config) -> int:
max_len = getattr(hf_config, "max_position_embeddings", None)
if max_len is None:
text_config = getattr(hf_config, "text_c... | we should keep sock alive here | from fastapi import FastAPI
logger = logging.getLogger(__file__)
def get_max_position_embeddings(hf_config) -> int:
max_len = getattr(hf_config, "max_position_embeddings", None)
if max_len is None:
text_config = getattr(hf_config, "text_config", None)
if text_config is not None:
m... | @@ -40,7 +40,7 @@ async def run_unvicorn(app: FastAPI, server_args, server_address, max_retries=5)
for i in range(max_retries):
try:
- server_port, sock = get_free_port(server_address)
+ server_port, _ = get_free_port(server_address) | verl/workers/rollout/utils.py | 26 | Python | 0.143 | suggestion | 30 | 51 | 51 | false | [ci] fix: occasional CI failures caused by sglang server port conflicts | 5,310 | volcengine/verl | 16,907 | Python | wuxibin89 | pengwu22 |
seq_losses = torch.sum(loss_mat * loss_mask, dim=-1) # token-sum
seq_mask = (torch.sum(loss_mask, dim=-1) > 0).float() # exclude fully masked sequences
if global_batch_size is None:
global_batch_size = seq_mask.sum()
loss = verl_F.masked_sum(seq_losses, seq_mask) / global_b... | In `seq-mean-token-sum-norm` mode, loss is neither mean over local batch_size nor mean over local token num, which mean it's already invariant to parallelism? Why we still need to adjust it by `dp_size`? | loss = verl_F.masked_sum(loss_mat, loss_mask) / batch_num_tokens * dp_size
elif loss_agg_mode == "seq-mean-token-sum":
seq_losses = torch.sum(loss_mat * loss_mask, dim=-1) # token-sum
seq_mask = (torch.sum(loss_mask, dim=-1) > 0).float() # exclude fully masked sequences
if global_b... | @@ -1054,26 +1054,35 @@ def agg_loss(
"""
if loss_agg_mode == "token-mean":
if batch_num_tokens is None:
+ if dp_size > 1:
+ raise ValueError("(global) batch_num_tokens is required when dp_size > 1")
batch_num_tokens = loss_mask.sum()
loss = verl_F.mask... | verl/trainer/ppo/core_algos.py | 26 | Python | 0.571 | performance | 203 | 51 | 51 | false | [algo] feat: Exception for agg_loss when `dp_size > 1` but global information is absent & fix: correct & consistent loss aggregation for "seq-mean-token-sum-norm" | 5,366 | volcengine/verl | 16,907 | Python | wuxibin89 | tongyx361 |
backend, bucket_size=bucket_size, **engine_kwargs
)
self.extra_rollout_args = args
self.extra_rollout_kwargs = kwargs
if self.server_adapter is None:
self.server_adapter = get_rollout_class(self.rollout_config.name, self.rollout_config.mode)(
*self... | @wuxibin89 Does adding these methods in base reasonable? | backend, bucket_size=bucket_size, **engine_kwargs
)
self.extra_rollout_args = args
self.extra_rollout_kwargs = kwargs
if self.server_adapter is None:
self.server_adapter = get_rollout_class(self.rollout_config.name, self.rollout_config.mode)(
*self... | @@ -291,6 +291,16 @@ async def update_weights(self):
def execute_checkpoint_engine(self, method: str, *args, **kwargs):
return getattr(self.checkpoint_engine, method)(*args, **kwargs)
+ @register(dispatch_mode=Dispatch.ONE_TO_ALL)
+ def get_replica_rank(self) -> int: | verl/checkpoint_engine/base.py | 26 | Python | 0.214 | question | 56 | 51 | 51 | false | [ci] fix: failed trtllm_unit_tests with attribute error | 5,446 | volcengine/verl | 16,907 | Python | vermouth1992 | HollowMan6 |
# set worker info for node affinity scheduling
ray.get(self.register_center.set_worker_info.remote(rank, ray.get_runtime_context().get_node_id()))
@classmethod
def env_keys(cls):
"""The keys of the environment variables that are used to configure the Worker."""
return [
... | No issues found. |
# set worker info for node affinity scheduling
ray.get(self.register_center.set_worker_info.remote(rank, ray.get_runtime_context().get_node_id()))
@classmethod
def env_keys(cls):
"""The keys of the environment variables that are used to configure the Worker."""
return [
... | @@ -22,7 +22,7 @@
import ray
-from verl.utils.device import get_torch_device
+from verl.utils.device import get_torch_device, get_visible_devices_keyword
from .decorator import Dispatch, Execute, register
@@ -144,7 +144,7 @@ def env_keys(cls):
"LOCAL_RANK",
"MASTER_ADDR",
... | verl/single_controller/base/worker.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | [hardware] feat: support ray actor sharing situation on ASCEND NPU | 2,341 | volcengine/verl | 16,907 | Python | FightingZhen | |
code = parameters["code"]
matches = self.code_pattern.findall(code)
if matches:
code = matches[0].strip()
# NOTE: some script may not explicitly print result, we need to add a print statement to the end of the script
lines = code.split("\n")
for i, line in re... | No issues found. | code = parameters["code"]
matches = self.code_pattern.findall(code)
if matches:
code = matches[0].strip()
# NOTE: some script may not explicitly print result, we need to add a print statement to the end of the script
lines = code.split("\n")
for i, line in re... | @@ -112,7 +112,7 @@ def compute_score(data_source, solution_str, ground_truth, extra_info):
num_turns = extra_info["num_turns"]
if result["score"] < 0:
tool_call_reward = (num_turns - 2) / 2 * 0.1
- result["score"] = min(0, result["score"] + tool_call_reward)
+ result["score"] = min(-0.... | recipe/retool/retool.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | [WIP]: Setting DAPO baseline in SGLang multi-turn RL | 3,175 | volcengine/verl | 16,907 | Python | zhaochenyang20 | |
set -x
ENGINE=${1:-vllm}
python3 -m verl.trainer.main_ppo \
algorithm.adv_estimator=grpo \
data.train_files=$HOME/data/geo3k/train.parquet \
data.val_files=$HOME/data/geo3k/test.parquet \
data.train_batch_size=512 \
data.max_prompt_length=1024 \
data.max_response_length=2048 \
data.filter_o... | No issues found. | set -x
ENGINE=${1:-vllm}
python3 -m verl.trainer.main_ppo \
algorithm.adv_estimator=grpo \
data.train_files=$HOME/data/geo3k/train.parquet \
data.val_files=$HOME/data/geo3k/test.parquet \
data.train_batch_size=512 \
data.max_prompt_length=1024 \
data.max_response_length=2048 \
data.filter_o... | @@ -0,0 +1,47 @@
+set -x
+ENGINE=${1:-vllm}
+
+python3 -m verl.trainer.main_ppo \
+ algorithm.adv_estimator=grpo \
+ data.train_files=$HOME/data/geo3k/train.parquet \
+ data.val_files=$HOME/data/geo3k/test.parquet \
+ data.train_batch_size=512 \
+ data.max_prompt_length=1024 \
+ data.max_response_leng... | examples/grpo_trainer/run_qwen2_5_vl-7b_freeze_vision.sh | 0 | Shell | 1 | none | 16 | 48 | 48 | true | [trainer] feat: VL support freeze vision model | 3,178 | volcengine/verl | 16,907 | Python | maijia-cwh | |
gen_tp=4
RAY_DATA_HOME=${RAY_DATA_HOME:-"${HOME}/verl"}
MODEL_PATH=${MODEL_PATH:-"${RAY_DATA_HOME}/models/Qwen3-32B"}
TRAIN_FILE=${TRAIN_FILE:-"${RAY_DATA_HOME}/data/gsm8k/train.parquet"}
TEST_FILE=${TEST_FILE:-"${RAY_DATA_HOME}/data/gsm8k/test.parquet"}
python3 -m verl.trainer.main_ppo \
algorithm.adv_estimator=g... | No issues found. | gen_tp=4
RAY_DATA_HOME=${RAY_DATA_HOME:-"${HOME}/verl"}
MODEL_PATH=${MODEL_PATH:-"${RAY_DATA_HOME}/models/Qwen3-32B"}
TRAIN_FILE=${TRAIN_FILE:-"${RAY_DATA_HOME}/data/gsm8k/train.parquet"}
TEST_FILE=${TEST_FILE:-"${RAY_DATA_HOME}/data/gsm8k/test.parquet"}
python3 -m verl.trainer.main_ppo \
algorithm.adv_estimator=g... | @@ -0,0 +1,59 @@
+set -x
+
+project_name='GRPO-Qwen3'
+exp_name='GRPO-Qwen3-32b-npu'
+gen_tp=4
+RAY_DATA_HOME=${RAY_DATA_HOME:-"${HOME}/verl"}
+MODEL_PATH=${MODEL_PATH:-"${RAY_DATA_HOME}/models/Qwen3-32B"}
+TRAIN_FILE=${TRAIN_FILE:-"${RAY_DATA_HOME}/data/gsm8k/train.parquet"}
+TEST_FILE=${TEST_FILE:-"${RAY_DATA_HOME}/d... | examples/grpo_trainer/run_qwen3-32b_npu.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | [model] feat: add qwen3 grpo 8b/32b script on ASCEND NPU | 3,310 | volcengine/verl | 16,907 | Python | tardis-key | |
gen_tp=4
# Megatron backen
train_tp=4
train_ep=2
train_pp=2
train_cp=1
ray job submit --no-wait --runtime-env="${RUNTIME_ENV}" \
--address "${RAY_ADDRESS}" \
-- python3 -m recipe.dapo.main_dapo \
--config-name="dapo_megatron_trainer" \
data.filter_overlong_prompts=False \
data.train_files="${TRAIN... | No issues found. | gen_tp=4
# Megatron backen
train_tp=4
train_ep=2
train_pp=2
train_cp=1
ray job submit --no-wait --runtime-env="${RUNTIME_ENV}" \
--address "${RAY_ADDRESS}" \
-- python3 -m recipe.dapo.main_dapo \
--config-name="dapo_megatron_trainer" \
data.filter_overlong_prompts=False \
data.train_files="${TRAIN... | @@ -58,6 +58,9 @@ offload=True
max_num_batched_tokens=$((max_prompt_length + max_response_length))
+# vllm
+gen_tp=4
+
# Megatron backen
train_tp=4
train_ep=2 | recipe/dapo/run_dapo_qwen3_moe_30b_megatron_npu.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | [ci, megatron] test: Add Qwen3 Megatron+Mindspeed Ascend NPU CI | 3,465 | volcengine/verl | 16,907 | Python | wlf-darkmatter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.