-
Notifications
You must be signed in to change notification settings - Fork 34k
[Docs / BetterTransformer ] Added more details about flash attention + SDPA
#25265
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
fddb958
added more details about flash attention
younesbelkada e113c86
correct and add more details
younesbelkada b625e9e
Apply suggestions from code review
younesbelkada 36d33de
few modifs
younesbelkada 3400318
more details
younesbelkada 0bc132a
up
younesbelkada c150cc8
Apply suggestions from code review
younesbelkada af51646
Merge remote-tracking branch 'upstream/main' into sdpa-docs
younesbelkada 8acc2ae
adapt from suggestion
younesbelkada 0377105
Apply suggestions from code review
younesbelkada fd0848e
trigger CI
younesbelkada 05ae343
Apply suggestions from code review
younesbelkada 00ed550
fix nits and copies
younesbelkada f9a6592
add new section
younesbelkada 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -17,7 +17,9 @@ rendered properly in your Markdown viewer. | |
|
|
||
| In addition to this guide, relevant information can be found as well in [the guide for training on a single GPU](perf_train_gpu_one) and [the guide for inference on CPUs](perf_infer_cpu). | ||
|
|
||
| ## Better Transformer: PyTorch-native transformer fastpath | ||
| ## Better Transformer: PyTorch-native transformer fastpath that uses Flash Attention | ||
|
younesbelkada marked this conversation as resolved.
Outdated
|
||
|
|
||
| ### `BetterTransformer` API for encoder models | ||
|
younesbelkada marked this conversation as resolved.
Outdated
|
||
|
|
||
| PyTorch-native [`nn.MultiHeadAttention`](https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/) attention fastpath, called BetterTransformer, can be used with Transformers through the integration in the [🤗 Optimum library](https://huggingface.co/docs/optimum/bettertransformer/overview). | ||
|
|
||
|
|
@@ -36,8 +38,79 @@ model = model.reverse_bettertransformer() | |
| model.save_pretrained("saved_model") | ||
| ``` | ||
|
|
||
| ### `BetterTransformer` API and Flash attention for decoder models | ||
|
younesbelkada marked this conversation as resolved.
Outdated
|
||
|
|
||
| As of PyTorch 2.0, the attention fastpath is supported for both encoders and decoders. The list of supported architectures can be found [here](https://huggingface.co/docs/optimum/bettertransformer/overview#supported-models). | ||
|
|
||
| For decoder-based models (e.g. GPT, T5, Llama, etc.), the `BetterTransformer` API will convert all attention operations to use the [`torch.nn.functional.scaled_dot_product_attention` method](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) (SDPA), that is available only from PyTorch 2.0 and onwards. | ||
|
Member
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. Same comments for the rest of this section as in |
||
|
|
||
| An example usage of the `BetterTransformer` API is shown below: | ||
|
|
||
| ```python | ||
| from transformers import AutoModelForCausalLM | ||
|
|
||
| model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m") | ||
| # convert the model to BetterTransformer | ||
| model.to_bettertransformer() | ||
|
|
||
| # Use it for training or inference | ||
| ``` | ||
|
|
||
| According to the official documentation, `torch.nn.functional.scaled_dot_product_attention` can also call [Flash-Attention](https://arxiv.org/abs/2205.14135) kernels under the hood. If you want to force the usage of Flash Attention, you can use the [`torch.backends.cuda.sdp_kernel(enable_flash=True)`](https://pytorch.org/docs/master/backends.html#torch.backends.cuda.sdp_kernel) as below: | ||
|
younesbelkada marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| ```python | ||
| import torch | ||
| from transformers import AutoModelForCausalLM, AutoTokenizer | ||
|
|
||
| tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") | ||
| model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m").to("cuda") | ||
| # convert the model to BetterTransformer | ||
| model.to_bettertransformer() | ||
|
|
||
| input_text = "Hello my dog is cute and" | ||
| inputs = tokenizer(input_text, return_tensors="pt").to("cuda") | ||
|
|
||
| with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): | ||
| outputs = model.generate(**inputs) | ||
|
|
||
| print(tokenizer.decode(outputs[0], skip_special_tokens=True)) | ||
| ``` | ||
|
|
||
| If you see a bug with a traceback saying | ||
|
|
||
| ```bash | ||
| RuntimeError: No available kernel. Aborting execution. | ||
| ``` | ||
|
|
||
| Install the PyTorch nightly version | ||
|
younesbelkada marked this conversation as resolved.
Outdated
|
||
|
|
||
| ```bash | ||
| pip3 install -U --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu118 | ||
| ``` | ||
|
|
||
| Or alternatively try to add an autocast context manager in addition to the SDPA context manager: | ||
|
|
||
| ```python | ||
| import torch | ||
| from transformers import AutoModelForCausalLM, AutoTokenizer | ||
|
|
||
| tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") | ||
| model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m").to("cuda") | ||
| # convert the model to BetterTransformer | ||
| model.to_bettertransformer() | ||
|
|
||
| input_text = "Hello my dog is cute and" | ||
| inputs = tokenizer(input_text, return_tensors="pt").to("cuda") | ||
|
|
||
| with torch.cuda.amp.autocast(), torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): | ||
| outputs = model.generate(**inputs) | ||
|
|
||
| print(tokenizer.decode(outputs[0], skip_special_tokens=True)) | ||
| ``` | ||
|
younesbelkada marked this conversation as resolved.
Outdated
|
||
|
|
||
| Have a look at [this detailed blogpost](https://pytorch.org/blog/out-of-the-box-acceleration/) to read more about what is possible to do with `BetterTransformer` + SDPA API. | ||
|
|
||
| ## `bitsandbytes` integration for FP4 mixed-precision inference | ||
|
|
||
| You can install `bitsandbytes` and benefit from easy model compression on GPUs. Using FP4 quantization you can expect to reduce up to 8x the model size compared to its native full precision version. Check out below how to get started. | ||
|
|
||
This file contains hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.