verl icon indicating copy to clipboard operation
verl copied to clipboard

async reward function error

Open zhangxixi551 opened this issue 10 months ago • 5 comments

System Info

I defined a custom asynchronous reward function, and Verl supports asynchronous reward functions. After specifying custom_reward_function.path and custom_reward_function.name, I encountered the following error: File "/verl/trainer/main_ppo.py", line 341, in run trainer.fit() File "/verl/trainer/ppo/ray_trainer.py", line 982, in fit val_metrics = self._validate() File "/verl/trainer/ppo/ray_trainer.py", line 609, in _validate result = self.val_reward_fn(test_batch, return_dict=True) File "/verl/workers/reward_manager/naive.py", line 104, in call reward_tensor[i, valid_response_length - 1] = reward TypeError: can't assign a coroutine to a torch.FloatTensor

The configuration in the training shell script is as follows: python3 -m verl.trainer.main_ppo
--config-path=config
--config-name='ppo_megatron_trainer.yaml'
data.train_files="${TRAIN_FILE}"
data.val_files="${TEST_FILE}"
data.filter_overlong_prompts=True
data.truncation='error'
data.max_prompt_length=${max_prompt_length}
data.max_response_length=${max_response_length}
data.train_batch_size=${train_prompt_bsz}
actor_rollout_ref.rollout.n=${n_resp_per_prompt}
algorithm.adv_estimator=${adv_estimator}
algorithm.use_kl_in_reward=${use_kl_in_reward}
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=low_var_kl
actor_rollout_ref.model.use_remove_padding=True
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.model.path="${MODEL_PATH}"
actor_rollout_ref.actor.optim.lr=1e-6
actor_rollout_ref.actor.ppo_mini_batch_size=${train_prompt_mini_bsz}
actor_rollout_ref.actor.megatron.pipeline_model_parallel_size=${train_pp}
actor_rollout_ref.actor.megatron.tensor_model_parallel_size=${train_tp}
actor_rollout_ref.ref.megatron.pipeline_model_parallel_size=${train_pp}
actor_rollout_ref.ref.megatron.tensor_model_parallel_size=${train_tp}
actor_rollout_ref.actor.megatron.param_offload=${offload}
actor_rollout_ref.actor.megatron.optimizer_offload=${OPTIM_OFFLOAD}
actor_rollout_ref.actor.megatron.grad_offload=${offload}
actor_rollout_ref.actor.entropy_coeff=0
actor_rollout_ref.rollout.gpu_memory_utilization=0.65
actor_rollout_ref.rollout.tensor_model_parallel_size=${gen_tp}
actor_rollout_ref.rollout.name=vllm
actor_rollout_ref.rollout.max_num_batched_tokens=$((max_prompt_length + max_response_length))
actor_rollout_ref.ref.megatron.param_offload=${offload}
trainer.logger='["console","wandb"]'
trainer.project_name="${project_name}"
trainer.experiment_name="${exp_name}"
trainer.n_gpus_per_node=8
trainer.nnodes="${NNODES}"
trainer.test_freq=${test_freq}
trainer.save_freq=${save_freq}
trainer.total_epochs=${total_epochs}
trainer.default_local_dir="${CKPTS_DIR}"
trainer.critic_warmup=0
+reward_model.use_reward_loop=True
custom_reward_function.path=/data/phd/zhangxikai/monad_verl_0.6.1_multi_node_train/verl/custom_reward_fn/monad_reward_fn.py
custom_reward_function.name=monad_reward_fn

During debugging, we found that the program was using the NaiveRewardManager class. If an asynchronous reward function is needed, is it possible to use this class instead? Besides specifying custom_reward_function.path and custom_reward_function.name, is any additional configuration required? Or is it a problem with the verl/trainer/config/ppo_megatron_trainer.yaml configuration file (we noticed a line configured as reward_model@reward_model: megatron_reward_model)?

This question has been puzzling us for many days, and we would be extremely grateful for any answer!

我们自定义了异步的reward function,verl是支持异步reward function的。我指定 custom_reward_function.path 和 custom_reward_function.name后,发现如下报错:

File "/verl/trainer/main_ppo.py", line 341, in run trainer.fit() File "/verl/trainer/ppo/ray_trainer.py", line 982, in fit val_metrics = self._validate() File "/verl/trainer/ppo/ray_trainer.py", line 609, in _validate result = self.val_reward_fn(test_batch, return_dict=True) File "/verl/workers/reward_manager/naive.py", line 104, in call reward_tensor[i, valid_response_length - 1] = reward TypeError: can't assign a coroutine to a torch.FloatTensor

训练shell脚本中的配置如下: python3 -m verl.trainer.main_ppo
--config-path=config
--config-name='ppo_megatron_trainer.yaml'
data.train_files="${TRAIN_FILE}"
data.val_files="${TEST_FILE}"
data.filter_overlong_prompts=True
data.truncation='error'
data.max_prompt_length=${max_prompt_length}
data.max_response_length=${max_response_length}
data.train_batch_size=${train_prompt_bsz}
actor_rollout_ref.rollout.n=${n_resp_per_prompt}
algorithm.adv_estimator=${adv_estimator}
algorithm.use_kl_in_reward=${use_kl_in_reward}
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=low_var_kl
actor_rollout_ref.model.use_remove_padding=True
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.model.path="${MODEL_PATH}"
actor_rollout_ref.actor.optim.lr=1e-6
actor_rollout_ref.actor.ppo_mini_batch_size=${train_prompt_mini_bsz}
actor_rollout_ref.actor.megatron.pipeline_model_parallel_size=${train_pp}
actor_rollout_ref.actor.megatron.tensor_model_parallel_size=${train_tp}
actor_rollout_ref.ref.megatron.pipeline_model_parallel_size=${train_pp}
actor_rollout_ref.ref.megatron.tensor_model_parallel_size=${train_tp}
actor_rollout_ref.actor.megatron.param_offload=${offload}
actor_rollout_ref.actor.megatron.optimizer_offload=${OPTIM_OFFLOAD}
actor_rollout_ref.actor.megatron.grad_offload=${offload}
actor_rollout_ref.actor.entropy_coeff=0
actor_rollout_ref.rollout.gpu_memory_utilization=0.65
actor_rollout_ref.rollout.tensor_model_parallel_size=${gen_tp}
actor_rollout_ref.rollout.name=vllm
actor_rollout_ref.rollout.max_num_batched_tokens=$((max_prompt_length + max_response_length))
actor_rollout_ref.ref.megatron.param_offload=${offload}
trainer.logger='["console","wandb"]'
trainer.project_name="${project_name}"
trainer.experiment_name="${exp_name}"
trainer.n_gpus_per_node=8
trainer.nnodes="${NNODES}"
trainer.test_freq=${test_freq}
trainer.save_freq=${save_freq}
trainer.total_epochs=${total_epochs}
trainer.default_local_dir="${CKPTS_DIR}"
trainer.critic_warmup=0
+reward_model.use_reward_loop=True
custom_reward_function.path=/data/phd/zhangxikai/monad_verl_0.6.1_multi_node_train/verl/custom_reward_fn/monad_reward_fn.py
custom_reward_function.name=monad_reward_fn

我们在debug时发现程序走了 NaiveRewardManager 这个类。若需用异步reward function,是不能走这个类吗?除了指定 custom_reward_function.path 和 custom_reward_function.name,还需额外进行其他什么配置吗?或者是verl/trainer/config/ppo_megatron_trainer.yaml这个配置文件的问题(我们注意到其中有一行配置为reward_model@reward_model: megatron_reward_model)?

该问题困惑我们很多天了,若能收到解答,我们将不胜感激!

Information

  • [x] The official example scripts
  • [ ] My own modified scripts

Tasks

  • [x] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
  • [ ] My own task or dataset (give details below)

Reproduction

python3 -m verl.trainer.main_ppo
--config-path=config
--config-name='ppo_megatron_trainer.yaml'
data.train_files="${TRAIN_FILE}"
data.val_files="${TEST_FILE}"
data.filter_overlong_prompts=True
data.truncation='error'
data.max_prompt_length=${max_prompt_length}
data.max_response_length=${max_response_length}
data.train_batch_size=${train_prompt_bsz}
actor_rollout_ref.rollout.n=${n_resp_per_prompt}
algorithm.adv_estimator=${adv_estimator}
algorithm.use_kl_in_reward=${use_kl_in_reward}
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=low_var_kl
actor_rollout_ref.model.use_remove_padding=True
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=${micro_batch_size_per_gpu}
actor_rollout_ref.model.path="${MODEL_PATH}"
actor_rollout_ref.actor.optim.lr=1e-6
actor_rollout_ref.actor.ppo_mini_batch_size=${train_prompt_mini_bsz}
actor_rollout_ref.actor.megatron.pipeline_model_parallel_size=${train_pp}
actor_rollout_ref.actor.megatron.tensor_model_parallel_size=${train_tp}
actor_rollout_ref.ref.megatron.pipeline_model_parallel_size=${train_pp}
actor_rollout_ref.ref.megatron.tensor_model_parallel_size=${train_tp}
actor_rollout_ref.actor.megatron.param_offload=${offload}
actor_rollout_ref.actor.megatron.optimizer_offload=${OPTIM_OFFLOAD}
actor_rollout_ref.actor.megatron.grad_offload=${offload}
actor_rollout_ref.actor.entropy_coeff=0
actor_rollout_ref.rollout.gpu_memory_utilization=0.65
actor_rollout_ref.rollout.tensor_model_parallel_size=${gen_tp}
actor_rollout_ref.rollout.name=vllm
actor_rollout_ref.rollout.max_num_batched_tokens=$((max_prompt_length + max_response_length))
actor_rollout_ref.ref.megatron.param_offload=${offload}
trainer.logger='["console","wandb"]'
trainer.project_name="${project_name}"
trainer.experiment_name="${exp_name}"
trainer.n_gpus_per_node=8
trainer.nnodes="${NNODES}"
trainer.test_freq=${test_freq}
trainer.save_freq=${save_freq}
trainer.total_epochs=${total_epochs}
trainer.default_local_dir="${CKPTS_DIR}"
trainer.critic_warmup=0
+reward_model.use_reward_loop=True
custom_reward_function.path=/data/phd/zhangxikai/monad_verl_0.6.1_multi_node_train/verl/custom_reward_fn/monad_reward_fn.py
custom_reward_function.name=monad_reward_fn

Expected behavior

We hope to be able to properly support asynchronous reward functions!

zhangxixi551 avatar Jan 28 '26 04:01 zhangxixi551

The reward computation is invoked in the following order: reward_manager -> customized_reward_function. It's ok to invoke the naive manager Based on the error, please check your customized reward_function. It is currently returning a coroutine object instead of an actual value. You need to await this object inside the reward function to ensure that a concrete value is returned.

yyDing1 avatar Jan 28 '26 05:01 yyDing1

The reward computation is invoked in the following order: reward_manager -> customized_reward_function. It's ok to invoke the naive manager Based on the error, please check your customized reward_function. It is currently returning a coroutine object instead of an actual value. You need to await this object inside the reward function to ensure that a concrete value is returned.

I'm glad to receive your reply! During debugging, I observed that the actual error occurred in the following code: In the __call__ method of the NaiveRewardManager class:

       score = self.compute_score(
            data_source=data_source,
            solution_str=response_str,
            ground_truth=ground_truth,
            extra_info=extra_info,
        )

        if isinstance(score, dict):
            reward = score["score"]
            # Store the information including original reward
            for key, value in score.items():
                reward_extra_info[key].append(value)
        else:
            reward = score

        reward_tensor[i, valid_response_length - 1] = reward

The self.compute_score above is my custom reward function defined using async def. However, this is a coroutine. Do I need to modify the __call__ method of the NaiveRewardManager class, changing score = self.compute_score to score = await self.compute_score? But if I do that, the __call__ method of the NaiveRewardManager class also needs to be changed to async def. My custom reward function is as follows:

async def my_reward_fn(data_source, solution_str, ground_truth, extra_info):

    all_rewards, final_reward = await asyncio.gather(
       f1(solution_str, ground_truth),
       f2(solution_str, ground_truth)
    )
    
    middle_avg = sum(all_rewards) / len(all_rewards) 

    final_score =  middle_avg + final_reward
    
    return final_score

We would be very grateful for your reply!

很高兴收到您的回信!我在进行debug时观察到,真正报错的是如下代码: 在NaiveRewardManager类的__call__方法中:

       score = self.compute_score(
            data_source=data_source,
            solution_str=response_str,
            ground_truth=ground_truth,
            extra_info=extra_info,
        )

        if isinstance(score, dict):
            reward = score["score"]
            # Store the information including original reward
            for key, value in score.items():
                reward_extra_info[key].append(value)
        else:
            reward = score

        reward_tensor[i, valid_response_length - 1] = reward

上面的self.compute_score就是我用async def自定义的reward function。但这是一个coroutine。难道我需要更改NaiveRewardManager类的__call__方法,将 score = self.compute_score 改为 score = await self.compute_score 吗?但是这样一来,NaiveRewardManager类的__call__方法也要改成async def的。我自定义的reward function如下:

async def my_reward_fn(data_source, solution_str, ground_truth, extra_info):

    all_rewards, final_reward = await asyncio.gather(
       f1(solution_str, ground_truth),
       f2(solution_str, ground_truth)
    )
    
    middle_avg = sum(all_rewards) / len(all_rewards) 

    final_score =  middle_avg + final_reward
    
    return final_score

非常期待您的回复,我们将不胜感激!

zhangxixi551 avatar Jan 28 '26 06:01 zhangxixi551

Could you check if the reward manager correctly judges the type of reward function and fail into correct branch:

https://github.com/verl-project/verl/blob/b63fe7f5361b65436ec003f5f85b2bb1756f0f1b/verl/experimental/reward_loop/reward_manager/naive.py#L66-L84

yyDing1 avatar Jan 28 '26 06:01 yyDing1

The expected behavior is:

The reward score should be present in the batch after self.async_rollout_manager.generate_sequences(test_gen_batch_padded) (the reward computation process has been done in the agent loop)

As "rm_scores" has existed in the batch, the val_reward_fn will not compute reward scores.

But I observe it still uses val_reward_fn to compute reward scores, so you may check the intermediate results to figure out where sth goes wrong.

yyDing1 avatar Jan 28 '26 07:01 yyDing1

The expected behavior is:

The reward score should be present in the batch after self.async_rollout_manager.generate_sequences(test_gen_batch_padded) (the reward computation process has been done in the agent loop)

As "rm_scores" has existed in the batch, the val_reward_fn will not compute reward scores.

But I observe it still uses val_reward_fn to compute reward scores, so you may check the intermediate results to figure out where sth goes wrong.

Thank you so much for your reply! We found that updating the Verl code to the latest version successfully resolved the issue. Thank you so much for your help!

zhangxixi551 avatar Jan 28 '26 12:01 zhangxixi551