qwen2.5vl: fix bugs when using flash2+bf16 or num_return_sequences>1
Author: gewenbin0992
Pull request: yes

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @ylacombe, @eustlb
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
Hey @gewenbin0992 !

Just a small note, the precision thing with FA2 was fixed by https://github.com/huggingface/transformers/pull/36065. For the rest of changes, a small reproducer +description of problem will be needed before reviewing :)

```py
import json
import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info


# default: Load the model on the available device(s)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
)

# default processor
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# Preparation for inference
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)

inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to(model.device)

print('inputs.pixel_values.shape:', inputs.pixel_values.shape)

num_return_sequences = 3

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128, num_return_sequences=num_return_sequences)

input_ids_pxpended = torch.cat([inputs.input_ids] * num_return_sequences)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(input_ids_pxpended, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(json.dumps(output_text, indent=4))
```
# before these changes, the output was bad
```json
[
    "The image is a blank white background with no visible content or text. There are no discernible objects, colors, or patterns present in the image.",
    "The image appears to be a collage or a series of fragmented, pixelated sections that seem to depict a person's hand reaching out towards the sky. The background is a bright, overexposed sky with some indistinct shapes and colors that could be interpreted as clouds or abstract forms. The overall effect is glitchy and distorted, giving the impression of digital interference or a broken image. The hand is positioned in the center, with fingers extended upwards, suggesting a gesture of reaching or aspiration.",
    "The image appears to be a collage or a series of fragmented, pixelated sections that seem to depict a person wearing a plaid shirt and holding a camera. The sections are arranged in a grid-like pattern, with each section showing different parts of the person's body and attire. The overall effect is abstract and glitchy, giving the impression of digital distortion or interference."
]
```
**because torch.repeat_interleave disrupted the order of tensors without a batch size dimension:**
https://github.com/huggingface/transformers/blob/main/src/transformers/generation/utils.py#L744

**eg. inputs.pixel_values.shape: torch.Size([14308, 1176]):**
https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_5_vl/image_processing_qwen2_5_vl.py#L277

# after these changes, the output is good
```json
[
    "The image depicts a person sitting on the sandy beach, interacting with a light-colored dog. The person is wearing a plaid shirt and dark pants, and they appear to be giving the dog a treat or a small object. The dog is wearing a harness with colorful paw prints and is sitting upright, reaching up with its front paws towards the person's hand. The background shows the ocean with gentle waves and a bright, golden sunset, creating a warm and serene atmosphere. The scene suggests a moment of bonding between the person and their pet in a peaceful outdoor setting.",
    "The image depicts a person sitting on the sandy beach, interacting with a light-colored dog. The person is wearing a plaid shirt and dark pants, and they appear to be giving the dog a treat or a small object. The dog is sitting upright and extending its paw towards the person's hand, seemingly in response to a command or gesture. The background shows the ocean with gentle waves, and the sun is setting, casting a warm, golden glow over the scene. The overall atmosphere is serene and joyful, suggesting a moment of bonding between the person and their pet.",
    "The image depicts a person sitting on the sandy beach, interacting with a light-colored dog. The person is wearing a plaid shirt and dark pants, and they appear to be giving the dog a treat or a small object. The dog is sitting upright and extending its paw towards the person's hand, seemingly in response to a command or gesture. The background shows the ocean with gentle waves, and the sun is setting, casting a warm, golden glow over the scene. The overall atmosphere is serene and joyful, suggesting a moment of bonding between the person and their pet."
]
```
@zucchini-nlp please review

if num_return_sequences > 1, this bug will be triggered.

@zucchini-nlp thanks for you review, i got it, we should not do cat

the key point is we need to do the right repeat_interleave by samples

1. if there is a batch dimension, torch.repeat_interleave works fine
2. if there is **no batch dimension**, we need to split the tensor into samples, then do repeat_interleave by samples

updated, please review again : )

@ArthurZucker Right, we fixed the bug in `_expand_inputs_for_generation`, which is also used for beam searching.
And, sorry for the complicated code, we are fixing the failed tests.



It's actually quite good! I would just remove the extra nesting and rather use external functions, but that kind of code is much needed for continious batching so completely understand! It shall leave in `generation/utils` once we standardize well

@ArthurZucker @minostauros @zucchini-nlp 
All tests about qwen have passed, please check these failed tests
Can we merge?