verl icon indicating copy to clipboard operation
verl copied to clipboard

about use_remove_padding=True in PPO&GRPO

Open yangzhch6 opened this issue 1 year ago • 8 comments

设置use_remove_padding=True/False, 导致LLM计算logits结果不一致,具体问题描述如下

I think this is caused by the minor calculation error of flash attention, but it is not clear how this minor error affects the performance.

I find the following question:

In short, the output log_probs is different for use_remove_padding=True/False, It mat cause some kind of drawback during training

For a given sequence 1:

  • input_ids: (bsz x seq_len)
  • attention_mask
  • position_ids

I set a suffix of attention_mask to 0, format the new sequence 2:

  • input_ids_: (bsz x seq_len)
  • attention_mask_
  • position_ids_

When use_remove_padding=False, the output log_probs for the unmasked positions of sequence 1 & 2 are the same

But, when use_remove_padding=True, the log_probs are different.

I think there are certain problems with the implementation of use_remove_padding.

yangzhch6 avatar May 04 '25 08:05 yangzhch6

The modified code is provided as here:

In verl.trainer.ppo.ray_trainer.py

def tmp_extract_values_with_mask(self, tensor_A, tensor_mask):
        """
        根据attention_mask提取向量A中的数值
        
        参数:
        tensor_A: 输入向量 (1 x len)
        tensor_mask: attention_mask (1 x len)
        
        返回:
        提取的数值 (1 x m, m为mask中1的数量)
        """
        # 去除可能的额外维度
        tensor_A = tensor_A.squeeze()
        tensor_mask = tensor_mask.squeeze()
        
        # 使用布尔索引提取对应的A中的数值
        extracted_values = tensor_A[tensor_mask.bool()]
        
        return extracted_values
original_batch = copy.deepcopy(batch)
original_batch2 = copy.deepcopy(batch)
original_batch2.batch["attention_mask"][:, 2148:] = 0


# recompute old_log_probs
with _timer('old_log_prob', timing_raw):
    original_old_log_prob = self.actor_rollout_wg.compute_log_prob(original_batch)
    original_batch = original_batch.union(original_old_log_prob)

# recompute old_log_probs
with _timer('old_log_prob', timing_raw):
    original_old_log_prob2 = self.actor_rollout_wg.compute_log_prob(original_batch2)
    original_batch2 = original_batch2.union(original_old_log_prob2)

old_log_prob = original_batch.batch['old_log_probs']
old_log_prob2 = original_batch2.batch['old_log_probs']


old_log_prob = self.tmp_extract_values_with_mask(old_log_prob[0], original_batch2.batch['attention_mask'][0][self.config.data.max_prompt_length:])
old_log_prob2 = self.tmp_extract_values_with_mask(old_log_prob2[0], original_batch2.batch['attention_mask'][0][self.config.data.max_prompt_length:])

assert torch.equal(old_log_prob, old_log_prob2), "old_log_prob not equal"

Above is all the modification.

  • When use_remove_padding=False, the assertion is correct
  • When use_remove_padding=True, the assertion is wrong

Bellow is the script:

#!/bin/bash
set -x

# Warning: Export VLLM_ATTENTION_BACKEND on every machine before starting Ray cluster.
# vLLM without XFORMERS will results in CUDA errors.
export VLLM_ATTENTION_BACKEND=XFORMERS
export MODEL_PATH="..."

# Train over a single node, 2 A800-80GB GPUs.
python3 -m verl.trainer.main_ppo \
    algorithm.adv_estimator=grpo \
    data.train_files=$HOME/data/train/debug_deepscaler_cot_train.parquet \
    data.val_files=$HOME/data/test/debug_deepscaler_cot_test.parquet \
    data.train_batch_size=2 \
    data.val_batch_size=512 \
    data.max_prompt_length=2048 \
    data.max_response_length=4096 \
    actor_rollout_ref.model.path=$MODEL_PATH \
    actor_rollout_ref.actor.optim.lr=1e-6 \
    actor_rollout_ref.model.use_remove_padding=True/False \
    actor_rollout_ref.actor.ppo_mini_batch_size=2 \
    actor_rollout_ref.actor.use_dynamic_bsz=True \
    actor_rollout_ref.actor.ppo_max_token_len_per_gpu=32768 \
    actor_rollout_ref.actor.use_kl_loss=True \
    actor_rollout_ref.actor.kl_loss_coef=0.001 \
    actor_rollout_ref.actor.kl_loss_type=low_var_kl \
    actor_rollout_ref.actor.ulysses_sequence_parallel_size=1 \
    actor_rollout_ref.model.enable_gradient_checkpointing=True \
    actor_rollout_ref.actor.fsdp_config.param_offload=False \
    actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
    actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
    actor_rollout_ref.rollout.name=vllm \
    actor_rollout_ref.rollout.temperature=0.6 \
    actor_rollout_ref.rollout.val_temperature=0.6 \
    actor_rollout_ref.rollout.gpu_memory_utilization=0.85 \
    actor_rollout_ref.rollout.n=2 \
    actor_rollout_ref.rollout.n_val=2 \
    actor_rollout_ref.ref.fsdp_config.param_offload=True \
    +reward_model.ignore_think=True \
    algorithm.kl_ctrl.kl_coef=0.001 \
    trainer.critic_warmup=0 \
    trainer.logger=['console','wandb'] \
    trainer.project_name='test' \
    trainer.experiment_name='debug-qwen2.5-1.5b-math-4k' \
    +trainer.val_before_train=False \
    trainer.n_gpus_per_node=2 \
    trainer.nnodes=1 \
    trainer.save_freq=20 \
    trainer.test_freq=20 \
    trainer.default_hdfs_dir=null \
    trainer.total_epochs=30 "${@:1}"

This is just a test script, so the batch_size is small. But the bug has no relationship with the batch_size

yangzhch6 avatar May 04 '25 08:05 yangzhch6

@yangzhch6 Hello, maybe it is caused by the wrong input in https://github.com/volcengine/verl/blob/821689e0e9e19f4d6b169635ee3dce7c503d6c42/verl/workers/actor/dp_actor.py#L156 . In use_remove_padding=True, we can not simply shift the input_ids to compute log_probs, as some different samples are packed. The underlying reason is that the label of the last token in the previous sequence is the first token of the next sequence in the current implementation, which is theoretically wrong in my understanding.

yingtongxiong avatar May 22 '25 03:05 yingtongxiong

use_remove_padding设置为False有什么影响吗?因为我在roll_out的采用内容做了一些截取的操作,然后又将结果重新encode回去,担心use_remove_padding=True会影响log_pro的计算

The modified code is provided as here:

In verl.trainer.ppo.ray_trainer.py

def tmp_extract_values_with_mask(self, tensor_A, tensor_mask):
        """
        根据attention_mask提取向量A中的数值
        
        参数:
        tensor_A: 输入向量 (1 x len)
        tensor_mask: attention_mask (1 x len)
        
        返回:
        提取的数值 (1 x m, m为mask中1的数量)
        """
        # 去除可能的额外维度
        tensor_A = tensor_A.squeeze()
        tensor_mask = tensor_mask.squeeze()
        
        # 使用布尔索引提取对应的A中的数值
        extracted_values = tensor_A[tensor_mask.bool()]
        
        return extracted_values
original_batch = copy.deepcopy(batch)
original_batch2 = copy.deepcopy(batch)
original_batch2.batch["attention_mask"][:, 2148:] = 0


# recompute old_log_probs
with _timer('old_log_prob', timing_raw):
    original_old_log_prob = self.actor_rollout_wg.compute_log_prob(original_batch)
    original_batch = original_batch.union(original_old_log_prob)

# recompute old_log_probs
with _timer('old_log_prob', timing_raw):
    original_old_log_prob2 = self.actor_rollout_wg.compute_log_prob(original_batch2)
    original_batch2 = original_batch2.union(original_old_log_prob2)

old_log_prob = original_batch.batch['old_log_probs']
old_log_prob2 = original_batch2.batch['old_log_probs']


old_log_prob = self.tmp_extract_values_with_mask(old_log_prob[0], original_batch2.batch['attention_mask'][0][self.config.data.max_prompt_length:])
old_log_prob2 = self.tmp_extract_values_with_mask(old_log_prob2[0], original_batch2.batch['attention_mask'][0][self.config.data.max_prompt_length:])

assert torch.equal(old_log_prob, old_log_prob2), "old_log_prob not equal"

Above is all the modification.

  • When use_remove_padding=False, the assertion is correct
  • When use_remove_padding=True, the assertion is wrong

Bellow is the script:

#!/bin/bash
set -x

# Warning: Export VLLM_ATTENTION_BACKEND on every machine before starting Ray cluster.
# vLLM without XFORMERS will results in CUDA errors.
export VLLM_ATTENTION_BACKEND=XFORMERS
export MODEL_PATH="..."

# Train over a single node, 2 A800-80GB GPUs.
python3 -m verl.trainer.main_ppo \
    algorithm.adv_estimator=grpo \
    data.train_files=$HOME/data/train/debug_deepscaler_cot_train.parquet \
    data.val_files=$HOME/data/test/debug_deepscaler_cot_test.parquet \
    data.train_batch_size=2 \
    data.val_batch_size=512 \
    data.max_prompt_length=2048 \
    data.max_response_length=4096 \
    actor_rollout_ref.model.path=$MODEL_PATH \
    actor_rollout_ref.actor.optim.lr=1e-6 \
    actor_rollout_ref.model.use_remove_padding=True/False \
    actor_rollout_ref.actor.ppo_mini_batch_size=2 \
    actor_rollout_ref.actor.use_dynamic_bsz=True \
    actor_rollout_ref.actor.ppo_max_token_len_per_gpu=32768 \
    actor_rollout_ref.actor.use_kl_loss=True \
    actor_rollout_ref.actor.kl_loss_coef=0.001 \
    actor_rollout_ref.actor.kl_loss_type=low_var_kl \
    actor_rollout_ref.actor.ulysses_sequence_parallel_size=1 \
    actor_rollout_ref.model.enable_gradient_checkpointing=True \
    actor_rollout_ref.actor.fsdp_config.param_offload=False \
    actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
    actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
    actor_rollout_ref.rollout.name=vllm \
    actor_rollout_ref.rollout.temperature=0.6 \
    actor_rollout_ref.rollout.val_temperature=0.6 \
    actor_rollout_ref.rollout.gpu_memory_utilization=0.85 \
    actor_rollout_ref.rollout.n=2 \
    actor_rollout_ref.rollout.n_val=2 \
    actor_rollout_ref.ref.fsdp_config.param_offload=True \
    +reward_model.ignore_think=True \
    algorithm.kl_ctrl.kl_coef=0.001 \
    trainer.critic_warmup=0 \
    trainer.logger=['console','wandb'] \
    trainer.project_name='test' \
    trainer.experiment_name='debug-qwen2.5-1.5b-math-4k' \
    +trainer.val_before_train=False \
    trainer.n_gpus_per_node=2 \
    trainer.nnodes=1 \
    trainer.save_freq=20 \
    trainer.test_freq=20 \
    trainer.default_hdfs_dir=null \
    trainer.total_epochs=30 "${@:1}"

This is just a test script, so the batch_size is small. But the bug has no relationship with the batch_size

use_remove_padding设置为False有什么影响吗?因为我在roll_out的采用内容做了一些截取的操作,然后又将结果重新encode回去,担心use_remove_padding=True会影响log_pro的计算

zyf8818 avatar Jul 23 '25 06:07 zyf8818

我个人觉得不会,这东西应该就是flash attn里面一些近似导致的

yangzhch6 avatar Jul 25 '25 16:07 yangzhch6

@yangzhch6 Hello, maybe it is caused by the wrong input in 你好,可能是由于输入错误造成的

verl/verl/workers/actor/dp_actor.py

Line 156 in 821689e

log_probs = logprobs_from_logits( . In use_remove_padding=True, we can not simply shift the input_ids to compute log_probs, as some different samples are packed. The underlying reason is that the label of the last token in the previous sequence is the first token of the next sequence in the current implementation, which is theoretically wrong in my understanding. 在 use_remove_padding=True 的情况下,我们不能简单地移动 input_ids 来计算 log_probs,因为一些不同的样本被打包了。根本原因是,在当前实现中,前一个序列中最后一个 token 的标签是下一个序列的第一个 token,在我看来,这在理论上是错误的。

Is there any solution? For use_rmpad, how should we modify logprobs_from_logits?

Clementine24 avatar Aug 08 '25 06:08 Clementine24

我个人觉得不会,这东西应该就是flash attn里面一些近似导致的

hi,我非常激动终于找到了和我有一样问题的人!请问有任何解决办法了吗,对于use_rmpad,我们应该如何保证两次的logprob一致,毕竟对于长上下文,不能使用remove padding会导致推理时间大幅增加

Clementine24 avatar Aug 08 '25 06:08 Clementine24

我个人觉得不会,这东西应该就是flash attn里面一些近似导致的

hi,我非常激动终于找到了和我有一样问题的人!请问有任何解决办法了吗,对于use_rmpad,我们应该如何保证两次的logprob一致,毕竟对于长上下文,不能使用remove padding会导致推理时间大幅增加

我也不知道咋搞,但我认为影响是极其有限可忽略不计的

yangzhch6 avatar Aug 08 '25 08:08 yangzhch6

Scheduled issue cleanup / 定时 issue 清理

中文:该 issue 命中定时清理规则:最近一次非当前运行账号的公开回复或引用已经超过 6 个月。因此按定时清理标准先关闭。若作者或社区成员仍能提供新的复现、证据或需求背景,欢迎继续评论请求重开,或创建带有最新信息的新 issue。

证据:

  • Issue: https://github.com/verl-project/verl/issues/1381
  • 最近一次非当前运行账号的公开回复或公开引用是 2025-08-08T08:29:47Z UTC(comment by @yangzhch6),截至 2026-07-05 已超过 6 个月。
  • 已检查 comments 来源:https://api.github.com/repos/verl-project/verl/issues/1381/comments
  • 已检查 timeline 来源:https://api.github.com/repos/verl-project/verl/issues/1381/timeline

English: This issue matches the scheduled cleanup rule: the latest public reply or reference by an account other than the current runner is older than 6 months. Therefore, this is being closed under the scheduled cleanup policy. If the author or community members can still provide a fresh reproduction, evidence, or requirement context, please comment to request reopening or open a new issue with updated information.

Evidence:

  • Issue: https://github.com/verl-project/verl/issues/1381
  • The latest public reply or public reference from an account other than the current runner was 2025-08-08T08:29:47Z UTC (comment by @yangzhch6), which is more than 6 months before 2026-07-05.
  • Checked comments source: https://api.github.com/repos/verl-project/verl/issues/1381/comments
  • Checked timeline source: https://api.github.com/repos/verl-project/verl/issues/1381/timeline

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

Kirrito-k423 avatar Jul 05 '26 01:07 Kirrito-k423