-
Notifications
You must be signed in to change notification settings - Fork 28.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add sdpa
and FA2 for CLIP
#31940
Merged
Merged
Add sdpa
and FA2 for CLIP
#31940
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
0d1fa8e
Squashed commit of the following:
qubvel cca2ec6
Remove fallback for empty attention mask (expensive operation)
qubvel f3d8024
Fix typing in copies
qubvel 0bbc912
Add flash attention
qubvel 06c1cea
Add flash attention tests
qubvel 650aaa5
List CLIP in FA docs
qubvel fa01bb6
Fix embeddings attributes and tf
qubvel 60207fe
[run-slow] clip
qubvel df54b52
Update clip documentation
qubvel e5c8aae
Remove commented code, skip compile dynamic for CLIPModel
qubvel 8376f43
Fix doc
qubvel 088a4ec
Fix doc 2
qubvel 9028968
Remove double transpose
qubvel ec859fc
Add torch version check for contiguous()
qubvel 778ef65
Add comment to test mixin
qubvel 1528708
Fix copies
qubvel de681a5
Add comment for mask
qubvel cfc5240
Update docs
qubvel d2328d3
[run-slow] clip
qubvel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -79,6 +79,123 @@ encode the text and prepare the images. The following example shows how to get t | |
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities | ||
``` | ||
|
||
|
||
### Combining CLIP and Flash Attention 2 | ||
|
||
First, make sure to install the latest version of Flash Attention 2. | ||
|
||
```bash | ||
pip install -U flash-attn --no-build-isolation | ||
``` | ||
|
||
Make also sure that you have a hardware that is compatible with Flash-Attention 2. Read more about it in the official documentation of flash-attn repository. Make also sure to load your model in half-precision (e.g. `torch.float16`) | ||
|
||
<Tip warning={true}> | ||
|
||
For small batch sizes, you might notice a slowdown in your model when using flash attention. Refer to the section [Expected speedups with Flash Attention and SDPA](#Expected-speedups-with-Flash-Attention-and-SDPA) below and select an appropriate attention implementation. | ||
|
||
</Tip> | ||
|
||
To load and run a model using Flash Attention 2, refer to the snippet below: | ||
|
||
```python | ||
>>> import torch | ||
>>> import requests | ||
>>> from PIL import Image | ||
|
||
>>> from transformers import CLIPProcessor, CLIPModel | ||
|
||
>>> device = "cuda" | ||
>>> torch_dtype = torch.float16 | ||
|
||
>>> model = CLIPModel.from_pretrained( | ||
... "openai/clip-vit-base-patch32", | ||
... attn_implementation="flash_attention_2", | ||
... device_map=device, | ||
... torch_dtype=torch_dtype, | ||
... ) | ||
>>> processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") | ||
|
||
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" | ||
>>> image = Image.open(requests.get(url, stream=True).raw) | ||
|
||
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) | ||
>>> inputs.to(device) | ||
|
||
>>> with torch.no_grad(): | ||
... with torch.autocast(device): | ||
... outputs = model(**inputs) | ||
|
||
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score | ||
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities | ||
>>> print(probs) | ||
tensor([[0.9946, 0.0052]], device='cuda:0', dtype=torch.float16) | ||
``` | ||
|
||
|
||
### Using Scaled Dot Product Attention (SDPA) | ||
|
||
PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function | ||
encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the | ||
[official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) | ||
or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) | ||
page for more information. | ||
|
||
SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set | ||
`attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. | ||
|
||
```python | ||
from transformers import CLIPModel | ||
|
||
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32", torch_dtype=torch.float16, attn_implementation="sdpa") | ||
``` | ||
|
||
For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). | ||
|
||
### Expected speedups with Flash Attention and SDPA | ||
|
||
On a local benchmark (NVIDIA A10G, PyTorch 2.3.1+cu121) with `float16`, we saw the following speedups during inference for `"openai/clip-vit-large-patch14"` checkpoint ([code](https://gist.github.com/qubvel/ac691a54e54f9fae8144275f866a7ff8)): | ||
|
||
#### CLIPTextModel | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These tables are beautiful - thanks for taking the time to get such detailed benchmarks. It's incredible valuable for important checkpoints like CLIP ❤️ |
||
|
||
| Num text labels | Eager (s/iter) | FA2 (s/iter) | FA2 speedup | SDPA (s/iter) | SDPA speedup | | ||
|------------------:|-----------------:|---------------:|--------------:|----------------:|---------------:| | ||
| 4 | 0.009 | 0.012 | 0.737 | 0.007 | 1.269 | | ||
| 16 | 0.009 | 0.014 | 0.659 | 0.008 | 1.187 | | ||
| 32 | 0.018 | 0.021 | 0.862 | 0.016 | 1.142 | | ||
| 64 | 0.034 | 0.034 | 1.001 | 0.03 | 1.163 | | ||
| 128 | 0.063 | 0.058 | 1.09 | 0.054 | 1.174 | | ||
|
||
 | ||
|
||
#### CLIPVisionModel | ||
|
||
| Image batch size | Eager (s/iter) | FA2 (s/iter) | FA2 speedup | SDPA (s/iter) | SDPA speedup | | ||
|-------------------:|-----------------:|---------------:|--------------:|----------------:|---------------:| | ||
| 1 | 0.016 | 0.013 | 1.247 | 0.012 | 1.318 | | ||
| 4 | 0.025 | 0.021 | 1.198 | 0.021 | 1.202 | | ||
| 16 | 0.093 | 0.075 | 1.234 | 0.075 | 1.24 | | ||
| 32 | 0.181 | 0.147 | 1.237 | 0.146 | 1.241 | | ||
|
||
 | ||
|
||
#### CLIPModel | ||
|
||
| Image batch size | Num text labels | Eager (s/iter) | FA2 (s/iter) | FA2 speedup | SDPA (s/iter) | SDPA speedup | | ||
|-------------------:|------------------:|-----------------:|---------------:|--------------:|----------------:|---------------:| | ||
| 1 | 4 | 0.025 | 0.026 | 0.954 | 0.02 | 1.217 | | ||
| 1 | 16 | 0.026 | 0.028 | 0.918 | 0.02 | 1.287 | | ||
| 1 | 64 | 0.042 | 0.046 | 0.906 | 0.036 | 1.167 | | ||
| 4 | 4 | 0.028 | 0.033 | 0.849 | 0.024 | 1.189 | | ||
| 4 | 16 | 0.034 | 0.035 | 0.955 | 0.029 | 1.169 | | ||
| 4 | 64 | 0.059 | 0.055 | 1.072 | 0.05 | 1.179 | | ||
| 16 | 4 | 0.096 | 0.088 | 1.091 | 0.078 | 1.234 | | ||
| 16 | 16 | 0.102 | 0.09 | 1.129 | 0.083 | 1.224 | | ||
| 16 | 64 | 0.127 | 0.11 | 1.157 | 0.105 | 1.218 | | ||
| 32 | 4 | 0.185 | 0.159 | 1.157 | 0.149 | 1.238 | | ||
| 32 | 16 | 0.19 | 0.162 | 1.177 | 0.154 | 1.233 | | ||
| 32 | 64 | 0.216 | 0.181 | 1.19 | 0.176 | 1.228 | | ||
|
||
## Resources | ||
|
||
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with CLIP. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just out of curiosity -- do these trends roughly hold for other checkpoints too? Anyway, you picked the most popular checkpoint I think since it's used in the diffusion community quite heavily.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
roughly holds for sdpa, however FA2 is worse for "base" checkpoint for CLIPModel
“openai/clip-vit-base-patch32”
CLIPTextModel
CLIPVisionModel
CLIPModel
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FA2 results are super interesting!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Okay, in general, SDPA seems to be still producing better speedups.