Remove graph breaks for torch.compile() in flash_attention_forward when Lllama Model is padding free tuned
Author: Abhishek-TAMU
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 -->

This PR removes the function call `prepare_fa2_from_position_ids` in `flash_attention_forward` as it causes graph break when `torch_compile` flag is turned on in Training [arguments](https://huggingface.co/docs/transformers/en/main_classes/trainer#transformers.TrainingArguments.torch_compile) to use in SFTTrainer to perform padding free tuning of Llama model. This is because code in `prepare_fa2_from_position_ids` incur a cpu-gpu sync that is unavoidable. 
Hence `cu_seq_lens_q`, `cu_seq_lens_k`, `max_length_k`, `max_length_q` is now taken from the batch in `DataCollatorForCompletionOnlyLM` with this [PR](https://github.com/huggingface/trl/pull/2158) to avoid call to `prepare_fa2_from_position_ids` in `flash_attention_forward`. 

CC: @ani300 @ArthurZucker

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] 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

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:
This way we can potentially add more kwargs without changing the forward! 


Thanks for the review and welcoming this PR.
The changes suggested by you have been made @ArthurZucker 

@ArthurZucker Made the necessary changes. 
Feel free to suggest changes if required any. Thanks!

@ArthurZucker Would you mind facilitating in moving ahead with the related PR in TRL which supports this PR: https://github.com/huggingface/trl/pull/2158 ?

Okay! Overall looks good. 
1. we need to protect the import of Unpack : 
2. let's just add an example in the documentation of how to use this! a small python snippet!

The CI's should mostly go green with this! 
Then you will have `make fix-copies` that is gonna propagate the changes! 


Once we merge I'll ping TRL team to make sure they don't miss it! 

@ArthurZucker Changes have been pushed to fix CI tests. 

For documentation does below sample script works which only performs tuning of Llama model using `SFTTrainer` with `torch_compile` flag on and using DataCollator with padding free ? @ArthurZucker 


```
#################### IMPORTS ###################

import math
import datasets, dataclasses
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TrainingArguments
)
from trl import SFTConfig, SFTTrainer, DataCollatorForCompletionOnlyLM

#################### MODEL LOADING USING FLASH ATTENTION ###################

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B", attn_implementation="flash_attention_2")
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)

#################### DATA PREPROCESSING (PADDING_FREE) ###################

response_template = "\n### Label:"
response_template_ids = tokenizer.encode(
    response_template, add_special_tokens=False
)[2:]
data_collator = DataCollatorForCompletionOnlyLM(
    response_template_ids,
    tokenizer=tokenizer,
    ignore_index= -100,
    padding_free=True
)
format_dataset = lambda example: {  
    "output": example["output"] + tokenizer.eos_token
}
data_files = {"train": "path/to/dataset"}
json_dataset = datasets.load_dataset("json", data_files=data_files)
formatted_train_dataset = json_dataset["train"].map(format_dataset)

################# Trainer CONFIG ############################

train_args = TrainingArguments(
    num_train_epochs=5,
    per_device_train_batch_size=4,
    per_device_eval_batch_size=4,
    gradient_accumulation_steps=4,
    learning_rate=0.00001,
    weight_decay=0,
    warmup_ratio=0.03,
    lr_scheduler_type="cosine",
    logging_steps=1,
    include_tokens_per_second=True,
    save_strategy="epoch",
    output_dir="tmp",
    torch_compile=True,
    torch_compile_backend="inductor",
    torch_compile_mode="default"
)
transformer_train_arg_fields = [x.name for x in dataclasses.fields(SFTConfig)]
transformer_kwargs = {
    k: v
    for k, v in train_args.to_dict().items()
    if k in transformer_train_arg_fields
}
training_args = SFTConfig(**transformer_kwargs)

####################### TUNING #####################

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=formatted_train_dataset,
    data_collator=data_collator,
    dataset_text_field="output",
    args=training_args,
)
trainer.train()
```

Yep looks perfect! Especially if we can have % improvement ! 


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

Made changes as suggested. Feel free to have a look at overall changes to confirm @ArthurZucker . Also which section can I add the above documentation script ?

Probably under this section: https://huggingface.co/docs/transformers/llm_optims#flashattention-2 

If you have issue with just make fix copies I can take it over if you want!

Sure, That would be helpful. Thank you! There seems to be some mismatch in `src/transformers/models/glm/modeling_glm.py`. 

On it!

I am just waiting on #34283 to be merged!

The new helper will be this:
<img width="441" alt="image" src="https://github.com/user-attachments/assets/d7061ff6-535e-4558-b454-039869d2c345">

(with loss kwargs!)

Thanks @ArthurZucker for the code change to accomodate LossKwargs. 

Thanks @Abhishek-TAMU for your contribution! 🚀 

> Once we merge I'll ping TRL team to make sure they don't miss it

Hi @ArthurZucker, do you mind facilitating this ? PR: https://github.com/huggingface/trl/pull/2158

Hi @Abhishek-TAMU @ArthurZucker , very nice PR for adding FlashAttentionKwargs. 
In [modeling_llama.py#L959](https://github.com/Abhishek-TAMU/transformers/blob/cb08b6371101dae92867d52b1a3b24405779d46f/src/transformers/models/llama/modeling_llama.py#L959), I noticed that `**flash_attn_kwargs` is added to the inputs of `decoder_layer` when gradient checkpointing is not used. Could you please also add `flash_attn_kwargs` when using gradient checkpointing in the above [if branch at line 938](https://github.com/Abhishek-TAMU/transformers/blob/cb08b6371101dae92867d52b1a3b24405779d46f/src/transformers/models/llama/modeling_llama.py#L938)? If checkpointing function does not accept kwargs, can we make all FlashAttentionKwargs as optional input fields of `LlamaDecoderLayer.forward`?

kwargs are by default optional! 
Checkpoint indeed does not support kwargs, at least the way we have formulated it. Will be fixed by #34987