simple align qwen2vl kv_seq_len calculation with qwen2
Author: simonJJJ
Pull request: yes
Labels: name: run-slow

# 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 -->

it's a simple align of qwen2vl kv_seq_len calculation with qwen2 new code.


## Before submitting
- [x] 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?
- [x] 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
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc

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:
@ArthurZucker @zucchini-nlp we made a simple kv_seq_len caculation align to the newest qwen2 code.

it's not conflict with the current qwen2 code change? we just want to flash-attention works right.

> Do you have a reproducer with flash attention issue? Overall the kv seqlen is exactly cache position (that is what we use for other models)

Yes, when using pure text input with flash attention, the position_ids is wrong before fixing by the PR.

Hmm, does making it `max(cache_position[-1], position_ids[:, -1].max().item() + 1) if position_ids is not None else cache_position[-1]` work? 🤔  since `kv_seq_len` should be same as `cache_position`

> Hmm, does making it `max(cache_position[-1], position_ids[:, -1].max().item() + 1) if position_ids is not None else cache_position[-1]` work? 🤔 since `kv_seq_len` should be same as `cache_position`

tbh, we just want the implementation to be the "same" with the qwen2 model, so we just copy the code from `modeling_qwen2.py`

Hi@zucchini-nlp @ArthurZucker , if you have any further questions regarding this change, please let us know.

@ShuaiBai623 Nice to have a test pls, of there wasn't any 

Is it required to add a test for `flashatt2` in the `Qwen2VLIntegrationTest`, like this:

```python
@slow
@require_bitsandbytes
def test_small_model_integration_test_batch_wo_image_flashatt2(self):
    model = Qwen2VLForConditionalGeneration.from_pretrained(
       "Qwen/Qwen2-VL-7B-Instruct",
       torch_dtype=torch.bfloat16,
       attn_implementation="flash_attention_2",
       device_map="auto",
    )
    text = self.processor.apply_chat_template(self.messages, tokenize=False, add_generation_prompt=True)
    messages2 = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who are you?"},
    ]
    text2 = self.processor.apply_chat_template(messages2, tokenize=False, add_generation_prompt=True)
    inputs = self.processor(text=[text, text2], images=[self.image], return_tensors="pt").to(torch_device)

    # it should not matter whether two images are the same size or not
    output = model.generate(**inputs, max_new_tokens=30)

    EXPECTED_DECODED_TEXT = [
        "system\nYou are a helpful assistant.\nuser\nWhat kind of dog is this?assistant\nThe dog in the picture appears to be a Labrador Retriever. Labradors are known for their friendly and outgoing personalities, as well as their",
        "system\nYou are a helpful assistant.user\nWho are you?assistant\nI am Qwen, a large language model created by Alibaba Cloud. I am designed to assist with various tasks and answer a wide range of questions to",
    ]

    self.assertEqual(
        self.processor.batch_decode(output, skip_special_tokens=True),
        EXPECTED_DECODED_TEXT,
    )
```

Seems like the slow tests result in OOM, and I believe it should be fixed. Maybe we can use smaller resolution for tests, so that image tokens don't take up much space? Or is there any other reason for OOM (our runners are 14GB)?

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_33161). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Thanks a lot! I see some qwen2-vl tests are failing which I guess is due to torch-version or hardware that causes small numerical differences and thus different generations. I can fix those to match our runner's results (in scope of this PR)

ping @ArthurZucker for final review 

thanks ❤️

In my local env (A100 + torch2.4), the test passed. There was a slight difference at the 30th token during batch test, which I consider acceptable, so I removed the check for "they are identical."