ms-swift icon indicating copy to clipboard operation
ms-swift copied to clipboard

DeepSpeed-Ulysses not work for Qwen-3.5

Open mccatec opened this issue 8 months ago • 4 comments

Checklist / 检查清单

  • [x] I have searched existing issues, and this is a new bug report. / 我已经搜索过现有的 issues,确认这是一个新的 bug report。

Bug Description / Bug 描述

When I use DeepSpeed Ulysses by setting --sequence_parallel_size 4 in MS-Swift, an error is encountered as follows.

[rank0]: Traceback (most recent call last): [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/cli/rlhf.py", line 7, in [rank0]: rlhf_main() [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/pipelines/train/rlhf.py", line 243, in rlhf_main [rank0]: return SwiftRLHF(args).main() [rank0]: ^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/pipelines/base.py", line 52, in main [rank0]: result = self.run() [rank0]: ^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/ray/base.py", line 168, in wrapper [rank0]: return func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/pipelines/train/sft.py", line 197, in run [rank0]: return self.train(trainer) [rank0]: ^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/pipelines/train/sft.py", line 270, in train [rank0]: trainer.train(resume_checkpoint) [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/trainers/mixin.py", line 895, in train [rank0]: res = super().train(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/trainer.py", line 1412, in train [rank0]: return inner_training_loop( [rank0]: ^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/trainer.py", line 1742, in _inner_training_loop [rank0]: tr_loss_step = self.training_step(model, inputs, num_items_in_batch) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 1881, in training_step [rank0]: return super().training_step(model, inputs, num_items_in_batch) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/trl/trainer/grpo_trainer.py", line 1038, in training_step [rank0]: output = super().training_step(model, inputs, num_items_in_batch) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/trainer.py", line 1945, in training_step [rank0]: inputs = self._prepare_inputs(inputs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/utils.py", line 607, in wrapper [rank0]: return func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 203, in _prepare_inputs [rank0]: generation_batch = self._generate_and_score_completions(generation_batch) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/utils.py", line 607, in wrapper [rank0]: return func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 244, in _generate_and_score_completions [rank0]: batch_encoded_inputs = self._prepare_batch_inputs(inputs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/utils.py", line 607, in wrapper [rank0]: return func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 935, in _prepare_batch_inputs [rank0]: self._get_per_token_logps_and_entropies(self.model, batch_encoded_inputs)[0]) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/utils.py", line 607, in wrapper [rank0]: return func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 1672, in _get_per_token_logps_and_entropies [rank0]: return self._get_per_token_logps_and_entropies_single(model, inputs, compute_entropy=compute_entropy) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 1713, in _get_per_token_logps_and_entropies_single [rank0]: logps, entropies = self._get_logps_via_sp( [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/rlhf_trainers/grpo_trainer.py", line 1529, in _get_logps_via_sp [rank0]: output = model(**model_inputs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1879, in _call_impl [rank0]: return inner() [rank0]: ^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1827, in inner [rank0]: result = forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/peft/peft_model.py", line 1923, in forward [rank0]: return self.base_model( [rank0]: ^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1879, in _call_impl [rank0]: return inner() [rank0]: ^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1827, in inner [rank0]: result = forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 311, in forward [rank0]: return self.model.forward(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/utils/generic.py", line 841, in wrapper [rank0]: output = func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1938, in forward [rank0]: outputs = self.model( [rank0]: ^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1879, in _call_impl [rank0]: return inner() [rank0]: ^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1827, in inner [rank0]: result = forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/utils/generic.py", line 841, in wrapper [rank0]: output = func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1694, in forward [rank0]: outputs = self.language_model( [rank0]: ^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1879, in _call_impl [rank0]: return inner() [rank0]: ^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1827, in inner [rank0]: result = forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/utils/generic.py", line 915, in wrapper [rank0]: output = func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/utils/output_capturing.py", line 253, in wrapper [rank0]: outputs = func(self, *args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 1370, in forward [rank0]: hidden_states = decoder_layer( [rank0]: ^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/modeling_layers.py", line 93, in call [rank0]: return super().call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1879, in _call_impl [rank0]: return inner() [rank0]: ^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1827, in inner [rank0]: result = forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 864, in forward [rank0]: hidden_states, _ = self.self_attn( [rank0]: ^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1879, in _call_impl [rank0]: return inner() [rank0]: ^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1827, in inner [rank0]: result = forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/transformers/models/qwen3_5/modeling_qwen3_5.py", line 773, in forward [rank0]: attn_output, attn_weights = attention_interface( [rank0]: ^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/sequence_parallel/ulysses.py", line 333, in local_flash_attn [rank0]: return dist_attn( [rank0]: ^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl [rank0]: return self._call_impl(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl [rank0]: return forward_call(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/swift/sequence_parallel/ulysses.py", line 148, in forward [rank0]: dist.all_gather_into_tensor(position_ids_output, position_ids, group=self.sequence_parallel.sp_group) [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/distributed/c10d_logger.py", line 81, in wrapper [rank0]: return func(*args, **kwargs) [rank0]: ^^^^^^^^^^^^^^^^^^^^^ [rank0]: File "/home/xx/conda/envs/train/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py", line 3986, in all_gather_into_tensor [rank0]: work = group._allgather_base(output_tensor, input_tensor, opts) [rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [rank0]: ValueError: output tensor size must be equal to world_size times input tensor size

How to Reproduce / 如何复现

ms-swift: 4.0.1 CUDA: 12.8 torch: 2.8.0 flash attn: 2.8.3 transformers: 5.2.0

By setting sequence_parallel_size greater than 1 in any GRPO training script, this error appears.

Additional Information / 补充信息

I found that this issue was related to position_ids, since position_ids can be 2D (batch, seq_len) or 3D (3, batch, seq_len) for mrope models. I can supply a quick fix for this issue, thanks for you concern.

mccatec avatar Mar 30 '26 01:03 mccatec

同遇到,不过是sft场景

singing4you avatar Apr 09 '26 01:04 singing4you

Qwen3.5 在SFT sequence_parallel_size=2 同样遇到 以下是解决过程

sequence_parallel_size > 1 Compatibility Issue With Qwen3.5 Multimodal / MRoPE

Summary

sequence_parallel_size > 1 currently has compatibility issues with Qwen3.5 multimodal / MRoPE training.

In SFT with sequence_parallel_size=2, distributed attention fails because the current sequence parallel implementation appears to assume 2D position_ids and computes cu_seqlens from MRoPE position_ids, which is incorrect for Qwen3.5 multimodal models.

Scenario

  • Task: SFT
  • Model: Qwen3.5 multimodal
  • Attention implementation: flash_attention_2
  • sequence_parallel_size=2
  • use_logits_to_keep=false

Note: use_logits_to_keep=true is also incompatible with SP because prepare_logits_to_keep() explicitly raises when sequence_parallel_size > 1.

Observed Errors

Error 1

ValueError: output tensor size must be equal to world_size times input tensor size

Location:

swift/sequence_parallel/ulysses.py
DistributedAttention.forward()
dist.all_gather_into_tensor(position_ids_output, position_ids, group=...)

The current code appears to assume position_ids is 2D:

[batch, seq]

But Qwen3.5 multimodal / MRoPE may pass 3D position ids:

[3, batch, seq]

Error 2

After changing the gather logic to handle 3D position_ids, training then fails with:

AssertionError
assert query.shape[2] == cu_seqlens[-1]

Location:

swift/sequence_parallel/ulysses.py
local_flash_attn -> _attention()

The issue appears to be that cu_seqlens is computed from MRoPE position_ids. Visual tokens may contain repeated or non-linear position values, so using MRoPE positions to infer sequence boundaries is incorrect.

For Qwen3.5 multimodal, cu_seqlens should be computed from linear text_position_ids, while the original MRoPE position_ids should still be passed to rotary embedding / attention.

Relevant Qwen3.5 Behavior

In the HuggingFace Qwen3.5 modeling code, position_ids may have shape:

[4, batch, seq]

where:

position_ids[0] = text_position_ids
position_ids[1:] = MRoPE position ids

The model forward then splits them:

if position_ids.ndim == 3 and position_ids.shape[0] == 4:
    text_position_ids = position_ids[0]
    position_ids = position_ids[1:]
else:
    text_position_ids = position_ids[0]

So sequence parallel should use text_position_ids for cu_seqlens, but keep MRoPE position_ids for attention / rotary embedding.

Local Patch

I applied the following local changes.

1. Gather position_ids along the sequence dimension

Instead of assuming 2D position_ids and using all_gather_into_tensor, use all_gather and concatenate on the last dimension:

gathered_position_ids = [
    torch.empty_like(position_ids) for _ in range(self.sequence_parallel.sp_world_size)
]
dist.all_gather(gathered_position_ids, position_ids, group=self.sequence_parallel.sp_group)
position_ids = torch.cat(gathered_position_ids, dim=-1)

2. Compute cu_seqlens from linear text_position_ids

Add a helper:

def _get_cu_position_ids(self, position_ids: torch.Tensor) -> torch.Tensor:
    cu_position_ids = self.real_position_ids
    if cu_position_ids is None:
        if position_ids.dim() == 3:
            cu_position_ids = torch.arange(
                position_ids.shape[-1], dtype=position_ids.dtype, device=position_ids.device)
            cu_position_ids = cu_position_ids.unsqueeze(0).expand(position_ids.shape[1], -1)
        else:
            cu_position_ids = position_ids
    pad_dim = -1 if cu_position_ids.dim() == 3 else 1
    cu_position_ids = self.pad(cu_position_ids, padding_value=-1, position_ids=cu_position_ids, dim=pad_dim)
    if cu_position_ids.dim() == 3:
        cu_position_ids = cu_position_ids[0]
    return cu_position_ids

Then replace:

cu_seqlens = get_cu_seqlens_from_position_ids(position_ids).to(torch.int32)

with:

cu_position_ids = self._get_cu_position_ids(position_ids)
cu_seqlens = get_cu_seqlens_from_position_ids(cu_position_ids).to(torch.int32)

3. Cache text_position_ids even when using inputs_embeds

Original code only cached text_position_ids when input_ids existed and shapes matched:

if position_ids is not None and input_ids is not None and position_ids.shape[0] == input_ids.shape[0]:
    self.extra_kwargs['text_position_ids'] = position_ids.clone()

Changed to:

if position_ids is not None:
    self.extra_kwargs['text_position_ids'] = position_ids.clone()

This matters because Qwen multimodal training often uses inputs_embeds instead of input_ids.

4. Apply the same patch to both duplicated implementations

The same changes were applied to both files:

swift/sequence_parallel/ulysses.py
swift/trainers/sequence_parallel/ulysses.py

Additional Incompatibility

use_logits_to_keep=true is incompatible with sequence_parallel_size > 1.

Current code:

def prepare_logits_to_keep(self, inputs):
    labels = inputs['labels']
    loss_scale = inputs.get('loss_scale')
    if self.template.sequence_parallel_size > 1:
        raise NotImplementedError()

So SP training currently requires:

USE_LOGITS_TO_KEEP=false
SEQUENCE_PARALLEL_SIZE=2

It may be useful to either document this limitation or automatically disable use_logits_to_keep when sequence_parallel_size > 1.

Expected Behavior

sequence_parallel_size > 1 should support Qwen3.5 multimodal / MRoPE by:

  • preserving MRoPE position_ids for rotary embedding / attention
  • using linear text_position_ids to compute cu_seqlens
  • supporting gather/split for both 2D and 3D position ids
  • documenting or gracefully handling the incompatibility between use_logits_to_keep and SP

Current Local Result

After applying the local patches above, sequence_parallel_size=2 no longer crashes during the initial forward training steps.

seraph900112 avatar May 27 '26 10:05 seraph900112

I'll take a look tomorrow.

Jintao-Huang avatar May 27 '26 15:05 Jintao-Huang

https://github.com/modelscope/ms-swift/pull/9434

Tested the ms-swift main branch with transformers 5.9.0 and there are no major issues.

Qwen3.5 SP is supported in ms-swift >= 4.2.0.

Jintao-Huang avatar May 28 '26 02:05 Jintao-Huang