drbh commited on
Commit
46ba691
·
unverified ·
0 Parent(s):

Migrated from kernels-community/flash-attn3

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +36 -0
  2. README.md +55 -0
  3. benchmark.py +17 -0
  4. benchmarks/benchmark.py +17 -0
  5. build/torch210-cxx11-cu128-x86_64-linux/__init__.py +17 -0
  6. build/torch210-cxx11-cu128-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so +3 -0
  7. build/torch210-cxx11-cu128-x86_64-linux/_ops.py +9 -0
  8. build/torch210-cxx11-cu128-x86_64-linux/flash_attn3/__init__.py +26 -0
  9. build/torch210-cxx11-cu128-x86_64-linux/flash_attn_config.py +7 -0
  10. build/torch210-cxx11-cu128-x86_64-linux/flash_attn_interface.py +1127 -0
  11. build/torch210-cxx11-cu128-x86_64-linux/metadata.json +12 -0
  12. build/torch210-cxx11-cu130-x86_64-linux/__init__.py +17 -0
  13. build/torch210-cxx11-cu130-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so +3 -0
  14. build/torch210-cxx11-cu130-x86_64-linux/_ops.py +9 -0
  15. build/torch210-cxx11-cu130-x86_64-linux/flash_attn3/__init__.py +26 -0
  16. build/torch210-cxx11-cu130-x86_64-linux/flash_attn_config.py +7 -0
  17. build/torch210-cxx11-cu130-x86_64-linux/flash_attn_interface.py +1127 -0
  18. build/torch210-cxx11-cu130-x86_64-linux/metadata.json +12 -0
  19. build/torch211-cxx11-cu128-x86_64-linux/__init__.py +17 -0
  20. build/torch211-cxx11-cu128-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so +3 -0
  21. build/torch211-cxx11-cu128-x86_64-linux/_ops.py +9 -0
  22. build/torch211-cxx11-cu128-x86_64-linux/flash_attn3/__init__.py +26 -0
  23. build/torch211-cxx11-cu128-x86_64-linux/flash_attn_config.py +7 -0
  24. build/torch211-cxx11-cu128-x86_64-linux/flash_attn_interface.py +1127 -0
  25. build/torch211-cxx11-cu128-x86_64-linux/metadata.json +12 -0
  26. build/torch211-cxx11-cu130-x86_64-linux/__init__.py +17 -0
  27. build/torch211-cxx11-cu130-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so +3 -0
  28. build/torch211-cxx11-cu130-x86_64-linux/_ops.py +9 -0
  29. build/torch211-cxx11-cu130-x86_64-linux/flash_attn3/__init__.py +26 -0
  30. build/torch211-cxx11-cu130-x86_64-linux/flash_attn_config.py +7 -0
  31. build/torch211-cxx11-cu130-x86_64-linux/flash_attn_interface.py +1127 -0
  32. build/torch211-cxx11-cu130-x86_64-linux/metadata.json +12 -0
  33. build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/__init__.py +17 -0
  34. build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so +3 -0
  35. build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so +3 -0
  36. build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/_ops.py +9 -0
  37. build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/flash_attn_interface.py +828 -0
  38. build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/__init__.py +17 -0
  39. build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so +3 -0
  40. build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so +3 -0
  41. build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/_ops.py +9 -0
  42. build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/flash_attn_interface.py +828 -0
  43. build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/__init__.py +17 -0
  44. build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so +3 -0
  45. build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so +3 -0
  46. build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/_ops.py +9 -0
  47. build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/flash_attn_interface.py +828 -0
  48. build/torch26-cxx98-cu126-x86_64-linux/flash_attn3/__init__.py +17 -0
  49. build/torch26-cxx98-cu126-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so +3 -0
  50. build/torch26-cxx98-cu126-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so +3 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.so filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: kernels
3
+ license: apache-2.0
4
+ ---
5
+
6
+ <!-- This model card has automatically been generated. You
7
+ should probably proofread and complete it, then remove this comment. -->
8
+
9
+
10
+ This is the repository card of {repo_id} that has been pushed on the Hub. It was built to be used with the [`kernels` library](https://github.com/huggingface/kernels). This card was automatically generated.
11
+
12
+
13
+ ## How to use
14
+
15
+ ```python
16
+ # make sure `kernels` is installed: `pip install -U kernels`
17
+ from kernels import get_kernel
18
+
19
+ kernel_module = get_kernel("kernels-community/flash-attn3") # <- change the ID if needed
20
+ flash_attn_combine = kernel_module.flash_attn_combine
21
+
22
+ flash_attn_combine(...)
23
+ ```
24
+
25
+ ## Available functions
26
+
27
+ - `flash_attn_combine`
28
+ - `flash_attn_func`
29
+ - `flash_attn_qkvpacked_func`
30
+ - `flash_attn_varlen_func`
31
+ - `flash_attn_with_kvcache`
32
+ - `get_scheduler_metadata`
33
+
34
+ ## Supported backends
35
+
36
+ - cuda
37
+
38
+ ## CUDA Capabilities
39
+
40
+ - 8.0
41
+ - 9.0a
42
+
43
+ ## Benchmarks
44
+
45
+ Benchmarking script is available for this kernel. Make sure to run `kernels benchmark org-id/repo-id` (replace "org-id" and "repo-id" with actual values).
46
+
47
+ [TODO: provide benchmarks if available]
48
+
49
+ ## Source code
50
+
51
+ [TODO: provide original source code and other relevant citations if available]
52
+
53
+ ## Notes
54
+
55
+ [TODO: provide additional notes about this kernel if needed]
benchmark.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from kernels.benchmarks import (
2
+ FlashAttentionBenchmark,
3
+ FlashAttentionCausalBenchmark,
4
+ FlashAttentionVarlenBenchmark,
5
+ )
6
+
7
+
8
+ class FlashAttn(FlashAttentionBenchmark):
9
+ pass
10
+
11
+
12
+ class FlashAttnCausal(FlashAttentionCausalBenchmark):
13
+ pass
14
+
15
+
16
+ class FlashAttnVarlen(FlashAttentionVarlenBenchmark):
17
+ pass
benchmarks/benchmark.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from kernels.benchmarks import (
2
+ FlashAttentionBenchmark,
3
+ FlashAttentionCausalBenchmark,
4
+ FlashAttentionVarlenBenchmark,
5
+ )
6
+
7
+
8
+ class FlashAttn(FlashAttentionBenchmark):
9
+ pass
10
+
11
+
12
+ class FlashAttnCausal(FlashAttentionCausalBenchmark):
13
+ pass
14
+
15
+
16
+ class FlashAttnVarlen(FlashAttentionVarlenBenchmark):
17
+ pass
build/torch210-cxx11-cu128-x86_64-linux/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch210-cxx11-cu128-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c778c8063c340a4dfd13a5a4f372722dcef8f8b758af149eca664689d9c54847
3
+ size 804191136
build/torch210-cxx11-cu128-x86_64-linux/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_cuda_e1d5be2
3
+ ops = torch.ops._flash_attn3_cuda_e1d5be2
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_cuda_e1d5be2::{op_name}"
build/torch210-cxx11-cu128-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import importlib.util
3
+ import sys
4
+ from pathlib import Path
5
+ from types import ModuleType
6
+
7
+
8
+ def _import_from_path(file_path: Path) -> ModuleType:
9
+ # We cannot use the module name as-is, after adding it to `sys.modules`,
10
+ # it would also be used for other imports. So, we make a module name that
11
+ # depends on the path for it to be unique using the hex-encoded hash of
12
+ # the path.
13
+ path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
+ module_name = path_hash
15
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
16
+ if spec is None:
17
+ raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
+ module = importlib.util.module_from_spec(spec)
19
+ if module is None:
20
+ raise ImportError(f"Cannot load module {module_name} from spec")
21
+ sys.modules[module_name] = module
22
+ spec.loader.exec_module(module) # type: ignore
23
+ return module
24
+
25
+
26
+ globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
build/torch210-cxx11-cu128-x86_64-linux/flash_attn_config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Auto-generated by flash attention 3 setup.py
2
+ CONFIG = {'build_flags': {'FLASHATTENTION_DISABLE_BACKWARD': False, 'FLASHATTENTION_DISABLE_SPLIT': False, 'FLASHATTENTION_DISABLE_PAGEDKV': False, 'FLASHATTENTION_DISABLE_APPENDKV': False, 'FLASHATTENTION_DISABLE_LOCAL': False, 'FLASHATTENTION_DISABLE_SOFTCAP': False, 'FLASHATTENTION_DISABLE_PACKGQA': False, 'FLASHATTENTION_DISABLE_FP16': False, 'FLASHATTENTION_DISABLE_FP8': False, 'FLASHATTENTION_DISABLE_VARLEN': False, 'FLASHATTENTION_DISABLE_CLUSTER': False, 'FLASHATTENTION_DISABLE_HDIM64': False, 'FLASHATTENTION_DISABLE_HDIM96': False, 'FLASHATTENTION_DISABLE_HDIM128': False, 'FLASHATTENTION_DISABLE_HDIM192': False, 'FLASHATTENTION_DISABLE_HDIM256': False, 'FLASHATTENTION_DISABLE_SM8x': False, 'FLASHATTENTION_ENABLE_VCOLMAJOR': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF64': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF192': False}}
3
+
4
+ def show():
5
+ from pprint import pprint
6
+ pprint(CONFIG)
7
+
build/torch210-cxx11-cu128-x86_64-linux/flash_attn_interface.py ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union, List, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+ from ._ops import add_op_namespace_prefix
10
+
11
+ def maybe_contiguous(x):
12
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
13
+
14
+
15
+ def round_multiple(x, m):
16
+ return (x + m - 1) // m * m
17
+
18
+
19
+ def round_up_headdim(head_size: int) -> int:
20
+ from .flash_attn_config import CONFIG
21
+
22
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM64"]:
23
+ if head_size <= 64:
24
+ return 64
25
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM96"]:
26
+ if head_size <= 96:
27
+ return 96
28
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM128"]:
29
+ if head_size <= 128:
30
+ return 128
31
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM192"]:
32
+ if head_size <= 192:
33
+ return 192
34
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM256"]:
35
+ if head_size <= 256:
36
+ return 256
37
+ return 256
38
+
39
+
40
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types="cuda")
41
+ def _flash_attn_forward(
42
+ q: torch.Tensor,
43
+ k: torch.Tensor,
44
+ v: torch.Tensor,
45
+ k_new: Optional[torch.Tensor] = None,
46
+ v_new: Optional[torch.Tensor] = None,
47
+ qv: Optional[torch.Tensor] = None,
48
+ out_: Optional[torch.Tensor] = None,
49
+ cu_seqlens_q: Optional[torch.Tensor] = None,
50
+ cu_seqlens_k: Optional[torch.Tensor] = None,
51
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
52
+ seqused_q: Optional[torch.Tensor] = None,
53
+ seqused_k: Optional[torch.Tensor] = None,
54
+ max_seqlen_q: Optional[int] = None,
55
+ max_seqlen_k: Optional[int] = None,
56
+ page_table: Optional[torch.Tensor] = None,
57
+ kv_batch_idx: Optional[torch.Tensor] = None,
58
+ leftpad_k: Optional[torch.Tensor] = None,
59
+ rotary_cos: Optional[torch.Tensor] = None,
60
+ rotary_sin: Optional[torch.Tensor] = None,
61
+ seqlens_rotary: Optional[torch.Tensor] = None,
62
+ q_descale: Optional[torch.Tensor] = None,
63
+ k_descale: Optional[torch.Tensor] = None,
64
+ v_descale: Optional[torch.Tensor] = None,
65
+ softmax_scale: Optional[float] = None,
66
+ causal: bool = False,
67
+ window_size_left: int = -1,
68
+ window_size_right: int = -1,
69
+ attention_chunk: int = 0,
70
+ softcap: float = 0.0,
71
+ rotary_interleaved: bool = True,
72
+ scheduler_metadata: Optional[torch.Tensor] = None,
73
+ num_splits: int = 1,
74
+ pack_gqa: Optional[bool] = None,
75
+ sm_margin: int = 0,
76
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
77
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
78
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
79
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
80
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
81
+ ]
82
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
83
+ page_table, kv_batch_idx, leftpad_k = [
84
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
85
+ ]
86
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
87
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
88
+ out, softmax_lse, out_accum, softmax_lse_accum = flash_attn_3_cuda.fwd(
89
+ q,
90
+ k,
91
+ v,
92
+ k_new,
93
+ v_new,
94
+ qv,
95
+ out_,
96
+ cu_seqlens_q,
97
+ cu_seqlens_k,
98
+ cu_seqlens_k_new,
99
+ seqused_q,
100
+ seqused_k,
101
+ max_seqlen_q,
102
+ max_seqlen_k,
103
+ page_table,
104
+ kv_batch_idx,
105
+ leftpad_k,
106
+ rotary_cos,
107
+ rotary_sin,
108
+ seqlens_rotary,
109
+ q_descale,
110
+ k_descale,
111
+ v_descale,
112
+ softmax_scale,
113
+ causal,
114
+ window_size_left,
115
+ window_size_right,
116
+ attention_chunk,
117
+ softcap,
118
+ rotary_interleaved,
119
+ scheduler_metadata,
120
+ num_splits,
121
+ pack_gqa,
122
+ sm_margin,
123
+ )
124
+
125
+ if out_accum is None:
126
+ out_accum = torch.tensor([], device=out.device)
127
+
128
+ if softmax_lse_accum is None:
129
+ softmax_lse_accum = torch.tensor([], device=out.device)
130
+
131
+ return out, softmax_lse, out_accum, softmax_lse_accum
132
+
133
+
134
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
135
+ def _flash_attn_forward_fake(
136
+ q: torch.Tensor,
137
+ k: torch.Tensor,
138
+ v: torch.Tensor,
139
+ k_new: Optional[torch.Tensor] = None,
140
+ v_new: Optional[torch.Tensor] = None,
141
+ qv: Optional[torch.Tensor] = None,
142
+ out_: Optional[torch.Tensor] = None,
143
+ cu_seqlens_q: Optional[torch.Tensor] = None,
144
+ cu_seqlens_k: Optional[torch.Tensor] = None,
145
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
146
+ seqused_q: Optional[torch.Tensor] = None,
147
+ seqused_k: Optional[torch.Tensor] = None,
148
+ max_seqlen_q: Optional[int] = None,
149
+ max_seqlen_k: Optional[int] = None,
150
+ page_table: Optional[torch.Tensor] = None,
151
+ kv_batch_idx: Optional[torch.Tensor] = None,
152
+ leftpad_k: Optional[torch.Tensor] = None,
153
+ rotary_cos: Optional[torch.Tensor] = None,
154
+ rotary_sin: Optional[torch.Tensor] = None,
155
+ seqlens_rotary: Optional[torch.Tensor] = None,
156
+ q_descale: Optional[torch.Tensor] = None,
157
+ k_descale: Optional[torch.Tensor] = None,
158
+ v_descale: Optional[torch.Tensor] = None,
159
+ softmax_scale: Optional[float] = None,
160
+ causal: bool = False,
161
+ window_size_left: int = -1,
162
+ window_size_right: int = -1,
163
+ attention_chunk: int = 0,
164
+ softcap: float = 0.0,
165
+ rotary_interleaved: bool = True,
166
+ scheduler_metadata: Optional[torch.Tensor] = None,
167
+ num_splits: int = 1,
168
+ pack_gqa: Optional[bool] = None,
169
+ sm_margin: int = 0,
170
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
171
+ """
172
+ Symbolic fake implementation of flash attention forward.
173
+ Returns tensors with the correct shapes and dtypes without actual computation.
174
+ """
175
+
176
+ # Determine if we're in varlen mode
177
+ is_varlen_q = cu_seqlens_q is not None
178
+
179
+ # Get dimensions from query tensor
180
+ if is_varlen_q:
181
+ # varlen mode: q is (total_q, num_heads, head_size)
182
+ total_q, num_heads, head_size = q.shape
183
+ batch_size = cu_seqlens_q.shape[0] - 1
184
+
185
+ if max_seqlen_q is None:
186
+ raise ValueError("max_seqlen_q must be provided if cu_seqlens_q is provided")
187
+ seqlen_q = max_seqlen_q
188
+ else:
189
+ # batch mode: q is (batch_size, seqlen_q, num_heads, head_size)
190
+ batch_size, seqlen_q, num_heads, head_size = q.shape
191
+ total_q = batch_size * q.shape[1]
192
+ # Get value head dimension
193
+ head_size_v = v.shape[-1]
194
+
195
+ # Determine output dtype (FP8 inputs produce BF16 outputs)
196
+ q_type = q.dtype
197
+ if q_type == torch.float8_e4m3fn:
198
+ out_dtype = torch.bfloat16
199
+ else:
200
+ out_dtype = q_type
201
+
202
+ # Create output tensor
203
+ if out_ is not None:
204
+ # If out_ is provided, _flash_attn_forward becomes non-functional
205
+ raise TypeError("Tracing (torch.compile/torch.export) with pre-allocated output tensor is not supported.")
206
+
207
+ if is_varlen_q:
208
+ out = torch.empty((total_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
209
+ else:
210
+ out = torch.empty((batch_size, seqlen_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
211
+
212
+ # Create softmax_lse tensor
213
+ if is_varlen_q:
214
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device)
215
+ else:
216
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
217
+
218
+ # TODO(guilhermeleobas): Implement "get_num_splits"
219
+ # There's an heuristic to compute num_splits when "num_splits <= 0"
220
+ # assert that num_splits is > 0 for now
221
+ if num_splits <= 0:
222
+ raise ValueError(f"tracing (torch.compile/torch.export) with num_splits <= 0 not supported. Got {num_splits=}")
223
+
224
+ if num_splits > 1:
225
+ if is_varlen_q:
226
+ out_accum = torch.empty((num_splits, num_heads, total_q, head_size_v), dtype=torch.float32, device=q.device)
227
+ softmax_lse_accum = torch.empty((num_splits, num_heads, total_q), dtype=torch.float32, device=q.device)
228
+ else:
229
+ out_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q, head_size_v), dtype=torch.float32, device=q.device)
230
+ softmax_lse_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
231
+ else:
232
+ # Tensors are not set when num_splits < 1
233
+ out_accum = torch.tensor([], device=out.device)
234
+ softmax_lse_accum = torch.tensor([], device=out.device)
235
+
236
+ return out, softmax_lse, out_accum, softmax_lse_accum
237
+
238
+
239
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types="cuda")
240
+ def _flash_attn_backward(
241
+ dout: torch.Tensor,
242
+ q: torch.Tensor,
243
+ k: torch.Tensor,
244
+ v: torch.Tensor,
245
+ out: torch.Tensor,
246
+ softmax_lse: torch.Tensor,
247
+ cu_seqlens_q: Optional[torch.Tensor] = None,
248
+ cu_seqlens_k: Optional[torch.Tensor] = None,
249
+ sequed_q: Optional[torch.Tensor] = None,
250
+ sequed_k: Optional[torch.Tensor] = None,
251
+ max_seqlen_q: Optional[int] = None,
252
+ max_seqlen_k: Optional[int] = None,
253
+ dq: Optional[torch.Tensor] = None,
254
+ dk: Optional[torch.Tensor] = None,
255
+ dv: Optional[torch.Tensor] = None,
256
+ softmax_scale: Optional[float] = None,
257
+ is_causal: bool = False,
258
+ window_size_left: int = -1,
259
+ window_size_right: int = -1,
260
+ softcap: float = 0.0,
261
+ deterministic: bool = False,
262
+ sm_margin: int = 0,
263
+ ) -> torch.Tensor:
264
+ # dq, dk, dv are allocated by us so they should already be contiguous
265
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
266
+ softmax_d, *rest = flash_attn_3_cuda.bwd(
267
+ dout,
268
+ q,
269
+ k,
270
+ v,
271
+ out,
272
+ softmax_lse,
273
+ dq,
274
+ dk,
275
+ dv,
276
+ cu_seqlens_q,
277
+ cu_seqlens_k,
278
+ sequed_q,
279
+ sequed_k,
280
+ max_seqlen_q,
281
+ max_seqlen_k,
282
+ softmax_scale,
283
+ is_causal,
284
+ window_size_left,
285
+ window_size_right,
286
+ softcap,
287
+ deterministic,
288
+ sm_margin,
289
+ )
290
+ return softmax_d
291
+
292
+
293
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
294
+ def _flash_attn_backward_fake(
295
+ dout: torch.Tensor,
296
+ q: torch.Tensor,
297
+ k: torch.Tensor,
298
+ v: torch.Tensor,
299
+ out: torch.Tensor,
300
+ softmax_lse: torch.Tensor,
301
+ cu_seqlens_q: Optional[torch.Tensor] = None,
302
+ cu_seqlens_k: Optional[torch.Tensor] = None,
303
+ sequed_q: Optional[torch.Tensor] = None,
304
+ sequed_k: Optional[torch.Tensor] = None,
305
+ max_seqlen_q: Optional[int] = None,
306
+ max_seqlen_k: Optional[int] = None,
307
+ dq: Optional[torch.Tensor] = None,
308
+ dk: Optional[torch.Tensor] = None,
309
+ dv: Optional[torch.Tensor] = None,
310
+ softmax_scale: Optional[float] = None,
311
+ is_causal: bool = False,
312
+ window_size_left: int = -1,
313
+ window_size_right: int = -1,
314
+ softcap: float = 0.0,
315
+ deterministic: bool = False,
316
+ sm_margin: int = 0,
317
+ ) -> torch.Tensor:
318
+
319
+ is_varlen_q = cu_seqlens_q is not None
320
+ is_varlen_k = cu_seqlens_q is not None
321
+ is_varlen = is_varlen_q or is_varlen_k or sequed_q is not None or sequed_k is not None
322
+
323
+ if not is_varlen_q:
324
+ batch_size = q.size(0)
325
+ seqlen_q = q.size(1)
326
+ seqlen_k = k.size(1)
327
+ total_q = batch_size * q.size(1)
328
+ else:
329
+ batch_size = cu_seqlens_q.size(0) - 1
330
+ total_q = q.size(0)
331
+ seqlen_q = max_seqlen_q
332
+ seqlen_k = max_seqlen_k
333
+
334
+ if window_size_left >= seqlen_k - 1:
335
+ window_size_left = -1
336
+
337
+ if window_size_right >= seqlen_q - 1:
338
+ window_size_right = -1
339
+
340
+ if is_causal:
341
+ window_size_right = 0
342
+
343
+ is_causal = window_size_left < 0 and window_size_right == 0
344
+
345
+ head_size = q.size(-1)
346
+ head_size_v = v.size(-1)
347
+ head_size_rounded = round_up_headdim(max(head_size, head_size_v))
348
+
349
+ # Hopper gpus uses cuda compute capabilities 9.0
350
+ cap = torch.cuda.get_device_capability(q.device)
351
+ arch = cap[0] * 10 + cap[1]
352
+
353
+ is_local = (window_size_left >= 0 or window_size_right >= 0) and not is_causal
354
+
355
+ if head_size_rounded <= 64:
356
+ kBlockM_sm90 = 96 if (is_causal and softcap > 0.0) else 128
357
+ elif head_size_rounded <= 96:
358
+ kBlockM_sm90 = 64
359
+ elif head_size_rounded <= 128:
360
+ kBlockM_sm90 = 64 if (is_causal or is_local or softcap > 0.0) else 80
361
+ else:
362
+ kBlockM_sm90 = 64
363
+
364
+ kBlockM_sm80 = 128 if head_size_rounded <= 64 else 64
365
+ kBlockM_sm86 = 64 if head_size_rounded <= 192 else 32
366
+
367
+ if arch >= 90:
368
+ kBlockM = kBlockM_sm90
369
+ elif arch == 86 or arch == 89:
370
+ kBlockM = kBlockM_sm86
371
+ else:
372
+ kBlockM = kBlockM_sm80
373
+
374
+ num_heads = q.shape[-2]
375
+ seqlen_q_rounded = round_multiple(seqlen_q, kBlockM)
376
+
377
+ total_q_padded_rounded = round_multiple(total_q + batch_size * kBlockM, kBlockM)
378
+
379
+ dq = torch.empty_like(q) if dq is None else dq
380
+ dk = torch.empty_like(k) if dk is None else dk
381
+ dv = torch.empty_like(v) if dv is None else dv
382
+
383
+ if not is_varlen:
384
+ softmax_d = torch.empty((batch_size, num_heads, seqlen_q_rounded), dtype=torch.float32, device=q.device)
385
+ else:
386
+ softmax_d = torch.empty((num_heads, total_q_padded_rounded), dtype=torch.float32, device=q.device)
387
+
388
+ return softmax_d
389
+
390
+
391
+ def setup_context(ctx, inputs, output):
392
+ q, k, v = inputs[:3]
393
+ out, softmax_lse, _, _ = output
394
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
395
+ ctx.softmax_scale = inputs[-11]
396
+ ctx.causal = inputs[-10]
397
+ ctx.window_size = [inputs[-9], inputs[-8]]
398
+ ctx.attention_chunk = inputs[-7]
399
+ ctx.softcap = inputs[-6]
400
+ ctx.sm_margin = inputs[-1]
401
+
402
+
403
+ def _backward(ctx, dout, *grads):
404
+ q, k, v, out, softmax_lse = ctx.saved_tensors
405
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
406
+ _flash_attn_backward(
407
+ dout,
408
+ q,
409
+ k,
410
+ v,
411
+ out,
412
+ softmax_lse,
413
+ None, None, # cu_seqlens_q, cu_seqlens_k,
414
+ None, None, # sequed_q, sequed_k,
415
+ None, None, # max_seqlen_q, max_seqlen_k,
416
+ dq,
417
+ dk,
418
+ dv,
419
+ ctx.softmax_scale,
420
+ ctx.causal,
421
+ ctx.window_size[0],
422
+ ctx.window_size[1],
423
+ ctx.softcap,
424
+ False, # deterministic
425
+ ctx.sm_margin,
426
+ )
427
+ return dq, dk, dv, *((None,) * 21)
428
+
429
+
430
+ _flash_attn_forward.register_autograd(_backward, setup_context=setup_context)
431
+
432
+
433
+
434
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
435
+ @staticmethod
436
+ def forward(
437
+ ctx,
438
+ qkv,
439
+ softmax_scale,
440
+ causal,
441
+ q_descale=None, k_descale=None, v_descale=None,
442
+ window_size=(-1, -1),
443
+ attention_chunk=0,
444
+ softcap=0.0,
445
+ deterministic=False,
446
+ num_heads_q=None,
447
+ sm_margin=0,
448
+ return_softmax=False,
449
+ ):
450
+ if softmax_scale is None:
451
+ softmax_scale = qkv.shape[-1] ** (-0.5)
452
+ if qkv.dim() == 5:
453
+ assert qkv.shape[-3] == 3
454
+ q, k, v = qkv.unbind(dim=-3)
455
+ else:
456
+ assert qkv.dim() == 4
457
+ assert num_heads_q is not None
458
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
459
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
460
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
461
+ out, softmax_lse, *rest = _flash_attn_forward(
462
+ q,
463
+ k,
464
+ v,
465
+ None, None, # k_new, v_new
466
+ None, # qv
467
+ None, # out
468
+ None, None, None, # cu_seqlens_q/k/k_new
469
+ None, None, # seqused_q/k
470
+ None, None, # max_seqlen_q/k
471
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
472
+ None, None, None, # rotary_cos/sin, seqlens_rotary
473
+ q_descale, k_descale, v_descale,
474
+ softmax_scale,
475
+ causal=causal,
476
+ window_size_left=window_size[0],
477
+ window_size_right=window_size[1],
478
+ attention_chunk=attention_chunk,
479
+ softcap=softcap,
480
+ sm_margin=sm_margin,
481
+ )
482
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
483
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
484
+ ctx.softmax_scale = softmax_scale
485
+ ctx.causal = causal
486
+ ctx.window_size = window_size
487
+ ctx.attention_chunk = attention_chunk
488
+ ctx.softcap = softcap
489
+ ctx.deterministic = deterministic
490
+ ctx.ndim = qkv.dim()
491
+ ctx.sm_margin = sm_margin
492
+ return (out, softmax_lse) if return_softmax else out
493
+
494
+ @staticmethod
495
+ def backward(ctx, dout, *args):
496
+ q, k, v, out, softmax_lse = ctx.saved_tensors
497
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
498
+ if ctx.ndim == 5:
499
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
500
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
501
+ dq, dk, dv = dqkv.unbind(dim=-3)
502
+ else:
503
+ num_heads_q = q.shape[2]
504
+ num_heads_k = k.shape[2]
505
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
506
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
507
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
508
+ _flash_attn_backward(
509
+ dout,
510
+ q,
511
+ k,
512
+ v,
513
+ out,
514
+ softmax_lse,
515
+ None, None, # cu_seqlens_q, cu_seqlens_k,
516
+ None, None, # sequed_q, sequed_k,
517
+ None, None, # max_seqlen_q, max_seqlen_k,
518
+ dq,
519
+ dk,
520
+ dv,
521
+ ctx.softmax_scale,
522
+ ctx.causal,
523
+ ctx.window_size[0],
524
+ ctx.window_size[1],
525
+ ctx.softcap,
526
+ ctx.deterministic,
527
+ ctx.sm_margin,
528
+ )
529
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
530
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None, None
531
+
532
+
533
+ class FlashAttnFunc(torch.autograd.Function):
534
+
535
+ @staticmethod
536
+ def forward(
537
+ ctx,
538
+ q,
539
+ k,
540
+ v,
541
+ softmax_scale,
542
+ causal,
543
+ qv=None,
544
+ q_descale=None, k_descale=None, v_descale=None,
545
+ window_size=(-1, -1),
546
+ attention_chunk=0,
547
+ softcap=0.0,
548
+ num_splits=1,
549
+ pack_gqa=None,
550
+ deterministic=False,
551
+ sm_margin=0,
552
+ return_softmax=False,
553
+ ):
554
+ if softmax_scale is None:
555
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
556
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
557
+ out, softmax_lse, *rest = _flash_attn_forward(
558
+ q,
559
+ k,
560
+ v,
561
+ None, None, # k_new, v_new
562
+ qv, # qv
563
+ None, # out
564
+ None, None, None, # cu_seqlens_q/k/k_new
565
+ None, None, # seqused_q/k
566
+ None, None, # max_seqlen_q/k
567
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
568
+ None, None, None, # rotary_cos/sin, seqlens_rotary
569
+ q_descale, k_descale, v_descale,
570
+ softmax_scale,
571
+ causal=causal,
572
+ window_size_left=window_size[0],
573
+ window_size_right=window_size[1],
574
+ attention_chunk=attention_chunk,
575
+ softcap=softcap,
576
+ num_splits=num_splits,
577
+ pack_gqa=pack_gqa,
578
+ sm_margin=sm_margin,
579
+ )
580
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
581
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
582
+ ctx.softmax_scale = softmax_scale
583
+ ctx.causal = causal
584
+ ctx.window_size = window_size
585
+ ctx.attention_chunk = attention_chunk
586
+ ctx.softcap = softcap
587
+ ctx.deterministic = deterministic
588
+ ctx.sm_margin = sm_margin
589
+ return (out, softmax_lse) if return_softmax else out
590
+
591
+ @staticmethod
592
+ def backward(ctx, dout, *args):
593
+ q, k, v, out, softmax_lse = ctx.saved_tensors
594
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
595
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
596
+ _flash_attn_backward(
597
+ dout,
598
+ q,
599
+ k,
600
+ v,
601
+ out,
602
+ softmax_lse,
603
+ None, None, # cu_seqlens_q, cu_seqlens_k,
604
+ None, None, # sequed_q, sequed_k,
605
+ None, None, # max_seqlen_q, max_seqlen_k,
606
+ dq,
607
+ dk,
608
+ dv,
609
+ ctx.softmax_scale,
610
+ ctx.causal,
611
+ ctx.window_size[0],
612
+ ctx.window_size[1],
613
+ ctx.softcap,
614
+ ctx.deterministic,
615
+ ctx.sm_margin,
616
+ )
617
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
618
+ dk = dk[..., : k.shape[-1]]
619
+ dv = dv[..., : v.shape[-1]]
620
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
621
+
622
+
623
+ class FlashAttnVarlenFunc(torch.autograd.Function):
624
+
625
+ @staticmethod
626
+ def forward(
627
+ ctx,
628
+ q,
629
+ k,
630
+ v,
631
+ cu_seqlens_q,
632
+ cu_seqlens_k,
633
+ seqused_q,
634
+ seqused_k,
635
+ max_seqlen_q,
636
+ max_seqlen_k,
637
+ softmax_scale,
638
+ causal,
639
+ qv=None,
640
+ q_descale=None, k_descale=None, v_descale=None,
641
+ window_size=(-1, -1),
642
+ attention_chunk=0,
643
+ softcap=0.0,
644
+ num_splits=1,
645
+ pack_gqa=None,
646
+ deterministic=False,
647
+ sm_margin=0,
648
+ return_softmax=False,
649
+ ):
650
+ if softmax_scale is None:
651
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
652
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
653
+ out, softmax_lse, *rest = _flash_attn_forward(
654
+ q,
655
+ k,
656
+ v,
657
+ None, None, # k_new, v_new
658
+ qv, # qv
659
+ None, # out
660
+ cu_seqlens_q,
661
+ cu_seqlens_k,
662
+ None, # cu_seqlens_k_new
663
+ seqused_q,
664
+ seqused_k,
665
+ max_seqlen_q,
666
+ max_seqlen_k,
667
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
668
+ None, None, None, # rotary_cos/sin, seqlens_rotary
669
+ q_descale, k_descale, v_descale,
670
+ softmax_scale,
671
+ causal=causal,
672
+ window_size_left=window_size[0],
673
+ window_size_right=window_size[1],
674
+ attention_chunk=attention_chunk,
675
+ softcap=softcap,
676
+ num_splits=num_splits,
677
+ pack_gqa=pack_gqa,
678
+ sm_margin=sm_margin,
679
+ )
680
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
681
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
682
+ ctx.max_seqlen_q = max_seqlen_q
683
+ ctx.max_seqlen_k = max_seqlen_k
684
+ ctx.softmax_scale = softmax_scale
685
+ ctx.causal = causal
686
+ ctx.window_size = window_size
687
+ ctx.attention_chunk = attention_chunk
688
+ ctx.softcap = softcap
689
+ ctx.deterministic = deterministic
690
+ ctx.sm_margin = sm_margin
691
+ return (out, softmax_lse) if return_softmax else out
692
+
693
+ @staticmethod
694
+ def backward(ctx, dout, *args):
695
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
696
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
697
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
698
+ _flash_attn_backward(
699
+ dout,
700
+ q,
701
+ k,
702
+ v,
703
+ out,
704
+ softmax_lse,
705
+ cu_seqlens_q,
706
+ cu_seqlens_k,
707
+ seqused_q,
708
+ seqused_k,
709
+ ctx.max_seqlen_q,
710
+ ctx.max_seqlen_k,
711
+ dq,
712
+ dk,
713
+ dv,
714
+ ctx.softmax_scale,
715
+ ctx.causal,
716
+ ctx.window_size[0],
717
+ ctx.window_size[1],
718
+ ctx.softcap,
719
+ ctx.deterministic,
720
+ ctx.sm_margin,
721
+ )
722
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
723
+ dk = dk[..., : k.shape[-1]]
724
+ dv = dv[..., : v.shape[-1]]
725
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
726
+
727
+
728
+ def flash_attn_qkvpacked_func(
729
+ qkv,
730
+ softmax_scale=None,
731
+ causal=False,
732
+ q_descale=None, k_descale=None, v_descale=None,
733
+ window_size=(-1, -1),
734
+ attention_chunk=0,
735
+ softcap=0.0,
736
+ deterministic=False,
737
+ num_heads_q=None,
738
+ sm_margin=0,
739
+ return_attn_probs=False,
740
+ ):
741
+ """dropout_p should be set to 0.0 during evaluation
742
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
743
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
744
+ of the gradients of Q, K, V.
745
+ For multi-query and grouped-query attention (MQA/GQA), please see
746
+ flash_attn_kvpacked_func and flash_attn_func.
747
+
748
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
749
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
750
+
751
+ Arguments:
752
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
753
+ dropout_p: float. Dropout probability.
754
+ softmax_scale: float. The scaling of QK^T before applying softmax.
755
+ Default to 1 / sqrt(headdim).
756
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
757
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
758
+ softcap: float. Anything > 0 activates softcapping attention.
759
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
760
+ the attention score of query i and key j.
761
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
762
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
763
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
764
+ testing only. The returned probabilities are not guaranteed to be correct
765
+ (they might not have the right scaling).
766
+ Return:
767
+ out: (batch_size, seqlen, nheads, headdim).
768
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
769
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
770
+ normalization factor).
771
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
772
+ The output of softmax (possibly with different scaling). It also encodes the dropout
773
+ pattern (negative means that location was dropped, nonnegative means it was kept).
774
+ """
775
+ return FlashAttnQKVPackedFunc.apply(
776
+ qkv,
777
+ softmax_scale,
778
+ causal,
779
+ q_descale, k_descale, v_descale,
780
+ window_size,
781
+ attention_chunk,
782
+ softcap,
783
+ deterministic,
784
+ num_heads_q,
785
+ sm_margin,
786
+ return_attn_probs,
787
+ )
788
+
789
+
790
+ def flash_attn_func(
791
+ q,
792
+ k,
793
+ v,
794
+ softmax_scale=None,
795
+ causal=False,
796
+ qv=None,
797
+ q_descale=None, k_descale=None, v_descale=None,
798
+ window_size=(-1, -1),
799
+ attention_chunk=0,
800
+ softcap=0.0,
801
+ num_splits=1,
802
+ pack_gqa=None,
803
+ deterministic=False,
804
+ sm_margin=0,
805
+ return_attn_probs=False,
806
+ ):
807
+ """dropout_p should be set to 0.0 during evaluation
808
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
809
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
810
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
811
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
812
+
813
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
814
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
815
+ 1 1 1 1 0
816
+ 1 1 1 1 1
817
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
818
+ 0 0
819
+ 0 0
820
+ 0 0
821
+ 1 0
822
+ 1 1
823
+ If the row of the mask is all zero, the output will be zero.
824
+
825
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
826
+ will only attend to keys between
827
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
828
+
829
+ Arguments:
830
+ q: (batch_size, seqlen, nheads, headdim)
831
+ k: (batch_size, seqlen, nheads_k, headdim)
832
+ v: (batch_size, seqlen, nheads_k, headdim)
833
+ dropout_p: float. Dropout probability.
834
+ softmax_scale: float. The scaling of QK^T before applying softmax.
835
+ Default to 1 / sqrt(headdim).
836
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
837
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
838
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
839
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
840
+ is added to the attention score of query i and key j.
841
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
842
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
843
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
844
+ testing only. The returned probabilities are not guaranteed to be correct
845
+ (they might not have the right scaling).
846
+ Return:
847
+ out: (batch_size, seqlen, nheads, headdim).
848
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
849
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
850
+ normalization factor).
851
+ """
852
+ return FlashAttnFunc.apply(
853
+ q,
854
+ k,
855
+ v,
856
+ softmax_scale,
857
+ causal,
858
+ qv,
859
+ q_descale, k_descale, v_descale,
860
+ window_size,
861
+ attention_chunk,
862
+ softcap,
863
+ num_splits,
864
+ pack_gqa,
865
+ deterministic,
866
+ sm_margin,
867
+ return_attn_probs,
868
+ )
869
+
870
+
871
+ def flash_attn_varlen_func(
872
+ q,
873
+ k,
874
+ v,
875
+ cu_seqlens_q,
876
+ cu_seqlens_k,
877
+ max_seqlen_q,
878
+ max_seqlen_k,
879
+ seqused_q=None,
880
+ seqused_k=None,
881
+ softmax_scale=None,
882
+ causal=False,
883
+ qv=None,
884
+ q_descale=None, k_descale=None, v_descale=None,
885
+ window_size=(-1, -1),
886
+ attention_chunk=0,
887
+ softcap=0.0,
888
+ num_splits=1,
889
+ pack_gqa=None,
890
+ deterministic=False,
891
+ sm_margin=0,
892
+ return_attn_probs=False,
893
+ ):
894
+ return FlashAttnVarlenFunc.apply(
895
+ q,
896
+ k,
897
+ v,
898
+ cu_seqlens_q,
899
+ cu_seqlens_k,
900
+ seqused_q,
901
+ seqused_k,
902
+ max_seqlen_q,
903
+ max_seqlen_k,
904
+ softmax_scale,
905
+ causal,
906
+ qv,
907
+ q_descale, k_descale, v_descale,
908
+ window_size,
909
+ attention_chunk,
910
+ softcap,
911
+ num_splits,
912
+ pack_gqa,
913
+ deterministic,
914
+ sm_margin,
915
+ return_attn_probs,
916
+ )
917
+
918
+
919
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
920
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
921
+
922
+
923
+ def flash_attn_with_kvcache(
924
+ q,
925
+ k_cache,
926
+ v_cache,
927
+ k=None,
928
+ v=None,
929
+ qv=None,
930
+ rotary_cos=None,
931
+ rotary_sin=None,
932
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
933
+ cache_batch_idx: Optional[torch.Tensor] = None,
934
+ cache_leftpad: Optional[torch.Tensor] = None,
935
+ page_table: Optional[torch.Tensor] = None,
936
+ cu_seqlens_q: Optional[torch.Tensor] = None,
937
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
938
+ max_seqlen_q: Optional[int] = None,
939
+ rotary_seqlens: Optional[torch.Tensor] = None,
940
+ q_descale: Optional[torch.Tensor] = None,
941
+ k_descale: Optional[torch.Tensor] = None,
942
+ v_descale: Optional[torch.Tensor] = None,
943
+ softmax_scale=None,
944
+ causal=False,
945
+ window_size=(-1, -1), # -1 means infinite context window
946
+ attention_chunk=0,
947
+ softcap=0.0, # 0.0 means deactivated
948
+ rotary_interleaved=True,
949
+ scheduler_metadata=None,
950
+ num_splits=0, # Can be tuned for speed
951
+ pack_gqa=None, # Can be tuned for speed
952
+ sm_margin=0, # Can be tuned if some SMs are used for communication
953
+ return_softmax_lse=False,
954
+ ):
955
+ """
956
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
957
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
958
+ the previous step, and update them with the new keys/values from the current step, and do
959
+ attention with the updated cache, all in 1 kernel.
960
+
961
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
962
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
963
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
964
+
965
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
966
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
967
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
968
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
969
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
970
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
971
+
972
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
973
+
974
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
975
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
976
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
977
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
978
+
979
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
980
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
981
+ 1 1 1 1 0
982
+ 1 1 1 1 1
983
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
984
+ 0 0
985
+ 0 0
986
+ 0 0
987
+ 1 0
988
+ 1 1
989
+ If the row of the mask is all zero, the output will be zero.
990
+
991
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
992
+ will only attend to keys between
993
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
994
+
995
+ Note: Does not support backward pass.
996
+
997
+ Arguments:
998
+ q: (batch_size, seqlen, nheads, headdim)
999
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
1000
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
1001
+ page_block_size can be arbitrary (e.g, 1, 2, 3, 64, etc.).
1002
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
1003
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
1004
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
1005
+ k with k_cache, starting at the indices specified by cache_seqlens.
1006
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
1007
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
1008
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
1009
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
1010
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
1011
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
1012
+ KV cache.
1013
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
1014
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
1015
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
1016
+ might come from any of the duplicate indices.
1017
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
1018
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
1019
+ softmax_scale: float. The scaling of QK^T before applying softmax.
1020
+ Default to 1 / sqrt(headdim).
1021
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
1022
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
1023
+ softcap: float. Anything > 0 activates softcapping attention.
1024
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
1025
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
1026
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
1027
+ (i.e. GPT-NeoX style).
1028
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
1029
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
1030
+ to automatically determine the number of splits.
1031
+ Don't change this unless you know what you are doing.
1032
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
1033
+
1034
+ Return:
1035
+ out: (batch_size, seqlen, nheads, headdim).
1036
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
1037
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
1038
+ normalization factor).
1039
+ """
1040
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
1041
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
1042
+ if softmax_scale is None:
1043
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
1044
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
1045
+ cache_seqlens = torch.full(
1046
+ (q.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
1047
+ )
1048
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1049
+ out, softmax_lse, *rest = _flash_attn_forward(
1050
+ q,
1051
+ k_cache,
1052
+ v_cache,
1053
+ k,
1054
+ v,
1055
+ qv,
1056
+ None, # out
1057
+ cu_seqlens_q,
1058
+ None, # cu_seqlens_k
1059
+ cu_seqlens_k_new,
1060
+ None, # seqused_q
1061
+ cache_seqlens,
1062
+ max_seqlen_q,
1063
+ None, # max_seqlen_k
1064
+ page_table,
1065
+ cache_batch_idx,
1066
+ cache_leftpad,
1067
+ rotary_cos,
1068
+ rotary_sin,
1069
+ rotary_seqlens,
1070
+ q_descale, k_descale, v_descale,
1071
+ softmax_scale,
1072
+ causal=causal,
1073
+ window_size_left=window_size[0],
1074
+ window_size_right=window_size[1],
1075
+ attention_chunk=attention_chunk,
1076
+ softcap=softcap,
1077
+ rotary_interleaved=rotary_interleaved,
1078
+ scheduler_metadata=scheduler_metadata,
1079
+ num_splits=num_splits,
1080
+ pack_gqa=pack_gqa,
1081
+ sm_margin=sm_margin,
1082
+ )
1083
+ # return (out, softmax_lse) if return_softmax_lse else out
1084
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
1085
+
1086
+
1087
+ def get_scheduler_metadata(
1088
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
1089
+ cache_seqlens: torch.Tensor,
1090
+ qkv_dtype=torch.bfloat16,
1091
+ headdim_v=None,
1092
+ cu_seqlens_q: Optional[torch.Tensor] = None,
1093
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
1094
+ cache_leftpad: Optional[torch.Tensor] = None,
1095
+ page_size: Optional[int] = None,
1096
+ max_seqlen_k_new=0,
1097
+ causal=False,
1098
+ window_size=(-1, -1), # -1 means infinite context window
1099
+ attention_chunk=0,
1100
+ has_softcap=False,
1101
+ num_splits=0, # Can be tuned for speed
1102
+ pack_gqa=None, # Can be tuned for speed
1103
+ sm_margin=0, # Can be tuned if some SMs are used for communication
1104
+ ):
1105
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1106
+ if headdim_v is None:
1107
+ headdim_v = headdim
1108
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
1109
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
1110
+ qkv_dtype,
1111
+ cache_seqlens,
1112
+ cu_seqlens_q,
1113
+ None, # cu_seqlens_k
1114
+ cu_seqlens_k_new,
1115
+ None, # seqused_q
1116
+ cache_leftpad,
1117
+ page_size,
1118
+ max_seqlen_k_new,
1119
+ causal,
1120
+ window_size[0], window_size[1],
1121
+ attention_chunk,
1122
+ has_softcap,
1123
+ num_splits,
1124
+ pack_gqa,
1125
+ sm_margin,
1126
+ )
1127
+ return scheduler_metadata
build/torch210-cxx11-cu128-x86_64-linux/metadata.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "license": "BSD-3-Clause",
4
+ "python-depends": [],
5
+ "backend": {
6
+ "type": "cuda",
7
+ "archs": [
8
+ "8.0",
9
+ "9.0a"
10
+ ]
11
+ }
12
+ }
build/torch210-cxx11-cu130-x86_64-linux/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch210-cxx11-cu130-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:745d488c7c96de2e8b2625c6a0331dd7ecf7693054e8500e6a92c00a5a2fd11c
3
+ size 823699368
build/torch210-cxx11-cu130-x86_64-linux/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_cuda_e1d5be2
3
+ ops = torch.ops._flash_attn3_cuda_e1d5be2
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_cuda_e1d5be2::{op_name}"
build/torch210-cxx11-cu130-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import importlib.util
3
+ import sys
4
+ from pathlib import Path
5
+ from types import ModuleType
6
+
7
+
8
+ def _import_from_path(file_path: Path) -> ModuleType:
9
+ # We cannot use the module name as-is, after adding it to `sys.modules`,
10
+ # it would also be used for other imports. So, we make a module name that
11
+ # depends on the path for it to be unique using the hex-encoded hash of
12
+ # the path.
13
+ path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
+ module_name = path_hash
15
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
16
+ if spec is None:
17
+ raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
+ module = importlib.util.module_from_spec(spec)
19
+ if module is None:
20
+ raise ImportError(f"Cannot load module {module_name} from spec")
21
+ sys.modules[module_name] = module
22
+ spec.loader.exec_module(module) # type: ignore
23
+ return module
24
+
25
+
26
+ globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
build/torch210-cxx11-cu130-x86_64-linux/flash_attn_config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Auto-generated by flash attention 3 setup.py
2
+ CONFIG = {'build_flags': {'FLASHATTENTION_DISABLE_BACKWARD': False, 'FLASHATTENTION_DISABLE_SPLIT': False, 'FLASHATTENTION_DISABLE_PAGEDKV': False, 'FLASHATTENTION_DISABLE_APPENDKV': False, 'FLASHATTENTION_DISABLE_LOCAL': False, 'FLASHATTENTION_DISABLE_SOFTCAP': False, 'FLASHATTENTION_DISABLE_PACKGQA': False, 'FLASHATTENTION_DISABLE_FP16': False, 'FLASHATTENTION_DISABLE_FP8': False, 'FLASHATTENTION_DISABLE_VARLEN': False, 'FLASHATTENTION_DISABLE_CLUSTER': False, 'FLASHATTENTION_DISABLE_HDIM64': False, 'FLASHATTENTION_DISABLE_HDIM96': False, 'FLASHATTENTION_DISABLE_HDIM128': False, 'FLASHATTENTION_DISABLE_HDIM192': False, 'FLASHATTENTION_DISABLE_HDIM256': False, 'FLASHATTENTION_DISABLE_SM8x': False, 'FLASHATTENTION_ENABLE_VCOLMAJOR': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF64': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF192': False}}
3
+
4
+ def show():
5
+ from pprint import pprint
6
+ pprint(CONFIG)
7
+
build/torch210-cxx11-cu130-x86_64-linux/flash_attn_interface.py ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union, List, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+ from ._ops import add_op_namespace_prefix
10
+
11
+ def maybe_contiguous(x):
12
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
13
+
14
+
15
+ def round_multiple(x, m):
16
+ return (x + m - 1) // m * m
17
+
18
+
19
+ def round_up_headdim(head_size: int) -> int:
20
+ from .flash_attn_config import CONFIG
21
+
22
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM64"]:
23
+ if head_size <= 64:
24
+ return 64
25
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM96"]:
26
+ if head_size <= 96:
27
+ return 96
28
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM128"]:
29
+ if head_size <= 128:
30
+ return 128
31
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM192"]:
32
+ if head_size <= 192:
33
+ return 192
34
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM256"]:
35
+ if head_size <= 256:
36
+ return 256
37
+ return 256
38
+
39
+
40
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types="cuda")
41
+ def _flash_attn_forward(
42
+ q: torch.Tensor,
43
+ k: torch.Tensor,
44
+ v: torch.Tensor,
45
+ k_new: Optional[torch.Tensor] = None,
46
+ v_new: Optional[torch.Tensor] = None,
47
+ qv: Optional[torch.Tensor] = None,
48
+ out_: Optional[torch.Tensor] = None,
49
+ cu_seqlens_q: Optional[torch.Tensor] = None,
50
+ cu_seqlens_k: Optional[torch.Tensor] = None,
51
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
52
+ seqused_q: Optional[torch.Tensor] = None,
53
+ seqused_k: Optional[torch.Tensor] = None,
54
+ max_seqlen_q: Optional[int] = None,
55
+ max_seqlen_k: Optional[int] = None,
56
+ page_table: Optional[torch.Tensor] = None,
57
+ kv_batch_idx: Optional[torch.Tensor] = None,
58
+ leftpad_k: Optional[torch.Tensor] = None,
59
+ rotary_cos: Optional[torch.Tensor] = None,
60
+ rotary_sin: Optional[torch.Tensor] = None,
61
+ seqlens_rotary: Optional[torch.Tensor] = None,
62
+ q_descale: Optional[torch.Tensor] = None,
63
+ k_descale: Optional[torch.Tensor] = None,
64
+ v_descale: Optional[torch.Tensor] = None,
65
+ softmax_scale: Optional[float] = None,
66
+ causal: bool = False,
67
+ window_size_left: int = -1,
68
+ window_size_right: int = -1,
69
+ attention_chunk: int = 0,
70
+ softcap: float = 0.0,
71
+ rotary_interleaved: bool = True,
72
+ scheduler_metadata: Optional[torch.Tensor] = None,
73
+ num_splits: int = 1,
74
+ pack_gqa: Optional[bool] = None,
75
+ sm_margin: int = 0,
76
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
77
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
78
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
79
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
80
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
81
+ ]
82
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
83
+ page_table, kv_batch_idx, leftpad_k = [
84
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
85
+ ]
86
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
87
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
88
+ out, softmax_lse, out_accum, softmax_lse_accum = flash_attn_3_cuda.fwd(
89
+ q,
90
+ k,
91
+ v,
92
+ k_new,
93
+ v_new,
94
+ qv,
95
+ out_,
96
+ cu_seqlens_q,
97
+ cu_seqlens_k,
98
+ cu_seqlens_k_new,
99
+ seqused_q,
100
+ seqused_k,
101
+ max_seqlen_q,
102
+ max_seqlen_k,
103
+ page_table,
104
+ kv_batch_idx,
105
+ leftpad_k,
106
+ rotary_cos,
107
+ rotary_sin,
108
+ seqlens_rotary,
109
+ q_descale,
110
+ k_descale,
111
+ v_descale,
112
+ softmax_scale,
113
+ causal,
114
+ window_size_left,
115
+ window_size_right,
116
+ attention_chunk,
117
+ softcap,
118
+ rotary_interleaved,
119
+ scheduler_metadata,
120
+ num_splits,
121
+ pack_gqa,
122
+ sm_margin,
123
+ )
124
+
125
+ if out_accum is None:
126
+ out_accum = torch.tensor([], device=out.device)
127
+
128
+ if softmax_lse_accum is None:
129
+ softmax_lse_accum = torch.tensor([], device=out.device)
130
+
131
+ return out, softmax_lse, out_accum, softmax_lse_accum
132
+
133
+
134
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
135
+ def _flash_attn_forward_fake(
136
+ q: torch.Tensor,
137
+ k: torch.Tensor,
138
+ v: torch.Tensor,
139
+ k_new: Optional[torch.Tensor] = None,
140
+ v_new: Optional[torch.Tensor] = None,
141
+ qv: Optional[torch.Tensor] = None,
142
+ out_: Optional[torch.Tensor] = None,
143
+ cu_seqlens_q: Optional[torch.Tensor] = None,
144
+ cu_seqlens_k: Optional[torch.Tensor] = None,
145
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
146
+ seqused_q: Optional[torch.Tensor] = None,
147
+ seqused_k: Optional[torch.Tensor] = None,
148
+ max_seqlen_q: Optional[int] = None,
149
+ max_seqlen_k: Optional[int] = None,
150
+ page_table: Optional[torch.Tensor] = None,
151
+ kv_batch_idx: Optional[torch.Tensor] = None,
152
+ leftpad_k: Optional[torch.Tensor] = None,
153
+ rotary_cos: Optional[torch.Tensor] = None,
154
+ rotary_sin: Optional[torch.Tensor] = None,
155
+ seqlens_rotary: Optional[torch.Tensor] = None,
156
+ q_descale: Optional[torch.Tensor] = None,
157
+ k_descale: Optional[torch.Tensor] = None,
158
+ v_descale: Optional[torch.Tensor] = None,
159
+ softmax_scale: Optional[float] = None,
160
+ causal: bool = False,
161
+ window_size_left: int = -1,
162
+ window_size_right: int = -1,
163
+ attention_chunk: int = 0,
164
+ softcap: float = 0.0,
165
+ rotary_interleaved: bool = True,
166
+ scheduler_metadata: Optional[torch.Tensor] = None,
167
+ num_splits: int = 1,
168
+ pack_gqa: Optional[bool] = None,
169
+ sm_margin: int = 0,
170
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
171
+ """
172
+ Symbolic fake implementation of flash attention forward.
173
+ Returns tensors with the correct shapes and dtypes without actual computation.
174
+ """
175
+
176
+ # Determine if we're in varlen mode
177
+ is_varlen_q = cu_seqlens_q is not None
178
+
179
+ # Get dimensions from query tensor
180
+ if is_varlen_q:
181
+ # varlen mode: q is (total_q, num_heads, head_size)
182
+ total_q, num_heads, head_size = q.shape
183
+ batch_size = cu_seqlens_q.shape[0] - 1
184
+
185
+ if max_seqlen_q is None:
186
+ raise ValueError("max_seqlen_q must be provided if cu_seqlens_q is provided")
187
+ seqlen_q = max_seqlen_q
188
+ else:
189
+ # batch mode: q is (batch_size, seqlen_q, num_heads, head_size)
190
+ batch_size, seqlen_q, num_heads, head_size = q.shape
191
+ total_q = batch_size * q.shape[1]
192
+ # Get value head dimension
193
+ head_size_v = v.shape[-1]
194
+
195
+ # Determine output dtype (FP8 inputs produce BF16 outputs)
196
+ q_type = q.dtype
197
+ if q_type == torch.float8_e4m3fn:
198
+ out_dtype = torch.bfloat16
199
+ else:
200
+ out_dtype = q_type
201
+
202
+ # Create output tensor
203
+ if out_ is not None:
204
+ # If out_ is provided, _flash_attn_forward becomes non-functional
205
+ raise TypeError("Tracing (torch.compile/torch.export) with pre-allocated output tensor is not supported.")
206
+
207
+ if is_varlen_q:
208
+ out = torch.empty((total_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
209
+ else:
210
+ out = torch.empty((batch_size, seqlen_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
211
+
212
+ # Create softmax_lse tensor
213
+ if is_varlen_q:
214
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device)
215
+ else:
216
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
217
+
218
+ # TODO(guilhermeleobas): Implement "get_num_splits"
219
+ # There's an heuristic to compute num_splits when "num_splits <= 0"
220
+ # assert that num_splits is > 0 for now
221
+ if num_splits <= 0:
222
+ raise ValueError(f"tracing (torch.compile/torch.export) with num_splits <= 0 not supported. Got {num_splits=}")
223
+
224
+ if num_splits > 1:
225
+ if is_varlen_q:
226
+ out_accum = torch.empty((num_splits, num_heads, total_q, head_size_v), dtype=torch.float32, device=q.device)
227
+ softmax_lse_accum = torch.empty((num_splits, num_heads, total_q), dtype=torch.float32, device=q.device)
228
+ else:
229
+ out_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q, head_size_v), dtype=torch.float32, device=q.device)
230
+ softmax_lse_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
231
+ else:
232
+ # Tensors are not set when num_splits < 1
233
+ out_accum = torch.tensor([], device=out.device)
234
+ softmax_lse_accum = torch.tensor([], device=out.device)
235
+
236
+ return out, softmax_lse, out_accum, softmax_lse_accum
237
+
238
+
239
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types="cuda")
240
+ def _flash_attn_backward(
241
+ dout: torch.Tensor,
242
+ q: torch.Tensor,
243
+ k: torch.Tensor,
244
+ v: torch.Tensor,
245
+ out: torch.Tensor,
246
+ softmax_lse: torch.Tensor,
247
+ cu_seqlens_q: Optional[torch.Tensor] = None,
248
+ cu_seqlens_k: Optional[torch.Tensor] = None,
249
+ sequed_q: Optional[torch.Tensor] = None,
250
+ sequed_k: Optional[torch.Tensor] = None,
251
+ max_seqlen_q: Optional[int] = None,
252
+ max_seqlen_k: Optional[int] = None,
253
+ dq: Optional[torch.Tensor] = None,
254
+ dk: Optional[torch.Tensor] = None,
255
+ dv: Optional[torch.Tensor] = None,
256
+ softmax_scale: Optional[float] = None,
257
+ is_causal: bool = False,
258
+ window_size_left: int = -1,
259
+ window_size_right: int = -1,
260
+ softcap: float = 0.0,
261
+ deterministic: bool = False,
262
+ sm_margin: int = 0,
263
+ ) -> torch.Tensor:
264
+ # dq, dk, dv are allocated by us so they should already be contiguous
265
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
266
+ softmax_d, *rest = flash_attn_3_cuda.bwd(
267
+ dout,
268
+ q,
269
+ k,
270
+ v,
271
+ out,
272
+ softmax_lse,
273
+ dq,
274
+ dk,
275
+ dv,
276
+ cu_seqlens_q,
277
+ cu_seqlens_k,
278
+ sequed_q,
279
+ sequed_k,
280
+ max_seqlen_q,
281
+ max_seqlen_k,
282
+ softmax_scale,
283
+ is_causal,
284
+ window_size_left,
285
+ window_size_right,
286
+ softcap,
287
+ deterministic,
288
+ sm_margin,
289
+ )
290
+ return softmax_d
291
+
292
+
293
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
294
+ def _flash_attn_backward_fake(
295
+ dout: torch.Tensor,
296
+ q: torch.Tensor,
297
+ k: torch.Tensor,
298
+ v: torch.Tensor,
299
+ out: torch.Tensor,
300
+ softmax_lse: torch.Tensor,
301
+ cu_seqlens_q: Optional[torch.Tensor] = None,
302
+ cu_seqlens_k: Optional[torch.Tensor] = None,
303
+ sequed_q: Optional[torch.Tensor] = None,
304
+ sequed_k: Optional[torch.Tensor] = None,
305
+ max_seqlen_q: Optional[int] = None,
306
+ max_seqlen_k: Optional[int] = None,
307
+ dq: Optional[torch.Tensor] = None,
308
+ dk: Optional[torch.Tensor] = None,
309
+ dv: Optional[torch.Tensor] = None,
310
+ softmax_scale: Optional[float] = None,
311
+ is_causal: bool = False,
312
+ window_size_left: int = -1,
313
+ window_size_right: int = -1,
314
+ softcap: float = 0.0,
315
+ deterministic: bool = False,
316
+ sm_margin: int = 0,
317
+ ) -> torch.Tensor:
318
+
319
+ is_varlen_q = cu_seqlens_q is not None
320
+ is_varlen_k = cu_seqlens_q is not None
321
+ is_varlen = is_varlen_q or is_varlen_k or sequed_q is not None or sequed_k is not None
322
+
323
+ if not is_varlen_q:
324
+ batch_size = q.size(0)
325
+ seqlen_q = q.size(1)
326
+ seqlen_k = k.size(1)
327
+ total_q = batch_size * q.size(1)
328
+ else:
329
+ batch_size = cu_seqlens_q.size(0) - 1
330
+ total_q = q.size(0)
331
+ seqlen_q = max_seqlen_q
332
+ seqlen_k = max_seqlen_k
333
+
334
+ if window_size_left >= seqlen_k - 1:
335
+ window_size_left = -1
336
+
337
+ if window_size_right >= seqlen_q - 1:
338
+ window_size_right = -1
339
+
340
+ if is_causal:
341
+ window_size_right = 0
342
+
343
+ is_causal = window_size_left < 0 and window_size_right == 0
344
+
345
+ head_size = q.size(-1)
346
+ head_size_v = v.size(-1)
347
+ head_size_rounded = round_up_headdim(max(head_size, head_size_v))
348
+
349
+ # Hopper gpus uses cuda compute capabilities 9.0
350
+ cap = torch.cuda.get_device_capability(q.device)
351
+ arch = cap[0] * 10 + cap[1]
352
+
353
+ is_local = (window_size_left >= 0 or window_size_right >= 0) and not is_causal
354
+
355
+ if head_size_rounded <= 64:
356
+ kBlockM_sm90 = 96 if (is_causal and softcap > 0.0) else 128
357
+ elif head_size_rounded <= 96:
358
+ kBlockM_sm90 = 64
359
+ elif head_size_rounded <= 128:
360
+ kBlockM_sm90 = 64 if (is_causal or is_local or softcap > 0.0) else 80
361
+ else:
362
+ kBlockM_sm90 = 64
363
+
364
+ kBlockM_sm80 = 128 if head_size_rounded <= 64 else 64
365
+ kBlockM_sm86 = 64 if head_size_rounded <= 192 else 32
366
+
367
+ if arch >= 90:
368
+ kBlockM = kBlockM_sm90
369
+ elif arch == 86 or arch == 89:
370
+ kBlockM = kBlockM_sm86
371
+ else:
372
+ kBlockM = kBlockM_sm80
373
+
374
+ num_heads = q.shape[-2]
375
+ seqlen_q_rounded = round_multiple(seqlen_q, kBlockM)
376
+
377
+ total_q_padded_rounded = round_multiple(total_q + batch_size * kBlockM, kBlockM)
378
+
379
+ dq = torch.empty_like(q) if dq is None else dq
380
+ dk = torch.empty_like(k) if dk is None else dk
381
+ dv = torch.empty_like(v) if dv is None else dv
382
+
383
+ if not is_varlen:
384
+ softmax_d = torch.empty((batch_size, num_heads, seqlen_q_rounded), dtype=torch.float32, device=q.device)
385
+ else:
386
+ softmax_d = torch.empty((num_heads, total_q_padded_rounded), dtype=torch.float32, device=q.device)
387
+
388
+ return softmax_d
389
+
390
+
391
+ def setup_context(ctx, inputs, output):
392
+ q, k, v = inputs[:3]
393
+ out, softmax_lse, _, _ = output
394
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
395
+ ctx.softmax_scale = inputs[-11]
396
+ ctx.causal = inputs[-10]
397
+ ctx.window_size = [inputs[-9], inputs[-8]]
398
+ ctx.attention_chunk = inputs[-7]
399
+ ctx.softcap = inputs[-6]
400
+ ctx.sm_margin = inputs[-1]
401
+
402
+
403
+ def _backward(ctx, dout, *grads):
404
+ q, k, v, out, softmax_lse = ctx.saved_tensors
405
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
406
+ _flash_attn_backward(
407
+ dout,
408
+ q,
409
+ k,
410
+ v,
411
+ out,
412
+ softmax_lse,
413
+ None, None, # cu_seqlens_q, cu_seqlens_k,
414
+ None, None, # sequed_q, sequed_k,
415
+ None, None, # max_seqlen_q, max_seqlen_k,
416
+ dq,
417
+ dk,
418
+ dv,
419
+ ctx.softmax_scale,
420
+ ctx.causal,
421
+ ctx.window_size[0],
422
+ ctx.window_size[1],
423
+ ctx.softcap,
424
+ False, # deterministic
425
+ ctx.sm_margin,
426
+ )
427
+ return dq, dk, dv, *((None,) * 21)
428
+
429
+
430
+ _flash_attn_forward.register_autograd(_backward, setup_context=setup_context)
431
+
432
+
433
+
434
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
435
+ @staticmethod
436
+ def forward(
437
+ ctx,
438
+ qkv,
439
+ softmax_scale,
440
+ causal,
441
+ q_descale=None, k_descale=None, v_descale=None,
442
+ window_size=(-1, -1),
443
+ attention_chunk=0,
444
+ softcap=0.0,
445
+ deterministic=False,
446
+ num_heads_q=None,
447
+ sm_margin=0,
448
+ return_softmax=False,
449
+ ):
450
+ if softmax_scale is None:
451
+ softmax_scale = qkv.shape[-1] ** (-0.5)
452
+ if qkv.dim() == 5:
453
+ assert qkv.shape[-3] == 3
454
+ q, k, v = qkv.unbind(dim=-3)
455
+ else:
456
+ assert qkv.dim() == 4
457
+ assert num_heads_q is not None
458
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
459
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
460
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
461
+ out, softmax_lse, *rest = _flash_attn_forward(
462
+ q,
463
+ k,
464
+ v,
465
+ None, None, # k_new, v_new
466
+ None, # qv
467
+ None, # out
468
+ None, None, None, # cu_seqlens_q/k/k_new
469
+ None, None, # seqused_q/k
470
+ None, None, # max_seqlen_q/k
471
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
472
+ None, None, None, # rotary_cos/sin, seqlens_rotary
473
+ q_descale, k_descale, v_descale,
474
+ softmax_scale,
475
+ causal=causal,
476
+ window_size_left=window_size[0],
477
+ window_size_right=window_size[1],
478
+ attention_chunk=attention_chunk,
479
+ softcap=softcap,
480
+ sm_margin=sm_margin,
481
+ )
482
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
483
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
484
+ ctx.softmax_scale = softmax_scale
485
+ ctx.causal = causal
486
+ ctx.window_size = window_size
487
+ ctx.attention_chunk = attention_chunk
488
+ ctx.softcap = softcap
489
+ ctx.deterministic = deterministic
490
+ ctx.ndim = qkv.dim()
491
+ ctx.sm_margin = sm_margin
492
+ return (out, softmax_lse) if return_softmax else out
493
+
494
+ @staticmethod
495
+ def backward(ctx, dout, *args):
496
+ q, k, v, out, softmax_lse = ctx.saved_tensors
497
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
498
+ if ctx.ndim == 5:
499
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
500
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
501
+ dq, dk, dv = dqkv.unbind(dim=-3)
502
+ else:
503
+ num_heads_q = q.shape[2]
504
+ num_heads_k = k.shape[2]
505
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
506
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
507
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
508
+ _flash_attn_backward(
509
+ dout,
510
+ q,
511
+ k,
512
+ v,
513
+ out,
514
+ softmax_lse,
515
+ None, None, # cu_seqlens_q, cu_seqlens_k,
516
+ None, None, # sequed_q, sequed_k,
517
+ None, None, # max_seqlen_q, max_seqlen_k,
518
+ dq,
519
+ dk,
520
+ dv,
521
+ ctx.softmax_scale,
522
+ ctx.causal,
523
+ ctx.window_size[0],
524
+ ctx.window_size[1],
525
+ ctx.softcap,
526
+ ctx.deterministic,
527
+ ctx.sm_margin,
528
+ )
529
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
530
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None, None
531
+
532
+
533
+ class FlashAttnFunc(torch.autograd.Function):
534
+
535
+ @staticmethod
536
+ def forward(
537
+ ctx,
538
+ q,
539
+ k,
540
+ v,
541
+ softmax_scale,
542
+ causal,
543
+ qv=None,
544
+ q_descale=None, k_descale=None, v_descale=None,
545
+ window_size=(-1, -1),
546
+ attention_chunk=0,
547
+ softcap=0.0,
548
+ num_splits=1,
549
+ pack_gqa=None,
550
+ deterministic=False,
551
+ sm_margin=0,
552
+ return_softmax=False,
553
+ ):
554
+ if softmax_scale is None:
555
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
556
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
557
+ out, softmax_lse, *rest = _flash_attn_forward(
558
+ q,
559
+ k,
560
+ v,
561
+ None, None, # k_new, v_new
562
+ qv, # qv
563
+ None, # out
564
+ None, None, None, # cu_seqlens_q/k/k_new
565
+ None, None, # seqused_q/k
566
+ None, None, # max_seqlen_q/k
567
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
568
+ None, None, None, # rotary_cos/sin, seqlens_rotary
569
+ q_descale, k_descale, v_descale,
570
+ softmax_scale,
571
+ causal=causal,
572
+ window_size_left=window_size[0],
573
+ window_size_right=window_size[1],
574
+ attention_chunk=attention_chunk,
575
+ softcap=softcap,
576
+ num_splits=num_splits,
577
+ pack_gqa=pack_gqa,
578
+ sm_margin=sm_margin,
579
+ )
580
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
581
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
582
+ ctx.softmax_scale = softmax_scale
583
+ ctx.causal = causal
584
+ ctx.window_size = window_size
585
+ ctx.attention_chunk = attention_chunk
586
+ ctx.softcap = softcap
587
+ ctx.deterministic = deterministic
588
+ ctx.sm_margin = sm_margin
589
+ return (out, softmax_lse) if return_softmax else out
590
+
591
+ @staticmethod
592
+ def backward(ctx, dout, *args):
593
+ q, k, v, out, softmax_lse = ctx.saved_tensors
594
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
595
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
596
+ _flash_attn_backward(
597
+ dout,
598
+ q,
599
+ k,
600
+ v,
601
+ out,
602
+ softmax_lse,
603
+ None, None, # cu_seqlens_q, cu_seqlens_k,
604
+ None, None, # sequed_q, sequed_k,
605
+ None, None, # max_seqlen_q, max_seqlen_k,
606
+ dq,
607
+ dk,
608
+ dv,
609
+ ctx.softmax_scale,
610
+ ctx.causal,
611
+ ctx.window_size[0],
612
+ ctx.window_size[1],
613
+ ctx.softcap,
614
+ ctx.deterministic,
615
+ ctx.sm_margin,
616
+ )
617
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
618
+ dk = dk[..., : k.shape[-1]]
619
+ dv = dv[..., : v.shape[-1]]
620
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
621
+
622
+
623
+ class FlashAttnVarlenFunc(torch.autograd.Function):
624
+
625
+ @staticmethod
626
+ def forward(
627
+ ctx,
628
+ q,
629
+ k,
630
+ v,
631
+ cu_seqlens_q,
632
+ cu_seqlens_k,
633
+ seqused_q,
634
+ seqused_k,
635
+ max_seqlen_q,
636
+ max_seqlen_k,
637
+ softmax_scale,
638
+ causal,
639
+ qv=None,
640
+ q_descale=None, k_descale=None, v_descale=None,
641
+ window_size=(-1, -1),
642
+ attention_chunk=0,
643
+ softcap=0.0,
644
+ num_splits=1,
645
+ pack_gqa=None,
646
+ deterministic=False,
647
+ sm_margin=0,
648
+ return_softmax=False,
649
+ ):
650
+ if softmax_scale is None:
651
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
652
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
653
+ out, softmax_lse, *rest = _flash_attn_forward(
654
+ q,
655
+ k,
656
+ v,
657
+ None, None, # k_new, v_new
658
+ qv, # qv
659
+ None, # out
660
+ cu_seqlens_q,
661
+ cu_seqlens_k,
662
+ None, # cu_seqlens_k_new
663
+ seqused_q,
664
+ seqused_k,
665
+ max_seqlen_q,
666
+ max_seqlen_k,
667
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
668
+ None, None, None, # rotary_cos/sin, seqlens_rotary
669
+ q_descale, k_descale, v_descale,
670
+ softmax_scale,
671
+ causal=causal,
672
+ window_size_left=window_size[0],
673
+ window_size_right=window_size[1],
674
+ attention_chunk=attention_chunk,
675
+ softcap=softcap,
676
+ num_splits=num_splits,
677
+ pack_gqa=pack_gqa,
678
+ sm_margin=sm_margin,
679
+ )
680
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
681
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
682
+ ctx.max_seqlen_q = max_seqlen_q
683
+ ctx.max_seqlen_k = max_seqlen_k
684
+ ctx.softmax_scale = softmax_scale
685
+ ctx.causal = causal
686
+ ctx.window_size = window_size
687
+ ctx.attention_chunk = attention_chunk
688
+ ctx.softcap = softcap
689
+ ctx.deterministic = deterministic
690
+ ctx.sm_margin = sm_margin
691
+ return (out, softmax_lse) if return_softmax else out
692
+
693
+ @staticmethod
694
+ def backward(ctx, dout, *args):
695
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
696
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
697
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
698
+ _flash_attn_backward(
699
+ dout,
700
+ q,
701
+ k,
702
+ v,
703
+ out,
704
+ softmax_lse,
705
+ cu_seqlens_q,
706
+ cu_seqlens_k,
707
+ seqused_q,
708
+ seqused_k,
709
+ ctx.max_seqlen_q,
710
+ ctx.max_seqlen_k,
711
+ dq,
712
+ dk,
713
+ dv,
714
+ ctx.softmax_scale,
715
+ ctx.causal,
716
+ ctx.window_size[0],
717
+ ctx.window_size[1],
718
+ ctx.softcap,
719
+ ctx.deterministic,
720
+ ctx.sm_margin,
721
+ )
722
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
723
+ dk = dk[..., : k.shape[-1]]
724
+ dv = dv[..., : v.shape[-1]]
725
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
726
+
727
+
728
+ def flash_attn_qkvpacked_func(
729
+ qkv,
730
+ softmax_scale=None,
731
+ causal=False,
732
+ q_descale=None, k_descale=None, v_descale=None,
733
+ window_size=(-1, -1),
734
+ attention_chunk=0,
735
+ softcap=0.0,
736
+ deterministic=False,
737
+ num_heads_q=None,
738
+ sm_margin=0,
739
+ return_attn_probs=False,
740
+ ):
741
+ """dropout_p should be set to 0.0 during evaluation
742
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
743
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
744
+ of the gradients of Q, K, V.
745
+ For multi-query and grouped-query attention (MQA/GQA), please see
746
+ flash_attn_kvpacked_func and flash_attn_func.
747
+
748
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
749
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
750
+
751
+ Arguments:
752
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
753
+ dropout_p: float. Dropout probability.
754
+ softmax_scale: float. The scaling of QK^T before applying softmax.
755
+ Default to 1 / sqrt(headdim).
756
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
757
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
758
+ softcap: float. Anything > 0 activates softcapping attention.
759
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
760
+ the attention score of query i and key j.
761
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
762
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
763
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
764
+ testing only. The returned probabilities are not guaranteed to be correct
765
+ (they might not have the right scaling).
766
+ Return:
767
+ out: (batch_size, seqlen, nheads, headdim).
768
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
769
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
770
+ normalization factor).
771
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
772
+ The output of softmax (possibly with different scaling). It also encodes the dropout
773
+ pattern (negative means that location was dropped, nonnegative means it was kept).
774
+ """
775
+ return FlashAttnQKVPackedFunc.apply(
776
+ qkv,
777
+ softmax_scale,
778
+ causal,
779
+ q_descale, k_descale, v_descale,
780
+ window_size,
781
+ attention_chunk,
782
+ softcap,
783
+ deterministic,
784
+ num_heads_q,
785
+ sm_margin,
786
+ return_attn_probs,
787
+ )
788
+
789
+
790
+ def flash_attn_func(
791
+ q,
792
+ k,
793
+ v,
794
+ softmax_scale=None,
795
+ causal=False,
796
+ qv=None,
797
+ q_descale=None, k_descale=None, v_descale=None,
798
+ window_size=(-1, -1),
799
+ attention_chunk=0,
800
+ softcap=0.0,
801
+ num_splits=1,
802
+ pack_gqa=None,
803
+ deterministic=False,
804
+ sm_margin=0,
805
+ return_attn_probs=False,
806
+ ):
807
+ """dropout_p should be set to 0.0 during evaluation
808
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
809
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
810
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
811
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
812
+
813
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
814
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
815
+ 1 1 1 1 0
816
+ 1 1 1 1 1
817
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
818
+ 0 0
819
+ 0 0
820
+ 0 0
821
+ 1 0
822
+ 1 1
823
+ If the row of the mask is all zero, the output will be zero.
824
+
825
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
826
+ will only attend to keys between
827
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
828
+
829
+ Arguments:
830
+ q: (batch_size, seqlen, nheads, headdim)
831
+ k: (batch_size, seqlen, nheads_k, headdim)
832
+ v: (batch_size, seqlen, nheads_k, headdim)
833
+ dropout_p: float. Dropout probability.
834
+ softmax_scale: float. The scaling of QK^T before applying softmax.
835
+ Default to 1 / sqrt(headdim).
836
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
837
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
838
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
839
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
840
+ is added to the attention score of query i and key j.
841
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
842
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
843
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
844
+ testing only. The returned probabilities are not guaranteed to be correct
845
+ (they might not have the right scaling).
846
+ Return:
847
+ out: (batch_size, seqlen, nheads, headdim).
848
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
849
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
850
+ normalization factor).
851
+ """
852
+ return FlashAttnFunc.apply(
853
+ q,
854
+ k,
855
+ v,
856
+ softmax_scale,
857
+ causal,
858
+ qv,
859
+ q_descale, k_descale, v_descale,
860
+ window_size,
861
+ attention_chunk,
862
+ softcap,
863
+ num_splits,
864
+ pack_gqa,
865
+ deterministic,
866
+ sm_margin,
867
+ return_attn_probs,
868
+ )
869
+
870
+
871
+ def flash_attn_varlen_func(
872
+ q,
873
+ k,
874
+ v,
875
+ cu_seqlens_q,
876
+ cu_seqlens_k,
877
+ max_seqlen_q,
878
+ max_seqlen_k,
879
+ seqused_q=None,
880
+ seqused_k=None,
881
+ softmax_scale=None,
882
+ causal=False,
883
+ qv=None,
884
+ q_descale=None, k_descale=None, v_descale=None,
885
+ window_size=(-1, -1),
886
+ attention_chunk=0,
887
+ softcap=0.0,
888
+ num_splits=1,
889
+ pack_gqa=None,
890
+ deterministic=False,
891
+ sm_margin=0,
892
+ return_attn_probs=False,
893
+ ):
894
+ return FlashAttnVarlenFunc.apply(
895
+ q,
896
+ k,
897
+ v,
898
+ cu_seqlens_q,
899
+ cu_seqlens_k,
900
+ seqused_q,
901
+ seqused_k,
902
+ max_seqlen_q,
903
+ max_seqlen_k,
904
+ softmax_scale,
905
+ causal,
906
+ qv,
907
+ q_descale, k_descale, v_descale,
908
+ window_size,
909
+ attention_chunk,
910
+ softcap,
911
+ num_splits,
912
+ pack_gqa,
913
+ deterministic,
914
+ sm_margin,
915
+ return_attn_probs,
916
+ )
917
+
918
+
919
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
920
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
921
+
922
+
923
+ def flash_attn_with_kvcache(
924
+ q,
925
+ k_cache,
926
+ v_cache,
927
+ k=None,
928
+ v=None,
929
+ qv=None,
930
+ rotary_cos=None,
931
+ rotary_sin=None,
932
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
933
+ cache_batch_idx: Optional[torch.Tensor] = None,
934
+ cache_leftpad: Optional[torch.Tensor] = None,
935
+ page_table: Optional[torch.Tensor] = None,
936
+ cu_seqlens_q: Optional[torch.Tensor] = None,
937
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
938
+ max_seqlen_q: Optional[int] = None,
939
+ rotary_seqlens: Optional[torch.Tensor] = None,
940
+ q_descale: Optional[torch.Tensor] = None,
941
+ k_descale: Optional[torch.Tensor] = None,
942
+ v_descale: Optional[torch.Tensor] = None,
943
+ softmax_scale=None,
944
+ causal=False,
945
+ window_size=(-1, -1), # -1 means infinite context window
946
+ attention_chunk=0,
947
+ softcap=0.0, # 0.0 means deactivated
948
+ rotary_interleaved=True,
949
+ scheduler_metadata=None,
950
+ num_splits=0, # Can be tuned for speed
951
+ pack_gqa=None, # Can be tuned for speed
952
+ sm_margin=0, # Can be tuned if some SMs are used for communication
953
+ return_softmax_lse=False,
954
+ ):
955
+ """
956
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
957
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
958
+ the previous step, and update them with the new keys/values from the current step, and do
959
+ attention with the updated cache, all in 1 kernel.
960
+
961
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
962
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
963
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
964
+
965
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
966
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
967
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
968
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
969
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
970
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
971
+
972
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
973
+
974
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
975
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
976
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
977
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
978
+
979
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
980
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
981
+ 1 1 1 1 0
982
+ 1 1 1 1 1
983
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
984
+ 0 0
985
+ 0 0
986
+ 0 0
987
+ 1 0
988
+ 1 1
989
+ If the row of the mask is all zero, the output will be zero.
990
+
991
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
992
+ will only attend to keys between
993
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
994
+
995
+ Note: Does not support backward pass.
996
+
997
+ Arguments:
998
+ q: (batch_size, seqlen, nheads, headdim)
999
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
1000
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
1001
+ page_block_size can be arbitrary (e.g, 1, 2, 3, 64, etc.).
1002
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
1003
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
1004
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
1005
+ k with k_cache, starting at the indices specified by cache_seqlens.
1006
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
1007
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
1008
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
1009
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
1010
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
1011
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
1012
+ KV cache.
1013
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
1014
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
1015
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
1016
+ might come from any of the duplicate indices.
1017
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
1018
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
1019
+ softmax_scale: float. The scaling of QK^T before applying softmax.
1020
+ Default to 1 / sqrt(headdim).
1021
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
1022
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
1023
+ softcap: float. Anything > 0 activates softcapping attention.
1024
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
1025
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
1026
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
1027
+ (i.e. GPT-NeoX style).
1028
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
1029
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
1030
+ to automatically determine the number of splits.
1031
+ Don't change this unless you know what you are doing.
1032
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
1033
+
1034
+ Return:
1035
+ out: (batch_size, seqlen, nheads, headdim).
1036
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
1037
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
1038
+ normalization factor).
1039
+ """
1040
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
1041
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
1042
+ if softmax_scale is None:
1043
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
1044
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
1045
+ cache_seqlens = torch.full(
1046
+ (q.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
1047
+ )
1048
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1049
+ out, softmax_lse, *rest = _flash_attn_forward(
1050
+ q,
1051
+ k_cache,
1052
+ v_cache,
1053
+ k,
1054
+ v,
1055
+ qv,
1056
+ None, # out
1057
+ cu_seqlens_q,
1058
+ None, # cu_seqlens_k
1059
+ cu_seqlens_k_new,
1060
+ None, # seqused_q
1061
+ cache_seqlens,
1062
+ max_seqlen_q,
1063
+ None, # max_seqlen_k
1064
+ page_table,
1065
+ cache_batch_idx,
1066
+ cache_leftpad,
1067
+ rotary_cos,
1068
+ rotary_sin,
1069
+ rotary_seqlens,
1070
+ q_descale, k_descale, v_descale,
1071
+ softmax_scale,
1072
+ causal=causal,
1073
+ window_size_left=window_size[0],
1074
+ window_size_right=window_size[1],
1075
+ attention_chunk=attention_chunk,
1076
+ softcap=softcap,
1077
+ rotary_interleaved=rotary_interleaved,
1078
+ scheduler_metadata=scheduler_metadata,
1079
+ num_splits=num_splits,
1080
+ pack_gqa=pack_gqa,
1081
+ sm_margin=sm_margin,
1082
+ )
1083
+ # return (out, softmax_lse) if return_softmax_lse else out
1084
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
1085
+
1086
+
1087
+ def get_scheduler_metadata(
1088
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
1089
+ cache_seqlens: torch.Tensor,
1090
+ qkv_dtype=torch.bfloat16,
1091
+ headdim_v=None,
1092
+ cu_seqlens_q: Optional[torch.Tensor] = None,
1093
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
1094
+ cache_leftpad: Optional[torch.Tensor] = None,
1095
+ page_size: Optional[int] = None,
1096
+ max_seqlen_k_new=0,
1097
+ causal=False,
1098
+ window_size=(-1, -1), # -1 means infinite context window
1099
+ attention_chunk=0,
1100
+ has_softcap=False,
1101
+ num_splits=0, # Can be tuned for speed
1102
+ pack_gqa=None, # Can be tuned for speed
1103
+ sm_margin=0, # Can be tuned if some SMs are used for communication
1104
+ ):
1105
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1106
+ if headdim_v is None:
1107
+ headdim_v = headdim
1108
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
1109
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
1110
+ qkv_dtype,
1111
+ cache_seqlens,
1112
+ cu_seqlens_q,
1113
+ None, # cu_seqlens_k
1114
+ cu_seqlens_k_new,
1115
+ None, # seqused_q
1116
+ cache_leftpad,
1117
+ page_size,
1118
+ max_seqlen_k_new,
1119
+ causal,
1120
+ window_size[0], window_size[1],
1121
+ attention_chunk,
1122
+ has_softcap,
1123
+ num_splits,
1124
+ pack_gqa,
1125
+ sm_margin,
1126
+ )
1127
+ return scheduler_metadata
build/torch210-cxx11-cu130-x86_64-linux/metadata.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "license": "BSD-3-Clause",
4
+ "python-depends": [],
5
+ "backend": {
6
+ "type": "cuda",
7
+ "archs": [
8
+ "8.0",
9
+ "9.0a"
10
+ ]
11
+ }
12
+ }
build/torch211-cxx11-cu128-x86_64-linux/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch211-cxx11-cu128-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1cb641764fe0815bab292dab3bab1d93edb5b21cf08fe1e6ee8b3d4e3e4276ff
3
+ size 804184120
build/torch211-cxx11-cu128-x86_64-linux/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_cuda_e1d5be2
3
+ ops = torch.ops._flash_attn3_cuda_e1d5be2
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_cuda_e1d5be2::{op_name}"
build/torch211-cxx11-cu128-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import importlib.util
3
+ import sys
4
+ from pathlib import Path
5
+ from types import ModuleType
6
+
7
+
8
+ def _import_from_path(file_path: Path) -> ModuleType:
9
+ # We cannot use the module name as-is, after adding it to `sys.modules`,
10
+ # it would also be used for other imports. So, we make a module name that
11
+ # depends on the path for it to be unique using the hex-encoded hash of
12
+ # the path.
13
+ path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
+ module_name = path_hash
15
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
16
+ if spec is None:
17
+ raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
+ module = importlib.util.module_from_spec(spec)
19
+ if module is None:
20
+ raise ImportError(f"Cannot load module {module_name} from spec")
21
+ sys.modules[module_name] = module
22
+ spec.loader.exec_module(module) # type: ignore
23
+ return module
24
+
25
+
26
+ globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
build/torch211-cxx11-cu128-x86_64-linux/flash_attn_config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Auto-generated by flash attention 3 setup.py
2
+ CONFIG = {'build_flags': {'FLASHATTENTION_DISABLE_BACKWARD': False, 'FLASHATTENTION_DISABLE_SPLIT': False, 'FLASHATTENTION_DISABLE_PAGEDKV': False, 'FLASHATTENTION_DISABLE_APPENDKV': False, 'FLASHATTENTION_DISABLE_LOCAL': False, 'FLASHATTENTION_DISABLE_SOFTCAP': False, 'FLASHATTENTION_DISABLE_PACKGQA': False, 'FLASHATTENTION_DISABLE_FP16': False, 'FLASHATTENTION_DISABLE_FP8': False, 'FLASHATTENTION_DISABLE_VARLEN': False, 'FLASHATTENTION_DISABLE_CLUSTER': False, 'FLASHATTENTION_DISABLE_HDIM64': False, 'FLASHATTENTION_DISABLE_HDIM96': False, 'FLASHATTENTION_DISABLE_HDIM128': False, 'FLASHATTENTION_DISABLE_HDIM192': False, 'FLASHATTENTION_DISABLE_HDIM256': False, 'FLASHATTENTION_DISABLE_SM8x': False, 'FLASHATTENTION_ENABLE_VCOLMAJOR': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF64': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF192': False}}
3
+
4
+ def show():
5
+ from pprint import pprint
6
+ pprint(CONFIG)
7
+
build/torch211-cxx11-cu128-x86_64-linux/flash_attn_interface.py ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union, List, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+ from ._ops import add_op_namespace_prefix
10
+
11
+ def maybe_contiguous(x):
12
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
13
+
14
+
15
+ def round_multiple(x, m):
16
+ return (x + m - 1) // m * m
17
+
18
+
19
+ def round_up_headdim(head_size: int) -> int:
20
+ from .flash_attn_config import CONFIG
21
+
22
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM64"]:
23
+ if head_size <= 64:
24
+ return 64
25
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM96"]:
26
+ if head_size <= 96:
27
+ return 96
28
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM128"]:
29
+ if head_size <= 128:
30
+ return 128
31
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM192"]:
32
+ if head_size <= 192:
33
+ return 192
34
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM256"]:
35
+ if head_size <= 256:
36
+ return 256
37
+ return 256
38
+
39
+
40
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types="cuda")
41
+ def _flash_attn_forward(
42
+ q: torch.Tensor,
43
+ k: torch.Tensor,
44
+ v: torch.Tensor,
45
+ k_new: Optional[torch.Tensor] = None,
46
+ v_new: Optional[torch.Tensor] = None,
47
+ qv: Optional[torch.Tensor] = None,
48
+ out_: Optional[torch.Tensor] = None,
49
+ cu_seqlens_q: Optional[torch.Tensor] = None,
50
+ cu_seqlens_k: Optional[torch.Tensor] = None,
51
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
52
+ seqused_q: Optional[torch.Tensor] = None,
53
+ seqused_k: Optional[torch.Tensor] = None,
54
+ max_seqlen_q: Optional[int] = None,
55
+ max_seqlen_k: Optional[int] = None,
56
+ page_table: Optional[torch.Tensor] = None,
57
+ kv_batch_idx: Optional[torch.Tensor] = None,
58
+ leftpad_k: Optional[torch.Tensor] = None,
59
+ rotary_cos: Optional[torch.Tensor] = None,
60
+ rotary_sin: Optional[torch.Tensor] = None,
61
+ seqlens_rotary: Optional[torch.Tensor] = None,
62
+ q_descale: Optional[torch.Tensor] = None,
63
+ k_descale: Optional[torch.Tensor] = None,
64
+ v_descale: Optional[torch.Tensor] = None,
65
+ softmax_scale: Optional[float] = None,
66
+ causal: bool = False,
67
+ window_size_left: int = -1,
68
+ window_size_right: int = -1,
69
+ attention_chunk: int = 0,
70
+ softcap: float = 0.0,
71
+ rotary_interleaved: bool = True,
72
+ scheduler_metadata: Optional[torch.Tensor] = None,
73
+ num_splits: int = 1,
74
+ pack_gqa: Optional[bool] = None,
75
+ sm_margin: int = 0,
76
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
77
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
78
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
79
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
80
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
81
+ ]
82
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
83
+ page_table, kv_batch_idx, leftpad_k = [
84
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
85
+ ]
86
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
87
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
88
+ out, softmax_lse, out_accum, softmax_lse_accum = flash_attn_3_cuda.fwd(
89
+ q,
90
+ k,
91
+ v,
92
+ k_new,
93
+ v_new,
94
+ qv,
95
+ out_,
96
+ cu_seqlens_q,
97
+ cu_seqlens_k,
98
+ cu_seqlens_k_new,
99
+ seqused_q,
100
+ seqused_k,
101
+ max_seqlen_q,
102
+ max_seqlen_k,
103
+ page_table,
104
+ kv_batch_idx,
105
+ leftpad_k,
106
+ rotary_cos,
107
+ rotary_sin,
108
+ seqlens_rotary,
109
+ q_descale,
110
+ k_descale,
111
+ v_descale,
112
+ softmax_scale,
113
+ causal,
114
+ window_size_left,
115
+ window_size_right,
116
+ attention_chunk,
117
+ softcap,
118
+ rotary_interleaved,
119
+ scheduler_metadata,
120
+ num_splits,
121
+ pack_gqa,
122
+ sm_margin,
123
+ )
124
+
125
+ if out_accum is None:
126
+ out_accum = torch.tensor([], device=out.device)
127
+
128
+ if softmax_lse_accum is None:
129
+ softmax_lse_accum = torch.tensor([], device=out.device)
130
+
131
+ return out, softmax_lse, out_accum, softmax_lse_accum
132
+
133
+
134
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
135
+ def _flash_attn_forward_fake(
136
+ q: torch.Tensor,
137
+ k: torch.Tensor,
138
+ v: torch.Tensor,
139
+ k_new: Optional[torch.Tensor] = None,
140
+ v_new: Optional[torch.Tensor] = None,
141
+ qv: Optional[torch.Tensor] = None,
142
+ out_: Optional[torch.Tensor] = None,
143
+ cu_seqlens_q: Optional[torch.Tensor] = None,
144
+ cu_seqlens_k: Optional[torch.Tensor] = None,
145
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
146
+ seqused_q: Optional[torch.Tensor] = None,
147
+ seqused_k: Optional[torch.Tensor] = None,
148
+ max_seqlen_q: Optional[int] = None,
149
+ max_seqlen_k: Optional[int] = None,
150
+ page_table: Optional[torch.Tensor] = None,
151
+ kv_batch_idx: Optional[torch.Tensor] = None,
152
+ leftpad_k: Optional[torch.Tensor] = None,
153
+ rotary_cos: Optional[torch.Tensor] = None,
154
+ rotary_sin: Optional[torch.Tensor] = None,
155
+ seqlens_rotary: Optional[torch.Tensor] = None,
156
+ q_descale: Optional[torch.Tensor] = None,
157
+ k_descale: Optional[torch.Tensor] = None,
158
+ v_descale: Optional[torch.Tensor] = None,
159
+ softmax_scale: Optional[float] = None,
160
+ causal: bool = False,
161
+ window_size_left: int = -1,
162
+ window_size_right: int = -1,
163
+ attention_chunk: int = 0,
164
+ softcap: float = 0.0,
165
+ rotary_interleaved: bool = True,
166
+ scheduler_metadata: Optional[torch.Tensor] = None,
167
+ num_splits: int = 1,
168
+ pack_gqa: Optional[bool] = None,
169
+ sm_margin: int = 0,
170
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
171
+ """
172
+ Symbolic fake implementation of flash attention forward.
173
+ Returns tensors with the correct shapes and dtypes without actual computation.
174
+ """
175
+
176
+ # Determine if we're in varlen mode
177
+ is_varlen_q = cu_seqlens_q is not None
178
+
179
+ # Get dimensions from query tensor
180
+ if is_varlen_q:
181
+ # varlen mode: q is (total_q, num_heads, head_size)
182
+ total_q, num_heads, head_size = q.shape
183
+ batch_size = cu_seqlens_q.shape[0] - 1
184
+
185
+ if max_seqlen_q is None:
186
+ raise ValueError("max_seqlen_q must be provided if cu_seqlens_q is provided")
187
+ seqlen_q = max_seqlen_q
188
+ else:
189
+ # batch mode: q is (batch_size, seqlen_q, num_heads, head_size)
190
+ batch_size, seqlen_q, num_heads, head_size = q.shape
191
+ total_q = batch_size * q.shape[1]
192
+ # Get value head dimension
193
+ head_size_v = v.shape[-1]
194
+
195
+ # Determine output dtype (FP8 inputs produce BF16 outputs)
196
+ q_type = q.dtype
197
+ if q_type == torch.float8_e4m3fn:
198
+ out_dtype = torch.bfloat16
199
+ else:
200
+ out_dtype = q_type
201
+
202
+ # Create output tensor
203
+ if out_ is not None:
204
+ # If out_ is provided, _flash_attn_forward becomes non-functional
205
+ raise TypeError("Tracing (torch.compile/torch.export) with pre-allocated output tensor is not supported.")
206
+
207
+ if is_varlen_q:
208
+ out = torch.empty((total_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
209
+ else:
210
+ out = torch.empty((batch_size, seqlen_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
211
+
212
+ # Create softmax_lse tensor
213
+ if is_varlen_q:
214
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device)
215
+ else:
216
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
217
+
218
+ # TODO(guilhermeleobas): Implement "get_num_splits"
219
+ # There's an heuristic to compute num_splits when "num_splits <= 0"
220
+ # assert that num_splits is > 0 for now
221
+ if num_splits <= 0:
222
+ raise ValueError(f"tracing (torch.compile/torch.export) with num_splits <= 0 not supported. Got {num_splits=}")
223
+
224
+ if num_splits > 1:
225
+ if is_varlen_q:
226
+ out_accum = torch.empty((num_splits, num_heads, total_q, head_size_v), dtype=torch.float32, device=q.device)
227
+ softmax_lse_accum = torch.empty((num_splits, num_heads, total_q), dtype=torch.float32, device=q.device)
228
+ else:
229
+ out_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q, head_size_v), dtype=torch.float32, device=q.device)
230
+ softmax_lse_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
231
+ else:
232
+ # Tensors are not set when num_splits < 1
233
+ out_accum = torch.tensor([], device=out.device)
234
+ softmax_lse_accum = torch.tensor([], device=out.device)
235
+
236
+ return out, softmax_lse, out_accum, softmax_lse_accum
237
+
238
+
239
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types="cuda")
240
+ def _flash_attn_backward(
241
+ dout: torch.Tensor,
242
+ q: torch.Tensor,
243
+ k: torch.Tensor,
244
+ v: torch.Tensor,
245
+ out: torch.Tensor,
246
+ softmax_lse: torch.Tensor,
247
+ cu_seqlens_q: Optional[torch.Tensor] = None,
248
+ cu_seqlens_k: Optional[torch.Tensor] = None,
249
+ sequed_q: Optional[torch.Tensor] = None,
250
+ sequed_k: Optional[torch.Tensor] = None,
251
+ max_seqlen_q: Optional[int] = None,
252
+ max_seqlen_k: Optional[int] = None,
253
+ dq: Optional[torch.Tensor] = None,
254
+ dk: Optional[torch.Tensor] = None,
255
+ dv: Optional[torch.Tensor] = None,
256
+ softmax_scale: Optional[float] = None,
257
+ is_causal: bool = False,
258
+ window_size_left: int = -1,
259
+ window_size_right: int = -1,
260
+ softcap: float = 0.0,
261
+ deterministic: bool = False,
262
+ sm_margin: int = 0,
263
+ ) -> torch.Tensor:
264
+ # dq, dk, dv are allocated by us so they should already be contiguous
265
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
266
+ softmax_d, *rest = flash_attn_3_cuda.bwd(
267
+ dout,
268
+ q,
269
+ k,
270
+ v,
271
+ out,
272
+ softmax_lse,
273
+ dq,
274
+ dk,
275
+ dv,
276
+ cu_seqlens_q,
277
+ cu_seqlens_k,
278
+ sequed_q,
279
+ sequed_k,
280
+ max_seqlen_q,
281
+ max_seqlen_k,
282
+ softmax_scale,
283
+ is_causal,
284
+ window_size_left,
285
+ window_size_right,
286
+ softcap,
287
+ deterministic,
288
+ sm_margin,
289
+ )
290
+ return softmax_d
291
+
292
+
293
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
294
+ def _flash_attn_backward_fake(
295
+ dout: torch.Tensor,
296
+ q: torch.Tensor,
297
+ k: torch.Tensor,
298
+ v: torch.Tensor,
299
+ out: torch.Tensor,
300
+ softmax_lse: torch.Tensor,
301
+ cu_seqlens_q: Optional[torch.Tensor] = None,
302
+ cu_seqlens_k: Optional[torch.Tensor] = None,
303
+ sequed_q: Optional[torch.Tensor] = None,
304
+ sequed_k: Optional[torch.Tensor] = None,
305
+ max_seqlen_q: Optional[int] = None,
306
+ max_seqlen_k: Optional[int] = None,
307
+ dq: Optional[torch.Tensor] = None,
308
+ dk: Optional[torch.Tensor] = None,
309
+ dv: Optional[torch.Tensor] = None,
310
+ softmax_scale: Optional[float] = None,
311
+ is_causal: bool = False,
312
+ window_size_left: int = -1,
313
+ window_size_right: int = -1,
314
+ softcap: float = 0.0,
315
+ deterministic: bool = False,
316
+ sm_margin: int = 0,
317
+ ) -> torch.Tensor:
318
+
319
+ is_varlen_q = cu_seqlens_q is not None
320
+ is_varlen_k = cu_seqlens_q is not None
321
+ is_varlen = is_varlen_q or is_varlen_k or sequed_q is not None or sequed_k is not None
322
+
323
+ if not is_varlen_q:
324
+ batch_size = q.size(0)
325
+ seqlen_q = q.size(1)
326
+ seqlen_k = k.size(1)
327
+ total_q = batch_size * q.size(1)
328
+ else:
329
+ batch_size = cu_seqlens_q.size(0) - 1
330
+ total_q = q.size(0)
331
+ seqlen_q = max_seqlen_q
332
+ seqlen_k = max_seqlen_k
333
+
334
+ if window_size_left >= seqlen_k - 1:
335
+ window_size_left = -1
336
+
337
+ if window_size_right >= seqlen_q - 1:
338
+ window_size_right = -1
339
+
340
+ if is_causal:
341
+ window_size_right = 0
342
+
343
+ is_causal = window_size_left < 0 and window_size_right == 0
344
+
345
+ head_size = q.size(-1)
346
+ head_size_v = v.size(-1)
347
+ head_size_rounded = round_up_headdim(max(head_size, head_size_v))
348
+
349
+ # Hopper gpus uses cuda compute capabilities 9.0
350
+ cap = torch.cuda.get_device_capability(q.device)
351
+ arch = cap[0] * 10 + cap[1]
352
+
353
+ is_local = (window_size_left >= 0 or window_size_right >= 0) and not is_causal
354
+
355
+ if head_size_rounded <= 64:
356
+ kBlockM_sm90 = 96 if (is_causal and softcap > 0.0) else 128
357
+ elif head_size_rounded <= 96:
358
+ kBlockM_sm90 = 64
359
+ elif head_size_rounded <= 128:
360
+ kBlockM_sm90 = 64 if (is_causal or is_local or softcap > 0.0) else 80
361
+ else:
362
+ kBlockM_sm90 = 64
363
+
364
+ kBlockM_sm80 = 128 if head_size_rounded <= 64 else 64
365
+ kBlockM_sm86 = 64 if head_size_rounded <= 192 else 32
366
+
367
+ if arch >= 90:
368
+ kBlockM = kBlockM_sm90
369
+ elif arch == 86 or arch == 89:
370
+ kBlockM = kBlockM_sm86
371
+ else:
372
+ kBlockM = kBlockM_sm80
373
+
374
+ num_heads = q.shape[-2]
375
+ seqlen_q_rounded = round_multiple(seqlen_q, kBlockM)
376
+
377
+ total_q_padded_rounded = round_multiple(total_q + batch_size * kBlockM, kBlockM)
378
+
379
+ dq = torch.empty_like(q) if dq is None else dq
380
+ dk = torch.empty_like(k) if dk is None else dk
381
+ dv = torch.empty_like(v) if dv is None else dv
382
+
383
+ if not is_varlen:
384
+ softmax_d = torch.empty((batch_size, num_heads, seqlen_q_rounded), dtype=torch.float32, device=q.device)
385
+ else:
386
+ softmax_d = torch.empty((num_heads, total_q_padded_rounded), dtype=torch.float32, device=q.device)
387
+
388
+ return softmax_d
389
+
390
+
391
+ def setup_context(ctx, inputs, output):
392
+ q, k, v = inputs[:3]
393
+ out, softmax_lse, _, _ = output
394
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
395
+ ctx.softmax_scale = inputs[-11]
396
+ ctx.causal = inputs[-10]
397
+ ctx.window_size = [inputs[-9], inputs[-8]]
398
+ ctx.attention_chunk = inputs[-7]
399
+ ctx.softcap = inputs[-6]
400
+ ctx.sm_margin = inputs[-1]
401
+
402
+
403
+ def _backward(ctx, dout, *grads):
404
+ q, k, v, out, softmax_lse = ctx.saved_tensors
405
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
406
+ _flash_attn_backward(
407
+ dout,
408
+ q,
409
+ k,
410
+ v,
411
+ out,
412
+ softmax_lse,
413
+ None, None, # cu_seqlens_q, cu_seqlens_k,
414
+ None, None, # sequed_q, sequed_k,
415
+ None, None, # max_seqlen_q, max_seqlen_k,
416
+ dq,
417
+ dk,
418
+ dv,
419
+ ctx.softmax_scale,
420
+ ctx.causal,
421
+ ctx.window_size[0],
422
+ ctx.window_size[1],
423
+ ctx.softcap,
424
+ False, # deterministic
425
+ ctx.sm_margin,
426
+ )
427
+ return dq, dk, dv, *((None,) * 21)
428
+
429
+
430
+ _flash_attn_forward.register_autograd(_backward, setup_context=setup_context)
431
+
432
+
433
+
434
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
435
+ @staticmethod
436
+ def forward(
437
+ ctx,
438
+ qkv,
439
+ softmax_scale,
440
+ causal,
441
+ q_descale=None, k_descale=None, v_descale=None,
442
+ window_size=(-1, -1),
443
+ attention_chunk=0,
444
+ softcap=0.0,
445
+ deterministic=False,
446
+ num_heads_q=None,
447
+ sm_margin=0,
448
+ return_softmax=False,
449
+ ):
450
+ if softmax_scale is None:
451
+ softmax_scale = qkv.shape[-1] ** (-0.5)
452
+ if qkv.dim() == 5:
453
+ assert qkv.shape[-3] == 3
454
+ q, k, v = qkv.unbind(dim=-3)
455
+ else:
456
+ assert qkv.dim() == 4
457
+ assert num_heads_q is not None
458
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
459
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
460
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
461
+ out, softmax_lse, *rest = _flash_attn_forward(
462
+ q,
463
+ k,
464
+ v,
465
+ None, None, # k_new, v_new
466
+ None, # qv
467
+ None, # out
468
+ None, None, None, # cu_seqlens_q/k/k_new
469
+ None, None, # seqused_q/k
470
+ None, None, # max_seqlen_q/k
471
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
472
+ None, None, None, # rotary_cos/sin, seqlens_rotary
473
+ q_descale, k_descale, v_descale,
474
+ softmax_scale,
475
+ causal=causal,
476
+ window_size_left=window_size[0],
477
+ window_size_right=window_size[1],
478
+ attention_chunk=attention_chunk,
479
+ softcap=softcap,
480
+ sm_margin=sm_margin,
481
+ )
482
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
483
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
484
+ ctx.softmax_scale = softmax_scale
485
+ ctx.causal = causal
486
+ ctx.window_size = window_size
487
+ ctx.attention_chunk = attention_chunk
488
+ ctx.softcap = softcap
489
+ ctx.deterministic = deterministic
490
+ ctx.ndim = qkv.dim()
491
+ ctx.sm_margin = sm_margin
492
+ return (out, softmax_lse) if return_softmax else out
493
+
494
+ @staticmethod
495
+ def backward(ctx, dout, *args):
496
+ q, k, v, out, softmax_lse = ctx.saved_tensors
497
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
498
+ if ctx.ndim == 5:
499
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
500
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
501
+ dq, dk, dv = dqkv.unbind(dim=-3)
502
+ else:
503
+ num_heads_q = q.shape[2]
504
+ num_heads_k = k.shape[2]
505
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
506
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
507
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
508
+ _flash_attn_backward(
509
+ dout,
510
+ q,
511
+ k,
512
+ v,
513
+ out,
514
+ softmax_lse,
515
+ None, None, # cu_seqlens_q, cu_seqlens_k,
516
+ None, None, # sequed_q, sequed_k,
517
+ None, None, # max_seqlen_q, max_seqlen_k,
518
+ dq,
519
+ dk,
520
+ dv,
521
+ ctx.softmax_scale,
522
+ ctx.causal,
523
+ ctx.window_size[0],
524
+ ctx.window_size[1],
525
+ ctx.softcap,
526
+ ctx.deterministic,
527
+ ctx.sm_margin,
528
+ )
529
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
530
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None, None
531
+
532
+
533
+ class FlashAttnFunc(torch.autograd.Function):
534
+
535
+ @staticmethod
536
+ def forward(
537
+ ctx,
538
+ q,
539
+ k,
540
+ v,
541
+ softmax_scale,
542
+ causal,
543
+ qv=None,
544
+ q_descale=None, k_descale=None, v_descale=None,
545
+ window_size=(-1, -1),
546
+ attention_chunk=0,
547
+ softcap=0.0,
548
+ num_splits=1,
549
+ pack_gqa=None,
550
+ deterministic=False,
551
+ sm_margin=0,
552
+ return_softmax=False,
553
+ ):
554
+ if softmax_scale is None:
555
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
556
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
557
+ out, softmax_lse, *rest = _flash_attn_forward(
558
+ q,
559
+ k,
560
+ v,
561
+ None, None, # k_new, v_new
562
+ qv, # qv
563
+ None, # out
564
+ None, None, None, # cu_seqlens_q/k/k_new
565
+ None, None, # seqused_q/k
566
+ None, None, # max_seqlen_q/k
567
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
568
+ None, None, None, # rotary_cos/sin, seqlens_rotary
569
+ q_descale, k_descale, v_descale,
570
+ softmax_scale,
571
+ causal=causal,
572
+ window_size_left=window_size[0],
573
+ window_size_right=window_size[1],
574
+ attention_chunk=attention_chunk,
575
+ softcap=softcap,
576
+ num_splits=num_splits,
577
+ pack_gqa=pack_gqa,
578
+ sm_margin=sm_margin,
579
+ )
580
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
581
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
582
+ ctx.softmax_scale = softmax_scale
583
+ ctx.causal = causal
584
+ ctx.window_size = window_size
585
+ ctx.attention_chunk = attention_chunk
586
+ ctx.softcap = softcap
587
+ ctx.deterministic = deterministic
588
+ ctx.sm_margin = sm_margin
589
+ return (out, softmax_lse) if return_softmax else out
590
+
591
+ @staticmethod
592
+ def backward(ctx, dout, *args):
593
+ q, k, v, out, softmax_lse = ctx.saved_tensors
594
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
595
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
596
+ _flash_attn_backward(
597
+ dout,
598
+ q,
599
+ k,
600
+ v,
601
+ out,
602
+ softmax_lse,
603
+ None, None, # cu_seqlens_q, cu_seqlens_k,
604
+ None, None, # sequed_q, sequed_k,
605
+ None, None, # max_seqlen_q, max_seqlen_k,
606
+ dq,
607
+ dk,
608
+ dv,
609
+ ctx.softmax_scale,
610
+ ctx.causal,
611
+ ctx.window_size[0],
612
+ ctx.window_size[1],
613
+ ctx.softcap,
614
+ ctx.deterministic,
615
+ ctx.sm_margin,
616
+ )
617
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
618
+ dk = dk[..., : k.shape[-1]]
619
+ dv = dv[..., : v.shape[-1]]
620
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
621
+
622
+
623
+ class FlashAttnVarlenFunc(torch.autograd.Function):
624
+
625
+ @staticmethod
626
+ def forward(
627
+ ctx,
628
+ q,
629
+ k,
630
+ v,
631
+ cu_seqlens_q,
632
+ cu_seqlens_k,
633
+ seqused_q,
634
+ seqused_k,
635
+ max_seqlen_q,
636
+ max_seqlen_k,
637
+ softmax_scale,
638
+ causal,
639
+ qv=None,
640
+ q_descale=None, k_descale=None, v_descale=None,
641
+ window_size=(-1, -1),
642
+ attention_chunk=0,
643
+ softcap=0.0,
644
+ num_splits=1,
645
+ pack_gqa=None,
646
+ deterministic=False,
647
+ sm_margin=0,
648
+ return_softmax=False,
649
+ ):
650
+ if softmax_scale is None:
651
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
652
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
653
+ out, softmax_lse, *rest = _flash_attn_forward(
654
+ q,
655
+ k,
656
+ v,
657
+ None, None, # k_new, v_new
658
+ qv, # qv
659
+ None, # out
660
+ cu_seqlens_q,
661
+ cu_seqlens_k,
662
+ None, # cu_seqlens_k_new
663
+ seqused_q,
664
+ seqused_k,
665
+ max_seqlen_q,
666
+ max_seqlen_k,
667
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
668
+ None, None, None, # rotary_cos/sin, seqlens_rotary
669
+ q_descale, k_descale, v_descale,
670
+ softmax_scale,
671
+ causal=causal,
672
+ window_size_left=window_size[0],
673
+ window_size_right=window_size[1],
674
+ attention_chunk=attention_chunk,
675
+ softcap=softcap,
676
+ num_splits=num_splits,
677
+ pack_gqa=pack_gqa,
678
+ sm_margin=sm_margin,
679
+ )
680
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
681
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
682
+ ctx.max_seqlen_q = max_seqlen_q
683
+ ctx.max_seqlen_k = max_seqlen_k
684
+ ctx.softmax_scale = softmax_scale
685
+ ctx.causal = causal
686
+ ctx.window_size = window_size
687
+ ctx.attention_chunk = attention_chunk
688
+ ctx.softcap = softcap
689
+ ctx.deterministic = deterministic
690
+ ctx.sm_margin = sm_margin
691
+ return (out, softmax_lse) if return_softmax else out
692
+
693
+ @staticmethod
694
+ def backward(ctx, dout, *args):
695
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
696
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
697
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
698
+ _flash_attn_backward(
699
+ dout,
700
+ q,
701
+ k,
702
+ v,
703
+ out,
704
+ softmax_lse,
705
+ cu_seqlens_q,
706
+ cu_seqlens_k,
707
+ seqused_q,
708
+ seqused_k,
709
+ ctx.max_seqlen_q,
710
+ ctx.max_seqlen_k,
711
+ dq,
712
+ dk,
713
+ dv,
714
+ ctx.softmax_scale,
715
+ ctx.causal,
716
+ ctx.window_size[0],
717
+ ctx.window_size[1],
718
+ ctx.softcap,
719
+ ctx.deterministic,
720
+ ctx.sm_margin,
721
+ )
722
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
723
+ dk = dk[..., : k.shape[-1]]
724
+ dv = dv[..., : v.shape[-1]]
725
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
726
+
727
+
728
+ def flash_attn_qkvpacked_func(
729
+ qkv,
730
+ softmax_scale=None,
731
+ causal=False,
732
+ q_descale=None, k_descale=None, v_descale=None,
733
+ window_size=(-1, -1),
734
+ attention_chunk=0,
735
+ softcap=0.0,
736
+ deterministic=False,
737
+ num_heads_q=None,
738
+ sm_margin=0,
739
+ return_attn_probs=False,
740
+ ):
741
+ """dropout_p should be set to 0.0 during evaluation
742
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
743
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
744
+ of the gradients of Q, K, V.
745
+ For multi-query and grouped-query attention (MQA/GQA), please see
746
+ flash_attn_kvpacked_func and flash_attn_func.
747
+
748
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
749
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
750
+
751
+ Arguments:
752
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
753
+ dropout_p: float. Dropout probability.
754
+ softmax_scale: float. The scaling of QK^T before applying softmax.
755
+ Default to 1 / sqrt(headdim).
756
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
757
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
758
+ softcap: float. Anything > 0 activates softcapping attention.
759
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
760
+ the attention score of query i and key j.
761
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
762
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
763
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
764
+ testing only. The returned probabilities are not guaranteed to be correct
765
+ (they might not have the right scaling).
766
+ Return:
767
+ out: (batch_size, seqlen, nheads, headdim).
768
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
769
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
770
+ normalization factor).
771
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
772
+ The output of softmax (possibly with different scaling). It also encodes the dropout
773
+ pattern (negative means that location was dropped, nonnegative means it was kept).
774
+ """
775
+ return FlashAttnQKVPackedFunc.apply(
776
+ qkv,
777
+ softmax_scale,
778
+ causal,
779
+ q_descale, k_descale, v_descale,
780
+ window_size,
781
+ attention_chunk,
782
+ softcap,
783
+ deterministic,
784
+ num_heads_q,
785
+ sm_margin,
786
+ return_attn_probs,
787
+ )
788
+
789
+
790
+ def flash_attn_func(
791
+ q,
792
+ k,
793
+ v,
794
+ softmax_scale=None,
795
+ causal=False,
796
+ qv=None,
797
+ q_descale=None, k_descale=None, v_descale=None,
798
+ window_size=(-1, -1),
799
+ attention_chunk=0,
800
+ softcap=0.0,
801
+ num_splits=1,
802
+ pack_gqa=None,
803
+ deterministic=False,
804
+ sm_margin=0,
805
+ return_attn_probs=False,
806
+ ):
807
+ """dropout_p should be set to 0.0 during evaluation
808
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
809
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
810
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
811
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
812
+
813
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
814
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
815
+ 1 1 1 1 0
816
+ 1 1 1 1 1
817
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
818
+ 0 0
819
+ 0 0
820
+ 0 0
821
+ 1 0
822
+ 1 1
823
+ If the row of the mask is all zero, the output will be zero.
824
+
825
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
826
+ will only attend to keys between
827
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
828
+
829
+ Arguments:
830
+ q: (batch_size, seqlen, nheads, headdim)
831
+ k: (batch_size, seqlen, nheads_k, headdim)
832
+ v: (batch_size, seqlen, nheads_k, headdim)
833
+ dropout_p: float. Dropout probability.
834
+ softmax_scale: float. The scaling of QK^T before applying softmax.
835
+ Default to 1 / sqrt(headdim).
836
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
837
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
838
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
839
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
840
+ is added to the attention score of query i and key j.
841
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
842
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
843
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
844
+ testing only. The returned probabilities are not guaranteed to be correct
845
+ (they might not have the right scaling).
846
+ Return:
847
+ out: (batch_size, seqlen, nheads, headdim).
848
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
849
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
850
+ normalization factor).
851
+ """
852
+ return FlashAttnFunc.apply(
853
+ q,
854
+ k,
855
+ v,
856
+ softmax_scale,
857
+ causal,
858
+ qv,
859
+ q_descale, k_descale, v_descale,
860
+ window_size,
861
+ attention_chunk,
862
+ softcap,
863
+ num_splits,
864
+ pack_gqa,
865
+ deterministic,
866
+ sm_margin,
867
+ return_attn_probs,
868
+ )
869
+
870
+
871
+ def flash_attn_varlen_func(
872
+ q,
873
+ k,
874
+ v,
875
+ cu_seqlens_q,
876
+ cu_seqlens_k,
877
+ max_seqlen_q,
878
+ max_seqlen_k,
879
+ seqused_q=None,
880
+ seqused_k=None,
881
+ softmax_scale=None,
882
+ causal=False,
883
+ qv=None,
884
+ q_descale=None, k_descale=None, v_descale=None,
885
+ window_size=(-1, -1),
886
+ attention_chunk=0,
887
+ softcap=0.0,
888
+ num_splits=1,
889
+ pack_gqa=None,
890
+ deterministic=False,
891
+ sm_margin=0,
892
+ return_attn_probs=False,
893
+ ):
894
+ return FlashAttnVarlenFunc.apply(
895
+ q,
896
+ k,
897
+ v,
898
+ cu_seqlens_q,
899
+ cu_seqlens_k,
900
+ seqused_q,
901
+ seqused_k,
902
+ max_seqlen_q,
903
+ max_seqlen_k,
904
+ softmax_scale,
905
+ causal,
906
+ qv,
907
+ q_descale, k_descale, v_descale,
908
+ window_size,
909
+ attention_chunk,
910
+ softcap,
911
+ num_splits,
912
+ pack_gqa,
913
+ deterministic,
914
+ sm_margin,
915
+ return_attn_probs,
916
+ )
917
+
918
+
919
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
920
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
921
+
922
+
923
+ def flash_attn_with_kvcache(
924
+ q,
925
+ k_cache,
926
+ v_cache,
927
+ k=None,
928
+ v=None,
929
+ qv=None,
930
+ rotary_cos=None,
931
+ rotary_sin=None,
932
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
933
+ cache_batch_idx: Optional[torch.Tensor] = None,
934
+ cache_leftpad: Optional[torch.Tensor] = None,
935
+ page_table: Optional[torch.Tensor] = None,
936
+ cu_seqlens_q: Optional[torch.Tensor] = None,
937
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
938
+ max_seqlen_q: Optional[int] = None,
939
+ rotary_seqlens: Optional[torch.Tensor] = None,
940
+ q_descale: Optional[torch.Tensor] = None,
941
+ k_descale: Optional[torch.Tensor] = None,
942
+ v_descale: Optional[torch.Tensor] = None,
943
+ softmax_scale=None,
944
+ causal=False,
945
+ window_size=(-1, -1), # -1 means infinite context window
946
+ attention_chunk=0,
947
+ softcap=0.0, # 0.0 means deactivated
948
+ rotary_interleaved=True,
949
+ scheduler_metadata=None,
950
+ num_splits=0, # Can be tuned for speed
951
+ pack_gqa=None, # Can be tuned for speed
952
+ sm_margin=0, # Can be tuned if some SMs are used for communication
953
+ return_softmax_lse=False,
954
+ ):
955
+ """
956
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
957
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
958
+ the previous step, and update them with the new keys/values from the current step, and do
959
+ attention with the updated cache, all in 1 kernel.
960
+
961
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
962
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
963
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
964
+
965
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
966
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
967
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
968
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
969
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
970
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
971
+
972
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
973
+
974
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
975
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
976
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
977
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
978
+
979
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
980
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
981
+ 1 1 1 1 0
982
+ 1 1 1 1 1
983
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
984
+ 0 0
985
+ 0 0
986
+ 0 0
987
+ 1 0
988
+ 1 1
989
+ If the row of the mask is all zero, the output will be zero.
990
+
991
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
992
+ will only attend to keys between
993
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
994
+
995
+ Note: Does not support backward pass.
996
+
997
+ Arguments:
998
+ q: (batch_size, seqlen, nheads, headdim)
999
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
1000
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
1001
+ page_block_size can be arbitrary (e.g, 1, 2, 3, 64, etc.).
1002
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
1003
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
1004
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
1005
+ k with k_cache, starting at the indices specified by cache_seqlens.
1006
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
1007
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
1008
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
1009
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
1010
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
1011
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
1012
+ KV cache.
1013
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
1014
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
1015
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
1016
+ might come from any of the duplicate indices.
1017
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
1018
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
1019
+ softmax_scale: float. The scaling of QK^T before applying softmax.
1020
+ Default to 1 / sqrt(headdim).
1021
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
1022
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
1023
+ softcap: float. Anything > 0 activates softcapping attention.
1024
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
1025
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
1026
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
1027
+ (i.e. GPT-NeoX style).
1028
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
1029
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
1030
+ to automatically determine the number of splits.
1031
+ Don't change this unless you know what you are doing.
1032
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
1033
+
1034
+ Return:
1035
+ out: (batch_size, seqlen, nheads, headdim).
1036
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
1037
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
1038
+ normalization factor).
1039
+ """
1040
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
1041
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
1042
+ if softmax_scale is None:
1043
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
1044
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
1045
+ cache_seqlens = torch.full(
1046
+ (q.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
1047
+ )
1048
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1049
+ out, softmax_lse, *rest = _flash_attn_forward(
1050
+ q,
1051
+ k_cache,
1052
+ v_cache,
1053
+ k,
1054
+ v,
1055
+ qv,
1056
+ None, # out
1057
+ cu_seqlens_q,
1058
+ None, # cu_seqlens_k
1059
+ cu_seqlens_k_new,
1060
+ None, # seqused_q
1061
+ cache_seqlens,
1062
+ max_seqlen_q,
1063
+ None, # max_seqlen_k
1064
+ page_table,
1065
+ cache_batch_idx,
1066
+ cache_leftpad,
1067
+ rotary_cos,
1068
+ rotary_sin,
1069
+ rotary_seqlens,
1070
+ q_descale, k_descale, v_descale,
1071
+ softmax_scale,
1072
+ causal=causal,
1073
+ window_size_left=window_size[0],
1074
+ window_size_right=window_size[1],
1075
+ attention_chunk=attention_chunk,
1076
+ softcap=softcap,
1077
+ rotary_interleaved=rotary_interleaved,
1078
+ scheduler_metadata=scheduler_metadata,
1079
+ num_splits=num_splits,
1080
+ pack_gqa=pack_gqa,
1081
+ sm_margin=sm_margin,
1082
+ )
1083
+ # return (out, softmax_lse) if return_softmax_lse else out
1084
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
1085
+
1086
+
1087
+ def get_scheduler_metadata(
1088
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
1089
+ cache_seqlens: torch.Tensor,
1090
+ qkv_dtype=torch.bfloat16,
1091
+ headdim_v=None,
1092
+ cu_seqlens_q: Optional[torch.Tensor] = None,
1093
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
1094
+ cache_leftpad: Optional[torch.Tensor] = None,
1095
+ page_size: Optional[int] = None,
1096
+ max_seqlen_k_new=0,
1097
+ causal=False,
1098
+ window_size=(-1, -1), # -1 means infinite context window
1099
+ attention_chunk=0,
1100
+ has_softcap=False,
1101
+ num_splits=0, # Can be tuned for speed
1102
+ pack_gqa=None, # Can be tuned for speed
1103
+ sm_margin=0, # Can be tuned if some SMs are used for communication
1104
+ ):
1105
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1106
+ if headdim_v is None:
1107
+ headdim_v = headdim
1108
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
1109
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
1110
+ qkv_dtype,
1111
+ cache_seqlens,
1112
+ cu_seqlens_q,
1113
+ None, # cu_seqlens_k
1114
+ cu_seqlens_k_new,
1115
+ None, # seqused_q
1116
+ cache_leftpad,
1117
+ page_size,
1118
+ max_seqlen_k_new,
1119
+ causal,
1120
+ window_size[0], window_size[1],
1121
+ attention_chunk,
1122
+ has_softcap,
1123
+ num_splits,
1124
+ pack_gqa,
1125
+ sm_margin,
1126
+ )
1127
+ return scheduler_metadata
build/torch211-cxx11-cu128-x86_64-linux/metadata.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "license": "BSD-3-Clause",
4
+ "python-depends": [],
5
+ "backend": {
6
+ "type": "cuda",
7
+ "archs": [
8
+ "8.0",
9
+ "9.0a"
10
+ ]
11
+ }
12
+ }
build/torch211-cxx11-cu130-x86_64-linux/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch211-cxx11-cu130-x86_64-linux/_flash_attn3_cuda_e1d5be2.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd55c8f7b848dce30414fd77aee49d9167b6d0a8f73e6832c47de618ac58b24f
3
+ size 823692344
build/torch211-cxx11-cu130-x86_64-linux/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_cuda_e1d5be2
3
+ ops = torch.ops._flash_attn3_cuda_e1d5be2
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_cuda_e1d5be2::{op_name}"
build/torch211-cxx11-cu130-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import importlib.util
3
+ import sys
4
+ from pathlib import Path
5
+ from types import ModuleType
6
+
7
+
8
+ def _import_from_path(file_path: Path) -> ModuleType:
9
+ # We cannot use the module name as-is, after adding it to `sys.modules`,
10
+ # it would also be used for other imports. So, we make a module name that
11
+ # depends on the path for it to be unique using the hex-encoded hash of
12
+ # the path.
13
+ path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
+ module_name = path_hash
15
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
16
+ if spec is None:
17
+ raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
+ module = importlib.util.module_from_spec(spec)
19
+ if module is None:
20
+ raise ImportError(f"Cannot load module {module_name} from spec")
21
+ sys.modules[module_name] = module
22
+ spec.loader.exec_module(module) # type: ignore
23
+ return module
24
+
25
+
26
+ globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
build/torch211-cxx11-cu130-x86_64-linux/flash_attn_config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Auto-generated by flash attention 3 setup.py
2
+ CONFIG = {'build_flags': {'FLASHATTENTION_DISABLE_BACKWARD': False, 'FLASHATTENTION_DISABLE_SPLIT': False, 'FLASHATTENTION_DISABLE_PAGEDKV': False, 'FLASHATTENTION_DISABLE_APPENDKV': False, 'FLASHATTENTION_DISABLE_LOCAL': False, 'FLASHATTENTION_DISABLE_SOFTCAP': False, 'FLASHATTENTION_DISABLE_PACKGQA': False, 'FLASHATTENTION_DISABLE_FP16': False, 'FLASHATTENTION_DISABLE_FP8': False, 'FLASHATTENTION_DISABLE_VARLEN': False, 'FLASHATTENTION_DISABLE_CLUSTER': False, 'FLASHATTENTION_DISABLE_HDIM64': False, 'FLASHATTENTION_DISABLE_HDIM96': False, 'FLASHATTENTION_DISABLE_HDIM128': False, 'FLASHATTENTION_DISABLE_HDIM192': False, 'FLASHATTENTION_DISABLE_HDIM256': False, 'FLASHATTENTION_DISABLE_SM8x': False, 'FLASHATTENTION_ENABLE_VCOLMAJOR': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF64': False, 'FLASH_ATTENTION_DISABLE_HDIMDIFF192': False}}
3
+
4
+ def show():
5
+ from pprint import pprint
6
+ pprint(CONFIG)
7
+
build/torch211-cxx11-cu130-x86_64-linux/flash_attn_interface.py ADDED
@@ -0,0 +1,1127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union, List, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+ from ._ops import add_op_namespace_prefix
10
+
11
+ def maybe_contiguous(x):
12
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
13
+
14
+
15
+ def round_multiple(x, m):
16
+ return (x + m - 1) // m * m
17
+
18
+
19
+ def round_up_headdim(head_size: int) -> int:
20
+ from .flash_attn_config import CONFIG
21
+
22
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM64"]:
23
+ if head_size <= 64:
24
+ return 64
25
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM96"]:
26
+ if head_size <= 96:
27
+ return 96
28
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM128"]:
29
+ if head_size <= 128:
30
+ return 128
31
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM192"]:
32
+ if head_size <= 192:
33
+ return 192
34
+ if not CONFIG["build_flags"]["FLASHATTENTION_DISABLE_HDIM256"]:
35
+ if head_size <= 256:
36
+ return 256
37
+ return 256
38
+
39
+
40
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_forward"), mutates_args=(), device_types="cuda")
41
+ def _flash_attn_forward(
42
+ q: torch.Tensor,
43
+ k: torch.Tensor,
44
+ v: torch.Tensor,
45
+ k_new: Optional[torch.Tensor] = None,
46
+ v_new: Optional[torch.Tensor] = None,
47
+ qv: Optional[torch.Tensor] = None,
48
+ out_: Optional[torch.Tensor] = None,
49
+ cu_seqlens_q: Optional[torch.Tensor] = None,
50
+ cu_seqlens_k: Optional[torch.Tensor] = None,
51
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
52
+ seqused_q: Optional[torch.Tensor] = None,
53
+ seqused_k: Optional[torch.Tensor] = None,
54
+ max_seqlen_q: Optional[int] = None,
55
+ max_seqlen_k: Optional[int] = None,
56
+ page_table: Optional[torch.Tensor] = None,
57
+ kv_batch_idx: Optional[torch.Tensor] = None,
58
+ leftpad_k: Optional[torch.Tensor] = None,
59
+ rotary_cos: Optional[torch.Tensor] = None,
60
+ rotary_sin: Optional[torch.Tensor] = None,
61
+ seqlens_rotary: Optional[torch.Tensor] = None,
62
+ q_descale: Optional[torch.Tensor] = None,
63
+ k_descale: Optional[torch.Tensor] = None,
64
+ v_descale: Optional[torch.Tensor] = None,
65
+ softmax_scale: Optional[float] = None,
66
+ causal: bool = False,
67
+ window_size_left: int = -1,
68
+ window_size_right: int = -1,
69
+ attention_chunk: int = 0,
70
+ softcap: float = 0.0,
71
+ rotary_interleaved: bool = True,
72
+ scheduler_metadata: Optional[torch.Tensor] = None,
73
+ num_splits: int = 1,
74
+ pack_gqa: Optional[bool] = None,
75
+ sm_margin: int = 0,
76
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
77
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
78
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
79
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
80
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
81
+ ]
82
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
83
+ page_table, kv_batch_idx, leftpad_k = [
84
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
85
+ ]
86
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
87
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
88
+ out, softmax_lse, out_accum, softmax_lse_accum = flash_attn_3_cuda.fwd(
89
+ q,
90
+ k,
91
+ v,
92
+ k_new,
93
+ v_new,
94
+ qv,
95
+ out_,
96
+ cu_seqlens_q,
97
+ cu_seqlens_k,
98
+ cu_seqlens_k_new,
99
+ seqused_q,
100
+ seqused_k,
101
+ max_seqlen_q,
102
+ max_seqlen_k,
103
+ page_table,
104
+ kv_batch_idx,
105
+ leftpad_k,
106
+ rotary_cos,
107
+ rotary_sin,
108
+ seqlens_rotary,
109
+ q_descale,
110
+ k_descale,
111
+ v_descale,
112
+ softmax_scale,
113
+ causal,
114
+ window_size_left,
115
+ window_size_right,
116
+ attention_chunk,
117
+ softcap,
118
+ rotary_interleaved,
119
+ scheduler_metadata,
120
+ num_splits,
121
+ pack_gqa,
122
+ sm_margin,
123
+ )
124
+
125
+ if out_accum is None:
126
+ out_accum = torch.tensor([], device=out.device)
127
+
128
+ if softmax_lse_accum is None:
129
+ softmax_lse_accum = torch.tensor([], device=out.device)
130
+
131
+ return out, softmax_lse, out_accum, softmax_lse_accum
132
+
133
+
134
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_forward"))
135
+ def _flash_attn_forward_fake(
136
+ q: torch.Tensor,
137
+ k: torch.Tensor,
138
+ v: torch.Tensor,
139
+ k_new: Optional[torch.Tensor] = None,
140
+ v_new: Optional[torch.Tensor] = None,
141
+ qv: Optional[torch.Tensor] = None,
142
+ out_: Optional[torch.Tensor] = None,
143
+ cu_seqlens_q: Optional[torch.Tensor] = None,
144
+ cu_seqlens_k: Optional[torch.Tensor] = None,
145
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
146
+ seqused_q: Optional[torch.Tensor] = None,
147
+ seqused_k: Optional[torch.Tensor] = None,
148
+ max_seqlen_q: Optional[int] = None,
149
+ max_seqlen_k: Optional[int] = None,
150
+ page_table: Optional[torch.Tensor] = None,
151
+ kv_batch_idx: Optional[torch.Tensor] = None,
152
+ leftpad_k: Optional[torch.Tensor] = None,
153
+ rotary_cos: Optional[torch.Tensor] = None,
154
+ rotary_sin: Optional[torch.Tensor] = None,
155
+ seqlens_rotary: Optional[torch.Tensor] = None,
156
+ q_descale: Optional[torch.Tensor] = None,
157
+ k_descale: Optional[torch.Tensor] = None,
158
+ v_descale: Optional[torch.Tensor] = None,
159
+ softmax_scale: Optional[float] = None,
160
+ causal: bool = False,
161
+ window_size_left: int = -1,
162
+ window_size_right: int = -1,
163
+ attention_chunk: int = 0,
164
+ softcap: float = 0.0,
165
+ rotary_interleaved: bool = True,
166
+ scheduler_metadata: Optional[torch.Tensor] = None,
167
+ num_splits: int = 1,
168
+ pack_gqa: Optional[bool] = None,
169
+ sm_margin: int = 0,
170
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
171
+ """
172
+ Symbolic fake implementation of flash attention forward.
173
+ Returns tensors with the correct shapes and dtypes without actual computation.
174
+ """
175
+
176
+ # Determine if we're in varlen mode
177
+ is_varlen_q = cu_seqlens_q is not None
178
+
179
+ # Get dimensions from query tensor
180
+ if is_varlen_q:
181
+ # varlen mode: q is (total_q, num_heads, head_size)
182
+ total_q, num_heads, head_size = q.shape
183
+ batch_size = cu_seqlens_q.shape[0] - 1
184
+
185
+ if max_seqlen_q is None:
186
+ raise ValueError("max_seqlen_q must be provided if cu_seqlens_q is provided")
187
+ seqlen_q = max_seqlen_q
188
+ else:
189
+ # batch mode: q is (batch_size, seqlen_q, num_heads, head_size)
190
+ batch_size, seqlen_q, num_heads, head_size = q.shape
191
+ total_q = batch_size * q.shape[1]
192
+ # Get value head dimension
193
+ head_size_v = v.shape[-1]
194
+
195
+ # Determine output dtype (FP8 inputs produce BF16 outputs)
196
+ q_type = q.dtype
197
+ if q_type == torch.float8_e4m3fn:
198
+ out_dtype = torch.bfloat16
199
+ else:
200
+ out_dtype = q_type
201
+
202
+ # Create output tensor
203
+ if out_ is not None:
204
+ # If out_ is provided, _flash_attn_forward becomes non-functional
205
+ raise TypeError("Tracing (torch.compile/torch.export) with pre-allocated output tensor is not supported.")
206
+
207
+ if is_varlen_q:
208
+ out = torch.empty((total_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
209
+ else:
210
+ out = torch.empty((batch_size, seqlen_q, num_heads, head_size_v), dtype=out_dtype, device=q.device)
211
+
212
+ # Create softmax_lse tensor
213
+ if is_varlen_q:
214
+ softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device)
215
+ else:
216
+ softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
217
+
218
+ # TODO(guilhermeleobas): Implement "get_num_splits"
219
+ # There's an heuristic to compute num_splits when "num_splits <= 0"
220
+ # assert that num_splits is > 0 for now
221
+ if num_splits <= 0:
222
+ raise ValueError(f"tracing (torch.compile/torch.export) with num_splits <= 0 not supported. Got {num_splits=}")
223
+
224
+ if num_splits > 1:
225
+ if is_varlen_q:
226
+ out_accum = torch.empty((num_splits, num_heads, total_q, head_size_v), dtype=torch.float32, device=q.device)
227
+ softmax_lse_accum = torch.empty((num_splits, num_heads, total_q), dtype=torch.float32, device=q.device)
228
+ else:
229
+ out_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q, head_size_v), dtype=torch.float32, device=q.device)
230
+ softmax_lse_accum = torch.empty((num_splits, batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device)
231
+ else:
232
+ # Tensors are not set when num_splits < 1
233
+ out_accum = torch.tensor([], device=out.device)
234
+ softmax_lse_accum = torch.tensor([], device=out.device)
235
+
236
+ return out, softmax_lse, out_accum, softmax_lse_accum
237
+
238
+
239
+ @torch.library.custom_op(add_op_namespace_prefix("_flash_attn_backward"), mutates_args=("dq", "dk", "dv"), device_types="cuda")
240
+ def _flash_attn_backward(
241
+ dout: torch.Tensor,
242
+ q: torch.Tensor,
243
+ k: torch.Tensor,
244
+ v: torch.Tensor,
245
+ out: torch.Tensor,
246
+ softmax_lse: torch.Tensor,
247
+ cu_seqlens_q: Optional[torch.Tensor] = None,
248
+ cu_seqlens_k: Optional[torch.Tensor] = None,
249
+ sequed_q: Optional[torch.Tensor] = None,
250
+ sequed_k: Optional[torch.Tensor] = None,
251
+ max_seqlen_q: Optional[int] = None,
252
+ max_seqlen_k: Optional[int] = None,
253
+ dq: Optional[torch.Tensor] = None,
254
+ dk: Optional[torch.Tensor] = None,
255
+ dv: Optional[torch.Tensor] = None,
256
+ softmax_scale: Optional[float] = None,
257
+ is_causal: bool = False,
258
+ window_size_left: int = -1,
259
+ window_size_right: int = -1,
260
+ softcap: float = 0.0,
261
+ deterministic: bool = False,
262
+ sm_margin: int = 0,
263
+ ) -> torch.Tensor:
264
+ # dq, dk, dv are allocated by us so they should already be contiguous
265
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
266
+ softmax_d, *rest = flash_attn_3_cuda.bwd(
267
+ dout,
268
+ q,
269
+ k,
270
+ v,
271
+ out,
272
+ softmax_lse,
273
+ dq,
274
+ dk,
275
+ dv,
276
+ cu_seqlens_q,
277
+ cu_seqlens_k,
278
+ sequed_q,
279
+ sequed_k,
280
+ max_seqlen_q,
281
+ max_seqlen_k,
282
+ softmax_scale,
283
+ is_causal,
284
+ window_size_left,
285
+ window_size_right,
286
+ softcap,
287
+ deterministic,
288
+ sm_margin,
289
+ )
290
+ return softmax_d
291
+
292
+
293
+ @torch.library.register_fake(add_op_namespace_prefix("_flash_attn_backward"))
294
+ def _flash_attn_backward_fake(
295
+ dout: torch.Tensor,
296
+ q: torch.Tensor,
297
+ k: torch.Tensor,
298
+ v: torch.Tensor,
299
+ out: torch.Tensor,
300
+ softmax_lse: torch.Tensor,
301
+ cu_seqlens_q: Optional[torch.Tensor] = None,
302
+ cu_seqlens_k: Optional[torch.Tensor] = None,
303
+ sequed_q: Optional[torch.Tensor] = None,
304
+ sequed_k: Optional[torch.Tensor] = None,
305
+ max_seqlen_q: Optional[int] = None,
306
+ max_seqlen_k: Optional[int] = None,
307
+ dq: Optional[torch.Tensor] = None,
308
+ dk: Optional[torch.Tensor] = None,
309
+ dv: Optional[torch.Tensor] = None,
310
+ softmax_scale: Optional[float] = None,
311
+ is_causal: bool = False,
312
+ window_size_left: int = -1,
313
+ window_size_right: int = -1,
314
+ softcap: float = 0.0,
315
+ deterministic: bool = False,
316
+ sm_margin: int = 0,
317
+ ) -> torch.Tensor:
318
+
319
+ is_varlen_q = cu_seqlens_q is not None
320
+ is_varlen_k = cu_seqlens_q is not None
321
+ is_varlen = is_varlen_q or is_varlen_k or sequed_q is not None or sequed_k is not None
322
+
323
+ if not is_varlen_q:
324
+ batch_size = q.size(0)
325
+ seqlen_q = q.size(1)
326
+ seqlen_k = k.size(1)
327
+ total_q = batch_size * q.size(1)
328
+ else:
329
+ batch_size = cu_seqlens_q.size(0) - 1
330
+ total_q = q.size(0)
331
+ seqlen_q = max_seqlen_q
332
+ seqlen_k = max_seqlen_k
333
+
334
+ if window_size_left >= seqlen_k - 1:
335
+ window_size_left = -1
336
+
337
+ if window_size_right >= seqlen_q - 1:
338
+ window_size_right = -1
339
+
340
+ if is_causal:
341
+ window_size_right = 0
342
+
343
+ is_causal = window_size_left < 0 and window_size_right == 0
344
+
345
+ head_size = q.size(-1)
346
+ head_size_v = v.size(-1)
347
+ head_size_rounded = round_up_headdim(max(head_size, head_size_v))
348
+
349
+ # Hopper gpus uses cuda compute capabilities 9.0
350
+ cap = torch.cuda.get_device_capability(q.device)
351
+ arch = cap[0] * 10 + cap[1]
352
+
353
+ is_local = (window_size_left >= 0 or window_size_right >= 0) and not is_causal
354
+
355
+ if head_size_rounded <= 64:
356
+ kBlockM_sm90 = 96 if (is_causal and softcap > 0.0) else 128
357
+ elif head_size_rounded <= 96:
358
+ kBlockM_sm90 = 64
359
+ elif head_size_rounded <= 128:
360
+ kBlockM_sm90 = 64 if (is_causal or is_local or softcap > 0.0) else 80
361
+ else:
362
+ kBlockM_sm90 = 64
363
+
364
+ kBlockM_sm80 = 128 if head_size_rounded <= 64 else 64
365
+ kBlockM_sm86 = 64 if head_size_rounded <= 192 else 32
366
+
367
+ if arch >= 90:
368
+ kBlockM = kBlockM_sm90
369
+ elif arch == 86 or arch == 89:
370
+ kBlockM = kBlockM_sm86
371
+ else:
372
+ kBlockM = kBlockM_sm80
373
+
374
+ num_heads = q.shape[-2]
375
+ seqlen_q_rounded = round_multiple(seqlen_q, kBlockM)
376
+
377
+ total_q_padded_rounded = round_multiple(total_q + batch_size * kBlockM, kBlockM)
378
+
379
+ dq = torch.empty_like(q) if dq is None else dq
380
+ dk = torch.empty_like(k) if dk is None else dk
381
+ dv = torch.empty_like(v) if dv is None else dv
382
+
383
+ if not is_varlen:
384
+ softmax_d = torch.empty((batch_size, num_heads, seqlen_q_rounded), dtype=torch.float32, device=q.device)
385
+ else:
386
+ softmax_d = torch.empty((num_heads, total_q_padded_rounded), dtype=torch.float32, device=q.device)
387
+
388
+ return softmax_d
389
+
390
+
391
+ def setup_context(ctx, inputs, output):
392
+ q, k, v = inputs[:3]
393
+ out, softmax_lse, _, _ = output
394
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
395
+ ctx.softmax_scale = inputs[-11]
396
+ ctx.causal = inputs[-10]
397
+ ctx.window_size = [inputs[-9], inputs[-8]]
398
+ ctx.attention_chunk = inputs[-7]
399
+ ctx.softcap = inputs[-6]
400
+ ctx.sm_margin = inputs[-1]
401
+
402
+
403
+ def _backward(ctx, dout, *grads):
404
+ q, k, v, out, softmax_lse = ctx.saved_tensors
405
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
406
+ _flash_attn_backward(
407
+ dout,
408
+ q,
409
+ k,
410
+ v,
411
+ out,
412
+ softmax_lse,
413
+ None, None, # cu_seqlens_q, cu_seqlens_k,
414
+ None, None, # sequed_q, sequed_k,
415
+ None, None, # max_seqlen_q, max_seqlen_k,
416
+ dq,
417
+ dk,
418
+ dv,
419
+ ctx.softmax_scale,
420
+ ctx.causal,
421
+ ctx.window_size[0],
422
+ ctx.window_size[1],
423
+ ctx.softcap,
424
+ False, # deterministic
425
+ ctx.sm_margin,
426
+ )
427
+ return dq, dk, dv, *((None,) * 21)
428
+
429
+
430
+ _flash_attn_forward.register_autograd(_backward, setup_context=setup_context)
431
+
432
+
433
+
434
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
435
+ @staticmethod
436
+ def forward(
437
+ ctx,
438
+ qkv,
439
+ softmax_scale,
440
+ causal,
441
+ q_descale=None, k_descale=None, v_descale=None,
442
+ window_size=(-1, -1),
443
+ attention_chunk=0,
444
+ softcap=0.0,
445
+ deterministic=False,
446
+ num_heads_q=None,
447
+ sm_margin=0,
448
+ return_softmax=False,
449
+ ):
450
+ if softmax_scale is None:
451
+ softmax_scale = qkv.shape[-1] ** (-0.5)
452
+ if qkv.dim() == 5:
453
+ assert qkv.shape[-3] == 3
454
+ q, k, v = qkv.unbind(dim=-3)
455
+ else:
456
+ assert qkv.dim() == 4
457
+ assert num_heads_q is not None
458
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
459
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
460
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
461
+ out, softmax_lse, *rest = _flash_attn_forward(
462
+ q,
463
+ k,
464
+ v,
465
+ None, None, # k_new, v_new
466
+ None, # qv
467
+ None, # out
468
+ None, None, None, # cu_seqlens_q/k/k_new
469
+ None, None, # seqused_q/k
470
+ None, None, # max_seqlen_q/k
471
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
472
+ None, None, None, # rotary_cos/sin, seqlens_rotary
473
+ q_descale, k_descale, v_descale,
474
+ softmax_scale,
475
+ causal=causal,
476
+ window_size_left=window_size[0],
477
+ window_size_right=window_size[1],
478
+ attention_chunk=attention_chunk,
479
+ softcap=softcap,
480
+ sm_margin=sm_margin,
481
+ )
482
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
483
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
484
+ ctx.softmax_scale = softmax_scale
485
+ ctx.causal = causal
486
+ ctx.window_size = window_size
487
+ ctx.attention_chunk = attention_chunk
488
+ ctx.softcap = softcap
489
+ ctx.deterministic = deterministic
490
+ ctx.ndim = qkv.dim()
491
+ ctx.sm_margin = sm_margin
492
+ return (out, softmax_lse) if return_softmax else out
493
+
494
+ @staticmethod
495
+ def backward(ctx, dout, *args):
496
+ q, k, v, out, softmax_lse = ctx.saved_tensors
497
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
498
+ if ctx.ndim == 5:
499
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
500
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
501
+ dq, dk, dv = dqkv.unbind(dim=-3)
502
+ else:
503
+ num_heads_q = q.shape[2]
504
+ num_heads_k = k.shape[2]
505
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
506
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
507
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
508
+ _flash_attn_backward(
509
+ dout,
510
+ q,
511
+ k,
512
+ v,
513
+ out,
514
+ softmax_lse,
515
+ None, None, # cu_seqlens_q, cu_seqlens_k,
516
+ None, None, # sequed_q, sequed_k,
517
+ None, None, # max_seqlen_q, max_seqlen_k,
518
+ dq,
519
+ dk,
520
+ dv,
521
+ ctx.softmax_scale,
522
+ ctx.causal,
523
+ ctx.window_size[0],
524
+ ctx.window_size[1],
525
+ ctx.softcap,
526
+ ctx.deterministic,
527
+ ctx.sm_margin,
528
+ )
529
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
530
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None, None
531
+
532
+
533
+ class FlashAttnFunc(torch.autograd.Function):
534
+
535
+ @staticmethod
536
+ def forward(
537
+ ctx,
538
+ q,
539
+ k,
540
+ v,
541
+ softmax_scale,
542
+ causal,
543
+ qv=None,
544
+ q_descale=None, k_descale=None, v_descale=None,
545
+ window_size=(-1, -1),
546
+ attention_chunk=0,
547
+ softcap=0.0,
548
+ num_splits=1,
549
+ pack_gqa=None,
550
+ deterministic=False,
551
+ sm_margin=0,
552
+ return_softmax=False,
553
+ ):
554
+ if softmax_scale is None:
555
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
556
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
557
+ out, softmax_lse, *rest = _flash_attn_forward(
558
+ q,
559
+ k,
560
+ v,
561
+ None, None, # k_new, v_new
562
+ qv, # qv
563
+ None, # out
564
+ None, None, None, # cu_seqlens_q/k/k_new
565
+ None, None, # seqused_q/k
566
+ None, None, # max_seqlen_q/k
567
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
568
+ None, None, None, # rotary_cos/sin, seqlens_rotary
569
+ q_descale, k_descale, v_descale,
570
+ softmax_scale,
571
+ causal=causal,
572
+ window_size_left=window_size[0],
573
+ window_size_right=window_size[1],
574
+ attention_chunk=attention_chunk,
575
+ softcap=softcap,
576
+ num_splits=num_splits,
577
+ pack_gqa=pack_gqa,
578
+ sm_margin=sm_margin,
579
+ )
580
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
581
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
582
+ ctx.softmax_scale = softmax_scale
583
+ ctx.causal = causal
584
+ ctx.window_size = window_size
585
+ ctx.attention_chunk = attention_chunk
586
+ ctx.softcap = softcap
587
+ ctx.deterministic = deterministic
588
+ ctx.sm_margin = sm_margin
589
+ return (out, softmax_lse) if return_softmax else out
590
+
591
+ @staticmethod
592
+ def backward(ctx, dout, *args):
593
+ q, k, v, out, softmax_lse = ctx.saved_tensors
594
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
595
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
596
+ _flash_attn_backward(
597
+ dout,
598
+ q,
599
+ k,
600
+ v,
601
+ out,
602
+ softmax_lse,
603
+ None, None, # cu_seqlens_q, cu_seqlens_k,
604
+ None, None, # sequed_q, sequed_k,
605
+ None, None, # max_seqlen_q, max_seqlen_k,
606
+ dq,
607
+ dk,
608
+ dv,
609
+ ctx.softmax_scale,
610
+ ctx.causal,
611
+ ctx.window_size[0],
612
+ ctx.window_size[1],
613
+ ctx.softcap,
614
+ ctx.deterministic,
615
+ ctx.sm_margin,
616
+ )
617
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
618
+ dk = dk[..., : k.shape[-1]]
619
+ dv = dv[..., : v.shape[-1]]
620
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
621
+
622
+
623
+ class FlashAttnVarlenFunc(torch.autograd.Function):
624
+
625
+ @staticmethod
626
+ def forward(
627
+ ctx,
628
+ q,
629
+ k,
630
+ v,
631
+ cu_seqlens_q,
632
+ cu_seqlens_k,
633
+ seqused_q,
634
+ seqused_k,
635
+ max_seqlen_q,
636
+ max_seqlen_k,
637
+ softmax_scale,
638
+ causal,
639
+ qv=None,
640
+ q_descale=None, k_descale=None, v_descale=None,
641
+ window_size=(-1, -1),
642
+ attention_chunk=0,
643
+ softcap=0.0,
644
+ num_splits=1,
645
+ pack_gqa=None,
646
+ deterministic=False,
647
+ sm_margin=0,
648
+ return_softmax=False,
649
+ ):
650
+ if softmax_scale is None:
651
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
652
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
653
+ out, softmax_lse, *rest = _flash_attn_forward(
654
+ q,
655
+ k,
656
+ v,
657
+ None, None, # k_new, v_new
658
+ qv, # qv
659
+ None, # out
660
+ cu_seqlens_q,
661
+ cu_seqlens_k,
662
+ None, # cu_seqlens_k_new
663
+ seqused_q,
664
+ seqused_k,
665
+ max_seqlen_q,
666
+ max_seqlen_k,
667
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
668
+ None, None, None, # rotary_cos/sin, seqlens_rotary
669
+ q_descale, k_descale, v_descale,
670
+ softmax_scale,
671
+ causal=causal,
672
+ window_size_left=window_size[0],
673
+ window_size_right=window_size[1],
674
+ attention_chunk=attention_chunk,
675
+ softcap=softcap,
676
+ num_splits=num_splits,
677
+ pack_gqa=pack_gqa,
678
+ sm_margin=sm_margin,
679
+ )
680
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
681
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
682
+ ctx.max_seqlen_q = max_seqlen_q
683
+ ctx.max_seqlen_k = max_seqlen_k
684
+ ctx.softmax_scale = softmax_scale
685
+ ctx.causal = causal
686
+ ctx.window_size = window_size
687
+ ctx.attention_chunk = attention_chunk
688
+ ctx.softcap = softcap
689
+ ctx.deterministic = deterministic
690
+ ctx.sm_margin = sm_margin
691
+ return (out, softmax_lse) if return_softmax else out
692
+
693
+ @staticmethod
694
+ def backward(ctx, dout, *args):
695
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
696
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
697
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
698
+ _flash_attn_backward(
699
+ dout,
700
+ q,
701
+ k,
702
+ v,
703
+ out,
704
+ softmax_lse,
705
+ cu_seqlens_q,
706
+ cu_seqlens_k,
707
+ seqused_q,
708
+ seqused_k,
709
+ ctx.max_seqlen_q,
710
+ ctx.max_seqlen_k,
711
+ dq,
712
+ dk,
713
+ dv,
714
+ ctx.softmax_scale,
715
+ ctx.causal,
716
+ ctx.window_size[0],
717
+ ctx.window_size[1],
718
+ ctx.softcap,
719
+ ctx.deterministic,
720
+ ctx.sm_margin,
721
+ )
722
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
723
+ dk = dk[..., : k.shape[-1]]
724
+ dv = dv[..., : v.shape[-1]]
725
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
726
+
727
+
728
+ def flash_attn_qkvpacked_func(
729
+ qkv,
730
+ softmax_scale=None,
731
+ causal=False,
732
+ q_descale=None, k_descale=None, v_descale=None,
733
+ window_size=(-1, -1),
734
+ attention_chunk=0,
735
+ softcap=0.0,
736
+ deterministic=False,
737
+ num_heads_q=None,
738
+ sm_margin=0,
739
+ return_attn_probs=False,
740
+ ):
741
+ """dropout_p should be set to 0.0 during evaluation
742
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
743
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
744
+ of the gradients of Q, K, V.
745
+ For multi-query and grouped-query attention (MQA/GQA), please see
746
+ flash_attn_kvpacked_func and flash_attn_func.
747
+
748
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
749
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
750
+
751
+ Arguments:
752
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
753
+ dropout_p: float. Dropout probability.
754
+ softmax_scale: float. The scaling of QK^T before applying softmax.
755
+ Default to 1 / sqrt(headdim).
756
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
757
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
758
+ softcap: float. Anything > 0 activates softcapping attention.
759
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
760
+ the attention score of query i and key j.
761
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
762
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
763
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
764
+ testing only. The returned probabilities are not guaranteed to be correct
765
+ (they might not have the right scaling).
766
+ Return:
767
+ out: (batch_size, seqlen, nheads, headdim).
768
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
769
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
770
+ normalization factor).
771
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
772
+ The output of softmax (possibly with different scaling). It also encodes the dropout
773
+ pattern (negative means that location was dropped, nonnegative means it was kept).
774
+ """
775
+ return FlashAttnQKVPackedFunc.apply(
776
+ qkv,
777
+ softmax_scale,
778
+ causal,
779
+ q_descale, k_descale, v_descale,
780
+ window_size,
781
+ attention_chunk,
782
+ softcap,
783
+ deterministic,
784
+ num_heads_q,
785
+ sm_margin,
786
+ return_attn_probs,
787
+ )
788
+
789
+
790
+ def flash_attn_func(
791
+ q,
792
+ k,
793
+ v,
794
+ softmax_scale=None,
795
+ causal=False,
796
+ qv=None,
797
+ q_descale=None, k_descale=None, v_descale=None,
798
+ window_size=(-1, -1),
799
+ attention_chunk=0,
800
+ softcap=0.0,
801
+ num_splits=1,
802
+ pack_gqa=None,
803
+ deterministic=False,
804
+ sm_margin=0,
805
+ return_attn_probs=False,
806
+ ):
807
+ """dropout_p should be set to 0.0 during evaluation
808
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
809
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
810
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
811
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
812
+
813
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
814
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
815
+ 1 1 1 1 0
816
+ 1 1 1 1 1
817
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
818
+ 0 0
819
+ 0 0
820
+ 0 0
821
+ 1 0
822
+ 1 1
823
+ If the row of the mask is all zero, the output will be zero.
824
+
825
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
826
+ will only attend to keys between
827
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
828
+
829
+ Arguments:
830
+ q: (batch_size, seqlen, nheads, headdim)
831
+ k: (batch_size, seqlen, nheads_k, headdim)
832
+ v: (batch_size, seqlen, nheads_k, headdim)
833
+ dropout_p: float. Dropout probability.
834
+ softmax_scale: float. The scaling of QK^T before applying softmax.
835
+ Default to 1 / sqrt(headdim).
836
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
837
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
838
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
839
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
840
+ is added to the attention score of query i and key j.
841
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
842
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
843
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
844
+ testing only. The returned probabilities are not guaranteed to be correct
845
+ (they might not have the right scaling).
846
+ Return:
847
+ out: (batch_size, seqlen, nheads, headdim).
848
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
849
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
850
+ normalization factor).
851
+ """
852
+ return FlashAttnFunc.apply(
853
+ q,
854
+ k,
855
+ v,
856
+ softmax_scale,
857
+ causal,
858
+ qv,
859
+ q_descale, k_descale, v_descale,
860
+ window_size,
861
+ attention_chunk,
862
+ softcap,
863
+ num_splits,
864
+ pack_gqa,
865
+ deterministic,
866
+ sm_margin,
867
+ return_attn_probs,
868
+ )
869
+
870
+
871
+ def flash_attn_varlen_func(
872
+ q,
873
+ k,
874
+ v,
875
+ cu_seqlens_q,
876
+ cu_seqlens_k,
877
+ max_seqlen_q,
878
+ max_seqlen_k,
879
+ seqused_q=None,
880
+ seqused_k=None,
881
+ softmax_scale=None,
882
+ causal=False,
883
+ qv=None,
884
+ q_descale=None, k_descale=None, v_descale=None,
885
+ window_size=(-1, -1),
886
+ attention_chunk=0,
887
+ softcap=0.0,
888
+ num_splits=1,
889
+ pack_gqa=None,
890
+ deterministic=False,
891
+ sm_margin=0,
892
+ return_attn_probs=False,
893
+ ):
894
+ return FlashAttnVarlenFunc.apply(
895
+ q,
896
+ k,
897
+ v,
898
+ cu_seqlens_q,
899
+ cu_seqlens_k,
900
+ seqused_q,
901
+ seqused_k,
902
+ max_seqlen_q,
903
+ max_seqlen_k,
904
+ softmax_scale,
905
+ causal,
906
+ qv,
907
+ q_descale, k_descale, v_descale,
908
+ window_size,
909
+ attention_chunk,
910
+ softcap,
911
+ num_splits,
912
+ pack_gqa,
913
+ deterministic,
914
+ sm_margin,
915
+ return_attn_probs,
916
+ )
917
+
918
+
919
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
920
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
921
+
922
+
923
+ def flash_attn_with_kvcache(
924
+ q,
925
+ k_cache,
926
+ v_cache,
927
+ k=None,
928
+ v=None,
929
+ qv=None,
930
+ rotary_cos=None,
931
+ rotary_sin=None,
932
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
933
+ cache_batch_idx: Optional[torch.Tensor] = None,
934
+ cache_leftpad: Optional[torch.Tensor] = None,
935
+ page_table: Optional[torch.Tensor] = None,
936
+ cu_seqlens_q: Optional[torch.Tensor] = None,
937
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
938
+ max_seqlen_q: Optional[int] = None,
939
+ rotary_seqlens: Optional[torch.Tensor] = None,
940
+ q_descale: Optional[torch.Tensor] = None,
941
+ k_descale: Optional[torch.Tensor] = None,
942
+ v_descale: Optional[torch.Tensor] = None,
943
+ softmax_scale=None,
944
+ causal=False,
945
+ window_size=(-1, -1), # -1 means infinite context window
946
+ attention_chunk=0,
947
+ softcap=0.0, # 0.0 means deactivated
948
+ rotary_interleaved=True,
949
+ scheduler_metadata=None,
950
+ num_splits=0, # Can be tuned for speed
951
+ pack_gqa=None, # Can be tuned for speed
952
+ sm_margin=0, # Can be tuned if some SMs are used for communication
953
+ return_softmax_lse=False,
954
+ ):
955
+ """
956
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
957
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
958
+ the previous step, and update them with the new keys/values from the current step, and do
959
+ attention with the updated cache, all in 1 kernel.
960
+
961
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
962
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
963
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
964
+
965
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
966
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
967
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
968
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
969
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
970
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
971
+
972
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
973
+
974
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
975
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
976
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
977
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
978
+
979
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
980
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
981
+ 1 1 1 1 0
982
+ 1 1 1 1 1
983
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
984
+ 0 0
985
+ 0 0
986
+ 0 0
987
+ 1 0
988
+ 1 1
989
+ If the row of the mask is all zero, the output will be zero.
990
+
991
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
992
+ will only attend to keys between
993
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
994
+
995
+ Note: Does not support backward pass.
996
+
997
+ Arguments:
998
+ q: (batch_size, seqlen, nheads, headdim)
999
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
1000
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
1001
+ page_block_size can be arbitrary (e.g, 1, 2, 3, 64, etc.).
1002
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
1003
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
1004
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
1005
+ k with k_cache, starting at the indices specified by cache_seqlens.
1006
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
1007
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
1008
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
1009
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
1010
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
1011
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
1012
+ KV cache.
1013
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
1014
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
1015
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
1016
+ might come from any of the duplicate indices.
1017
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
1018
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
1019
+ softmax_scale: float. The scaling of QK^T before applying softmax.
1020
+ Default to 1 / sqrt(headdim).
1021
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
1022
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
1023
+ softcap: float. Anything > 0 activates softcapping attention.
1024
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
1025
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
1026
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
1027
+ (i.e. GPT-NeoX style).
1028
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
1029
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
1030
+ to automatically determine the number of splits.
1031
+ Don't change this unless you know what you are doing.
1032
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
1033
+
1034
+ Return:
1035
+ out: (batch_size, seqlen, nheads, headdim).
1036
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
1037
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
1038
+ normalization factor).
1039
+ """
1040
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
1041
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
1042
+ if softmax_scale is None:
1043
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
1044
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
1045
+ cache_seqlens = torch.full(
1046
+ (q.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
1047
+ )
1048
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1049
+ out, softmax_lse, *rest = _flash_attn_forward(
1050
+ q,
1051
+ k_cache,
1052
+ v_cache,
1053
+ k,
1054
+ v,
1055
+ qv,
1056
+ None, # out
1057
+ cu_seqlens_q,
1058
+ None, # cu_seqlens_k
1059
+ cu_seqlens_k_new,
1060
+ None, # seqused_q
1061
+ cache_seqlens,
1062
+ max_seqlen_q,
1063
+ None, # max_seqlen_k
1064
+ page_table,
1065
+ cache_batch_idx,
1066
+ cache_leftpad,
1067
+ rotary_cos,
1068
+ rotary_sin,
1069
+ rotary_seqlens,
1070
+ q_descale, k_descale, v_descale,
1071
+ softmax_scale,
1072
+ causal=causal,
1073
+ window_size_left=window_size[0],
1074
+ window_size_right=window_size[1],
1075
+ attention_chunk=attention_chunk,
1076
+ softcap=softcap,
1077
+ rotary_interleaved=rotary_interleaved,
1078
+ scheduler_metadata=scheduler_metadata,
1079
+ num_splits=num_splits,
1080
+ pack_gqa=pack_gqa,
1081
+ sm_margin=sm_margin,
1082
+ )
1083
+ # return (out, softmax_lse) if return_softmax_lse else out
1084
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
1085
+
1086
+
1087
+ def get_scheduler_metadata(
1088
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
1089
+ cache_seqlens: torch.Tensor,
1090
+ qkv_dtype=torch.bfloat16,
1091
+ headdim_v=None,
1092
+ cu_seqlens_q: Optional[torch.Tensor] = None,
1093
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
1094
+ cache_leftpad: Optional[torch.Tensor] = None,
1095
+ page_size: Optional[int] = None,
1096
+ max_seqlen_k_new=0,
1097
+ causal=False,
1098
+ window_size=(-1, -1), # -1 means infinite context window
1099
+ attention_chunk=0,
1100
+ has_softcap=False,
1101
+ num_splits=0, # Can be tuned for speed
1102
+ pack_gqa=None, # Can be tuned for speed
1103
+ sm_margin=0, # Can be tuned if some SMs are used for communication
1104
+ ):
1105
+ cache_seqlens = maybe_contiguous(cache_seqlens)
1106
+ if headdim_v is None:
1107
+ headdim_v = headdim
1108
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
1109
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
1110
+ qkv_dtype,
1111
+ cache_seqlens,
1112
+ cu_seqlens_q,
1113
+ None, # cu_seqlens_k
1114
+ cu_seqlens_k_new,
1115
+ None, # seqused_q
1116
+ cache_leftpad,
1117
+ page_size,
1118
+ max_seqlen_k_new,
1119
+ causal,
1120
+ window_size[0], window_size[1],
1121
+ attention_chunk,
1122
+ has_softcap,
1123
+ num_splits,
1124
+ pack_gqa,
1125
+ sm_margin,
1126
+ )
1127
+ return scheduler_metadata
build/torch211-cxx11-cu130-x86_64-linux/metadata.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "license": "BSD-3-Clause",
4
+ "python-depends": [],
5
+ "backend": {
6
+ "type": "cuda",
7
+ "archs": [
8
+ "8.0",
9
+ "9.0a"
10
+ ]
11
+ }
12
+ }
build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21b44e8e5e447a8b8ee051d347f0e32a3446a750f79d0bd1755e553f2119aa3b
3
+ size 838459656
build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12d4ff964085fd02252777a2008f5ca47c90ea6a93da590e2fc5065dd5330207
3
+ size 838459656
build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_557701f
3
+ ops = torch.ops._flash_attn3_557701f
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_557701f::{op_name}"
build/torch26-cxx11-cu124-x86_64-linux/flash_attn3/flash_attn_interface.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+
10
+ def maybe_contiguous(x):
11
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
12
+
13
+
14
+ def _flash_attn_forward(
15
+ q,
16
+ k,
17
+ v,
18
+ k_new,
19
+ v_new,
20
+ qv,
21
+ out,
22
+ cu_seqlens_q,
23
+ cu_seqlens_k,
24
+ cu_seqlens_k_new,
25
+ seqused_q,
26
+ seqused_k,
27
+ max_seqlen_q,
28
+ max_seqlen_k,
29
+ page_table,
30
+ kv_batch_idx,
31
+ leftpad_k,
32
+ rotary_cos,
33
+ rotary_sin,
34
+ seqlens_rotary,
35
+ q_descale,
36
+ k_descale,
37
+ v_descale,
38
+ softmax_scale,
39
+ causal,
40
+ window_size=(-1, -1),
41
+ attention_chunk=0,
42
+ softcap=0.0,
43
+ rotary_interleaved=True,
44
+ scheduler_metadata=None,
45
+ num_splits=1,
46
+ pack_gqa=None,
47
+ sm_margin=0):
48
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
49
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
50
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
51
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
52
+ ]
53
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
54
+ page_table, kv_batch_idx, leftpad_k = [
55
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
56
+ ]
57
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
58
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
59
+ out, softmax_lse, *rest = flash_attn_3_cuda.fwd(
60
+ q,
61
+ k,
62
+ v,
63
+ k_new,
64
+ v_new,
65
+ qv,
66
+ out,
67
+ cu_seqlens_q,
68
+ cu_seqlens_k,
69
+ cu_seqlens_k_new,
70
+ seqused_q,
71
+ seqused_k,
72
+ max_seqlen_q,
73
+ max_seqlen_k,
74
+ page_table,
75
+ kv_batch_idx,
76
+ leftpad_k,
77
+ rotary_cos,
78
+ rotary_sin,
79
+ seqlens_rotary,
80
+ q_descale,
81
+ k_descale,
82
+ v_descale,
83
+ softmax_scale,
84
+ causal,
85
+ window_size[0],
86
+ window_size[1],
87
+ attention_chunk,
88
+ softcap,
89
+ rotary_interleaved,
90
+ scheduler_metadata,
91
+ num_splits,
92
+ pack_gqa,
93
+ sm_margin,
94
+ )
95
+ return out, softmax_lse, *rest
96
+
97
+
98
+ def _flash_attn_backward(
99
+ dout,
100
+ q,
101
+ k,
102
+ v,
103
+ out,
104
+ softmax_lse,
105
+ cu_seqlens_q,
106
+ cu_seqlens_k,
107
+ sequed_q,
108
+ sequed_k,
109
+ max_seqlen_q,
110
+ max_seqlen_k,
111
+ dq,
112
+ dk,
113
+ dv,
114
+ softmax_scale,
115
+ causal,
116
+ window_size=(-1, -1),
117
+ softcap=0.0,
118
+ deterministic=False,
119
+ sm_margin=0,
120
+ ):
121
+ # dq, dk, dv are allocated by us so they should already be contiguous
122
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
123
+ dq, dk, dv, softmax_d, *rest = flash_attn_3_cuda.bwd(
124
+ dout,
125
+ q,
126
+ k,
127
+ v,
128
+ out,
129
+ softmax_lse,
130
+ dq,
131
+ dk,
132
+ dv,
133
+ cu_seqlens_q,
134
+ cu_seqlens_k,
135
+ sequed_q,
136
+ sequed_k,
137
+ max_seqlen_q,
138
+ max_seqlen_k,
139
+ softmax_scale,
140
+ causal,
141
+ window_size[0],
142
+ window_size[1],
143
+ softcap,
144
+ deterministic,
145
+ sm_margin,
146
+ )
147
+ return dq, dk, dv, softmax_d
148
+
149
+
150
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
151
+ @staticmethod
152
+ def forward(
153
+ ctx,
154
+ qkv,
155
+ softmax_scale,
156
+ causal,
157
+ q_descale=None, k_descale=None, v_descale=None,
158
+ window_size=(-1, -1),
159
+ attention_chunk=0,
160
+ softcap=0.0,
161
+ deterministic=False,
162
+ num_heads_q=None,
163
+ sm_margin=0,
164
+ ):
165
+ if softmax_scale is None:
166
+ softmax_scale = qkv.shape[-1] ** (-0.5)
167
+ if qkv.dim() == 5:
168
+ assert qkv.shape[-3] == 3
169
+ q, k, v = qkv.unbind(dim=-3)
170
+ else:
171
+ assert qkv.dim() == 4
172
+ assert num_heads_q is not None
173
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
174
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
175
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
176
+ out, softmax_lse, *rest = _flash_attn_forward(
177
+ q,
178
+ k,
179
+ v,
180
+ None, None, # k_new, v_new
181
+ None, # qv
182
+ None, # out
183
+ None, None, None, # cu_seqlens_q/k/k_new
184
+ None, None, # seqused_q/k
185
+ None, None, # max_seqlen_q/k
186
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
187
+ None, None, None, # rotary_cos/sin, seqlens_rotary
188
+ q_descale, k_descale, v_descale,
189
+ softmax_scale,
190
+ causal=causal,
191
+ window_size=window_size,
192
+ attention_chunk=attention_chunk,
193
+ softcap=softcap,
194
+ sm_margin=sm_margin,
195
+ )
196
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
197
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
198
+ ctx.softmax_scale = softmax_scale
199
+ ctx.causal = causal
200
+ ctx.window_size = window_size
201
+ ctx.attention_chunk = attention_chunk
202
+ ctx.softcap = softcap
203
+ ctx.deterministic = deterministic
204
+ ctx.ndim = qkv.dim()
205
+ ctx.sm_margin = sm_margin
206
+ # return out, softmax_lse
207
+ return out
208
+
209
+ @staticmethod
210
+ def backward(ctx, dout, *args):
211
+ q, k, v, out, softmax_lse = ctx.saved_tensors
212
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
213
+ if ctx.ndim == 5:
214
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
215
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
216
+ dq, dk, dv = dqkv.unbind(dim=-3)
217
+ else:
218
+ num_heads_q = q.shape[2]
219
+ num_heads_k = k.shape[2]
220
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
221
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
222
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
223
+ _flash_attn_backward(
224
+ dout,
225
+ q,
226
+ k,
227
+ v,
228
+ out,
229
+ softmax_lse,
230
+ None, None, # cu_seqlens_q, cu_seqlens_k,
231
+ None, None, # sequed_q, sequed_k,
232
+ None, None, # max_seqlen_q, max_seqlen_k,
233
+ dq,
234
+ dk,
235
+ dv,
236
+ ctx.softmax_scale,
237
+ ctx.causal,
238
+ ctx.window_size,
239
+ ctx.softcap,
240
+ ctx.deterministic,
241
+ ctx.sm_margin,
242
+ )
243
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
244
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None
245
+
246
+
247
+ class FlashAttnFunc(torch.autograd.Function):
248
+
249
+ @staticmethod
250
+ def forward(
251
+ ctx,
252
+ q,
253
+ k,
254
+ v,
255
+ softmax_scale,
256
+ causal,
257
+ qv=None,
258
+ q_descale=None, k_descale=None, v_descale=None,
259
+ window_size=(-1, -1),
260
+ attention_chunk=0,
261
+ softcap=0.0,
262
+ num_splits=1,
263
+ pack_gqa=None,
264
+ deterministic=False,
265
+ sm_margin=0,
266
+ ):
267
+ if softmax_scale is None:
268
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
269
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
270
+ out, softmax_lse, *rest = _flash_attn_forward(
271
+ q,
272
+ k,
273
+ v,
274
+ None, None, # k_new, v_new
275
+ qv, # qv
276
+ None, # out
277
+ None, None, None, # cu_seqlens_q/k/k_new
278
+ None, None, # seqused_q/k
279
+ None, None, # max_seqlen_q/k
280
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
281
+ None, None, None, # rotary_cos/sin, seqlens_rotary
282
+ q_descale, k_descale, v_descale,
283
+ softmax_scale,
284
+ causal=causal,
285
+ window_size=window_size,
286
+ attention_chunk=attention_chunk,
287
+ softcap=softcap,
288
+ num_splits=num_splits,
289
+ pack_gqa=pack_gqa,
290
+ sm_margin=sm_margin,
291
+ )
292
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
293
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
294
+ ctx.softmax_scale = softmax_scale
295
+ ctx.causal = causal
296
+ ctx.window_size = window_size
297
+ ctx.attention_chunk = attention_chunk
298
+ ctx.softcap = softcap
299
+ ctx.deterministic = deterministic
300
+ ctx.sm_margin = sm_margin
301
+ return out, softmax_lse
302
+
303
+ @staticmethod
304
+ def backward(ctx, dout, *args):
305
+ q, k, v, out, softmax_lse = ctx.saved_tensors
306
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
307
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
308
+ _flash_attn_backward(
309
+ dout,
310
+ q,
311
+ k,
312
+ v,
313
+ out,
314
+ softmax_lse,
315
+ None, None, # cu_seqlens_q, cu_seqlens_k,
316
+ None, None, # sequed_q, sequed_k,
317
+ None, None, # max_seqlen_q, max_seqlen_k,
318
+ dq,
319
+ dk,
320
+ dv,
321
+ ctx.softmax_scale,
322
+ ctx.causal,
323
+ ctx.window_size,
324
+ ctx.softcap,
325
+ ctx.deterministic,
326
+ ctx.sm_margin,
327
+ )
328
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
329
+ dk = dk[..., : k.shape[-1]]
330
+ dv = dv[..., : v.shape[-1]]
331
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
332
+
333
+
334
+ class FlashAttnVarlenFunc(torch.autograd.Function):
335
+
336
+ @staticmethod
337
+ def forward(
338
+ ctx,
339
+ q,
340
+ k,
341
+ v,
342
+ cu_seqlens_q,
343
+ cu_seqlens_k,
344
+ seqused_q,
345
+ seqused_k,
346
+ max_seqlen_q,
347
+ max_seqlen_k,
348
+ softmax_scale,
349
+ causal,
350
+ qv=None,
351
+ q_descale=None, k_descale=None, v_descale=None,
352
+ window_size=(-1, -1),
353
+ attention_chunk=0,
354
+ softcap=0.0,
355
+ num_splits=1,
356
+ pack_gqa=None,
357
+ deterministic=False,
358
+ sm_margin=0,
359
+ ):
360
+ if softmax_scale is None:
361
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
362
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
363
+ out, softmax_lse, *rest = _flash_attn_forward(
364
+ q,
365
+ k,
366
+ v,
367
+ None, None, # k_new, v_new
368
+ qv, # qv
369
+ None, # out
370
+ cu_seqlens_q,
371
+ cu_seqlens_k,
372
+ None, # cu_seqlens_k_new
373
+ seqused_q,
374
+ seqused_k,
375
+ max_seqlen_q,
376
+ max_seqlen_k,
377
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
378
+ None, None, None, # rotary_cos/sin, seqlens_rotary
379
+ q_descale, k_descale, v_descale,
380
+ softmax_scale,
381
+ causal=causal,
382
+ window_size=window_size,
383
+ attention_chunk=attention_chunk,
384
+ softcap=softcap,
385
+ num_splits=num_splits,
386
+ pack_gqa=pack_gqa,
387
+ sm_margin=sm_margin,
388
+ )
389
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
390
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
391
+ ctx.max_seqlen_q = max_seqlen_q
392
+ ctx.max_seqlen_k = max_seqlen_k
393
+ ctx.softmax_scale = softmax_scale
394
+ ctx.causal = causal
395
+ ctx.window_size = window_size
396
+ ctx.attention_chunk = attention_chunk
397
+ ctx.softcap = softcap
398
+ ctx.deterministic = deterministic
399
+ ctx.sm_margin = sm_margin
400
+ return out, softmax_lse
401
+
402
+ @staticmethod
403
+ def backward(ctx, dout, *args):
404
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
405
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
406
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
407
+ _flash_attn_backward(
408
+ dout,
409
+ q,
410
+ k,
411
+ v,
412
+ out,
413
+ softmax_lse,
414
+ cu_seqlens_q,
415
+ cu_seqlens_k,
416
+ seqused_q,
417
+ seqused_k,
418
+ ctx.max_seqlen_q,
419
+ ctx.max_seqlen_k,
420
+ dq,
421
+ dk,
422
+ dv,
423
+ ctx.softmax_scale,
424
+ ctx.causal,
425
+ ctx.window_size,
426
+ ctx.softcap,
427
+ ctx.deterministic,
428
+ ctx.sm_margin,
429
+ )
430
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
431
+ dk = dk[..., : k.shape[-1]]
432
+ dv = dv[..., : v.shape[-1]]
433
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
434
+
435
+
436
+ def flash_attn_qkvpacked_func(
437
+ qkv,
438
+ softmax_scale=None,
439
+ causal=False,
440
+ q_descale=None, k_descale=None, v_descale=None,
441
+ window_size=(-1, -1),
442
+ attention_chunk=0,
443
+ softcap=0.0,
444
+ deterministic=False,
445
+ num_heads_q=None,
446
+ sm_margin=0,
447
+ ):
448
+ """dropout_p should be set to 0.0 during evaluation
449
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
450
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
451
+ of the gradients of Q, K, V.
452
+ For multi-query and grouped-query attention (MQA/GQA), please see
453
+ flash_attn_kvpacked_func and flash_attn_func.
454
+
455
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
456
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
457
+
458
+ Arguments:
459
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
460
+ dropout_p: float. Dropout probability.
461
+ softmax_scale: float. The scaling of QK^T before applying softmax.
462
+ Default to 1 / sqrt(headdim).
463
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
464
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
465
+ softcap: float. Anything > 0 activates softcapping attention.
466
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
467
+ the attention score of query i and key j.
468
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
469
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
470
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
471
+ testing only. The returned probabilities are not guaranteed to be correct
472
+ (they might not have the right scaling).
473
+ Return:
474
+ out: (batch_size, seqlen, nheads, headdim).
475
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
476
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
477
+ normalization factor).
478
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
479
+ The output of softmax (possibly with different scaling). It also encodes the dropout
480
+ pattern (negative means that location was dropped, nonnegative means it was kept).
481
+ """
482
+ return FlashAttnQKVPackedFunc.apply(
483
+ qkv,
484
+ softmax_scale,
485
+ causal,
486
+ q_descale, k_descale, v_descale,
487
+ window_size,
488
+ attention_chunk,
489
+ softcap,
490
+ deterministic,
491
+ num_heads_q,
492
+ sm_margin,
493
+ )
494
+
495
+
496
+ def flash_attn_func(
497
+ q,
498
+ k,
499
+ v,
500
+ softmax_scale=None,
501
+ causal=False,
502
+ qv=None,
503
+ q_descale=None, k_descale=None, v_descale=None,
504
+ window_size=(-1, -1),
505
+ attention_chunk=0,
506
+ softcap=0.0,
507
+ num_splits=1,
508
+ pack_gqa=None,
509
+ deterministic=False,
510
+ sm_margin=0,
511
+ ):
512
+ """dropout_p should be set to 0.0 during evaluation
513
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
514
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
515
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
516
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
517
+
518
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
519
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
520
+ 1 1 1 1 0
521
+ 1 1 1 1 1
522
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
523
+ 0 0
524
+ 0 0
525
+ 0 0
526
+ 1 0
527
+ 1 1
528
+ If the row of the mask is all zero, the output will be zero.
529
+
530
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
531
+ will only attend to keys between
532
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
533
+
534
+ Arguments:
535
+ q: (batch_size, seqlen, nheads, headdim)
536
+ k: (batch_size, seqlen, nheads_k, headdim)
537
+ v: (batch_size, seqlen, nheads_k, headdim)
538
+ dropout_p: float. Dropout probability.
539
+ softmax_scale: float. The scaling of QK^T before applying softmax.
540
+ Default to 1 / sqrt(headdim).
541
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
542
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
543
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
544
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
545
+ is added to the attention score of query i and key j.
546
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
547
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
548
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
549
+ testing only. The returned probabilities are not guaranteed to be correct
550
+ (they might not have the right scaling).
551
+ Return:
552
+ out: (batch_size, seqlen, nheads, headdim).
553
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
554
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
555
+ normalization factor).
556
+ """
557
+ return FlashAttnFunc.apply(
558
+ q,
559
+ k,
560
+ v,
561
+ softmax_scale,
562
+ causal,
563
+ qv,
564
+ q_descale, k_descale, v_descale,
565
+ window_size,
566
+ attention_chunk,
567
+ softcap,
568
+ num_splits,
569
+ pack_gqa,
570
+ deterministic,
571
+ sm_margin,
572
+ )
573
+
574
+
575
+ def flash_attn_varlen_func(
576
+ q,
577
+ k,
578
+ v,
579
+ cu_seqlens_q,
580
+ cu_seqlens_k,
581
+ max_seqlen_q,
582
+ max_seqlen_k,
583
+ seqused_q=None,
584
+ seqused_k=None,
585
+ softmax_scale=None,
586
+ causal=False,
587
+ qv=None,
588
+ q_descale=None, k_descale=None, v_descale=None,
589
+ window_size=(-1, -1),
590
+ attention_chunk=0,
591
+ softcap=0.0,
592
+ num_splits=1,
593
+ pack_gqa=None,
594
+ deterministic=False,
595
+ sm_margin=0,
596
+ ):
597
+ return FlashAttnVarlenFunc.apply(
598
+ q,
599
+ k,
600
+ v,
601
+ cu_seqlens_q,
602
+ cu_seqlens_k,
603
+ seqused_q,
604
+ seqused_k,
605
+ max_seqlen_q,
606
+ max_seqlen_k,
607
+ softmax_scale,
608
+ causal,
609
+ qv,
610
+ q_descale, k_descale, v_descale,
611
+ window_size,
612
+ attention_chunk,
613
+ softcap,
614
+ num_splits,
615
+ pack_gqa,
616
+ deterministic,
617
+ sm_margin,
618
+ )
619
+
620
+
621
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
622
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
623
+
624
+
625
+ def flash_attn_with_kvcache(
626
+ q,
627
+ k_cache,
628
+ v_cache,
629
+ k=None,
630
+ v=None,
631
+ qv=None,
632
+ rotary_cos=None,
633
+ rotary_sin=None,
634
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
635
+ cache_batch_idx: Optional[torch.Tensor] = None,
636
+ cache_leftpad: Optional[torch.Tensor] = None,
637
+ page_table: Optional[torch.Tensor] = None,
638
+ cu_seqlens_q: Optional[torch.Tensor] = None,
639
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
640
+ max_seqlen_q: Optional[int] = None,
641
+ rotary_seqlens: Optional[torch.Tensor] = None,
642
+ q_descale: Optional[torch.Tensor] = None,
643
+ k_descale: Optional[torch.Tensor] = None,
644
+ v_descale: Optional[torch.Tensor] = None,
645
+ softmax_scale=None,
646
+ causal=False,
647
+ window_size=(-1, -1), # -1 means infinite context window
648
+ attention_chunk=0,
649
+ softcap=0.0, # 0.0 means deactivated
650
+ rotary_interleaved=True,
651
+ scheduler_metadata=None,
652
+ num_splits=0, # Can be tuned for speed
653
+ pack_gqa=None, # Can be tuned for speed
654
+ sm_margin=0, # Can be tuned if some SMs are used for communication
655
+ return_softmax_lse=False,
656
+ ):
657
+ """
658
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
659
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
660
+ the previous step, and update them with the new keys/values from the current step, and do
661
+ attention with the updated cache, all in 1 kernel.
662
+
663
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
664
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
665
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
666
+
667
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
668
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
669
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
670
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
671
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
672
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
673
+
674
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
675
+
676
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
677
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
678
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
679
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
680
+
681
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
682
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
683
+ 1 1 1 1 0
684
+ 1 1 1 1 1
685
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
686
+ 0 0
687
+ 0 0
688
+ 0 0
689
+ 1 0
690
+ 1 1
691
+ If the row of the mask is all zero, the output will be zero.
692
+
693
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
694
+ will only attend to keys between
695
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
696
+
697
+ Note: Does not support backward pass.
698
+
699
+ Arguments:
700
+ q: (batch_size, seqlen, nheads, headdim)
701
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
702
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
703
+ page_block_size must be a multiple of 256.
704
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
705
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
706
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
707
+ k with k_cache, starting at the indices specified by cache_seqlens.
708
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
709
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
710
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
711
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
712
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
713
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
714
+ KV cache.
715
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
716
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
717
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
718
+ might come from any of the duplicate indices.
719
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
720
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
721
+ softmax_scale: float. The scaling of QK^T before applying softmax.
722
+ Default to 1 / sqrt(headdim).
723
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
724
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
725
+ softcap: float. Anything > 0 activates softcapping attention.
726
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
727
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
728
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
729
+ (i.e. GPT-NeoX style).
730
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
731
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
732
+ to automatically determine the number of splits.
733
+ Don't change this unless you know what you are doing.
734
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
735
+
736
+ Return:
737
+ out: (batch_size, seqlen, nheads, headdim).
738
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
739
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
740
+ normalization factor).
741
+ """
742
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
743
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
744
+ if softmax_scale is None:
745
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
746
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
747
+ cache_seqlens = torch.full(
748
+ (k_cache.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
749
+ )
750
+ cache_seqlens = maybe_contiguous(cache_seqlens)
751
+ out, softmax_lse, *rest = _flash_attn_forward(
752
+ q,
753
+ k_cache,
754
+ v_cache,
755
+ k,
756
+ v,
757
+ qv,
758
+ None, # out
759
+ cu_seqlens_q,
760
+ None, # cu_seqlens_k
761
+ cu_seqlens_k_new,
762
+ None, # seqused_q
763
+ cache_seqlens,
764
+ max_seqlen_q,
765
+ None, # max_seqlen_k
766
+ page_table,
767
+ cache_batch_idx,
768
+ cache_leftpad,
769
+ rotary_cos,
770
+ rotary_sin,
771
+ rotary_seqlens,
772
+ q_descale, k_descale, v_descale,
773
+ softmax_scale,
774
+ causal=causal,
775
+ window_size=window_size,
776
+ attention_chunk=attention_chunk,
777
+ softcap=softcap,
778
+ rotary_interleaved=rotary_interleaved,
779
+ scheduler_metadata=scheduler_metadata,
780
+ num_splits=num_splits,
781
+ pack_gqa=pack_gqa,
782
+ sm_margin=sm_margin,
783
+ )
784
+ # return (out, softmax_lse) if return_softmax_lse else out
785
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
786
+
787
+
788
+ def get_scheduler_metadata(
789
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
790
+ cache_seqlens: torch.Tensor,
791
+ qkv_dtype=torch.bfloat16,
792
+ headdim_v=None,
793
+ cu_seqlens_q: Optional[torch.Tensor] = None,
794
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
795
+ cache_leftpad: Optional[torch.Tensor] = None,
796
+ page_size: Optional[int] = None,
797
+ max_seqlen_k_new=0,
798
+ causal=False,
799
+ window_size=(-1, -1), # -1 means infinite context window
800
+ attention_chunk=0,
801
+ has_softcap=False,
802
+ num_splits=0, # Can be tuned for speed
803
+ pack_gqa=None, # Can be tuned for speed
804
+ sm_margin=0, # Can be tuned if some SMs are used for communication
805
+ ):
806
+ cache_seqlens = maybe_contiguous(cache_seqlens)
807
+ if headdim_v is None:
808
+ headdim_v = headdim
809
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
810
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
811
+ qkv_dtype,
812
+ cache_seqlens,
813
+ cu_seqlens_q,
814
+ None, # cu_seqlens_k
815
+ cu_seqlens_k_new,
816
+ None, # seqused_q
817
+ cache_leftpad,
818
+ page_size,
819
+ max_seqlen_k_new,
820
+ causal,
821
+ window_size[0], window_size[1],
822
+ attention_chunk,
823
+ has_softcap,
824
+ num_splits,
825
+ pack_gqa,
826
+ sm_margin,
827
+ )
828
+ return scheduler_metadata
build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21b44e8e5e447a8b8ee051d347f0e32a3446a750f79d0bd1755e553f2119aa3b
3
+ size 838459656
build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12d4ff964085fd02252777a2008f5ca47c90ea6a93da590e2fc5065dd5330207
3
+ size 838459656
build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_557701f
3
+ ops = torch.ops._flash_attn3_557701f
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_557701f::{op_name}"
build/torch26-cxx11-cu126-x86_64-linux/flash_attn3/flash_attn_interface.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+
10
+ def maybe_contiguous(x):
11
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
12
+
13
+
14
+ def _flash_attn_forward(
15
+ q,
16
+ k,
17
+ v,
18
+ k_new,
19
+ v_new,
20
+ qv,
21
+ out,
22
+ cu_seqlens_q,
23
+ cu_seqlens_k,
24
+ cu_seqlens_k_new,
25
+ seqused_q,
26
+ seqused_k,
27
+ max_seqlen_q,
28
+ max_seqlen_k,
29
+ page_table,
30
+ kv_batch_idx,
31
+ leftpad_k,
32
+ rotary_cos,
33
+ rotary_sin,
34
+ seqlens_rotary,
35
+ q_descale,
36
+ k_descale,
37
+ v_descale,
38
+ softmax_scale,
39
+ causal,
40
+ window_size=(-1, -1),
41
+ attention_chunk=0,
42
+ softcap=0.0,
43
+ rotary_interleaved=True,
44
+ scheduler_metadata=None,
45
+ num_splits=1,
46
+ pack_gqa=None,
47
+ sm_margin=0):
48
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
49
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
50
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
51
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
52
+ ]
53
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
54
+ page_table, kv_batch_idx, leftpad_k = [
55
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
56
+ ]
57
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
58
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
59
+ out, softmax_lse, *rest = flash_attn_3_cuda.fwd(
60
+ q,
61
+ k,
62
+ v,
63
+ k_new,
64
+ v_new,
65
+ qv,
66
+ out,
67
+ cu_seqlens_q,
68
+ cu_seqlens_k,
69
+ cu_seqlens_k_new,
70
+ seqused_q,
71
+ seqused_k,
72
+ max_seqlen_q,
73
+ max_seqlen_k,
74
+ page_table,
75
+ kv_batch_idx,
76
+ leftpad_k,
77
+ rotary_cos,
78
+ rotary_sin,
79
+ seqlens_rotary,
80
+ q_descale,
81
+ k_descale,
82
+ v_descale,
83
+ softmax_scale,
84
+ causal,
85
+ window_size[0],
86
+ window_size[1],
87
+ attention_chunk,
88
+ softcap,
89
+ rotary_interleaved,
90
+ scheduler_metadata,
91
+ num_splits,
92
+ pack_gqa,
93
+ sm_margin,
94
+ )
95
+ return out, softmax_lse, *rest
96
+
97
+
98
+ def _flash_attn_backward(
99
+ dout,
100
+ q,
101
+ k,
102
+ v,
103
+ out,
104
+ softmax_lse,
105
+ cu_seqlens_q,
106
+ cu_seqlens_k,
107
+ sequed_q,
108
+ sequed_k,
109
+ max_seqlen_q,
110
+ max_seqlen_k,
111
+ dq,
112
+ dk,
113
+ dv,
114
+ softmax_scale,
115
+ causal,
116
+ window_size=(-1, -1),
117
+ softcap=0.0,
118
+ deterministic=False,
119
+ sm_margin=0,
120
+ ):
121
+ # dq, dk, dv are allocated by us so they should already be contiguous
122
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
123
+ dq, dk, dv, softmax_d, *rest = flash_attn_3_cuda.bwd(
124
+ dout,
125
+ q,
126
+ k,
127
+ v,
128
+ out,
129
+ softmax_lse,
130
+ dq,
131
+ dk,
132
+ dv,
133
+ cu_seqlens_q,
134
+ cu_seqlens_k,
135
+ sequed_q,
136
+ sequed_k,
137
+ max_seqlen_q,
138
+ max_seqlen_k,
139
+ softmax_scale,
140
+ causal,
141
+ window_size[0],
142
+ window_size[1],
143
+ softcap,
144
+ deterministic,
145
+ sm_margin,
146
+ )
147
+ return dq, dk, dv, softmax_d
148
+
149
+
150
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
151
+ @staticmethod
152
+ def forward(
153
+ ctx,
154
+ qkv,
155
+ softmax_scale,
156
+ causal,
157
+ q_descale=None, k_descale=None, v_descale=None,
158
+ window_size=(-1, -1),
159
+ attention_chunk=0,
160
+ softcap=0.0,
161
+ deterministic=False,
162
+ num_heads_q=None,
163
+ sm_margin=0,
164
+ ):
165
+ if softmax_scale is None:
166
+ softmax_scale = qkv.shape[-1] ** (-0.5)
167
+ if qkv.dim() == 5:
168
+ assert qkv.shape[-3] == 3
169
+ q, k, v = qkv.unbind(dim=-3)
170
+ else:
171
+ assert qkv.dim() == 4
172
+ assert num_heads_q is not None
173
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
174
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
175
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
176
+ out, softmax_lse, *rest = _flash_attn_forward(
177
+ q,
178
+ k,
179
+ v,
180
+ None, None, # k_new, v_new
181
+ None, # qv
182
+ None, # out
183
+ None, None, None, # cu_seqlens_q/k/k_new
184
+ None, None, # seqused_q/k
185
+ None, None, # max_seqlen_q/k
186
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
187
+ None, None, None, # rotary_cos/sin, seqlens_rotary
188
+ q_descale, k_descale, v_descale,
189
+ softmax_scale,
190
+ causal=causal,
191
+ window_size=window_size,
192
+ attention_chunk=attention_chunk,
193
+ softcap=softcap,
194
+ sm_margin=sm_margin,
195
+ )
196
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
197
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
198
+ ctx.softmax_scale = softmax_scale
199
+ ctx.causal = causal
200
+ ctx.window_size = window_size
201
+ ctx.attention_chunk = attention_chunk
202
+ ctx.softcap = softcap
203
+ ctx.deterministic = deterministic
204
+ ctx.ndim = qkv.dim()
205
+ ctx.sm_margin = sm_margin
206
+ # return out, softmax_lse
207
+ return out
208
+
209
+ @staticmethod
210
+ def backward(ctx, dout, *args):
211
+ q, k, v, out, softmax_lse = ctx.saved_tensors
212
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
213
+ if ctx.ndim == 5:
214
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
215
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
216
+ dq, dk, dv = dqkv.unbind(dim=-3)
217
+ else:
218
+ num_heads_q = q.shape[2]
219
+ num_heads_k = k.shape[2]
220
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
221
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
222
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
223
+ _flash_attn_backward(
224
+ dout,
225
+ q,
226
+ k,
227
+ v,
228
+ out,
229
+ softmax_lse,
230
+ None, None, # cu_seqlens_q, cu_seqlens_k,
231
+ None, None, # sequed_q, sequed_k,
232
+ None, None, # max_seqlen_q, max_seqlen_k,
233
+ dq,
234
+ dk,
235
+ dv,
236
+ ctx.softmax_scale,
237
+ ctx.causal,
238
+ ctx.window_size,
239
+ ctx.softcap,
240
+ ctx.deterministic,
241
+ ctx.sm_margin,
242
+ )
243
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
244
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None
245
+
246
+
247
+ class FlashAttnFunc(torch.autograd.Function):
248
+
249
+ @staticmethod
250
+ def forward(
251
+ ctx,
252
+ q,
253
+ k,
254
+ v,
255
+ softmax_scale,
256
+ causal,
257
+ qv=None,
258
+ q_descale=None, k_descale=None, v_descale=None,
259
+ window_size=(-1, -1),
260
+ attention_chunk=0,
261
+ softcap=0.0,
262
+ num_splits=1,
263
+ pack_gqa=None,
264
+ deterministic=False,
265
+ sm_margin=0,
266
+ ):
267
+ if softmax_scale is None:
268
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
269
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
270
+ out, softmax_lse, *rest = _flash_attn_forward(
271
+ q,
272
+ k,
273
+ v,
274
+ None, None, # k_new, v_new
275
+ qv, # qv
276
+ None, # out
277
+ None, None, None, # cu_seqlens_q/k/k_new
278
+ None, None, # seqused_q/k
279
+ None, None, # max_seqlen_q/k
280
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
281
+ None, None, None, # rotary_cos/sin, seqlens_rotary
282
+ q_descale, k_descale, v_descale,
283
+ softmax_scale,
284
+ causal=causal,
285
+ window_size=window_size,
286
+ attention_chunk=attention_chunk,
287
+ softcap=softcap,
288
+ num_splits=num_splits,
289
+ pack_gqa=pack_gqa,
290
+ sm_margin=sm_margin,
291
+ )
292
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
293
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
294
+ ctx.softmax_scale = softmax_scale
295
+ ctx.causal = causal
296
+ ctx.window_size = window_size
297
+ ctx.attention_chunk = attention_chunk
298
+ ctx.softcap = softcap
299
+ ctx.deterministic = deterministic
300
+ ctx.sm_margin = sm_margin
301
+ return out, softmax_lse
302
+
303
+ @staticmethod
304
+ def backward(ctx, dout, *args):
305
+ q, k, v, out, softmax_lse = ctx.saved_tensors
306
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
307
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
308
+ _flash_attn_backward(
309
+ dout,
310
+ q,
311
+ k,
312
+ v,
313
+ out,
314
+ softmax_lse,
315
+ None, None, # cu_seqlens_q, cu_seqlens_k,
316
+ None, None, # sequed_q, sequed_k,
317
+ None, None, # max_seqlen_q, max_seqlen_k,
318
+ dq,
319
+ dk,
320
+ dv,
321
+ ctx.softmax_scale,
322
+ ctx.causal,
323
+ ctx.window_size,
324
+ ctx.softcap,
325
+ ctx.deterministic,
326
+ ctx.sm_margin,
327
+ )
328
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
329
+ dk = dk[..., : k.shape[-1]]
330
+ dv = dv[..., : v.shape[-1]]
331
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
332
+
333
+
334
+ class FlashAttnVarlenFunc(torch.autograd.Function):
335
+
336
+ @staticmethod
337
+ def forward(
338
+ ctx,
339
+ q,
340
+ k,
341
+ v,
342
+ cu_seqlens_q,
343
+ cu_seqlens_k,
344
+ seqused_q,
345
+ seqused_k,
346
+ max_seqlen_q,
347
+ max_seqlen_k,
348
+ softmax_scale,
349
+ causal,
350
+ qv=None,
351
+ q_descale=None, k_descale=None, v_descale=None,
352
+ window_size=(-1, -1),
353
+ attention_chunk=0,
354
+ softcap=0.0,
355
+ num_splits=1,
356
+ pack_gqa=None,
357
+ deterministic=False,
358
+ sm_margin=0,
359
+ ):
360
+ if softmax_scale is None:
361
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
362
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
363
+ out, softmax_lse, *rest = _flash_attn_forward(
364
+ q,
365
+ k,
366
+ v,
367
+ None, None, # k_new, v_new
368
+ qv, # qv
369
+ None, # out
370
+ cu_seqlens_q,
371
+ cu_seqlens_k,
372
+ None, # cu_seqlens_k_new
373
+ seqused_q,
374
+ seqused_k,
375
+ max_seqlen_q,
376
+ max_seqlen_k,
377
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
378
+ None, None, None, # rotary_cos/sin, seqlens_rotary
379
+ q_descale, k_descale, v_descale,
380
+ softmax_scale,
381
+ causal=causal,
382
+ window_size=window_size,
383
+ attention_chunk=attention_chunk,
384
+ softcap=softcap,
385
+ num_splits=num_splits,
386
+ pack_gqa=pack_gqa,
387
+ sm_margin=sm_margin,
388
+ )
389
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
390
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
391
+ ctx.max_seqlen_q = max_seqlen_q
392
+ ctx.max_seqlen_k = max_seqlen_k
393
+ ctx.softmax_scale = softmax_scale
394
+ ctx.causal = causal
395
+ ctx.window_size = window_size
396
+ ctx.attention_chunk = attention_chunk
397
+ ctx.softcap = softcap
398
+ ctx.deterministic = deterministic
399
+ ctx.sm_margin = sm_margin
400
+ return out, softmax_lse
401
+
402
+ @staticmethod
403
+ def backward(ctx, dout, *args):
404
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
405
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
406
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
407
+ _flash_attn_backward(
408
+ dout,
409
+ q,
410
+ k,
411
+ v,
412
+ out,
413
+ softmax_lse,
414
+ cu_seqlens_q,
415
+ cu_seqlens_k,
416
+ seqused_q,
417
+ seqused_k,
418
+ ctx.max_seqlen_q,
419
+ ctx.max_seqlen_k,
420
+ dq,
421
+ dk,
422
+ dv,
423
+ ctx.softmax_scale,
424
+ ctx.causal,
425
+ ctx.window_size,
426
+ ctx.softcap,
427
+ ctx.deterministic,
428
+ ctx.sm_margin,
429
+ )
430
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
431
+ dk = dk[..., : k.shape[-1]]
432
+ dv = dv[..., : v.shape[-1]]
433
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
434
+
435
+
436
+ def flash_attn_qkvpacked_func(
437
+ qkv,
438
+ softmax_scale=None,
439
+ causal=False,
440
+ q_descale=None, k_descale=None, v_descale=None,
441
+ window_size=(-1, -1),
442
+ attention_chunk=0,
443
+ softcap=0.0,
444
+ deterministic=False,
445
+ num_heads_q=None,
446
+ sm_margin=0,
447
+ ):
448
+ """dropout_p should be set to 0.0 during evaluation
449
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
450
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
451
+ of the gradients of Q, K, V.
452
+ For multi-query and grouped-query attention (MQA/GQA), please see
453
+ flash_attn_kvpacked_func and flash_attn_func.
454
+
455
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
456
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
457
+
458
+ Arguments:
459
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
460
+ dropout_p: float. Dropout probability.
461
+ softmax_scale: float. The scaling of QK^T before applying softmax.
462
+ Default to 1 / sqrt(headdim).
463
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
464
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
465
+ softcap: float. Anything > 0 activates softcapping attention.
466
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
467
+ the attention score of query i and key j.
468
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
469
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
470
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
471
+ testing only. The returned probabilities are not guaranteed to be correct
472
+ (they might not have the right scaling).
473
+ Return:
474
+ out: (batch_size, seqlen, nheads, headdim).
475
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
476
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
477
+ normalization factor).
478
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
479
+ The output of softmax (possibly with different scaling). It also encodes the dropout
480
+ pattern (negative means that location was dropped, nonnegative means it was kept).
481
+ """
482
+ return FlashAttnQKVPackedFunc.apply(
483
+ qkv,
484
+ softmax_scale,
485
+ causal,
486
+ q_descale, k_descale, v_descale,
487
+ window_size,
488
+ attention_chunk,
489
+ softcap,
490
+ deterministic,
491
+ num_heads_q,
492
+ sm_margin,
493
+ )
494
+
495
+
496
+ def flash_attn_func(
497
+ q,
498
+ k,
499
+ v,
500
+ softmax_scale=None,
501
+ causal=False,
502
+ qv=None,
503
+ q_descale=None, k_descale=None, v_descale=None,
504
+ window_size=(-1, -1),
505
+ attention_chunk=0,
506
+ softcap=0.0,
507
+ num_splits=1,
508
+ pack_gqa=None,
509
+ deterministic=False,
510
+ sm_margin=0,
511
+ ):
512
+ """dropout_p should be set to 0.0 during evaluation
513
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
514
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
515
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
516
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
517
+
518
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
519
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
520
+ 1 1 1 1 0
521
+ 1 1 1 1 1
522
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
523
+ 0 0
524
+ 0 0
525
+ 0 0
526
+ 1 0
527
+ 1 1
528
+ If the row of the mask is all zero, the output will be zero.
529
+
530
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
531
+ will only attend to keys between
532
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
533
+
534
+ Arguments:
535
+ q: (batch_size, seqlen, nheads, headdim)
536
+ k: (batch_size, seqlen, nheads_k, headdim)
537
+ v: (batch_size, seqlen, nheads_k, headdim)
538
+ dropout_p: float. Dropout probability.
539
+ softmax_scale: float. The scaling of QK^T before applying softmax.
540
+ Default to 1 / sqrt(headdim).
541
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
542
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
543
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
544
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
545
+ is added to the attention score of query i and key j.
546
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
547
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
548
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
549
+ testing only. The returned probabilities are not guaranteed to be correct
550
+ (they might not have the right scaling).
551
+ Return:
552
+ out: (batch_size, seqlen, nheads, headdim).
553
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
554
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
555
+ normalization factor).
556
+ """
557
+ return FlashAttnFunc.apply(
558
+ q,
559
+ k,
560
+ v,
561
+ softmax_scale,
562
+ causal,
563
+ qv,
564
+ q_descale, k_descale, v_descale,
565
+ window_size,
566
+ attention_chunk,
567
+ softcap,
568
+ num_splits,
569
+ pack_gqa,
570
+ deterministic,
571
+ sm_margin,
572
+ )
573
+
574
+
575
+ def flash_attn_varlen_func(
576
+ q,
577
+ k,
578
+ v,
579
+ cu_seqlens_q,
580
+ cu_seqlens_k,
581
+ max_seqlen_q,
582
+ max_seqlen_k,
583
+ seqused_q=None,
584
+ seqused_k=None,
585
+ softmax_scale=None,
586
+ causal=False,
587
+ qv=None,
588
+ q_descale=None, k_descale=None, v_descale=None,
589
+ window_size=(-1, -1),
590
+ attention_chunk=0,
591
+ softcap=0.0,
592
+ num_splits=1,
593
+ pack_gqa=None,
594
+ deterministic=False,
595
+ sm_margin=0,
596
+ ):
597
+ return FlashAttnVarlenFunc.apply(
598
+ q,
599
+ k,
600
+ v,
601
+ cu_seqlens_q,
602
+ cu_seqlens_k,
603
+ seqused_q,
604
+ seqused_k,
605
+ max_seqlen_q,
606
+ max_seqlen_k,
607
+ softmax_scale,
608
+ causal,
609
+ qv,
610
+ q_descale, k_descale, v_descale,
611
+ window_size,
612
+ attention_chunk,
613
+ softcap,
614
+ num_splits,
615
+ pack_gqa,
616
+ deterministic,
617
+ sm_margin,
618
+ )
619
+
620
+
621
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
622
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
623
+
624
+
625
+ def flash_attn_with_kvcache(
626
+ q,
627
+ k_cache,
628
+ v_cache,
629
+ k=None,
630
+ v=None,
631
+ qv=None,
632
+ rotary_cos=None,
633
+ rotary_sin=None,
634
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
635
+ cache_batch_idx: Optional[torch.Tensor] = None,
636
+ cache_leftpad: Optional[torch.Tensor] = None,
637
+ page_table: Optional[torch.Tensor] = None,
638
+ cu_seqlens_q: Optional[torch.Tensor] = None,
639
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
640
+ max_seqlen_q: Optional[int] = None,
641
+ rotary_seqlens: Optional[torch.Tensor] = None,
642
+ q_descale: Optional[torch.Tensor] = None,
643
+ k_descale: Optional[torch.Tensor] = None,
644
+ v_descale: Optional[torch.Tensor] = None,
645
+ softmax_scale=None,
646
+ causal=False,
647
+ window_size=(-1, -1), # -1 means infinite context window
648
+ attention_chunk=0,
649
+ softcap=0.0, # 0.0 means deactivated
650
+ rotary_interleaved=True,
651
+ scheduler_metadata=None,
652
+ num_splits=0, # Can be tuned for speed
653
+ pack_gqa=None, # Can be tuned for speed
654
+ sm_margin=0, # Can be tuned if some SMs are used for communication
655
+ return_softmax_lse=False,
656
+ ):
657
+ """
658
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
659
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
660
+ the previous step, and update them with the new keys/values from the current step, and do
661
+ attention with the updated cache, all in 1 kernel.
662
+
663
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
664
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
665
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
666
+
667
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
668
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
669
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
670
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
671
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
672
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
673
+
674
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
675
+
676
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
677
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
678
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
679
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
680
+
681
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
682
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
683
+ 1 1 1 1 0
684
+ 1 1 1 1 1
685
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
686
+ 0 0
687
+ 0 0
688
+ 0 0
689
+ 1 0
690
+ 1 1
691
+ If the row of the mask is all zero, the output will be zero.
692
+
693
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
694
+ will only attend to keys between
695
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
696
+
697
+ Note: Does not support backward pass.
698
+
699
+ Arguments:
700
+ q: (batch_size, seqlen, nheads, headdim)
701
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
702
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
703
+ page_block_size must be a multiple of 256.
704
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
705
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
706
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
707
+ k with k_cache, starting at the indices specified by cache_seqlens.
708
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
709
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
710
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
711
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
712
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
713
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
714
+ KV cache.
715
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
716
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
717
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
718
+ might come from any of the duplicate indices.
719
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
720
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
721
+ softmax_scale: float. The scaling of QK^T before applying softmax.
722
+ Default to 1 / sqrt(headdim).
723
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
724
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
725
+ softcap: float. Anything > 0 activates softcapping attention.
726
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
727
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
728
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
729
+ (i.e. GPT-NeoX style).
730
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
731
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
732
+ to automatically determine the number of splits.
733
+ Don't change this unless you know what you are doing.
734
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
735
+
736
+ Return:
737
+ out: (batch_size, seqlen, nheads, headdim).
738
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
739
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
740
+ normalization factor).
741
+ """
742
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
743
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
744
+ if softmax_scale is None:
745
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
746
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
747
+ cache_seqlens = torch.full(
748
+ (k_cache.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
749
+ )
750
+ cache_seqlens = maybe_contiguous(cache_seqlens)
751
+ out, softmax_lse, *rest = _flash_attn_forward(
752
+ q,
753
+ k_cache,
754
+ v_cache,
755
+ k,
756
+ v,
757
+ qv,
758
+ None, # out
759
+ cu_seqlens_q,
760
+ None, # cu_seqlens_k
761
+ cu_seqlens_k_new,
762
+ None, # seqused_q
763
+ cache_seqlens,
764
+ max_seqlen_q,
765
+ None, # max_seqlen_k
766
+ page_table,
767
+ cache_batch_idx,
768
+ cache_leftpad,
769
+ rotary_cos,
770
+ rotary_sin,
771
+ rotary_seqlens,
772
+ q_descale, k_descale, v_descale,
773
+ softmax_scale,
774
+ causal=causal,
775
+ window_size=window_size,
776
+ attention_chunk=attention_chunk,
777
+ softcap=softcap,
778
+ rotary_interleaved=rotary_interleaved,
779
+ scheduler_metadata=scheduler_metadata,
780
+ num_splits=num_splits,
781
+ pack_gqa=pack_gqa,
782
+ sm_margin=sm_margin,
783
+ )
784
+ # return (out, softmax_lse) if return_softmax_lse else out
785
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
786
+
787
+
788
+ def get_scheduler_metadata(
789
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
790
+ cache_seqlens: torch.Tensor,
791
+ qkv_dtype=torch.bfloat16,
792
+ headdim_v=None,
793
+ cu_seqlens_q: Optional[torch.Tensor] = None,
794
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
795
+ cache_leftpad: Optional[torch.Tensor] = None,
796
+ page_size: Optional[int] = None,
797
+ max_seqlen_k_new=0,
798
+ causal=False,
799
+ window_size=(-1, -1), # -1 means infinite context window
800
+ attention_chunk=0,
801
+ has_softcap=False,
802
+ num_splits=0, # Can be tuned for speed
803
+ pack_gqa=None, # Can be tuned for speed
804
+ sm_margin=0, # Can be tuned if some SMs are used for communication
805
+ ):
806
+ cache_seqlens = maybe_contiguous(cache_seqlens)
807
+ if headdim_v is None:
808
+ headdim_v = headdim
809
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
810
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
811
+ qkv_dtype,
812
+ cache_seqlens,
813
+ cu_seqlens_q,
814
+ None, # cu_seqlens_k
815
+ cu_seqlens_k_new,
816
+ None, # seqused_q
817
+ cache_leftpad,
818
+ page_size,
819
+ max_seqlen_k_new,
820
+ causal,
821
+ window_size[0], window_size[1],
822
+ attention_chunk,
823
+ has_softcap,
824
+ num_splits,
825
+ pack_gqa,
826
+ sm_margin,
827
+ )
828
+ return scheduler_metadata
build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9627e08ec8778d2a409a2a0477572edb3e03eaca2b45e7b4810ee0a9126d6547
3
+ size 838456048
build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07fe025ba95671f6ff957991f74c66063bfb10ab6737641c88f88116c9f83718
3
+ size 838456048
build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from . import _flash_attn3_557701f
3
+ ops = torch.ops._flash_attn3_557701f
4
+
5
+ def add_op_namespace_prefix(op_name: str):
6
+ """
7
+ Prefix op by namespace.
8
+ """
9
+ return f"_flash_attn3_557701f::{op_name}"
build/torch26-cxx98-cu124-x86_64-linux/flash_attn3/flash_attn_interface.py ADDED
@@ -0,0 +1,828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from ._ops import ops as flash_attn_3_cuda
9
+
10
+ def maybe_contiguous(x):
11
+ return x.contiguous() if x is not None and x.stride(-1) != 1 else x
12
+
13
+
14
+ def _flash_attn_forward(
15
+ q,
16
+ k,
17
+ v,
18
+ k_new,
19
+ v_new,
20
+ qv,
21
+ out,
22
+ cu_seqlens_q,
23
+ cu_seqlens_k,
24
+ cu_seqlens_k_new,
25
+ seqused_q,
26
+ seqused_k,
27
+ max_seqlen_q,
28
+ max_seqlen_k,
29
+ page_table,
30
+ kv_batch_idx,
31
+ leftpad_k,
32
+ rotary_cos,
33
+ rotary_sin,
34
+ seqlens_rotary,
35
+ q_descale,
36
+ k_descale,
37
+ v_descale,
38
+ softmax_scale,
39
+ causal,
40
+ window_size=(-1, -1),
41
+ attention_chunk=0,
42
+ softcap=0.0,
43
+ rotary_interleaved=True,
44
+ scheduler_metadata=None,
45
+ num_splits=1,
46
+ pack_gqa=None,
47
+ sm_margin=0):
48
+ q, k, k_new, v_new = [maybe_contiguous(x) for x in (q, k, k_new, v_new)]
49
+ v = v.contiguous() if v.stride(-1) != 1 and v.stride(-3) != 1 else v
50
+ cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new = [
51
+ maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new)
52
+ ]
53
+ seqused_q, seqused_k = [maybe_contiguous(x) for x in (seqused_q, seqused_k)]
54
+ page_table, kv_batch_idx, leftpad_k = [
55
+ maybe_contiguous(x) for x in (page_table, kv_batch_idx, leftpad_k)
56
+ ]
57
+ rotary_cos, rotary_sin = [maybe_contiguous(x) for x in (rotary_cos, rotary_sin)]
58
+ seqlens_rotary = maybe_contiguous(seqlens_rotary)
59
+ out, softmax_lse, *rest = flash_attn_3_cuda.fwd(
60
+ q,
61
+ k,
62
+ v,
63
+ k_new,
64
+ v_new,
65
+ qv,
66
+ out,
67
+ cu_seqlens_q,
68
+ cu_seqlens_k,
69
+ cu_seqlens_k_new,
70
+ seqused_q,
71
+ seqused_k,
72
+ max_seqlen_q,
73
+ max_seqlen_k,
74
+ page_table,
75
+ kv_batch_idx,
76
+ leftpad_k,
77
+ rotary_cos,
78
+ rotary_sin,
79
+ seqlens_rotary,
80
+ q_descale,
81
+ k_descale,
82
+ v_descale,
83
+ softmax_scale,
84
+ causal,
85
+ window_size[0],
86
+ window_size[1],
87
+ attention_chunk,
88
+ softcap,
89
+ rotary_interleaved,
90
+ scheduler_metadata,
91
+ num_splits,
92
+ pack_gqa,
93
+ sm_margin,
94
+ )
95
+ return out, softmax_lse, *rest
96
+
97
+
98
+ def _flash_attn_backward(
99
+ dout,
100
+ q,
101
+ k,
102
+ v,
103
+ out,
104
+ softmax_lse,
105
+ cu_seqlens_q,
106
+ cu_seqlens_k,
107
+ sequed_q,
108
+ sequed_k,
109
+ max_seqlen_q,
110
+ max_seqlen_k,
111
+ dq,
112
+ dk,
113
+ dv,
114
+ softmax_scale,
115
+ causal,
116
+ window_size=(-1, -1),
117
+ softcap=0.0,
118
+ deterministic=False,
119
+ sm_margin=0,
120
+ ):
121
+ # dq, dk, dv are allocated by us so they should already be contiguous
122
+ dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)]
123
+ dq, dk, dv, softmax_d, *rest = flash_attn_3_cuda.bwd(
124
+ dout,
125
+ q,
126
+ k,
127
+ v,
128
+ out,
129
+ softmax_lse,
130
+ dq,
131
+ dk,
132
+ dv,
133
+ cu_seqlens_q,
134
+ cu_seqlens_k,
135
+ sequed_q,
136
+ sequed_k,
137
+ max_seqlen_q,
138
+ max_seqlen_k,
139
+ softmax_scale,
140
+ causal,
141
+ window_size[0],
142
+ window_size[1],
143
+ softcap,
144
+ deterministic,
145
+ sm_margin,
146
+ )
147
+ return dq, dk, dv, softmax_d
148
+
149
+
150
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
151
+ @staticmethod
152
+ def forward(
153
+ ctx,
154
+ qkv,
155
+ softmax_scale,
156
+ causal,
157
+ q_descale=None, k_descale=None, v_descale=None,
158
+ window_size=(-1, -1),
159
+ attention_chunk=0,
160
+ softcap=0.0,
161
+ deterministic=False,
162
+ num_heads_q=None,
163
+ sm_margin=0,
164
+ ):
165
+ if softmax_scale is None:
166
+ softmax_scale = qkv.shape[-1] ** (-0.5)
167
+ if qkv.dim() == 5:
168
+ assert qkv.shape[-3] == 3
169
+ q, k, v = qkv.unbind(dim=-3)
170
+ else:
171
+ assert qkv.dim() == 4
172
+ assert num_heads_q is not None
173
+ num_heads_k = (qkv.shape[2] - num_heads_q) // 2
174
+ assert num_heads_k * 2 + num_heads_q == qkv.shape[2]
175
+ q, k, v = qkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
176
+ out, softmax_lse, *rest = _flash_attn_forward(
177
+ q,
178
+ k,
179
+ v,
180
+ None, None, # k_new, v_new
181
+ None, # qv
182
+ None, # out
183
+ None, None, None, # cu_seqlens_q/k/k_new
184
+ None, None, # seqused_q/k
185
+ None, None, # max_seqlen_q/k
186
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
187
+ None, None, None, # rotary_cos/sin, seqlens_rotary
188
+ q_descale, k_descale, v_descale,
189
+ softmax_scale,
190
+ causal=causal,
191
+ window_size=window_size,
192
+ attention_chunk=attention_chunk,
193
+ softcap=softcap,
194
+ sm_margin=sm_margin,
195
+ )
196
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
197
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
198
+ ctx.softmax_scale = softmax_scale
199
+ ctx.causal = causal
200
+ ctx.window_size = window_size
201
+ ctx.attention_chunk = attention_chunk
202
+ ctx.softcap = softcap
203
+ ctx.deterministic = deterministic
204
+ ctx.ndim = qkv.dim()
205
+ ctx.sm_margin = sm_margin
206
+ # return out, softmax_lse
207
+ return out
208
+
209
+ @staticmethod
210
+ def backward(ctx, dout, *args):
211
+ q, k, v, out, softmax_lse = ctx.saved_tensors
212
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
213
+ if ctx.ndim == 5:
214
+ qkv_shape = q.shape[:-2] + (3, *q.shape[-2:])
215
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
216
+ dq, dk, dv = dqkv.unbind(dim=-3)
217
+ else:
218
+ num_heads_q = q.shape[2]
219
+ num_heads_k = k.shape[2]
220
+ qkv_shape = q.shape[:-2] + (num_heads_q + num_heads_k * 2, *q.shape[-1:])
221
+ dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device)
222
+ dq, dk, dv = dqkv.split([num_heads_q, num_heads_k, num_heads_k], dim=-2)
223
+ _flash_attn_backward(
224
+ dout,
225
+ q,
226
+ k,
227
+ v,
228
+ out,
229
+ softmax_lse,
230
+ None, None, # cu_seqlens_q, cu_seqlens_k,
231
+ None, None, # sequed_q, sequed_k,
232
+ None, None, # max_seqlen_q, max_seqlen_k,
233
+ dq,
234
+ dk,
235
+ dv,
236
+ ctx.softmax_scale,
237
+ ctx.causal,
238
+ ctx.window_size,
239
+ ctx.softcap,
240
+ ctx.deterministic,
241
+ ctx.sm_margin,
242
+ )
243
+ dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension
244
+ return dqkv, None, None, None, None, None, None, None, None, None, None, None
245
+
246
+
247
+ class FlashAttnFunc(torch.autograd.Function):
248
+
249
+ @staticmethod
250
+ def forward(
251
+ ctx,
252
+ q,
253
+ k,
254
+ v,
255
+ softmax_scale,
256
+ causal,
257
+ qv=None,
258
+ q_descale=None, k_descale=None, v_descale=None,
259
+ window_size=(-1, -1),
260
+ attention_chunk=0,
261
+ softcap=0.0,
262
+ num_splits=1,
263
+ pack_gqa=None,
264
+ deterministic=False,
265
+ sm_margin=0,
266
+ ):
267
+ if softmax_scale is None:
268
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
269
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_forward(
270
+ out, softmax_lse, *rest = _flash_attn_forward(
271
+ q,
272
+ k,
273
+ v,
274
+ None, None, # k_new, v_new
275
+ qv, # qv
276
+ None, # out
277
+ None, None, None, # cu_seqlens_q/k/k_new
278
+ None, None, # seqused_q/k
279
+ None, None, # max_seqlen_q/k
280
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
281
+ None, None, None, # rotary_cos/sin, seqlens_rotary
282
+ q_descale, k_descale, v_descale,
283
+ softmax_scale,
284
+ causal=causal,
285
+ window_size=window_size,
286
+ attention_chunk=attention_chunk,
287
+ softcap=softcap,
288
+ num_splits=num_splits,
289
+ pack_gqa=pack_gqa,
290
+ sm_margin=sm_margin,
291
+ )
292
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse)
293
+ ctx.save_for_backward(q, k, v, out, softmax_lse)
294
+ ctx.softmax_scale = softmax_scale
295
+ ctx.causal = causal
296
+ ctx.window_size = window_size
297
+ ctx.attention_chunk = attention_chunk
298
+ ctx.softcap = softcap
299
+ ctx.deterministic = deterministic
300
+ ctx.sm_margin = sm_margin
301
+ return out, softmax_lse
302
+
303
+ @staticmethod
304
+ def backward(ctx, dout, *args):
305
+ q, k, v, out, softmax_lse = ctx.saved_tensors
306
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
307
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
308
+ _flash_attn_backward(
309
+ dout,
310
+ q,
311
+ k,
312
+ v,
313
+ out,
314
+ softmax_lse,
315
+ None, None, # cu_seqlens_q, cu_seqlens_k,
316
+ None, None, # sequed_q, sequed_k,
317
+ None, None, # max_seqlen_q, max_seqlen_k,
318
+ dq,
319
+ dk,
320
+ dv,
321
+ ctx.softmax_scale,
322
+ ctx.causal,
323
+ ctx.window_size,
324
+ ctx.softcap,
325
+ ctx.deterministic,
326
+ ctx.sm_margin,
327
+ )
328
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
329
+ dk = dk[..., : k.shape[-1]]
330
+ dv = dv[..., : v.shape[-1]]
331
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None
332
+
333
+
334
+ class FlashAttnVarlenFunc(torch.autograd.Function):
335
+
336
+ @staticmethod
337
+ def forward(
338
+ ctx,
339
+ q,
340
+ k,
341
+ v,
342
+ cu_seqlens_q,
343
+ cu_seqlens_k,
344
+ seqused_q,
345
+ seqused_k,
346
+ max_seqlen_q,
347
+ max_seqlen_k,
348
+ softmax_scale,
349
+ causal,
350
+ qv=None,
351
+ q_descale=None, k_descale=None, v_descale=None,
352
+ window_size=(-1, -1),
353
+ attention_chunk=0,
354
+ softcap=0.0,
355
+ num_splits=1,
356
+ pack_gqa=None,
357
+ deterministic=False,
358
+ sm_margin=0,
359
+ ):
360
+ if softmax_scale is None:
361
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
362
+ # out, q, k, v, out_padded, softmax_lse = _flash_attn_varlen_forward(
363
+ out, softmax_lse, *rest = _flash_attn_forward(
364
+ q,
365
+ k,
366
+ v,
367
+ None, None, # k_new, v_new
368
+ qv, # qv
369
+ None, # out
370
+ cu_seqlens_q,
371
+ cu_seqlens_k,
372
+ None, # cu_seqlens_k_new
373
+ seqused_q,
374
+ seqused_k,
375
+ max_seqlen_q,
376
+ max_seqlen_k,
377
+ None, None, None, # page_table, kv_batch_idx, leftpad_k,
378
+ None, None, None, # rotary_cos/sin, seqlens_rotary
379
+ q_descale, k_descale, v_descale,
380
+ softmax_scale,
381
+ causal=causal,
382
+ window_size=window_size,
383
+ attention_chunk=attention_chunk,
384
+ softcap=softcap,
385
+ num_splits=num_splits,
386
+ pack_gqa=pack_gqa,
387
+ sm_margin=sm_margin,
388
+ )
389
+ # ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
390
+ ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k)
391
+ ctx.max_seqlen_q = max_seqlen_q
392
+ ctx.max_seqlen_k = max_seqlen_k
393
+ ctx.softmax_scale = softmax_scale
394
+ ctx.causal = causal
395
+ ctx.window_size = window_size
396
+ ctx.attention_chunk = attention_chunk
397
+ ctx.softcap = softcap
398
+ ctx.deterministic = deterministic
399
+ ctx.sm_margin = sm_margin
400
+ return out, softmax_lse
401
+
402
+ @staticmethod
403
+ def backward(ctx, dout, *args):
404
+ q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, seqused_q, seqused_k = ctx.saved_tensors
405
+ assert ctx.attention_chunk == 0, "FA3 backward does not support attention_chunk"
406
+ dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
407
+ _flash_attn_backward(
408
+ dout,
409
+ q,
410
+ k,
411
+ v,
412
+ out,
413
+ softmax_lse,
414
+ cu_seqlens_q,
415
+ cu_seqlens_k,
416
+ seqused_q,
417
+ seqused_k,
418
+ ctx.max_seqlen_q,
419
+ ctx.max_seqlen_k,
420
+ dq,
421
+ dk,
422
+ dv,
423
+ ctx.softmax_scale,
424
+ ctx.causal,
425
+ ctx.window_size,
426
+ ctx.softcap,
427
+ ctx.deterministic,
428
+ ctx.sm_margin,
429
+ )
430
+ dq = dq[..., : q.shape[-1]] # We could have padded the head dimension
431
+ dk = dk[..., : k.shape[-1]]
432
+ dv = dv[..., : v.shape[-1]]
433
+ return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
434
+
435
+
436
+ def flash_attn_qkvpacked_func(
437
+ qkv,
438
+ softmax_scale=None,
439
+ causal=False,
440
+ q_descale=None, k_descale=None, v_descale=None,
441
+ window_size=(-1, -1),
442
+ attention_chunk=0,
443
+ softcap=0.0,
444
+ deterministic=False,
445
+ num_heads_q=None,
446
+ sm_margin=0,
447
+ ):
448
+ """dropout_p should be set to 0.0 during evaluation
449
+ If Q, K, V are already stacked into 1 tensor, this function will be faster than
450
+ calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
451
+ of the gradients of Q, K, V.
452
+ For multi-query and grouped-query attention (MQA/GQA), please see
453
+ flash_attn_kvpacked_func and flash_attn_func.
454
+
455
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
456
+ will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive.
457
+
458
+ Arguments:
459
+ qkv: (batch_size, seqlen, 3, nheads, headdim)
460
+ dropout_p: float. Dropout probability.
461
+ softmax_scale: float. The scaling of QK^T before applying softmax.
462
+ Default to 1 / sqrt(headdim).
463
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
464
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
465
+ softcap: float. Anything > 0 activates softcapping attention.
466
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to
467
+ the attention score of query i and key j.
468
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
469
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
470
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
471
+ testing only. The returned probabilities are not guaranteed to be correct
472
+ (they might not have the right scaling).
473
+ Return:
474
+ out: (batch_size, seqlen, nheads, headdim).
475
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
476
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
477
+ normalization factor).
478
+ S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
479
+ The output of softmax (possibly with different scaling). It also encodes the dropout
480
+ pattern (negative means that location was dropped, nonnegative means it was kept).
481
+ """
482
+ return FlashAttnQKVPackedFunc.apply(
483
+ qkv,
484
+ softmax_scale,
485
+ causal,
486
+ q_descale, k_descale, v_descale,
487
+ window_size,
488
+ attention_chunk,
489
+ softcap,
490
+ deterministic,
491
+ num_heads_q,
492
+ sm_margin,
493
+ )
494
+
495
+
496
+ def flash_attn_func(
497
+ q,
498
+ k,
499
+ v,
500
+ softmax_scale=None,
501
+ causal=False,
502
+ qv=None,
503
+ q_descale=None, k_descale=None, v_descale=None,
504
+ window_size=(-1, -1),
505
+ attention_chunk=0,
506
+ softcap=0.0,
507
+ num_splits=1,
508
+ pack_gqa=None,
509
+ deterministic=False,
510
+ sm_margin=0,
511
+ ):
512
+ """dropout_p should be set to 0.0 during evaluation
513
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
514
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
515
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
516
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
517
+
518
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
519
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
520
+ 1 1 1 1 0
521
+ 1 1 1 1 1
522
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
523
+ 0 0
524
+ 0 0
525
+ 0 0
526
+ 1 0
527
+ 1 1
528
+ If the row of the mask is all zero, the output will be zero.
529
+
530
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
531
+ will only attend to keys between
532
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
533
+
534
+ Arguments:
535
+ q: (batch_size, seqlen, nheads, headdim)
536
+ k: (batch_size, seqlen, nheads_k, headdim)
537
+ v: (batch_size, seqlen, nheads_k, headdim)
538
+ dropout_p: float. Dropout probability.
539
+ softmax_scale: float. The scaling of QK^T before applying softmax.
540
+ Default to 1 / sqrt(headdim).
541
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
542
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
543
+ alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of
544
+ (-alibi_slope * |i + seqlen_k - seqlen_q - j|)
545
+ is added to the attention score of query i and key j.
546
+ deterministic: bool. Whether to use the deterministic implementation of the backward pass,
547
+ which is slightly slower and uses more memory. The forward pass is always deterministic.
548
+ return_attn_probs: bool. Whether to return the attention probabilities. This option is for
549
+ testing only. The returned probabilities are not guaranteed to be correct
550
+ (they might not have the right scaling).
551
+ Return:
552
+ out: (batch_size, seqlen, nheads, headdim).
553
+ softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
554
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
555
+ normalization factor).
556
+ """
557
+ return FlashAttnFunc.apply(
558
+ q,
559
+ k,
560
+ v,
561
+ softmax_scale,
562
+ causal,
563
+ qv,
564
+ q_descale, k_descale, v_descale,
565
+ window_size,
566
+ attention_chunk,
567
+ softcap,
568
+ num_splits,
569
+ pack_gqa,
570
+ deterministic,
571
+ sm_margin,
572
+ )
573
+
574
+
575
+ def flash_attn_varlen_func(
576
+ q,
577
+ k,
578
+ v,
579
+ cu_seqlens_q,
580
+ cu_seqlens_k,
581
+ max_seqlen_q,
582
+ max_seqlen_k,
583
+ seqused_q=None,
584
+ seqused_k=None,
585
+ softmax_scale=None,
586
+ causal=False,
587
+ qv=None,
588
+ q_descale=None, k_descale=None, v_descale=None,
589
+ window_size=(-1, -1),
590
+ attention_chunk=0,
591
+ softcap=0.0,
592
+ num_splits=1,
593
+ pack_gqa=None,
594
+ deterministic=False,
595
+ sm_margin=0,
596
+ ):
597
+ return FlashAttnVarlenFunc.apply(
598
+ q,
599
+ k,
600
+ v,
601
+ cu_seqlens_q,
602
+ cu_seqlens_k,
603
+ seqused_q,
604
+ seqused_k,
605
+ max_seqlen_q,
606
+ max_seqlen_k,
607
+ softmax_scale,
608
+ causal,
609
+ qv,
610
+ q_descale, k_descale, v_descale,
611
+ window_size,
612
+ attention_chunk,
613
+ softcap,
614
+ num_splits,
615
+ pack_gqa,
616
+ deterministic,
617
+ sm_margin,
618
+ )
619
+
620
+
621
+ def flash_attn_combine(out_partial, lse_partial, out=None, out_dtype=None):
622
+ return flash_attn_3_cuda.fwd_combine(out_partial, lse_partial, out, out_dtype)
623
+
624
+
625
+ def flash_attn_with_kvcache(
626
+ q,
627
+ k_cache,
628
+ v_cache,
629
+ k=None,
630
+ v=None,
631
+ qv=None,
632
+ rotary_cos=None,
633
+ rotary_sin=None,
634
+ cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None,
635
+ cache_batch_idx: Optional[torch.Tensor] = None,
636
+ cache_leftpad: Optional[torch.Tensor] = None,
637
+ page_table: Optional[torch.Tensor] = None,
638
+ cu_seqlens_q: Optional[torch.Tensor] = None,
639
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
640
+ max_seqlen_q: Optional[int] = None,
641
+ rotary_seqlens: Optional[torch.Tensor] = None,
642
+ q_descale: Optional[torch.Tensor] = None,
643
+ k_descale: Optional[torch.Tensor] = None,
644
+ v_descale: Optional[torch.Tensor] = None,
645
+ softmax_scale=None,
646
+ causal=False,
647
+ window_size=(-1, -1), # -1 means infinite context window
648
+ attention_chunk=0,
649
+ softcap=0.0, # 0.0 means deactivated
650
+ rotary_interleaved=True,
651
+ scheduler_metadata=None,
652
+ num_splits=0, # Can be tuned for speed
653
+ pack_gqa=None, # Can be tuned for speed
654
+ sm_margin=0, # Can be tuned if some SMs are used for communication
655
+ return_softmax_lse=False,
656
+ ):
657
+ """
658
+ If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from
659
+ k and v. This is useful for incremental decoding: you can pass in the cached keys/values from
660
+ the previous step, and update them with the new keys/values from the current step, and do
661
+ attention with the updated cache, all in 1 kernel.
662
+
663
+ If you pass in k / v, you must make sure that the cache is large enough to hold the new values.
664
+ For example, the KV cache could be pre-allocated with the max sequence length, and you can use
665
+ cache_seqlens to keep track of the current sequence lengths of each sequence in the batch.
666
+
667
+ Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be
668
+ rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
669
+ If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos
670
+ and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc.
671
+ If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at
672
+ indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens).
673
+
674
+ See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function.
675
+
676
+ Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
677
+ than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
678
+ For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
679
+ 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
680
+
681
+ If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix.
682
+ For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is:
683
+ 1 1 1 1 0
684
+ 1 1 1 1 1
685
+ If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
686
+ 0 0
687
+ 0 0
688
+ 0 0
689
+ 1 0
690
+ 1 1
691
+ If the row of the mask is all zero, the output will be zero.
692
+
693
+ If window_size != (-1, -1), implements sliding window local attention. Query at position i
694
+ will only attend to keys between
695
+ [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
696
+
697
+ Note: Does not support backward pass.
698
+
699
+ Arguments:
700
+ q: (batch_size, seqlen, nheads, headdim)
701
+ k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no page_table,
702
+ or (num_blocks, page_block_size, nheads_k, headdim) if there's a page_table (i.e. paged KV cache)
703
+ page_block_size must be a multiple of 256.
704
+ v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim_v) if there's no page_table,
705
+ or (num_blocks, page_block_size, nheads_k, headdim_v) if there's a page_table (i.e. paged KV cache)
706
+ k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate
707
+ k with k_cache, starting at the indices specified by cache_seqlens.
708
+ v [optional]: (batch_size, seqlen_new, nheads_k, headdim_v). Similar to k.
709
+ qv [optional]: (batch_size, seqlen, nheads, headdim_v)
710
+ rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding
711
+ to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16.
712
+ rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos.
713
+ cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the
714
+ KV cache.
715
+ cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache.
716
+ If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1].
717
+ If the indices are not distinct, and k and v are provided, the values updated in the cache
718
+ might come from any of the duplicate indices.
719
+ cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0.
720
+ page_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32.
721
+ softmax_scale: float. The scaling of QK^T before applying softmax.
722
+ Default to 1 / sqrt(headdim).
723
+ causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
724
+ window_size: (left, right). If not (-1, -1), implements sliding window local attention.
725
+ softcap: float. Anything > 0 activates softcapping attention.
726
+ rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in.
727
+ If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False,
728
+ rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1
729
+ (i.e. GPT-NeoX style).
730
+ num_splits: int. If > 1, split the key/value into this many chunks along the sequence.
731
+ If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic
732
+ to automatically determine the number of splits.
733
+ Don't change this unless you know what you are doing.
734
+ return_softmax_lse: bool. Whether to return the logsumexp of the attention scores.
735
+
736
+ Return:
737
+ out: (batch_size, seqlen, nheads, headdim).
738
+ softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The
739
+ logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
740
+ normalization factor).
741
+ """
742
+ assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension"
743
+ assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension"
744
+ if softmax_scale is None:
745
+ softmax_scale = (q.shape[-1] + (qv.shape[-1] if qv is not None else 0)) ** (-0.5)
746
+ if cache_seqlens is not None and isinstance(cache_seqlens, int):
747
+ cache_seqlens = torch.full(
748
+ (k_cache.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device
749
+ )
750
+ cache_seqlens = maybe_contiguous(cache_seqlens)
751
+ out, softmax_lse, *rest = _flash_attn_forward(
752
+ q,
753
+ k_cache,
754
+ v_cache,
755
+ k,
756
+ v,
757
+ qv,
758
+ None, # out
759
+ cu_seqlens_q,
760
+ None, # cu_seqlens_k
761
+ cu_seqlens_k_new,
762
+ None, # seqused_q
763
+ cache_seqlens,
764
+ max_seqlen_q,
765
+ None, # max_seqlen_k
766
+ page_table,
767
+ cache_batch_idx,
768
+ cache_leftpad,
769
+ rotary_cos,
770
+ rotary_sin,
771
+ rotary_seqlens,
772
+ q_descale, k_descale, v_descale,
773
+ softmax_scale,
774
+ causal=causal,
775
+ window_size=window_size,
776
+ attention_chunk=attention_chunk,
777
+ softcap=softcap,
778
+ rotary_interleaved=rotary_interleaved,
779
+ scheduler_metadata=scheduler_metadata,
780
+ num_splits=num_splits,
781
+ pack_gqa=pack_gqa,
782
+ sm_margin=sm_margin,
783
+ )
784
+ # return (out, softmax_lse) if return_softmax_lse else out
785
+ return (out, softmax_lse, *rest) if return_softmax_lse else out
786
+
787
+
788
+ def get_scheduler_metadata(
789
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim,
790
+ cache_seqlens: torch.Tensor,
791
+ qkv_dtype=torch.bfloat16,
792
+ headdim_v=None,
793
+ cu_seqlens_q: Optional[torch.Tensor] = None,
794
+ cu_seqlens_k_new: Optional[torch.Tensor] = None,
795
+ cache_leftpad: Optional[torch.Tensor] = None,
796
+ page_size: Optional[int] = None,
797
+ max_seqlen_k_new=0,
798
+ causal=False,
799
+ window_size=(-1, -1), # -1 means infinite context window
800
+ attention_chunk=0,
801
+ has_softcap=False,
802
+ num_splits=0, # Can be tuned for speed
803
+ pack_gqa=None, # Can be tuned for speed
804
+ sm_margin=0, # Can be tuned if some SMs are used for communication
805
+ ):
806
+ cache_seqlens = maybe_contiguous(cache_seqlens)
807
+ if headdim_v is None:
808
+ headdim_v = headdim
809
+ scheduler_metadata = flash_attn_3_cuda.get_scheduler_metadata(
810
+ batch_size, max_seqlen_q, max_seqlen_k, num_heads_q, num_heads_kv, headdim, headdim_v,
811
+ qkv_dtype,
812
+ cache_seqlens,
813
+ cu_seqlens_q,
814
+ None, # cu_seqlens_k
815
+ cu_seqlens_k_new,
816
+ None, # seqused_q
817
+ cache_leftpad,
818
+ page_size,
819
+ max_seqlen_k_new,
820
+ causal,
821
+ window_size[0], window_size[1],
822
+ attention_chunk,
823
+ has_softcap,
824
+ num_splits,
825
+ pack_gqa,
826
+ sm_margin,
827
+ )
828
+ return scheduler_metadata
build/torch26-cxx98-cu126-x86_64-linux/flash_attn3/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .flash_attn_interface import (
2
+ flash_attn_combine,
3
+ flash_attn_func,
4
+ flash_attn_qkvpacked_func,
5
+ flash_attn_varlen_func,
6
+ flash_attn_with_kvcache,
7
+ get_scheduler_metadata,
8
+ )
9
+
10
+ __all__ = [
11
+ "flash_attn_combine",
12
+ "flash_attn_func",
13
+ "flash_attn_qkvpacked_func",
14
+ "flash_attn_varlen_func",
15
+ "flash_attn_with_kvcache",
16
+ "get_scheduler_metadata",
17
+ ]
build/torch26-cxx98-cu126-x86_64-linux/flash_attn3/_flash_attn3_2e75662.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9627e08ec8778d2a409a2a0477572edb3e03eaca2b45e7b4810ee0a9126d6547
3
+ size 838456048
build/torch26-cxx98-cu126-x86_64-linux/flash_attn3/_flash_attn3_557701f.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07fe025ba95671f6ff957991f74c66063bfb10ab6737641c88f88116c9f83718
3
+ size 838456048