Download examples/visualizer_code/source/nets/attention.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 1.01 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/attention.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/nets/attention.py
-
curl -L -o attention.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/nets/attention.py
1.01 kB
| """Attention backend with an optional FlashAttention fast path.""" | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn.functional as F | |
| try: | |
| from flash_attn import flash_attn_func as _flash_attn_func | |
| except ImportError: | |
| _flash_attn_func = None | |
| def memory_efficient_attention( | |
| query: torch.Tensor, | |
| key: torch.Tensor, | |
| value: torch.Tensor, | |
| *, | |
| dropout_p: float = 0.0, | |
| softmax_scale: float | None = None, | |
| ) -> torch.Tensor: | |
| """Apply attention to tensors shaped ``(batch, tokens, heads, dim)``.""" | |
| if _flash_attn_func is not None and query.is_cuda: | |
| return _flash_attn_func( | |
| query, | |
| key, | |
| value, | |
| dropout_p=dropout_p, | |
| softmax_scale=softmax_scale, | |
| ) | |
| output = F.scaled_dot_product_attention( | |
| query.transpose(1, 2), | |
| key.transpose(1, 2), | |
| value.transpose(1, 2), | |
| dropout_p=dropout_p, | |
| scale=softmax_scale, | |
| ) | |
| return output.transpose(1, 2) | |