verl icon indicating copy to clipboard operation
verl copied to clipboard

RLHFDataset filter overlong prompt doc2len function is not correct perfectly

Open zhaozhaoooo opened this issue 7 months ago • 1 comments

System Info

4*8 40G A800 Qwen3.5-9B GRPO

the script is:

#!/usr/bin/env bash
# Qwen3.5-35B-A3B MoE GRPO RL with Megatron (single node, 8 GPUs, geo3k dataset)
#
# notes on vllm:
#     by 20260225, the latest vllm nightly does not support qwen3.5 rollout, to use this script, you need to 
#         1. wait until vllm supports qwen3.5 officially, and build a verl docker with that version of vllm
#         2. self build a verl docker image with vllm from source code with qwen3.5 support (main branch 20260225 is OK)
#     I succeeded in running this script with the main branch of vllm on 20260225, yet there are still some minor issues
#     the vllm qwen3.5 during initialization, need to be fixed. Also, the cuda_graph is somehow not working, need to be 
#     fixed, either by verl team with supoorts to vllm0.16, or by vllm team.
# Requirements:
#   - 8 GPUs (80GB each, e.g. 1x8 H100/H200)
#   - Additional packages on top of the base image:
#       pip install --upgrade transformers
#       pip install flash-linear-attention
#       pip install -U git+https://github.com/ISEEKYAN/mbridge.git
#   - Megatron-LM==0.16.0
#
# Qwen3.5 architecture notes:
#   Qwen3.5 uses Gated Delta Net (GDN) linear attention which currently does
#   NOT support packed sequences (THD format) in Megatron-LM. Therefore:
#     - model.use_remove_padding=False           (deprecated option, will be removed in the future forces bshd compute format)
#     - actor.megatron.use_remove_padding=False  (forces bshd compute format)
#     - actor.use_dynamic_bsz=False              (required for bshd mode)
#
#   Once Megatron-LM adds THD support for Qwen3.5 GDN, use_remove_padding
#   can be set to True for better performance.
#
# Tested parallelism config (8 GPUs / 1 node):
#   TP=2 PP=1 CP=1 EP=8 ETP=1 GEN_TP=8
#

export CUDA_DEVICE_MAX_CONNECTIONS=1
export VLLM_USE_V1=1
export VLLM_ALLREDUCE_USE_SYMM_MEM=0

set -xeuo pipefail

########################### Quick Config ###########################

TP=${TP:-4}
PP=${PP:-4}
CP=${CP:-1}
EP=${EP:-8}
ETP=${ETP:-1}
GEN_TP=${GEN_TP:-8}

ALL_OFFLOAD=${ALL_OFFLOAD:-True}

rollout_name="vllm"
project_name='verl_grpo_GeneralRL'
exp_name='qwen3_5_9b_megatron'
adv_estimator=grpo
CKPT_SAVE_DIR='XXX'

HF_MODEL_PATH=${HF_MODEL_PATH:-"Qwen3.5-9B"}
TRAIN_DATA="XXX"
test_path=${test_path:-XXX}
########################### Parameter Arrays ###########################

DATA=(
    data.train_files=$TRAIN_DATA
    data.val_files=${test_path}
    data.train_batch_size=32
    data.max_prompt_length=1024
    data.max_response_length=2048
    data.truncation='left'
    data.filter_overlong_prompts=True
)

MODEL=(
    actor_rollout_ref.model.path=${HF_MODEL_PATH}
    actor_rollout_ref.model.trust_remote_code=True
    actor_rollout_ref.model.use_remove_padding=False
)

ACTOR=(
    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.ppo_max_token_len_per_gpu=4096
    actor_rollout_ref.actor.use_dynamic_bsz=False
    actor_rollout_ref.actor.use_kl_loss=True
    actor_rollout_ref.actor.kl_loss_coef=0.01
    actor_rollout_ref.actor.kl_loss_type=low_var_kl
    actor_rollout_ref.actor.entropy_coeff=0
    actor_rollout_ref.actor.megatron.use_mbridge=True
    actor_rollout_ref.actor.megatron.vanilla_mbridge=True
    actor_rollout_ref.actor.megatron.use_remove_padding=False
    actor_rollout_ref.actor.megatron.tensor_model_parallel_size=${TP}
    actor_rollout_ref.actor.megatron.pipeline_model_parallel_size=${PP}
    actor_rollout_ref.actor.megatron.context_parallel_size=${CP}
    actor_rollout_ref.actor.megatron.expert_tensor_parallel_size=${ETP}
    actor_rollout_ref.actor.megatron.param_offload=${ALL_OFFLOAD}
    actor_rollout_ref.actor.megatron.optimizer_offload=${ALL_OFFLOAD}
    actor_rollout_ref.actor.megatron.grad_offload=${ALL_OFFLOAD}
    actor_rollout_ref.actor.megatron.dtype=bfloat16
    actor_rollout_ref.actor.megatron.sequence_parallel=True
    actor_rollout_ref.actor.checkpoint.async_save=False
    actor_rollout_ref.actor.checkpoint.save_contents=[model,extra]
    ++actor_rollout_ref.actor.megatron.override_transformer_config.attention_backend=auto
    +actor_rollout_ref.actor.megatron.override_transformer_config.recompute_method=uniform
    +actor_rollout_ref.actor.megatron.override_transformer_config.recompute_granularity=full
    +actor_rollout_ref.actor.megatron.override_transformer_config.recompute_num_layers=4
    +actor_rollout_ref.actor.megatron.override_transformer_config.moe_aux_loss_coeff=0.01
    +actor_rollout_ref.actor.megatron.override_transformer_config.moe_z_loss_coeff=0.001
    +actor_rollout_ref.actor.optim.override_optimizer_config.optimizer_offload_fraction=1
    +actor_rollout_ref.actor.optim.override_optimizer_config.overlap_cpu_optimizer_d2h_h2d=True
    +actor_rollout_ref.actor.optim.override_optimizer_config.use_precision_aware_optimizer=True
    +actor_rollout_ref.actor.optim.override_optimizer_config.optimizer_cpu_offload=True
)

ROLLOUT=(
    actor_rollout_ref.rollout.name=${rollout_name}
    actor_rollout_ref.rollout.tensor_model_parallel_size=${GEN_TP}
    actor_rollout_ref.rollout.gpu_memory_utilization=0.45
    actor_rollout_ref.rollout.n=5
    actor_rollout_ref.rollout.dtype=bfloat16
    actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1
    actor_rollout_ref.rollout.log_prob_use_dynamic_bsz=False
    actor_rollout_ref.rollout.log_prob_max_token_len_per_gpu=4096
    actor_rollout_ref.rollout.checkpoint_engine.update_weights_bucket_megabytes=4096
    actor_rollout_ref.rollout.prompt_length=1024
    actor_rollout_ref.rollout.response_length=2048
)

REF=(
    actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=1
    actor_rollout_ref.ref.log_prob_use_dynamic_bsz=False
    actor_rollout_ref.ref.log_prob_max_token_len_per_gpu=4096
    actor_rollout_ref.ref.megatron.tensor_model_parallel_size=${TP}
    actor_rollout_ref.ref.megatron.pipeline_model_parallel_size=${PP}
    actor_rollout_ref.ref.megatron.context_parallel_size=${CP}
    actor_rollout_ref.ref.megatron.expert_model_parallel_size=${EP}
    actor_rollout_ref.ref.megatron.expert_tensor_parallel_size=${ETP}
    actor_rollout_ref.ref.megatron.param_offload=${ALL_OFFLOAD}
    actor_rollout_ref.ref.megatron.sequence_parallel=True
)

ALGORITHM=(
    algorithm.adv_estimator=${adv_estimator}
    algorithm.use_kl_in_reward=False
)

TRAINER=(
    trainer.critic_warmup=0
    trainer.default_local_dir=${CKPT_SAVE_DIR}
    trainer.logger='["console","wandb"]'
    trainer.project_name=${project_name}
    trainer.experiment_name=${exp_name}
    trainer.n_gpus_per_node=8
    trainer.nnodes=4
    trainer.save_freq=10
    trainer.val_before_train=False
    trainer.test_freq=10
    trainer.total_epochs=5
    trainer.max_actor_ckpt_to_keep=5
    ++trainer.async_save=False                    # 关闭异步保存
    ++trainer.save_use_memory_cache=False         # 关闭内存缓存
    ++trainer.save_optimizer_state=False          # 关闭保存优化器状态
)

########################### Launch ###########################

ray job submit \
    --runtime-env=verl/trainer/runtime_env.yaml \
    --no-wait \
    -- \
    python3 -m verl.trainer.main_ppo \
    --config-path=config \
    --config-name='ppo_megatron_trainer.yaml' \
    "${DATA[@]}" \
    "${ALGORITHM[@]}" \
    "${MODEL[@]}" \
    "${ROLLOUT[@]}" \
    "${ACTOR[@]}" \
    "${REF[@]}" \
    "${TRAINER[@]}" \
    "$@"

then when the doc2len dunction is not perfectly correct, the overlong prompt is not filtered, it will cause error in verl/experimental/agent_loop/agent_loop.py: prompt_ids = torch.cat([input.prompt_ids for input in inputs], dim=0) so the doc2len function should be changed to:

def maybe_filter_out_long_prompts(self, dataframe: datasets.Dataset = None):
        # filter out too long prompts
        if self.filter_overlong_prompts:
            tokenizer = self.tokenizer
            processor = self.processor
            prompt_key = self.prompt_key
            image_key = self.image_key
            video_key = self.video_key

            print(f"processor is {processor}")

            if processor is not None:
                from verl.utils.dataset.vision_utils import process_image, process_video

                def doc2len(doc) -> int:
                    try:
                        messages = self._build_messages(doc)
                        new_messages = list(messages)
                        from qwen_vl_utils import process_vision_info
                        images, videos = process_vision_info(new_messages, image_patch_size=processor.image_processor.patch_size, return_video_metadata=True)
                        from verl.utils.chat_template import apply_chat_template
                        raw_prompt = apply_chat_template(
                            processor,
                            new_messages,
                            tools=None,
                            add_generation_prompt=True,
                            tokenize=False,
                            **self.apply_chat_template_kwargs,
                        )
                        if videos is not None:
                            videos, video_metadatas = zip(*videos, strict=False)
                            videos, video_metadatas = list(videos), list(video_metadatas)
                        else:
                            video_metadatas = None
                        model_inputs = self.processor(
                            text=[raw_prompt],
                            images=images,
                            videos=videos,
                            video_metadata=video_metadatas,
                            return_tensors="pt",
                            do_sample_frames=False,
                        )
                        prompt_ids = normalize_token_ids(model_inputs.pop("input_ids"))
                        # pass tool schemas if available so the processor can format prompts
                        return len(prompt_ids)
                    except Exception:
                        print("Error processing one of the samples, skipping...")
                        traceback.print_exc()
                        return self.max_prompt_length + 1

            else:

                def doc2len(doc) -> int:
                    try:
                        apply_kwargs = dict(**self.apply_chat_template_kwargs)
                        if self.tool_schemas is not None:
                            apply_kwargs["tools"] = self.tool_schemas

                        # Keep explicit tokenization to avoid transformers version default changes.
                        apply_kwargs.pop("tokenize", None)
                        apply_kwargs.pop("return_dict", None)
                        apply_kwargs.pop("return_tensors", None)

                        tokenized_prompt = tokenizer.apply_chat_template(
                            doc[prompt_key], add_generation_prompt=True, tokenize=True, **apply_kwargs
                        )
                        return len(normalize_token_ids(tokenized_prompt))
                    except Exception:
                        print("Error processing one of the samples, skipping...")
                        traceback.print_exc()
                        return self.max_prompt_length + 1

            dataframe = dataframe.filter(
                lambda doc: doc2len(doc) <= self.max_prompt_length,
                num_proc=self.num_workers,
                desc=f"Filtering prompts longer than {self.max_prompt_length} tokens",
            )

            print(f"filter dataset len: {len(dataframe)}")
        return dataframe

Information

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

Tasks

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

Reproduction

None

Expected behavior

the function should be changed to:

def maybe_filter_out_long_prompts(self, dataframe: datasets.Dataset = None):
        # filter out too long prompts
        if self.filter_overlong_prompts:
            tokenizer = self.tokenizer
            processor = self.processor
            prompt_key = self.prompt_key
            image_key = self.image_key
            video_key = self.video_key

            print(f"processor is {processor}")

            if processor is not None:
                from verl.utils.dataset.vision_utils import process_image, process_video

                def doc2len(doc) -> int:
                    try:
                        messages = self._build_messages(doc)
                        new_messages = list(messages)
                        from qwen_vl_utils import process_vision_info
                        images, videos = process_vision_info(new_messages, image_patch_size=processor.image_processor.patch_size, return_video_metadata=True)
                        from verl.utils.chat_template import apply_chat_template
                        raw_prompt = apply_chat_template(
                            processor,
                            new_messages,
                            tools=None,
                            add_generation_prompt=True,
                            tokenize=False,
                            **self.apply_chat_template_kwargs,
                        )
                        if videos is not None:
                            videos, video_metadatas = zip(*videos, strict=False)
                            videos, video_metadatas = list(videos), list(video_metadatas)
                        else:
                            video_metadatas = None
                        model_inputs = self.processor(
                            text=[raw_prompt],
                            images=images,
                            videos=videos,
                            video_metadata=video_metadatas,
                            return_tensors="pt",
                            do_sample_frames=False,
                        )
                        prompt_ids = normalize_token_ids(model_inputs.pop("input_ids"))
                        # pass tool schemas if available so the processor can format prompts
                        return len(prompt_ids)
                    except Exception:
                        print("Error processing one of the samples, skipping...")
                        traceback.print_exc()
                        return self.max_prompt_length + 1

            else:

                def doc2len(doc) -> int:
                    try:
                        apply_kwargs = dict(**self.apply_chat_template_kwargs)
                        if self.tool_schemas is not None:
                            apply_kwargs["tools"] = self.tool_schemas

                        # Keep explicit tokenization to avoid transformers version default changes.
                        apply_kwargs.pop("tokenize", None)
                        apply_kwargs.pop("return_dict", None)
                        apply_kwargs.pop("return_tensors", None)

                        tokenized_prompt = tokenizer.apply_chat_template(
                            doc[prompt_key], add_generation_prompt=True, tokenize=True, **apply_kwargs
                        )
                        return len(normalize_token_ids(tokenized_prompt))
                    except Exception:
                        print("Error processing one of the samples, skipping...")
                        traceback.print_exc()
                        return self.max_prompt_length + 1

            dataframe = dataframe.filter(
                lambda doc: doc2len(doc) <= self.max_prompt_length,
                num_proc=self.num_workers,
                desc=f"Filtering prompts longer than {self.max_prompt_length} tokens",
            )

            print(f"filter dataset len: {len(dataframe)}")
        return dataframe

zhaozhaoooo avatar May 04 '26 07:05 zhaozhaoooo

Thank you for the detailed bug report and the proposed fix.

Your root cause analysis is correct: doc2len in RLHFDataset.maybe_filter_out_long_prompts() tokenizes only the prompt text via the chat template, but does not account for the tool schemas that the agent loop appends at render time. This means overlong prompts can slip through the filter and cause the torch.cat dimension mismatch error in agent_loop.py.

Key observations on your proposed fix:

  1. For the VLM path (processor is not None): Your fix correctly calls qwen_vl_utils.process_vision_info() and passes the rendered raw_prompt through the processor to get accurate token counts. This aligns with how the agent loop actually renders prompts.

  2. For the non-VLM path: The addition of if self.tool_schemas is not None: apply_kwargs["tools"] = self.tool_schemas is the right approach for the non-VLM case, ensuring doc2len uses the same tool schema configuration as the agent loop.

One consideration for tool schemas: In your non-VLM fix, you pass self.tool_schemas to apply_chat_template. However, note that the agent loop in agent_loop.py renders tool schemas at the template-apply stage (not during dataset filtering). If tool_schemas in your dataset config is None but the agent loop dynamically adds tool schemas from tool_config.yaml at runtime, the filtering-time measurement will still be inaccurate. A conservative workaround in this case is to set max_prompt_length with a fixed overhead (e.g., 512 tokens) to absorb tool-schema token cost.

Recommended next step: Would you be interested in opening a PR with this fix? The changes are well-scoped to verl/utils/dataset/rl_dataset.py's maybe_filter_out_long_prompts() method. Please reference this issue in the PR description.

For tracking purposes: this issue is related to the overlong-prompt filtering edge case described in issue #6221.

Kirrito-k423 avatar May 16 '26 19:05 Kirrito-k423