[Error] Task failed: Can't pickle <function xxx>: it's not the same object as custom_module.char_count_reward_function, completion:
Using the latest version of verl, when testing recipe/char_count/train_grpo.sh, an error occurs when reward_model.reward_manager=prime is used:
(TaskRunner pid=130527) [Error] Task failed: Can't pickle <function char_count_reward_function at 0x7eeec6809480>: it's not the same object as custom_module.char_count_reward_function, completion: There are 4 'v's in the given word x-h-j-v-v-q-v-p-v.
...
I met the similar issue with u
Same issue.
I added these three lines to the sh file I was executing:
custom_reward_function.path="path/to/my/reward.py" \
custom_reward_function.name="reward_fn" \
reward_model.reward_manager=prime \
During execution, the following error occurred:
[Error] Task failed: Can't pickle <function reward_fn at 0x7ed7c556c4c0>: it's not the same object as custom_module.reward_fn, completion:
Does anyone know why this is happening?
For this issue, I currently have a solution. I did not use the prime_reward_manager provided by verl, but instead modified the naive_reward_manager. The path is at verl/workers/reward_manager/naive.py. As you can see, the naive implementation uses a for loop to iterate through the data to calculate rewards, which has become the current bottleneck for reward computation. The loop iteration can be changed to use ProcessPoolExecutor for parallel computation. This reduces the reward computation time to one-fifth of the original and achieves the effect of parallel computation acceleration.
Same issue. I added these three lines to the sh file I was executing:
custom_reward_function.path="path/to/my/reward.py" \custom_reward_function.name="reward_fn" \reward_model.reward_manager=prime \During execution, the following error occurred:[Error] Task failed: Can't pickle <function reward_fn at 0x7ed7c556c4c0>: it's not the same object as custom_module.reward_fn, completion:Does anyone know why this is happening?
For this issue, I currently have a solution. I did not use the
prime_reward_managerprovided by verl, but instead modified thenaive_reward_manager. The path is atverl/workers/reward_manager/naive.py. As you can see, the naive implementation uses a for loop to iterate through the data to calculate rewards, which has become the current bottleneck for reward computation. The loop iteration can be changed to useProcessPoolExecutorfor parallel computation. This reduces the reward computation time to one-fifth of the original and achieves the effect of parallel computation acceleration.Same issue. I added these three lines to the sh file I was executing:
custom_reward_function.path="path/to/my/reward.py" \custom_reward_function.name="reward_fn" \reward_model.reward_manager=prime \During execution, the following error occurred:[Error] Task failed: Can't pickle <function reward_fn at 0x7ed7c556c4c0>: it's not the same object as custom_module.reward_fn, completion:Does anyone know why this is happening?
This helps me.
I just change the verl/workers/reward_manager/prime.py as(with the help of Claude Code)
# Copyright 2024 PRIME team 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 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.
import asyncio
from concurrent.futures import ThreadPoolExecutor # Changed from ProcessPoolExecutor to avoid pickle issues
from functools import partial
from typing import Callable, Optional
import psutil
import torch
from transformers import PreTrainedTokenizer
from verl import DataProto
from verl.utils.reward_score import default_compute_score
from verl.workers.reward_manager import register
async def single_compute_score(evaluation_func, completion, reference, task, task_extra_info, executor, timeout=300.0):
loop = asyncio.get_running_loop()
try:
# Ensure process_completion is called properly
future = loop.run_in_executor(executor, partial(evaluation_func, task, completion, reference, task_extra_info))
return await asyncio.wait_for(future, timeout=timeout)
except asyncio.TimeoutError:
print(f"[Timeout] Task timeout: {completion}")
return None # Default value for timed-out rows
except Exception as e:
print(f"[Error] Task failed: {e}, completion: {completion[:80]}")
return None # Default value for failed rows
async def parallel_compute_score_async(
evaluation_func, completions, references, tasks, extra_info=None, num_processes=64
):
if extra_info is None:
extra_info = [None] * len(tasks)
scores = []
with ThreadPoolExecutor(max_workers=num_processes) as executor: # Changed from ProcessPoolExecutor
# ThreadPoolExecutor shares memory with main process, avoiding pickle serialization issues
# Note: For CPU-bound tasks, ProcessPoolExecutor is better, but for I/O-bound HTTP calls, ThreadPoolExecutor works well
try:
# Create tasks for all rows
tasks_async = [
single_compute_score(evaluation_func, c, r, t, ei, executor, timeout=300.0)
for c, r, t, ei in zip(completions, references, tasks, extra_info, strict=True)
]
results = await asyncio.gather(*tasks_async, return_exceptions=False)
except Exception as e:
print(f"[Exception] async gather failed: {e}")
raise
finally:
# Only cleanup processes for ProcessPoolExecutor
if hasattr(executor, '_processes'):
terminated_count = 0
for pid, proc in executor._processes.items():
try:
p = psutil.Process(pid)
p.terminate()
try:
p.wait(timeout=5)
except psutil.TimeoutExpired:
p.kill()
terminated_count += 1
except Exception:
pass
print(f"[Shutdown] {terminated_count} subprocess(es) terminated.")
# ThreadPoolExecutor threads will be cleaned up automatically
# Process results
for result, completion, reference, task in zip(results, completions, references, tasks, strict=True):
if isinstance(result, Exception) or result is None:
# Handle failed or timed-out tasks
scores.append(0.0)
elif isinstance(result, int | float | bool):
scores.append(float(result))
else:
scores.append(float(result[0]))
return scores
def run_reward_scoring(evaluation_func, completions, references, tasks, extra_info=None, num_processes=64):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(
parallel_compute_score_async(evaluation_func, completions, references, tasks, extra_info, num_processes)
)
finally:
loop.close()
@register("prime")
class PrimeRewardManager:
"""
The Reward Manager used in https://github.com/PRIME-RL/PRIME
"""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
num_examine: int,
compute_score: Optional[Callable] = None,
reward_fn_key: str = "data_source",
) -> None:
self.tokenizer = tokenizer
self.num_examine = num_examine # the number of batches of decoded responses to print to the console
self.compute_score = compute_score or default_compute_score
self.reward_fn_key = reward_fn_key
def verify(self, data):
"""
verify the batch and save as ``acc`` tensor
"""
# batched scoring
prompt_ids = data.batch["prompts"]
response_ids = data.batch["responses"]
sequences_str = self.tokenizer.batch_decode(response_ids, skip_special_tokens=True)
ground_truth = [data_item.non_tensor_batch["reward_model"]["ground_truth"] for data_item in data]
data_sources = data.non_tensor_batch[self.reward_fn_key]
extra_info = data.non_tensor_batch.get("extra_info", None)
assert len(sequences_str) == len(ground_truth) == len(data_sources)
try:
scores = run_reward_scoring(
self.compute_score,
completions=sequences_str,
references=ground_truth,
tasks=data_sources,
extra_info=extra_info,
num_processes=64,
)
except asyncio.TimeoutError:
print("[Timeout] Global reward scoring timed out. Setting all as 0.")
scores = [0.0 for _ in range(len(sequences_str))]
except Exception as e:
print(f"[Error] Unexpected error during scoring. Setting all as 0. {e}")
scores = [0.0 for _ in range(len(sequences_str))]
data.batch["acc"] = torch.tensor(scores, dtype=torch.float32, device=prompt_ids.device)
return scores
def __call__(self, data: DataProto, return_dict: bool = False):
"""We will expand this function gradually based on the available datasets"""
# If there is rm score, we directly return rm score. Otherwise, we compute via rm_score_fn
if "rm_scores" in data.batch.keys():
return data.batch["rm_scores"]
reward_tensor = torch.zeros_like(data.batch["responses"], dtype=torch.float32)
already_print_data_sources = {}
# batched scoring
prompt_ids = data.batch["prompts"]
prompt_length = prompt_ids.shape[-1]
response_ids = data.batch["responses"]
valid_response_length = data.batch["attention_mask"][:, prompt_length:].sum(dim=-1)
sequences_str = self.tokenizer.batch_decode(response_ids, skip_special_tokens=True)
data_sources = data.non_tensor_batch["data_source"]
scores = self.verify(data)
for i in range(len(data)):
data_source = data_sources[i]
reward_tensor[i, valid_response_length[i].item() - 1] = scores[i]
if data_source not in already_print_data_sources:
already_print_data_sources[data_source] = 0
if already_print_data_sources[data_source] < self.num_examine:
already_print_data_sources[data_source] += 1
print(sequences_str)
if return_dict:
return {"reward_tensor": reward_tensor}
else:
return reward_tensor
and the error get fixed.
Hi,
I think I found the root cause of this issue, which it due to the fact that duplicated reward functions that have the same module name are loaded from the same custom code but with different memory id() address, and thus results in ProcessPoolExecutor fail to verify that RayPPOTrainer.reward_fn.score has the correct memory id() address.
I have open a PR #3404 to fix this issue, and my solution does not need to replacing ProcessPoolExecutor with ThreadPoolExecutor.
Hi @fshp971, your PR #3404 will cause error when reward_model.launch_reward_fn_async=True and use custom reward function:
Traceback (most recent call last): File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 42, in main run_ppo(config) File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 85, in run_ppo ray.get(runner.run.remote(config)) File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/auto_init_hook.py", line 22, in auto_init_wrapper return fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/client_mode_hook.py", line 104, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/worker.py", line 2882, in get values, debugger_breakpoint = worker.get_objects(object_refs, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/worker.py", line 968, in get_objects raise value.as_instanceof_cause() ray.exceptions.RayTaskError(RaySystemError): [36mray::TaskRunner.run()[39m (pid=1589418, ip=127.0.0.1, actor_id=caed284ed3b1e781ddfd0d4c01000000, repr=<main_ppo.TaskRunner object at 0x7f435b3af8d0>) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 316, in run trainer.fit() File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/ppo/ray_trainer.py", line 1079, in fit reward_tensor, reward_extra_infos_dict = ray.get(future_reward) ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ray.exceptions.RayTaskError(RaySystemError): [36mray::compute_reward_async()[39m (pid=1607240, ip=127.0.0.1) At least one of the input arguments for this task could not be computed: ray.exceptions.RaySystemError: System error: No module named 'custom_module' traceback: Traceback (most recent call last): ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'custom_module'
Hi @fshp971, your PR #3404 will cause error when reward_model.launch_reward_fn_async=True and use custom reward function:
Traceback (most recent call last): File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 42, in main run_ppo(config) File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 85, in run_ppo ray.get(runner.run.remote(config)) File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/auto_init_hook.py", line 22, in auto_init_wrapper return fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/client_mode_hook.py", line 104, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/worker.py", line 2882, in get values, debugger_breakpoint = worker.get_objects(object_refs, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/worker.py", line 968, in get_objects raise value.as_instanceof_cause() ray.exceptions.RayTaskError(RaySystemError): �[36mray::TaskRunner.run()�[39m (pid=1589418, ip=127.0.0.1, actor_id=caed284ed3b1e781ddfd0d4c01000000, repr=<main_ppo.TaskRunner object at 0x7f435b3af8d0>) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 316, in run trainer.fit() File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/ppo/ray_trainer.py", line 1079, in fit reward_tensor, reward_extra_infos_dict = ray.get(future_reward) ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ray.exceptions.RayTaskError(RaySystemError): �[36mray::compute_reward_async()�[39m (pid=1607240, ip=127.0.0.1) At least one of the input arguments for this task could not be computed: ray.exceptions.RaySystemError: System error: No module named 'custom_module' traceback: Traceback (most recent call last): ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'custom_module'
Hi, could you please share your scirpt for running verl?
Hi @fshp971, your PR #3404 will cause error when reward_model.launch_reward_fn_async=True and use custom reward function: Traceback (most recent call last): File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 42, in main run_ppo(config) File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 85, in run_ppo ray.get(runner.run.remote(config)) File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/auto_init_hook.py", line 22, in auto_init_wrapper return fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/client_mode_hook.py", line 104, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/worker.py", line 2882, in get values, debugger_breakpoint = worker.get_objects(object_refs, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/gpt_venv/lib/python3.11/site-packages/ray/_private/worker.py", line 968, in get_objects raise value.as_instanceof_cause() ray.exceptions.RayTaskError(RaySystemError): �[36mray::TaskRunner.run()�[39m (pid=1589418, ip=127.0.0.1, actor_id=caed284ed3b1e781ddfd0d4c01000000, repr=<main_ppo.TaskRunner object at 0x7f435b3af8d0>) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/main_ppo.py", line 316, in run trainer.fit() File "/opt/tiger/live_strategy_posttrain/verl/verl/trainer/ppo/ray_trainer.py", line 1079, in fit reward_tensor, reward_extra_infos_dict = ray.get(future_reward) ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ray.exceptions.RayTaskError(RaySystemError): �[36mray::compute_reward_async()�[39m (pid=1607240, ip=127.0.0.1) At least one of the input arguments for this task could not be computed: ray.exceptions.RaySystemError: System error: No module named 'custom_module' traceback: Traceback (most recent call last): ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'custom_module'
Hi, could you please share your scirpt for running verl?
like this: with batch reward manager and launch_reward_fn_async before this pr, It works. after update code, when I turn off launch_reward_fn_async, it works too.
the verl script:
custom_reward_function_path=${base_path}/reward_system/reward.py custom_reward_function_name=batch_analysis_reward_fn
python3 -u -m verl.trainer.main_ppo
data.train_files="$train_files"
data.val_files="$eval_files"
data.prompt_key=prompt
data.truncation='error'
data.max_prompt_length=${max_prompt_length}
data.max_response_length=${max_response_length}
data.train_batch_size=${train_prompt_bsz}
data.filter_overlong_prompts=True
data.filter_overlong_prompts_workers=64
actor_rollout_ref.rollout.n=${n_resp_per_prompt}
actor_rollout_ref.actor.use_kl_loss=${use_kl_loss}
actor_rollout_ref.actor.kl_loss_coef=${kl_loss_coef}
actor_rollout_ref.actor.kl_loss_type=${kl_loss_type}
actor_rollout_ref.actor.clip_ratio_low=${clip_ratio_low}
actor_rollout_ref.actor.clip_ratio_high=${clip_ratio_high}
actor_rollout_ref.actor.clip_ratio_c=10.0
algorithm.adv_estimator=${adv_estimator}
algorithm.use_kl_in_reward=${use_kl_in_reward}
algorithm.kl_ctrl.kl_coef=${kl_coef}
algorithm.norm_adv_by_std_in_grpo=False
actor_rollout_ref.actor.policy_loss.loss_mode="gspo"
actor_rollout_ref.model.use_remove_padding=True
actor_rollout_ref.actor.use_dynamic_bsz=${use_dynamic_bsz}
actor_rollout_ref.ref.log_prob_use_dynamic_bsz=${use_dynamic_bsz}
actor_rollout_ref.rollout.log_prob_use_dynamic_bsz=${use_dynamic_bsz}
actor_rollout_ref.actor.entropy_from_logits_with_chunking=True
actor_rollout_ref.ref.entropy_from_logits_with_chunking=True
actor_rollout_ref.ref.entropy_checkpointing=True
actor_rollout_ref.actor.entropy_checkpointing=True
actor_rollout_ref.actor.ppo_max_token_len_per_gpu=${actor_ppo_max_token_len}
actor_rollout_ref.ref.log_prob_max_token_len_per_gpu=${infer_ppo_max_token_len}
actor_rollout_ref.rollout.log_prob_max_token_len_per_gpu=${infer_ppo_max_token_len}
actor_rollout_ref.rollout.name=vllm
actor_rollout_ref.rollout.enforce_eager=False
actor_rollout_ref.rollout.free_cache_engine=True
actor_rollout_ref.model.path="$model_path"
actor_rollout_ref.model.enable_gradient_checkpointing=True
actor_rollout_ref.model.enable_activation_offload=${offload}
actor_rollout_ref.actor.optim.lr=1e-6
actor_rollout_ref.actor.optim.lr_warmup_steps=120
actor_rollout_ref.actor.optim.weight_decay=0.01
actor_rollout_ref.actor.ppo_mini_batch_size=${train_prompt_mini_bsz}
actor_rollout_ref.actor.ppo_micro_batch_size=${train_micro_batch_size}
actor_rollout_ref.actor.fsdp_config.param_offload=${offload}
actor_rollout_ref.actor.fsdp_config.optimizer_offload=${offload}
actor_rollout_ref.actor.strategy=${strategy}
actor_rollout_ref.actor.fsdp_config.offload_policy=${offload}
actor_rollout_ref.ref.strategy=${strategy}
actor_rollout_ref.ref.fsdp_config.param_offload=${offload}
actor_rollout_ref.actor.entropy_coeff=0
actor_rollout_ref.actor.grad_clip=2.0
actor_rollout_ref.actor.loss_agg_mode=${loss_agg_mode}
actor_rollout_ref.actor.ulysses_sequence_parallel_size=${sp_size}
actor_rollout_ref.rollout.gpu_memory_utilization=${gpu_memory_utilization}
actor_rollout_ref.rollout.max_num_seqs=${max_num_seqs}
actor_rollout_ref.rollout.log_prob_micro_batch_size=${infer_micro_batch_size}
actor_rollout_ref.rollout.tensor_model_parallel_size=4
actor_rollout_ref.rollout.enable_chunked_prefill=True
actor_rollout_ref.rollout.max_num_batched_tokens=${max_num_batched_tokens}
actor_rollout_ref.rollout.temperature=${temperature}
actor_rollout_ref.rollout.top_p=${top_p}
actor_rollout_ref.rollout.val_kwargs.temperature=${val_temperature}
actor_rollout_ref.rollout.val_kwargs.top_p=${val_top_p}
actor_rollout_ref.rollout.val_kwargs.do_sample=True
actor_rollout_ref.rollout.val_kwargs.n=2
actor_rollout_ref.ref.log_prob_micro_batch_size=${infer_micro_batch_size}
actor_rollout_ref.ref.ulysses_sequence_parallel_size=${sp_size}
actor_rollout_ref.actor.fsdp_config.fsdp_size=-1
reward_model.reward_manager=batch
reward_model.launch_reward_fn_async=True
custom_reward_function.path=${custom_reward_function_path}
custom_reward_function.name=${custom_reward_function_name}
trainer.logger=['console','wandb']
trainer.project_name="${project_name}"
trainer.experiment_name="${exp_name}"
trainer.n_gpus_per_node=8
trainer.nnodes=1
trainer.val_before_train=False
trainer.test_freq=20
trainer.save_freq=20
trainer.max_actor_ckpt_to_keep=8
trainer.total_epochs=1
trainer.default_local_dir="$ckpts_dir"
trainer.rollout_data_dir="$rollout_dir"
trainer.validation_data_dir="$val_dir"
trainer.balance_batch=False
trainer.resume_mode=auto
Hi @yellowbee686 , I figured out why the bug in your case happens.
It is because reward_model.launch_reward_fn_async=True will tell verl to do reward calculation via ray, but the implementation of loading custom reward modules, whether before or after this PR #3404, unfortunately is incompatible with ray.
The old code can run properly with reward_model.launch_reward_fn_async=True merely because another bug happens to prevent the incompatibility bug from happening... Specifically, in the old code before this PR, if you change the order of creating reward_fn and val_reward_fn in verl/trainer/main_ppo.py to first create val_reward_fn and then reward_fn, you will find the same bug happen again...
I could not explain more details about the mechanism behind this bug for now because I need to go sleep. I will detail the cause of the bug and add another patch to make get_custom_reward_fn compatible with ray in few days.
For now, you can diable my patch to bypass the bug in the setting reward_model.launch_reward_fn_async=True. You can simply replace the line module = sys.modules.get("custom_module", None) in verl/trainer/ppo/reward.py with module = None to ensure custom module is always re-imported from scratch.
Hi @yellowbee686 , I figured out why the bug in your case happens.
It is because
reward_model.launch_reward_fn_async=Truewill tell verl to do reward calculation viaray, but the implementation of loading custom reward modules, whether before or after this PR #3404, unfortunately is incompatible withray.The old code can run properly with
reward_model.launch_reward_fn_async=Truemerely because another bug happens to prevent the incompatibility bug from happening... Specifically, in the old code before this PR, if you change the order of creatingreward_fnandval_reward_fnin verl/trainer/main_ppo.py to first createval_reward_fnand thenreward_fn, you will find the same bug happen again...I could not explain more details about the mechanism behind this bug for now because I need to go sleep. I will detail the cause of the bug and add another patch to make
get_custom_reward_fncompatible withrayin few days.For now, you can diable my patch to bypass the bug in the setting
reward_model.launch_reward_fn_async=True. You can simply replace the linemodule = sys.modules.get("custom_module", None)in verl/trainer/ppo/reward.py withmodule = Noneto ensure custom module is always re-imported from scratch.
Thank you very much~
Hi, thanks for the report. I do not think this issue should be closed without a current-main confirmation yet.
Evidence checked:
- The original
custom_moduleduplicate-loading bug was addressed by PR #3404, merged as commit 491e636a8a6d52161a9b6c70b15850ef0941c1d7. - Current
verl/trainer/ppo/reward.pynow loads custom reward functions throughload_extern_object. - However, current
verl/workers/reward_manager/prime.pystill usesProcessPoolExecutor, so file-based custom reward functions still need to be pickle/import compatible. - Current
verl/utils/import_utils.pysays file-path modules are not added tosys.modulesunless a module name is explicitly provided, while the docs still describe usingcustom_reward_function.path/namefrom a separate file. - A later comment in this thread also points out a separate
reward_model.launch_reward_fn_async=True/ Ray compatibility case.
Could someone who can still reproduce please confirm on the latest main and share:
- the exact verl commit SHA,
- the full reward config override, especially
reward.reward_manager.nameor legacyreward_model.reward_manager, - whether async/Ray reward execution is enabled,
- a minimal custom reward file or whether it is importable as a package module,
- the full current traceback?
中文:感谢反馈。我不建议在没有当前 main 复现确认的情况下直接关闭这个 issue。
已核对的证据:
- 原始的
custom_module重复加载问题已由 PR #3404 修复,并通过 commit 491e636a8a6d52161a9b6c70b15850ef0941c1d7 合并。 - 当前
verl/trainer/ppo/reward.py已改为通过load_extern_object加载自定义 reward 函数。 - 但是当前
verl/workers/reward_manager/prime.py仍然使用ProcessPoolExecutor,因此文件路径形式的自定义 reward 函数仍然需要满足 Python 多进程 pickle/import 约束。 - 当前
verl/utils/import_utils.py说明普通文件路径加载时,如果没有显式传入 module name,就不会加入sys.modules;同时文档仍然推荐通过custom_reward_function.path/name指定单独文件中的自定义 reward。 - 本 issue 后续评论还提到了
reward_model.launch_reward_fn_async=True/ Ray 的另一类兼容性问题。
如果有人仍能在最新 main 复现,请补充:
- 精确的 verl commit SHA;
- 完整 reward 配置覆盖,尤其是
reward.reward_manager.name或旧版reward_model.reward_manager; - 是否启用了异步/Ray reward 执行;
- 最小化的自定义 reward 文件,或说明该函数是否可作为 package module import;
- 当前完整 traceback。
This response was generated by a scheduled Codex GPT5.5 issue processing task.