fix FlashAttentionKwargs RoPE
Author: garrett361
Pull request: yes

# What does this PR do?

#33932 introduced `FlashAttentionKwargs` as an alternative to using `position_ids` for padding-free training. The RoPE positional embedding are not currently applied correctly in the `FlashAttentionKwargs` code path. This PR ensures that RoPE is used properly for this path.

## Code Notes

### The Issue

The issue is that if `position_ids` not provided, then they are internally generated here: 

https://github.com/huggingface/transformers/blob/ec7afad60909dd97d998c1f14681812d69a15728/src/transformers/models/llama/modeling_llama.py?plain=1#L561-L562
 
and these are used to generate the rope embeddings here:

https://github.com/huggingface/transformers/blob/ec7afad60909dd97d998c1f14681812d69a15728/src/transformers/models/llama/modeling_llama.py?plain=1#L570-L571

These rope embeddings are `~ torch.arange`, whereas they should be non-trivially generated from the values in `FlashAttentionKwargs`

### The Fix

Introduce a `get_position_ids_from_cu_seq_lens` helper which coverts from `FlashAttentionKwargs -> position_ids`, when provided. 

Because many other models inherit from `LlamaDecoder`, this change propagates changes to many other models via `modular_model_converter.py`.

### Tests

The solution is tested in `LlamaModelTest::test_attn_mask_position_ids_flash_attn_equality`, which checks that logits in the follow cases are consistent with each other:
* No padding-free, just padding and attention masks
* Padding free via `position_ids`
* Padding free via `FlashAttentionKwargs`

This test fails on latest `main` without the above fix. 


<!--
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:
cc @Abhishek-TAMU @arthurzucker because this is an update to #33932 

@Abhishek-TAMU @ArthurZucker I removed the `draft` status and this work is ready for review. Please let me know if I can answer any questions about this PR. Thank you!

cc @cyrilvallez as well actually, since I think this relates to RoPE code you touched recently

Hey @garrett361! Very nice catch, this is indeed quite important! Here are a few thoughts/guidelines:

First, as the function is a helper directly related to FA2, it should be moved to `modeling_flash_attention_utils.py`. 
Second, may I know a bit more about the setting in which you use this? I kind of feel that when using packed tensor format, it should be the responsibility of the user to feed correct inputs to the model. It would avoid one more code path in our modeling.
Depending on where/how you use this, I suspect it could call the function upstream, and then feed correct position_ids to the model. 
Let me know what you think!

> Very nice catch, this is indeed quite important!

Thanks! 

> First, as the function is a helper directly related to FA2, it should be moved to modeling_flash_attention_utils.py.

Makes sense to me.

> Second, may I know a bit more about the setting in which you use this?

I hit this in the process of testing #35861, which makes related changes for padding-free training.  See there for some related discussion, as well.

>  I kind of feel that when using packed tensor format, it should be the responsibility of the user to feed correct inputs to the model. It would avoid one more code path in our modeling.

Agree it would be best if all of the needed data (both `position_ids` and `cu_seq_len_x`, in the present case) were computed and provided at the outset by, say, the dataloader.  But there seem to be  a bunch of different available code paths at the moment and am concerned about silent incorrectness issues if we don't have these kinds of helpers in the modeling code.

Examples:
1. HF's [DataCollatorWithFlattening](https://github.com/huggingface/transformers/blob/4563ba2c6f88d77ef2e47d80b2ec6c82a3589d17/src/transformers/data/data_collator.py?plain=1#L1694) only returns `position_ids`
2. `trl`'s [DataCollatorForCompletionOnlyLM](https://github.com/huggingface/trl/blob/724acb9716d5124c83993a3d92b6e6bb8bb73668/trl/trainer/utils.py#L206) does what we want and returns all of `{position_ids, cu_seq_lens_q, ...}`.

What do you suggest for next steps?

> First, as the function is a helper directly related to FA2, it should be moved to modeling_flash_attention_utils.py.
@Cyrilvallez @Rocketknight1 I moved the helper as requested.

Please let me know if any more is needed from my end!

Hey! Sorry, I agree with @Cyrilvallez and I think we should rather update / fix our Datacollator to make sure it passes the position ids and cu seqlens. We really don't want to add code that is specific to 1 integration path! 

🤗 

Ok cool @ArthurZucker , so close this PR and adjust [DataCollatorWithFlattening](https://github.com/huggingface/transformers/blob/4563ba2c6f88d77ef2e47d80b2ec6c82a3589d17/src/transformers/data/data_collator.py?plain=1#L1694) so that it returns `{position_ids, cu_seq_lens_q, ...}`?

Closing this: the intended padding-free code path with `FlashAttentionKwargs` is that both the `FlashAttentionKwargs` _and_ `position_ids` are provided to the model.

I plan to open a separate PR which sanity checks this and raises a `ValueError` if only `FlashAttentionKwargs` are provided, along with making the `FlashAttentionKwargs` explicit, properly typed args.