verl icon indicating copy to clipboard operation
verl copied to clipboard

deepeyes fixed

Open ffengylong opened this issue 9 months ago • 2 comments

System Info

recipe中deepeyes复现会有问题,下面是完整的修改代码方案。

Information

  • [ ] The official example scripts
  • [x] 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

  1. 首先是deepeyes.py中,因为pop会直接将image_key删去,后续row_dict.image_key为空,因此要将 row_dict_images = row_dict.pop(self.image_key, None)注释掉,然后在一开始加入 row_dict_images = row_dict.get(self.image_key, None), Image

  2. 然后是tool_agent_loop.py中需要修改这个函数,主要是要解决new_image_this_turn为空的问题,不可以输入空列表 async def _handle_processing_tools_state(self, agent_data: AgentData) -> AgentState:

     add_messages: list[dict[str, Any]] = []
     new_images_this_turn: list[Any] = []  # Local variable instead of agent_data attribute
    
     tasks = []
     tool_call_names = []
     for tool_call in agent_data.tool_calls[: self.max_parallel_calls]:
         tasks.append(self._call_tool(tool_call, agent_data.tools_kwargs, agent_data))
         tool_call_names.append(tool_call.name)
    
     with simple_timer("tool_calls", agent_data.metrics):
         responses = await asyncio.gather(*tasks)
    
     # Process tool responses and update multi_modal_data
     # Removed: agent_data.new_images_this_turn = []
     for tool_response, tool_reward, _ in responses:
         # Create message from tool response
         if tool_response.image or tool_response.video:
             # Multi-modal content with structured format
             if not getattr(self.processor, "image_processor", None):
                 raise ValueError(
                     "Multimedia data can only be processed by `processor`, but the processor is None. "
                     "This error is often caused if you are using a LLM model but your tool returns multimodal "
                     "data. Plase use a vlm as the base model."
                 )
             content = []
             if tool_response.image:
                 content.append({"type": "image"})
             if tool_response.video:
                 content.append({"type": "video"})
             if tool_response.text:
                 content.append({"type": "text", "text": tool_response.text})
             message = {"role": "tool", "content": content}
         else:
             # Text-only content
             message = {"role": "tool", "content": tool_response.text or ""}
    
         add_messages.append(message)
    
         # Handle image data
         if tool_response.image:
             # Add new image data
             if isinstance(tool_response.image, list):
                 # Ensure all elements in the list are valid image objects
                 for img in tool_response.image:
                     if img is not None:  # Add a check to ensure the image is not None
                         new_images_this_turn.append(img)  # Using local variable
             else:
                 # Ensure the image is not None
                 if tool_response.image is not None:
                     new_images_this_turn.append(tool_response.image)  # Using local variable
    
         # Handle video data
         if tool_response.video:
             # Currently not supported, raise informative error
             logger.warning("Multimedia type 'video' is not currently supported. Only 'image' is supported.")
             raise NotImplementedError(
                 "Multimedia type 'video' is not currently supported. Only 'image' is supported."
             )
    
         if tool_reward is not None:
             agent_data.tool_rewards.append(tool_reward)
     if not new_images_this_turn or len(new_images_this_turn)==0:
         new_images_this_turn=None
     agent_data.messages.extend(add_messages)
    
     if self.tool_parser_name == "gpt-oss":
         logger.info("manually format tool responses for gpt-oss")
         tool_response_text = build_gpt_oss_tool_response_text(add_messages, tool_call_names)
         response_ids = await self.loop.run_in_executor(
             None, lambda: self.tokenizer.encode(tool_response_text, add_special_tokens=False)
         )
     else:
         response_ids = await self.apply_chat_template(
             add_messages,
             images=new_images_this_turn,  # Using local variable
             videos=None,
             remove_system_prompt=True,
         )
    
     if len(agent_data.response_mask) + len(response_ids) >= self.response_length:
         return AgentState.TERMINATED
     # Update prompt_ids and response_mask
    
     if new_images_this_turn:
         if agent_data.image_data is None:
             agent_data.image_data = []
         elif not isinstance(agent_data.image_data, list):
             agent_data.image_data = [agent_data.image_data]
         for img in new_images_this_turn:
             agent_data.image_data.append(img)
    
     agent_data.prompt_ids += response_ids
     agent_data.response_mask += [0] * len(response_ids)
     if agent_data.response_logprobs:
         agent_data.response_logprobs += [0.0] * len(response_ids)
     agent_data.user_turns += 1
     return AgentState.GENERATING
    

主要加入这个在这个上下文中加入这个if判断: if tool_reward is not None: agent_data.tool_rewards.append(tool_reward) if not new_images_this_turn or len(new_images_this_turn)==0: new_images_this_turn=None agent_data.messages.extend(add_messages) 3. `protocal.py中进行以下修改,def union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict: """Union two tensordicts.""" assert tensor_dict1.batch_size == tensor_dict2.batch_size, ( f"Two tensor dict must have identical batch size. " f"Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}" )

# 这些字段在 rollout 后会被扩展(添加 response),应该用新的覆盖旧的
# 生成后的版本包含完整序列(prompt + response),是后续所有计算需要的
ROLLOUT_EXTENDED_FIELDS = {'input_ids', 'attention_mask', 'position_ids'}

for key in tensor_dict2.keys():
    if key not in tensor_dict1.keys():
        # 新字段,直接添加
        tensor_dict1[key] = tensor_dict2[key]
    elif key in ROLLOUT_EXTENDED_FIELDS:
        # Rollout 后的字段,用扩展后的版本覆盖原始版本
        # 原始: [bsz, prompt_len]
        # 扩展: [bsz, prompt_len + response_len]
        # if tensor_dict1[key].shape != tensor_dict2[key].shape:
        #     # print(f"[INFO] Overwriting '{key}' after rollout: "
        #     #       f"{tensor_dict1[key].shape} -> {tensor_dict2[key].shape}")
        tensor_dict1[key] = tensor_dict2[key]
    else:
        # 其他字段必须完全相同
        if not tensor_dict1[key].equal(tensor_dict2[key]):
            print(f"[ERROR] Tensor mismatch for key '{key}':")
            print(f"  shape1: {tensor_dict1[key].shape}")
            print(f"  shape2: {tensor_dict2[key].shape}")
            print(f"  First few values in tensor1: {tensor_dict1[key].flatten()[:10]}")
            print(f"  First few values in tensor2: {tensor_dict2[key].flatten()[:10]}")
            raise AssertionError(
                f"{key} in tensor_dict1 and tensor_dict2 are not the same object"
            )

return tensor_dict1`

总结一下:一共有3个函数需要修改,deepeyes.py,protocal.py和tool_agent_loop.py,不然在启动训练脚本的时候会出现一系列问题。下面附上训练启动脚本

``#!/bin/bash

set -x

export LLM_AS_A_JUDGE_BASE="" export WANDB_API_KEY=""

PROJECT_NAME="deepeyes_multiturn_grpo" EXPERIMENT_NAME="deepeyes_multiturn_grpo_$(date +%m%d_%H%M)"

BASEDIR=

VISUAL_DATASET_TRAIN_0_1_2= VISUAL_DATASET_TRAIN_0_8= EUREKA_DATASET_TRAIN=

REF_MODEL_PATH=

python3 -m verl.trainer.main_ppo
--config-path=${BASEDIR}/verl/recipe/deepeyes/configs
--config-name='deepeyes_multiturn_grpo'
data.train_files=[${VISUAL_DATASET_TRAIN_0_1_2},${EUREKA_DATASET_TRAIN}]
data.val_files=${EUREKA_DATASET_TRAIN}
data.train_batch_size=64
data.max_prompt_length=8192
data.max_response_length=20480
data.return_raw_chat=True
data.return_multi_modal_inputs=False
data.custom_cls.path=/deepeyes.py
data.custom_cls.name=CustomRLHFDataset
custom_reward_function.path=/deepeyes.py
custom_reward_function.name=compute_score
algorithm.adv_estimator=grpo
algorithm.kl_ctrl.kl_coef=0.0
actor_rollout_ref.hybrid_engine=True
actor_rollout_ref.model.path=${REF_MODEL_PATH}
actor_rollout_ref.model.use_remove_padding=True
actor_rollout_ref.model.use_fused_kernels=True
actor_rollout_ref.actor.optim.lr=1e-6
actor_rollout_ref.actor.ppo_mini_batch_size=32
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=1
actor_rollout_ref.actor.use_kl_loss=False
actor_rollout_ref.actor.kl_loss_coef=0.0
actor_rollout_ref.actor.kl_loss_type=low_var_kl
actor_rollout_ref.actor.entropy_coeff=0.0
actor_rollout_ref.actor.checkpoint.save_contents=['model','hf_model','optimizer','extra']
actor_rollout_ref.actor.ulysses_sequence_parallel_size=1
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1
actor_rollout_ref.rollout.tensor_model_parallel_size=1
actor_rollout_ref.rollout.name=vllm
actor_rollout_ref.rollout.mode=async
actor_rollout_ref.rollout.n=4
actor_rollout_ref.rollout.max_num_batched_tokens=32768
actor_rollout_ref.rollout.gpu_memory_utilization=0.7
actor_rollout_ref.rollout.enforce_eager=True
actor_rollout_ref.rollout.free_cache_engine=True
actor_rollout_ref.rollout.enable_chunked_prefill=True
actor_rollout_ref.actor.fsdp_config.param_offload=True
actor_rollout_ref.actor.fsdp_config.optimizer_offload=True
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=1
actor_rollout_ref.ref.fsdp_config.param_offload=True
actor_rollout_ref.rollout.multi_turn.enable=True
actor_rollout_ref.rollout.multi_turn.max_assistant_turns=5
actor_rollout_ref.rollout.multi_turn.max_user_turns=5
actor_rollout_ref.rollout.multi_turn.max_parallel_calls=1
actor_rollout_ref.rollout.multi_turn.tool_config_path=./verl/recipe/deepeyes/configs/image_zoom_in_tool_config.yaml
trainer.critic_warmup=0
trainer.logger=['console','wandb']
trainer.val_before_train=False
trainer.n_gpus_per_node=8
trainer.nnodes=1
trainer.save_freq=40
trainer.test_freq=10000
trainer.project_name=${PROJECT_NAME}
trainer.experiment_name=${EXPERIMENT_NAME}
trainer.default_local_dir=${SAVE_CHECKPOINT_DIR}/${PROJECT_NAME}/${EXPERIMENT_NAME}
+trainer.tensorboard_dir=${SAVE_CHECKPOINT_DIR}/logs/tensorboard
+trainer.rl_logging_board_dir=${SAVE_CHECKPOINT_DIR}/logs/rl_logging_board
trainer.total_epochs=32 2>&1 | tee ./logs/${EXPERIMENT_NAME}.log ``

Expected behavior

最后应该可以成功复现deepeyes。有问题联系[email protected]

ffengylong avatar Feb 20 '26 10:02 ffengylong

Thanks for sharing the fixes for the deepeyes recipe! This is helpful for others trying to reproduce the multi-turn GRPO training.

Key fixes you identified:

  1. deepeyes.py: row_dict.pop(self.image_key, None) removes the key, causing subsequent access to fail. Using row_dict.get() instead preserves the key.

  2. tool_agent_loop.py: Empty new_images_this_turn list being passed to apply_chat_template causes issues. Adding if not new_images_this_turn: new_images_this_turn=None handles this edge case.

  3. protocol.py: The union_tensor_dict function needs to handle fields that get extended during rollout (input_ids, attention_mask, position_ids) by using the new version instead of asserting equality.

Recommendation: Consider submitting a PR with these fixes so they can be merged upstream. This will:

  • Help other users avoid the same issues
  • Ensure the recipe stays working as the codebase evolves

The training script you provided is also a useful reference for multi-turn GRPO configuration.

Kirrito-k423 avatar Mar 17 '26 12:03 Kirrito-k423

中文:

我做了一次只读核对:#5358 里提到的前两个问题在当前代码路径中看起来已经有对应处理。当前 verl-recipe 的 DeepEyes recipe 已经在 _build_messages 前用 row_dict.get(self.image_key, None) 读取图片,并把 images 传给 processor;当前 verl 的 RLHFDataset._build_messages 也使用 example.get(...) 读取多模态字段。tool_agent_loop.py 也已经在没有新图片时传 images=None。

剩下不确定的是第三个问题:union_tensor_dict 目前仍对重复 tensor key 做严格相等断言。曾有 PR #5101 尝试按 DeepEyes 场景修改 protocol.py,但维护者认为不应为 DeepEyes 修改这个通用工具函数,而应该修 DeepEyes 侧逻辑;该 PR 未合并。

因此我建议暂时不要直接关闭。请在当前 verl main + 当前 verl-recipe main 上重新验证 DeepEyes 复现;如果仍失败,请补充最新完整 traceback,尤其说明是否仍卡在 union_tensor_dict / protocol.py 或 PPO rollout 合并阶段。

English:

I did a read-only triage. The first two issues mentioned in #5358 appear to be handled in the current code path. The current verl-recipe DeepEyes recipe reads images with row_dict.get(self.image_key, None) before _build_messages and passes images to the processor; current verl also uses example.get(...) for multimodal fields in RLHFDataset._build_messages. tool_agent_loop.py also passes images=None when there are no new images.

The remaining uncertainty is the third issue: union_tensor_dict still asserts equality for duplicate tensor keys. PR #5101 previously tried to change protocol.py for the DeepEyes case, but a maintainer commented that this shared utility should not be adjusted for DeepEyes and that the fix should be on the DeepEyes side; that PR was closed without merging.

So I would not close this directly yet. Please re-test on current verl main plus current verl-recipe main. If it still reproduces, please add the latest full traceback, especially whether the remaining failure is still in union_tensor_dict / protocol.py or PPO rollout merging.

This response was generated by a scheduled Codex GPT5.5 issue processing task.

Kirrito-k423 avatar Aug 05 '26 01:08 Kirrito-k423