Support gradient checkpointing in Qwen2VL ViT
Author: li-plus
Pull request: yes
Labels: name: Multimodal

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 -->

Support gradient checkpointing for Qwen2VL ViT part. The current implementation in main branch only supports gradient checkpointing in language part. This PR further supports checkpointing vision encoder.

## 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.

cc @ArthurZucker, @amyeroberts, @qubvel

<!-- 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:
Hi @li-plus! Thanks for your contribution! 

Can you please enable gradient checkpointing tests for this model to make sure it works properly? I see [these](https://github.com/huggingface/transformers/blob/main/tests/models/qwen2_vl/test_modeling_qwen2_vl.py#L288-L304) tests are skipped on `main`, however, I was able to run them without issues locally.

> Hi @li-plus! Thanks for your contribution!
> 
> Can you please enable gradient checkpointing tests for this model to make sure it works properly? I see [these](https://github.com/huggingface/transformers/blob/main/tests/models/qwen2_vl/test_modeling_qwen2_vl.py#L288-L304) tests are skipped on `main`, however, I was able to run them without issues locally.

@qubvel Thanks for advice. I've re-enable these gradient checkpointing tests for Qwen2VL in the latest commit. They run just fine on my machine.

Thanks! Can you please also push an empty commit with the message `[run-slow] qwen2_vl` to trigger all model tests? We should be fine here, cause `test_training_gradient_checkpointing` is not a `slow` test, however just to double check everything else is fine 🙂 

Thanks. Just pushed!

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

@qubvel It seems those failures are not related to this PR. Any idea?

@li-plus 

Thanks your commit!
when I use gradient_checkpointing for Qwen2VisionTransformerPretrainedModel, I meet this Error:


AttributeError: 'Qwen2VisionTransformerPretrainedModel' object has no attribute '_gradient_checkpointing_func'. Did you mean: 'gradient_checkpointing'?


Is it necessary to implement this '_gradient_checkpointing_func' in  'Qwen2VisionTransformerPretrainedModel' ?

> @li-plus
> 
> Thanks your commit! when I use gradient_checkpointing for Qwen2VisionTransformerPretrainedModel, I meet this Error:
> 
> AttributeError: 'Qwen2VisionTransformerPretrainedModel' object has no attribute '_gradient_checkpointing_func'. Did you mean: 'gradient_checkpointing'?
> 
> Is it necessary to implement this '_gradient_checkpointing_func' in 'Qwen2VisionTransformerPretrainedModel' ?

My  transfromers version is latest, and it is:
transformers ==4.47.0

@ShuaibinQi Hi, I did not reproduce this error using transformers 4.47.0 using this demo code:

```python
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info


processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")

model = Qwen2VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2-VL-7B-Instruct",
    torch_dtype=torch.bfloat16,
    attn_implementation="flash_attention_2",
    device_map="cuda",
)
model.gradient_checkpointing_enable()
model.train()

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."},
        ],
    }
]

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("cuda")

print(f'before forward {torch.cuda.memory_allocated()/1e9=:.3f} GB, {torch.cuda.memory_reserved()/1e9=:.3f} GB')
output = model(**inputs, use_cache=False)
print(f'after forward {torch.cuda.memory_allocated()/1e9=:.3f} GB, {torch.cuda.memory_reserved()/1e9=:.3f} GB')
output.logits.sum().backward()
print(f'after backward {torch.cuda.memory_allocated()/1e9=:.3f} GB, {torch.cuda.memory_reserved()/1e9=:.3f} GB')
```

Did you use `gradient_checkpointing_enable` to enable gradient checkpointing?