flex_attention.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. # mypy: allow-untyped-defs
  2. # flake8: noqa: B950
  3. """This module implements the user facing API for flex_attention in PyTorch."""
  4. import functools
  5. import inspect
  6. import itertools
  7. import math
  8. import operator
  9. import warnings
  10. from enum import Enum
  11. from typing import Any, Callable, NamedTuple, Optional, Union
  12. import torch
  13. from torch import Tensor
  14. try:
  15. from typing import TypedDict
  16. except ImportError:
  17. from typing_extensions import TypedDict
  18. try:
  19. from typing import NotRequired
  20. except ImportError:
  21. from typing_extensions import NotRequired
  22. from torch._higher_order_ops.flex_attention import flex_attention as flex_attention_hop
  23. from torch._higher_order_ops.utils import _set_compilation_env
  24. from torch._prims_common import DeviceLikeType
  25. from torch.fx.experimental.proxy_tensor import (
  26. _temp_remove_metadata_torch_function_mode,
  27. _temp_remove_pre_dispatch_torch_function_mode,
  28. )
  29. from torch.nn.attention._utils import _validate_sdpa_input
  30. from torch.utils._pytree import tree_map_only
  31. # Private debug flag to disable internal compilation wrapping for debugging purposes.
  32. # WARNING: This is intended ONLY for debugging score_mod and mask_mod functions.
  33. # When enabled, this bypasses the required internal compilation that ensures correctness
  34. # and performance. Only use this temporarily when you need to set breakpoints
  35. # in your score_mod/mask_mod functions during development.
  36. #
  37. # This flag only affects the internal compilation when flex_attention is called directly.
  38. # If you have already wrapped flex_attention in torch.compile(), this flag has no effect
  39. # and the user's compilation will still occur.
  40. #
  41. # Usage:
  42. # import torch.nn.attention.flex_attention as fa
  43. # fa._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True
  44. # # Now you can set breakpoints in your score_mod/mask_mod
  45. # output = fa.flex_attention(q, k, v, score_mod=my_score_mod)
  46. #
  47. _FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = False
  48. _WARNINGS_SHOWN: set[str] = set()
  49. def _warn_once(
  50. warning_id: str, message: str, category: type[Warning] = UserWarning
  51. ) -> None:
  52. """Helper to ensure each warning is shown only once per process."""
  53. if warning_id not in _WARNINGS_SHOWN:
  54. warnings.warn(message, category, stacklevel=2)
  55. _WARNINGS_SHOWN.add(warning_id)
  56. __all__ = [
  57. "BlockMask",
  58. "flex_attention",
  59. "AuxOutput",
  60. "AuxRequest",
  61. "FlexKernelOptions",
  62. "create_block_mask",
  63. "create_mask",
  64. "create_nested_block_mask",
  65. "or_masks",
  66. "and_masks",
  67. "noop_mask",
  68. ]
  69. _score_mod_signature = Callable[[Tensor, Tensor, Tensor, Tensor, Tensor], Tensor]
  70. _mask_mod_signature = Callable[[Tensor, Tensor, Tensor, Tensor], Tensor]
  71. class FlexKernelOptions(TypedDict, total=False):
  72. """Options for controlling the behavior of FlexAttention kernels.
  73. These options are passed to the underlying Triton kernels to control performance
  74. and numerical behavior. Most users will not need to specify these options as the
  75. default autotuning provides good performance.
  76. The options can be prefixed with ``fwd_`` or ``bwd_`` to apply only to forward or
  77. backward pass respectively. For example: ``fwd_BLOCK_M`` and ``bwd_BLOCK_M1``.
  78. Note:
  79. We currently do not provide any backward compatibility guarantees for these options.
  80. That being said most of these have remained pretty stable since their introduction. But
  81. We do not consider this part of the public API just yet. We think that some documentation
  82. Is better than secret hidden flags, but we may change these options in the future.
  83. Example Usage:
  84. .. code-block:: python
  85. # Using dictionary (backward compatible)
  86. kernel_opts = {"BLOCK_M": 64, "BLOCK_N": 64, "PRESCALE_QK": True}
  87. output = flex_attention(q, k, v, kernel_options=kernel_opts)
  88. # Using TypedDict (recommended for type safety)
  89. from torch.nn.attention.flex_attention import FlexKernelOptions
  90. kernel_opts: FlexKernelOptions = {
  91. "BLOCK_M": 64,
  92. "BLOCK_N": 64,
  93. "PRESCALE_QK": True,
  94. }
  95. output = flex_attention(q, k, v, kernel_options=kernel_opts)
  96. # Forward/backward specific options
  97. kernel_opts: FlexKernelOptions = {
  98. "fwd_BLOCK_M": 64,
  99. "bwd_BLOCK_M1": 32,
  100. "PRESCALE_QK": False,
  101. }
  102. output = flex_attention(q, k, v, kernel_options=kernel_opts)
  103. """
  104. # Performance tuning options
  105. num_warps: NotRequired[int]
  106. """Number of warps to use in the CUDA kernel. Higher values may improve performance
  107. but increase register pressure. Default is determined by autotuning."""
  108. num_stages: NotRequired[int]
  109. """Number of pipeline stages in the CUDA kernel. Higher values may improve performance
  110. but increase shared memory usage. Default is determined by autotuning."""
  111. BLOCK_M: NotRequired[int]
  112. """Thread block size for the sequence length dimension of Q in forward pass.
  113. Must be a power of 2. Common values: 16, 32, 64, 128. Default is determined by autotuning."""
  114. BLOCK_N: NotRequired[int]
  115. """Thread block size for the sequence length dimension of K/V in forward pass.
  116. Must be a power of 2. Common values: 16, 32, 64, 128. Default is determined by autotuning."""
  117. # Backward-specific block sizes (when prefixed with 'bwd_')
  118. BLOCK_M1: NotRequired[int]
  119. """Thread block size for Q dimension in backward pass. Use as 'bwd_BLOCK_M1'.
  120. Default is determined by autotuning."""
  121. BLOCK_N1: NotRequired[int]
  122. """Thread block size for K/V dimension in backward pass. Use as 'bwd_BLOCK_N1'.
  123. Default is determined by autotuning."""
  124. BLOCK_M2: NotRequired[int]
  125. """Thread block size for second Q dimension in backward pass. Use as 'bwd_BLOCK_M2'.
  126. Default is determined by autotuning."""
  127. BLOCK_N2: NotRequired[int]
  128. """Thread block size for second K/V dimension in backward pass. Use as 'bwd_BLOCK_N2'.
  129. Default is determined by autotuning."""
  130. PRESCALE_QK: NotRequired[bool]
  131. """Whether to pre-scale QK by 1/sqrt(d) and change of base. This is slightly faster but
  132. may have more numerical error. Default: False."""
  133. ROWS_GUARANTEED_SAFE: NotRequired[bool]
  134. """If True, guarantees that at least one value in each row is not masked out.
  135. Allows skipping safety checks for better performance. Only set this if you are certain
  136. your mask guarantees this property. For example, causal attention is guaranteed safe
  137. because each query has at least 1 key-value to attend to. Default: False."""
  138. BLOCKS_ARE_CONTIGUOUS: NotRequired[bool]
  139. """If True, guarantees that all blocks in the mask are contiguous.
  140. Allows optimizing block traversal. For example, causal masks would satisfy this,
  141. but prefix_lm + sliding window would not. Default: False."""
  142. WRITE_DQ: NotRequired[bool]
  143. """Controls whether gradient scatters are done in the DQ iteration loop of the backward pass.
  144. Setting this to False will force this to happen in the DK loop which depending on your
  145. specific score_mod and mask_mod might be faster. Default: True."""
  146. FORCE_USE_FLEX_ATTENTION: NotRequired[bool]
  147. """If True, forces the use of the flex attention kernel instead of potentially using
  148. the more optimized flex-decoding kernel for short sequences. This can be a helpful
  149. option for debugging. Default: False."""
  150. USE_TMA: NotRequired[bool]
  151. """Whether to use Tensor Memory Accelerator (TMA) on supported hardware.
  152. This is experimental and may not work on all hardware, currently specific
  153. to NVIDIA GPUs Hopper+. Default: False."""
  154. # ROCm-specific options
  155. kpack: NotRequired[int]
  156. """ROCm-specific kernel packing parameter."""
  157. matrix_instr_nonkdim: NotRequired[int]
  158. """ROCm-specific matrix instruction non-K dimension."""
  159. waves_per_eu: NotRequired[int]
  160. """ROCm-specific waves per execution unit."""
  161. class AuxRequest(NamedTuple):
  162. """Request which auxiliary outputs to compute from flex_attention.
  163. Each field is a boolean indicating whether that auxiliary output should be computed.
  164. """
  165. lse: bool = False
  166. max_scores: bool = False
  167. class AuxOutput(NamedTuple):
  168. """Auxiliary outputs from flex_attention operation.
  169. Fields will be None if not requested, or contain the tensor if requested.
  170. """
  171. lse: Optional[Tensor] = None
  172. max_scores: Optional[Tensor] = None
  173. class _ModificationType(Enum):
  174. """Enum for the type of modification function.
  175. - SCORE_MOD: score_mod function which accepts a score as the first argument
  176. - mask_mod: mask function which does not accept a score and is only used for generating
  177. block mask
  178. """
  179. SCORE_MOD = 1
  180. MASK_MOD = 2
  181. UNKNOWN = 3
  182. def _get_mod_type(fn: Callable) -> _ModificationType:
  183. """Get the type of modification function.
  184. This function inspects the number of positional arguments of the function to determine
  185. the type of modification function. If the function has 5 positional arguments, it is
  186. considered as a score_mod function. If the function has 4 positional arguments, it is
  187. considered as a mask function.
  188. """
  189. num_positional_args = sum(
  190. 1
  191. for param in inspect.signature(fn).parameters.values()
  192. if param.default == inspect.Parameter.empty
  193. )
  194. assert num_positional_args == 5 or num_positional_args == 4
  195. if num_positional_args == 5:
  196. return _ModificationType.SCORE_MOD
  197. elif num_positional_args == 4:
  198. return _ModificationType.MASK_MOD
  199. else:
  200. return _ModificationType.UNKNOWN
  201. # Need to define it here so that Dynamo doesn't skip it
  202. def _vmap_for_bhqkv(
  203. fn: Callable,
  204. prefix: tuple[Optional[int], ...],
  205. suffix: tuple[Optional[int], ...] = (),
  206. out_dims: Union[int, list[Optional[int]]] = 0,
  207. group_dim: bool = False,
  208. ):
  209. """Used to vmap both score_mods and mask_mods over 4-dimensional/5-dimension inputs.
  210. Mapping over the [b, hq, q_idx, kv_idx] or [b, hkv, g, q_idx, kv_idx] dimensions.
  211. Args:
  212. fn (callable): The function to vmap.
  213. prefix (tuple): The prefix of the vmap. For score mod functions,
  214. this should be set to (0,). For mask_mods = ()
  215. suffix (tuple): We need to add (0,) if gradOut is being mapped over,
  216. and (None,) * len(other_buffers).
  217. out_dims (tuple): For forward cases, keep this as the default 0 since
  218. we are only returning 1 output. For backwards, the joint
  219. graph returns grads for B, H, Q_idx, KV_idx and other_buffers,
  220. so we set this to (0, None, None, None, None) + (None,) * len(other_buffers).
  221. Returns:
  222. callable: The vmapped function.
  223. """
  224. # We vamp a function 4 times, broadcasting the [b, h, q_idx, kv_idx] dimensions
  225. dimensions: list[tuple[None | int, None | int, None | int, None | int]] = []
  226. dimensions = [
  227. (None, None, None, 0),
  228. (None, None, 0, None),
  229. (None, 0, None, None),
  230. ]
  231. if group_dim:
  232. dimensions += [
  233. (None, 0, None, None),
  234. ]
  235. dimensions += [
  236. (0, None, None, None),
  237. ]
  238. for dims in dimensions:
  239. fn = torch.vmap(fn, in_dims=prefix + dims + suffix, out_dims=out_dims) # type: ignore[arg-type]
  240. return fn
  241. def _identity(
  242. score: Tensor,
  243. batch: Tensor,
  244. head: Tensor,
  245. token_q: Tensor,
  246. token_kv: Tensor,
  247. ) -> Tensor:
  248. return score
  249. def noop_mask(
  250. batch: Tensor,
  251. head: Tensor,
  252. token_q: Tensor,
  253. token_kv: Tensor,
  254. ) -> Tensor:
  255. """Returns a noop mask_mod"""
  256. return batch.new_ones(size=(), dtype=torch.bool, device=batch.device)
  257. _DEFAULT_SPARSE_BLOCK_SIZE = 128
  258. _LARGE_SPARSE_BLOCK_SIZE = 1 << 30
  259. def _ordered_to_dense(num_blocks_in_row: Tensor, col_indices: Tensor):
  260. num_rows = col_indices.shape[-2]
  261. num_cols = col_indices.shape[-1]
  262. batch_dims = num_blocks_in_row.shape[:-1]
  263. device = num_blocks_in_row.device
  264. def create_dense_one(kv_num_blocks, kv_indices):
  265. dense_mask = kv_indices.new_zeros(num_rows, num_cols + 1, dtype=torch.int32)
  266. row_indices = torch.arange(num_rows, dtype=torch.int, device=device).unsqueeze(
  267. -1
  268. )
  269. col_range = torch.arange(num_cols, dtype=torch.int, device=device)
  270. index_mask = col_range < kv_num_blocks.unsqueeze(-1)
  271. # We write to one spot "out of bounds"
  272. valid_indices = torch.where(index_mask, kv_indices, num_cols)
  273. # set the values in 'a' to 1 where the indices are valid
  274. dense_mask[row_indices, valid_indices] = dense_mask.new_ones(())
  275. return dense_mask[:, :num_cols].contiguous()
  276. create_dense_batched = create_dense_one
  277. for _ in range(len(batch_dims)):
  278. create_dense_batched = torch.vmap(create_dense_batched, in_dims=(0, 0))
  279. out = create_dense_batched(num_blocks_in_row, col_indices)
  280. return out
  281. def _dense_to_ordered(dense_mask) -> tuple[Tensor, Tensor]:
  282. dense_mask = dense_mask.to(dtype=torch.int32)
  283. num_blocks_in_row = dense_mask.sum(dim=-1)
  284. col_indices = torch.argsort(dense_mask, dim=-1, descending=True, stable=True)
  285. return (
  286. num_blocks_in_row.to(torch.int32, memory_format=torch.contiguous_format),
  287. col_indices.to(torch.int32, memory_format=torch.contiguous_format),
  288. )
  289. def _transpose_ordered(num_blocks_in_row: Tensor, col_indices: Tensor):
  290. dense = _ordered_to_dense(num_blocks_in_row, col_indices)
  291. return _dense_to_ordered(dense.transpose(-2, -1))
  292. def _adjust_num_blocks_and_indices(
  293. num_blocks: Tensor,
  294. indices: Tensor,
  295. new_num_rows: int,
  296. new_num_cols: int,
  297. ):
  298. indices = indices[:, :, :new_num_rows, :new_num_cols]
  299. num_blocks = num_blocks[:, :, :new_num_rows]
  300. num_blocks = torch.where(num_blocks < new_num_cols, num_blocks, new_num_cols)
  301. num_blocks = torch.sum(indices < num_blocks[:, :, :, None], dim=-1).to(torch.int32)
  302. return num_blocks, indices
  303. class BlockMask:
  304. r"""
  305. BlockMask is our format for representing a block-sparse attention mask.
  306. It is somewhat of a cross in-between BCSR and a non-sparse format.
  307. **Basics**
  308. A block-sparse mask means that instead of representing the sparsity of
  309. individual elements in the mask, a KV_BLOCK_SIZE x Q_BLOCK_SIZE block is
  310. considered sparse only if every element within that block is sparse.
  311. This aligns well with hardware, which generally expects to perform
  312. contiguous loads and computation.
  313. This format is primarily optimized for 1. simplicity, and 2. kernel
  314. efficiency. Notably, it is *not* optimized for size, as this mask is always
  315. reduced by a factor of KV_BLOCK_SIZE * Q_BLOCK_SIZE. If the size is a
  316. concern, the tensors can be reduced in size by increasing the block size.
  317. The essentials of our format are:
  318. num_blocks_in_row: Tensor[ROWS]:
  319. Describes the number of blocks present in each row.
  320. col_indices: Tensor[ROWS, MAX_BLOCKS_IN_COL]:
  321. `col_indices[i]` is the sequence of block positions for row i. The values of
  322. this row after `col_indices[i][num_blocks_in_row[i]]` are undefined.
  323. For example, to reconstruct the original tensor from this format:
  324. .. code-block:: python
  325. dense_mask = torch.zeros(ROWS, COLS)
  326. for row in range(ROWS):
  327. for block_idx in range(num_blocks_in_row[row]):
  328. dense_mask[row, col_indices[row, block_idx]] = 1
  329. Notably, this format makes it easier to implement a reduction along the
  330. *rows* of the mask.
  331. **Details**
  332. The basics of our format require only kv_num_blocks and kv_indices. But, we
  333. have up to 8 tensors on this object. This represents 4 pairs:
  334. 1. (kv_num_blocks, kv_indices): Used for the forwards pass of attention, as
  335. we reduce along the KV dimension.
  336. 2. [OPTIONAL] (full_kv_num_blocks, full_kv_indices): This is optional and
  337. purely an optimization. As it turns out, applying masking to every block
  338. is quite expensive! If we specifically know which blocks are "full" and
  339. don't require masking at all, then we can skip applying mask_mod to these
  340. blocks. This requires the user to split out a separate mask_mod from the
  341. score_mod. For causal masks, this is about a 15% speedup.
  342. 3. [GENERATED] (q_num_blocks, q_indices): Required for the backwards pass,
  343. as computing dKV requires iterating along the mask along the Q dimension. These are autogenerated from 1.
  344. 4. [GENERATED] (full_q_num_blocks, full_q_indices): Same as above, but for
  345. the backwards pass. These are autogenerated from 2.
  346. """
  347. seq_lengths: tuple[int, int]
  348. kv_num_blocks: Tensor
  349. kv_indices: Tensor
  350. full_kv_num_blocks: Optional[Tensor]
  351. full_kv_indices: Optional[Tensor]
  352. q_num_blocks: Optional[Tensor]
  353. q_indices: Optional[Tensor]
  354. full_q_num_blocks: Optional[Tensor]
  355. full_q_indices: Optional[Tensor]
  356. BLOCK_SIZE: tuple[int, int]
  357. mask_mod: _mask_mod_signature
  358. def __init__(
  359. self,
  360. seq_lengths: tuple[int, int],
  361. kv_num_blocks: Tensor,
  362. kv_indices: Tensor,
  363. full_kv_num_blocks: Optional[Tensor],
  364. full_kv_indices: Optional[Tensor],
  365. q_num_blocks: Optional[Tensor],
  366. q_indices: Optional[Tensor],
  367. full_q_num_blocks: Optional[Tensor],
  368. full_q_indices: Optional[Tensor],
  369. BLOCK_SIZE: tuple[int, int],
  370. mask_mod: _mask_mod_signature,
  371. ):
  372. if kv_indices.dim() < 2:
  373. raise RuntimeError("BlockMask must have at least 2 dimensions")
  374. assert kv_num_blocks is not None, "kv_num_blocks must be provided"
  375. assert kv_indices is not None, "kv_indices must be provided"
  376. assert (full_kv_num_blocks is None) == (full_kv_indices is None), (
  377. "full_kv_num_blocks and full_kv_indices must be both provided or omitted"
  378. )
  379. assert (full_q_num_blocks is None) == (full_q_indices is None), (
  380. "full_q_num_blocks and full_q_indices must be both provided or omitted"
  381. )
  382. self.seq_lengths = seq_lengths
  383. self.kv_num_blocks = kv_num_blocks
  384. self.kv_indices = kv_indices
  385. self.full_kv_num_blocks = full_kv_num_blocks
  386. self.full_kv_indices = full_kv_indices
  387. self.q_num_blocks = q_num_blocks
  388. self.q_indices = q_indices
  389. self.full_q_num_blocks = full_q_num_blocks
  390. self.full_q_indices = full_q_indices
  391. self.BLOCK_SIZE = BLOCK_SIZE
  392. self.mask_mod = mask_mod
  393. @classmethod
  394. def from_kv_blocks(
  395. cls,
  396. kv_num_blocks: Tensor,
  397. kv_indices: Tensor,
  398. full_kv_num_blocks: Optional[Tensor] = None,
  399. full_kv_indices: Optional[Tensor] = None,
  400. BLOCK_SIZE: Union[int, tuple[int, int]] = _DEFAULT_SPARSE_BLOCK_SIZE,
  401. mask_mod: Optional[_mask_mod_signature] = None,
  402. seq_lengths: Optional[tuple[int, int]] = None,
  403. compute_q_blocks: bool = True,
  404. ):
  405. """
  406. Creates a BlockMask instance from key-value block information.
  407. Args:
  408. kv_num_blocks (Tensor): Number of kv_blocks in each Q_BLOCK_SIZE row tile.
  409. kv_indices (Tensor): Indices of key-value blocks in each Q_BLOCK_SIZE row tile.
  410. full_kv_num_blocks (Optional[Tensor]): Number of full kv_blocks in each Q_BLOCK_SIZE row tile.
  411. full_kv_indices (Optional[Tensor]): Indices of full key-value blocks in each Q_BLOCK_SIZE row tile.
  412. BLOCK_SIZE (Union[int, tuple[int, int]]): Size of KV_BLOCK_SIZE x Q_BLOCK_SIZE tiles.
  413. mask_mod (Optional[Callable]): Function to modify the mask.
  414. Returns:
  415. BlockMask: Instance with full Q information generated via _transposed_ordered
  416. Raises:
  417. RuntimeError: If kv_indices has < 2 dimensions.
  418. AssertionError: If only one of full_kv_* args is provided.
  419. """
  420. if kv_indices.dim() < 2:
  421. raise RuntimeError("BlockMask must have at least 2 dimensions")
  422. assert (full_kv_num_blocks is None) == (full_kv_indices is None), (
  423. "full_kv_num_blocks and full_kv_indices must be both provided or omitted"
  424. )
  425. # Generate q_num_blocks and q_indices
  426. if compute_q_blocks:
  427. q_num_blocks, q_indices = _transpose_ordered(kv_num_blocks, kv_indices)
  428. if full_kv_num_blocks is not None:
  429. assert full_kv_indices is not None
  430. full_q_num_blocks, full_q_indices = _transpose_ordered(
  431. full_kv_num_blocks, full_kv_indices
  432. )
  433. else:
  434. full_q_num_blocks, full_q_indices = None, None
  435. else:
  436. q_num_blocks, q_indices = None, None
  437. full_q_num_blocks, full_q_indices = None, None
  438. if isinstance(BLOCK_SIZE, int):
  439. BLOCK_SIZE = (BLOCK_SIZE, BLOCK_SIZE)
  440. mask_mod = mask_mod if mask_mod is not None else noop_mask
  441. if seq_lengths is None:
  442. q_length = kv_indices.shape[-2] * BLOCK_SIZE[0]
  443. kv_length = kv_indices.shape[-1] * BLOCK_SIZE[1]
  444. seq_lengths = (q_length, kv_length)
  445. return cls(
  446. seq_lengths=seq_lengths,
  447. kv_num_blocks=kv_num_blocks,
  448. kv_indices=kv_indices,
  449. full_kv_num_blocks=full_kv_num_blocks,
  450. full_kv_indices=full_kv_indices,
  451. q_num_blocks=q_num_blocks,
  452. q_indices=q_indices,
  453. full_q_num_blocks=full_q_num_blocks,
  454. full_q_indices=full_q_indices,
  455. BLOCK_SIZE=BLOCK_SIZE,
  456. mask_mod=mask_mod,
  457. )
  458. def as_tuple(self, flatten: bool = True):
  459. """
  460. Returns a tuple of the attributes of the BlockMask.
  461. Args:
  462. flatten (bool): If True, it will flatten the tuple of (KV_BLOCK_SIZE, Q_BLOCK_SIZE)
  463. """
  464. if flatten:
  465. block_size = (self.BLOCK_SIZE[0], self.BLOCK_SIZE[1]) # type: ignore[assignment]
  466. seq_lengths = (self.seq_lengths[0], self.seq_lengths[1]) # type: ignore[assignment]
  467. else:
  468. block_size = (self.BLOCK_SIZE,) # type: ignore[assignment]
  469. seq_lengths = (self.seq_lengths,) # type: ignore[assignment]
  470. return (
  471. *seq_lengths,
  472. self.kv_num_blocks,
  473. self.kv_indices,
  474. self.full_kv_num_blocks,
  475. self.full_kv_indices,
  476. self.q_num_blocks,
  477. self.q_indices,
  478. self.full_q_num_blocks,
  479. self.full_q_indices,
  480. *block_size,
  481. self.mask_mod,
  482. )
  483. @property
  484. def shape(self):
  485. *batch_dims, _, _ = self.kv_indices.shape
  486. return tuple(batch_dims) + self.seq_lengths
  487. def __str__(self):
  488. s = f"BlockMask(shape={self.shape}, sparsity={self.sparsity():.2f}%, \n"
  489. mask_str = self.to_string().strip()
  490. s += mask_str
  491. s += "\n)"
  492. return s
  493. def __getitem__(self, index) -> "BlockMask":
  494. """
  495. Returns a new BlockMask instance by getting the mask for the given index position.
  496. Args:
  497. index: Index to apply to all attributes.
  498. Example Usage:
  499. .. code-block:: python
  500. def causal_mask(b, h, q_idx, kv_idx):
  501. return q_idx >= kv_idx
  502. block_mask = create_block_mask(
  503. causal_mask, 4, 2, 512, 512, device="cuda"
  504. )
  505. assert block_mask.kv_num_blocks.shape == (4, 2, 4)
  506. assert block_mask.kv_indices.shape == (4, 2, 4, 4)
  507. # Index on batch dimension
  508. new_block_mask = block_mask[0]
  509. assert new_block_mask.kv_num_blocks.shape == (2, 4)
  510. assert new_block_mask.kv_indices.shape == (2, 4, 4)
  511. # Index on batch and head dimension
  512. new_block_mask = block_mask[0, 1]
  513. assert new_block_mask.kv_num_blocks.shape == (4,)
  514. assert new_block_mask.kv_indices.shape == (4, 4)
  515. # slicing on batch and head dimension
  516. new_block_mask = block_mask[0:2, 1:2]
  517. assert new_block_mask.kv_num_blocks.shape == (2, 1, 4)
  518. assert new_block_mask.kv_indices.shape == (2, 1, 4, 4)
  519. # slicing on batch, head, and query dimension
  520. new_block_mask = block_mask[
  521. 0:2, 1:2, torch.tensor([1], dtype=torch.int32)
  522. ]
  523. assert new_block_mask.kv_num_blocks.shape == (2, 1, 1)
  524. assert new_block_mask.kv_indices.shape == (2, 1, 1, 4)
  525. """
  526. index = (index,) if not isinstance(index, tuple) else index
  527. padded = (*index, slice(None), slice(None), slice(None))[:3]
  528. sizes = self.kv_num_blocks.shape[:3]
  529. index = tuple(
  530. (slice(i + n, i + n + 1) if -n <= i < 0 else slice(i, i + 1))
  531. if isinstance(i, int)
  532. else i
  533. for i, n in zip(padded, sizes)
  534. )
  535. new_kv_num_blocks = self.kv_num_blocks[index]
  536. new_kv_indices = self.kv_indices[index]
  537. if self.full_kv_num_blocks is not None:
  538. assert self.full_kv_indices is not None
  539. new_full_kv_num_blocks = self.full_kv_num_blocks[index]
  540. new_full_kv_indices = self.full_kv_indices[index]
  541. else:
  542. new_full_kv_num_blocks = None
  543. new_full_kv_indices = None
  544. return BlockMask.from_kv_blocks(
  545. new_kv_num_blocks,
  546. new_kv_indices,
  547. new_full_kv_num_blocks,
  548. new_full_kv_indices,
  549. BLOCK_SIZE=self.BLOCK_SIZE,
  550. mask_mod=None,
  551. seq_lengths=self.seq_lengths,
  552. compute_q_blocks=self.q_indices is not None,
  553. )
  554. def __repr__(self):
  555. def shape_or_none(x: Optional[torch.Tensor]):
  556. return x.shape if x is not None else None
  557. return (
  558. f"BlockMask(\n"
  559. f" kv_num_blocks={self.kv_num_blocks.shape},\n"
  560. f" kv_indices={self.kv_indices.shape},\n"
  561. f" full_kv_num_blocks={shape_or_none(self.full_kv_num_blocks)},\n"
  562. f" full_kv_indices={shape_or_none(self.full_kv_indices)},\n"
  563. f" q_num_blocks={shape_or_none(self.q_num_blocks)},\n"
  564. f" q_indices={shape_or_none(self.q_indices)},\n"
  565. f" full_q_num_blocks={shape_or_none(self.full_q_num_blocks)},\n"
  566. f" full_q_indices={shape_or_none(self.full_q_indices)},\n"
  567. f" BLOCK_SIZE={self.BLOCK_SIZE},\n"
  568. f" shape={self.shape},\n"
  569. f" sparsity={self.sparsity():.2f}%,\n"
  570. f" mask_mod={self.mask_mod.__name__ if hasattr(self.mask_mod, '__name__') else self.mask_mod}\n"
  571. f")"
  572. )
  573. def _adjust(self, new_q_len: int, new_kv_len: int):
  574. new_num_rows = (new_q_len + self.BLOCK_SIZE[0] - 1) // self.BLOCK_SIZE[0]
  575. new_num_cols = (new_kv_len + self.BLOCK_SIZE[1] - 1) // self.BLOCK_SIZE[1]
  576. new_kv_num_blocks, new_kv_indices = _adjust_num_blocks_and_indices(
  577. self.kv_num_blocks, self.kv_indices, new_num_rows, new_num_cols
  578. )
  579. if self.full_kv_num_blocks is not None:
  580. assert self.full_kv_indices is not None
  581. (
  582. new_full_kv_num_blocks,
  583. new_full_kv_indices,
  584. ) = _adjust_num_blocks_and_indices(
  585. self.full_kv_num_blocks,
  586. self.full_kv_indices,
  587. new_num_rows,
  588. new_num_cols,
  589. )
  590. else:
  591. new_full_kv_num_blocks = None
  592. new_full_kv_indices = None
  593. return self.from_kv_blocks(
  594. new_kv_num_blocks,
  595. new_kv_indices,
  596. new_full_kv_num_blocks,
  597. new_full_kv_indices,
  598. self.BLOCK_SIZE,
  599. self.mask_mod,
  600. )
  601. def numel(self):
  602. """Returns the number of elements (not accounting for sparsity) in the mask."""
  603. shape = self.shape
  604. def _prod(xs):
  605. return functools.reduce(operator.mul, xs, 1)
  606. return _prod(shape)
  607. def sparsity(self) -> float:
  608. """Computes the percentage of blocks that are sparse (i.e. not computed)"""
  609. total_size = self.numel()
  610. computed_blocks = self.kv_num_blocks.sum()
  611. if self.full_kv_num_blocks is not None:
  612. computed_blocks += self.full_kv_num_blocks.sum()
  613. computed_size = computed_blocks.item() * self.BLOCK_SIZE[0] * self.BLOCK_SIZE[1]
  614. dense_ratio = computed_size / total_size
  615. return 100 * (1 - dense_ratio)
  616. def to_dense(self) -> Tensor:
  617. """Returns a dense block that is equivalent to the block mask."""
  618. partial_dense = _ordered_to_dense(self.kv_num_blocks, self.kv_indices)
  619. if self.full_kv_num_blocks is not None:
  620. assert self.full_kv_indices is not None
  621. return partial_dense | _ordered_to_dense(
  622. self.full_kv_num_blocks, self.full_kv_indices
  623. )
  624. return partial_dense
  625. def to_string(self, grid_size=(20, 20), limit=4):
  626. """Returns a string representation of the block mask. Quite nifty.
  627. If grid_size is -1, prints out an uncompressed version. Warning, it can be quite big!
  628. """
  629. dense_mask = self.to_dense()
  630. *batch_dims, num_rows, num_cols = dense_mask.shape
  631. if isinstance(grid_size, int):
  632. max_rows = grid_size
  633. max_cols = grid_size
  634. elif grid_size == -1:
  635. max_rows = num_rows
  636. max_cols = num_cols
  637. else:
  638. max_rows, max_cols = grid_size
  639. def create_block_vis(*batch_idx):
  640. descriptors = []
  641. descriptors.append(f"{batch_idx}")
  642. vis = ", ".join(reversed(descriptors)) + "\n"
  643. def summarize_section(section):
  644. percentage = section.float().mean().item()
  645. if percentage == 1:
  646. return "█"
  647. elif percentage == 0:
  648. return " "
  649. else:
  650. return "░"
  651. def cdiv(a, b):
  652. return (a + (b - 1)) // b
  653. row_step = max(1, cdiv(num_rows, max_rows))
  654. col_step = max(1, cdiv(num_cols, max_cols))
  655. for r in range(0, num_rows, row_step):
  656. for c in range(0, num_cols, col_step):
  657. cur_mask = dense_mask
  658. for idx in batch_idx:
  659. cur_mask = cur_mask[idx]
  660. char = summarize_section(
  661. cur_mask[r : r + row_step, c : c + col_step]
  662. )
  663. vis += char * 2
  664. vis += "\n"
  665. return vis
  666. total_vis = []
  667. for idx, batch_idx in enumerate(
  668. itertools.product(*[range(i) for i in batch_dims])
  669. ):
  670. if idx == limit:
  671. total_vis.append("...")
  672. total_vis.append("To print out more, set BlockMask.to_string(limit=N)")
  673. total_vis.append(
  674. "You can also index (BlockMask[batch, head]) to choose a specific batch or head"
  675. )
  676. break
  677. block_vis = create_block_vis(*batch_idx)
  678. total_vis.append(block_vis)
  679. return "\n".join(total_vis)
  680. def to(self, device: Union[torch.device, str]) -> "BlockMask":
  681. """Moves the BlockMask to the specified device.
  682. Args:
  683. device (torch.device or str): The target device to move the BlockMask to.
  684. Can be a torch.device object or a string (e.g., 'cpu', 'cuda:0').
  685. Returns:
  686. BlockMask: A new BlockMask instance with all tensor components moved
  687. to the specified device.
  688. Note:
  689. This method does not modify the original BlockMask in-place.
  690. Instead, it returns a new BlockMask instance where individual tensor attributes
  691. may or may not be moved to the specified device, depending on their
  692. current device placement.
  693. """
  694. mapped_attributes = tree_map_only(
  695. torch.Tensor,
  696. lambda x: x.to(device),
  697. self.as_tuple(flatten=False),
  698. )
  699. return BlockMask(*mapped_attributes)
  700. def _broadcast_to_dim(x, dim):
  701. while x.dim() < dim:
  702. x = x.unsqueeze(0)
  703. return x
  704. def _round_up_to_multiple(x, multiple):
  705. return (x + multiple - 1) // multiple * multiple
  706. def _convert_mask_to_block_mask(
  707. mask: Tensor,
  708. Q_BLOCK_SIZE=_DEFAULT_SPARSE_BLOCK_SIZE,
  709. KV_BLOCK_SIZE=_DEFAULT_SPARSE_BLOCK_SIZE,
  710. separate_full_blocks: bool = False,
  711. ) -> tuple[Tensor, Optional[Tensor]]:
  712. assert mask.dtype == torch.bool
  713. mask = _broadcast_to_dim(mask, 4)
  714. def padding_needed_for_multiple(x, multiple):
  715. return _round_up_to_multiple(x, multiple) - x
  716. mask = torch.nn.functional.pad(
  717. mask,
  718. (
  719. 0,
  720. padding_needed_for_multiple(mask.shape[-1], KV_BLOCK_SIZE),
  721. 0,
  722. padding_needed_for_multiple(mask.shape[-2], Q_BLOCK_SIZE),
  723. ),
  724. )
  725. B, H, Q, KV = mask.shape
  726. assert Q % Q_BLOCK_SIZE == 0
  727. assert KV % KV_BLOCK_SIZE == 0
  728. mask = mask.view(
  729. B, H, Q // Q_BLOCK_SIZE, Q_BLOCK_SIZE, KV // KV_BLOCK_SIZE, KV_BLOCK_SIZE
  730. ) # [B, H, Q//Q_BLOCK_SIZE, Q_BLOCK_SIZE, KV//KV_BLOCK_SIZE, KV_BLOCK_SIZE]
  731. mask = mask.permute(
  732. 0, 1, 2, 4, 3, 5
  733. ) # [B, H, Q//Q_BLOCK_SIZE, KV//KV_BLOCK_SIZE, Q_BLOCK_SIZE, KV_BLOCK_SIZE]
  734. mask_block_sum = mask.sum(
  735. dim=[-2, -1]
  736. ) # [B, H, Q//Q_BLOCK_SIZE, KV//KV_BLOCK_SIZE]
  737. if separate_full_blocks:
  738. full_block_sum = Q_BLOCK_SIZE * KV_BLOCK_SIZE
  739. full_blocks = mask_block_sum == full_block_sum
  740. partial_blocks = (mask_block_sum > 0) & (mask_block_sum < full_block_sum)
  741. partial_blocks = partial_blocks.to(dtype=torch.int8)
  742. full_blocks = full_blocks.to(dtype=torch.int8)
  743. return partial_blocks, full_blocks
  744. else:
  745. partial_blocks = mask_block_sum > 0
  746. partial_blocks = partial_blocks.to(dtype=torch.int8)
  747. return partial_blocks, None
  748. def or_masks(*mask_mods: _mask_mod_signature) -> _mask_mod_signature:
  749. """Returns a mask_mod that's the union of provided mask_mods"""
  750. if not all(callable(arg) for arg in mask_mods):
  751. raise RuntimeError(f"All inputs should be callable mask_mods: {mask_mods}")
  752. def or_mask(b, h, q_idx, kv_idx):
  753. result = b.new_zeros((), dtype=torch.bool)
  754. for mask in mask_mods:
  755. result = result | mask(b, h, q_idx, kv_idx)
  756. return result
  757. return or_mask
  758. def and_masks(*mask_mods: _mask_mod_signature) -> _mask_mod_signature:
  759. """Returns a mask_mod that's the intersection of provided mask_mods"""
  760. if not all(callable(arg) for arg in mask_mods):
  761. raise RuntimeError(f"All inputs should be callable mask_mods: {mask_mods}")
  762. def and_mask(b, h, q_idx, kv_idx):
  763. result = b.new_ones((), dtype=torch.bool)
  764. for mask in mask_mods:
  765. result = result & mask(b, h, q_idx, kv_idx)
  766. return result
  767. return and_mask
  768. def _convert_block_mask_to_mask(
  769. block_mask,
  770. KV_BLOCK_SIZE=_DEFAULT_SPARSE_BLOCK_SIZE,
  771. Q_BLOCK_SIZE=_DEFAULT_SPARSE_BLOCK_SIZE,
  772. ) -> Tensor:
  773. assert block_mask.dim() == 4
  774. B, H, Q, KV = block_mask.shape
  775. block_mask = block_mask.expand(Q_BLOCK_SIZE, KV_BLOCK_SIZE, *block_mask.shape)
  776. block_mask = block_mask.permute(2, 3, 4, 0, 5, 1).reshape(
  777. B, H, Q * Q_BLOCK_SIZE, KV * KV_BLOCK_SIZE
  778. )
  779. return block_mask
  780. def _create_sparse_block_from_block_mask(
  781. block_mask: tuple[Tensor, Optional[Tensor]],
  782. mask_mod: Optional[Callable],
  783. seq_lengths: tuple[int, int],
  784. Q_BLOCK_SIZE: int = _DEFAULT_SPARSE_BLOCK_SIZE,
  785. KV_BLOCK_SIZE: int = _DEFAULT_SPARSE_BLOCK_SIZE,
  786. ) -> BlockMask:
  787. partial_blocks, full_blocks = block_mask
  788. partial_bm = _dense_to_ordered(partial_blocks)
  789. if full_blocks is not None:
  790. full_bm: tuple[Optional[Tensor], Optional[Tensor]] = _dense_to_ordered(
  791. full_blocks
  792. )
  793. else:
  794. full_bm = (None, None)
  795. return BlockMask.from_kv_blocks(
  796. partial_bm[0],
  797. partial_bm[1],
  798. full_bm[0],
  799. full_bm[1],
  800. BLOCK_SIZE=(Q_BLOCK_SIZE, KV_BLOCK_SIZE),
  801. mask_mod=mask_mod,
  802. seq_lengths=seq_lengths,
  803. )
  804. def create_mask(
  805. mod_fn: Union[_score_mod_signature, _mask_mod_signature],
  806. B: Optional[int],
  807. H: Optional[int],
  808. Q_LEN: int,
  809. KV_LEN: int,
  810. device: DeviceLikeType = "cuda",
  811. ) -> Tensor:
  812. r"""This function creates a mask tensor from a mod_fn function.
  813. Args:
  814. mod_fn (Union[_score_mod_signature, _mask_mod_signature]): Function to modify attention scores.
  815. B (int): Batch size.
  816. H (int): Number of query heads.
  817. Q_LEN (int): Sequence length of query.
  818. KV_LEN (int): Sequence length of key/value.
  819. device (str): Device to run the mask creation on.
  820. Returns:
  821. mask (Tensor): A mask tensor with shape (B, H, M, N).
  822. """
  823. if B is None:
  824. B = 1
  825. if H is None:
  826. H = 1
  827. b = torch.arange(0, B, device=device)
  828. h = torch.arange(0, H, device=device)
  829. m = torch.arange(0, Q_LEN, device=device)
  830. n = torch.arange(0, KV_LEN, device=device)
  831. mod_type = _get_mod_type(mod_fn)
  832. from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
  833. with TransformGetItemToIndex():
  834. if mod_type == _ModificationType.SCORE_MOD:
  835. score_mod = mod_fn
  836. score_mod = _vmap_for_bhqkv(score_mod, prefix=(0,)) # first input is score
  837. out = score_mod(torch.zeros(B, H, Q_LEN, KV_LEN, device=device), b, h, m, n)
  838. mask = torch.where(torch.isneginf(out), False, True)
  839. return mask
  840. elif mod_type == _ModificationType.MASK_MOD:
  841. mask_mod = mod_fn
  842. mask_mod = _vmap_for_bhqkv(mask_mod, prefix=())
  843. mask = mask_mod(b, h, m, n)
  844. return mask
  845. else:
  846. raise AssertionError
  847. def create_block_mask(
  848. mask_mod: _mask_mod_signature,
  849. B: Optional[int],
  850. H: Optional[int],
  851. Q_LEN: int,
  852. KV_LEN: int,
  853. device: DeviceLikeType = "cuda",
  854. BLOCK_SIZE: Union[int, tuple[int, int]] = _DEFAULT_SPARSE_BLOCK_SIZE,
  855. _compile=False,
  856. ) -> BlockMask:
  857. r"""This function creates a block mask tuple from a mask_mod function.
  858. Args:
  859. mask_mod (Callable): mask_mod function. This is a callable that defines the
  860. masking pattern for the attention mechanism. It takes four arguments:
  861. b (batch size), h (number of heads), q_idx (query index), and kv_idx (key/value index).
  862. It should return a boolean tensor indicating which attention connections are allowed (True)
  863. or masked out (False).
  864. B (int): Batch size.
  865. H (int): Number of query heads.
  866. Q_LEN (int): Sequence length of query.
  867. KV_LEN (int): Sequence length of key/value.
  868. device (str): Device to run the mask creation on.
  869. BLOCK_SIZE (int or tuple[int, int]): Block size for the block mask. If a single int is provided it is used for both query and key/value.
  870. Returns:
  871. BlockMask: A BlockMask object that contains the block mask information.
  872. Example Usage:
  873. .. code-block:: python
  874. def causal_mask(b, h, q_idx, kv_idx):
  875. return q_idx >= kv_idx
  876. block_mask = create_block_mask(causal_mask, 1, 1, 8192, 8192, device="cuda")
  877. query = torch.randn(1, 1, 8192, 64, device="cuda", dtype=torch.float16)
  878. key = torch.randn(1, 1, 8192, 64, device="cuda", dtype=torch.float16)
  879. value = torch.randn(1, 1, 8192, 64, device="cuda", dtype=torch.float16)
  880. output = flex_attention(query, key, value, block_mask=block_mask)
  881. """
  882. mod_type = _get_mod_type(mask_mod)
  883. assert mod_type == _ModificationType.MASK_MOD, (
  884. f"create-block_mask requires a mask_mod function! Got {mask_mod}"
  885. )
  886. if B is None:
  887. B = 1
  888. if H is None:
  889. H = 1
  890. if isinstance(BLOCK_SIZE, int):
  891. Q_BLOCK_SIZE = BLOCK_SIZE
  892. KV_BLOCK_SIZE = BLOCK_SIZE
  893. else:
  894. Q_BLOCK_SIZE, KV_BLOCK_SIZE = BLOCK_SIZE
  895. if _compile:
  896. warnings.warn(
  897. "_compile flag on create_block_mask was originally added to work around a torch.compile limitation. That limitation has since been addressed. So, to compile create_block_mask, we suggest doing torch.compile(create_block_mask). This still works for now, but will be removed in the future.",
  898. DeprecationWarning,
  899. )
  900. return torch.compile(create_block_mask)(
  901. mask_mod, B, H, Q_LEN, KV_LEN, device, BLOCK_SIZE
  902. )
  903. mask_tensor = create_mask(mask_mod, B, H, Q_LEN, KV_LEN, device)
  904. partial_block_mask, full_block_mask = _convert_mask_to_block_mask(
  905. mask_tensor,
  906. Q_BLOCK_SIZE=Q_BLOCK_SIZE,
  907. KV_BLOCK_SIZE=KV_BLOCK_SIZE,
  908. separate_full_blocks=True,
  909. )
  910. block_mask = _create_sparse_block_from_block_mask(
  911. (partial_block_mask, full_block_mask),
  912. mask_mod,
  913. (Q_LEN, KV_LEN),
  914. Q_BLOCK_SIZE,
  915. KV_BLOCK_SIZE,
  916. )
  917. return block_mask
  918. def _create_empty_block_mask(query: Tensor, key: Tensor) -> BlockMask:
  919. r"""Default block mask for flex attention.
  920. If users don't specify any block sparse mask info, we create this
  921. empty block sparse mask. Which creates a BlockMask with 1 block that is the full length
  922. of the query and key tensors.
  923. """
  924. device = query.device
  925. return BlockMask.from_kv_blocks(
  926. kv_num_blocks=torch.ones([1, 1, 1], dtype=torch.int32, device=device),
  927. kv_indices=torch.zeros([1, 1, 1, 1], dtype=torch.int32, device=device),
  928. BLOCK_SIZE=_LARGE_SPARSE_BLOCK_SIZE,
  929. seq_lengths=(1, 1),
  930. )
  931. def _nested_mod_func_adapter(
  932. orig_mod_func: Union[_score_mod_signature, _mask_mod_signature],
  933. q_nt: torch.Tensor,
  934. kv_nt: torch.Tensor,
  935. is_score_mod: bool,
  936. ) -> Union[_score_mod_signature, _mask_mod_signature]:
  937. r"""Adapter to convert a score_mod / mask_mod to be NJT-compatible. The given mod func
  938. should be written as if operating over a single sequence at a item. This adapter will
  939. handle conversion from indices operating over a "stacked sequence" of length ``sum(S)``
  940. for sequence length ``S`` in the NJT to "sequence relative" indices in range ``[0, S)``.
  941. Args:
  942. orig_mod_func (Callable): Function to modify attention scores. It takes four or five
  943. arguments, depending on whether a mask_mod or score_mod func is passed.
  944. q_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
  945. structure for query.
  946. kv_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
  947. structure for key / value.
  948. is_score_mod (bool): Indicates whether the mod function is a score_mod.
  949. Returns:
  950. nt_score_mod: An NJT-compatible version of orig_score_mod
  951. """
  952. # Used to convert indices within the "stacked" sequence (range [0, sum(*)))
  953. # to "sequence local" indices (range [0, S) for each S).
  954. def _build_seq_idx(offsets, total_length):
  955. range_tensor = torch.arange(
  956. total_length, device=offsets.device, dtype=torch.int32
  957. )
  958. # Use searchsorted to find the index for each position
  959. # NB: This assumes offsets[0] to offsets[-1] spans the packed dim of values.
  960. # If we ever loosen this restriction, this logic will need to be updated.
  961. seq_idx = torch.searchsorted(offsets, range_tensor, right=True) - 1
  962. return seq_idx
  963. q_offsets = q_nt._offsets # type: ignore[attr-defined]
  964. kv_offsets = kv_nt._offsets # type: ignore[attr-defined]
  965. q_seq_idx = _build_seq_idx(q_offsets, q_nt._values.shape[q_nt._ragged_idx - 1]) # type: ignore[attr-defined]
  966. if q_nt is kv_nt:
  967. kv_seq_idx = q_seq_idx
  968. else:
  969. # cross attention case
  970. kv_seq_idx = _build_seq_idx(
  971. kv_offsets,
  972. kv_nt._values.shape[kv_nt._ragged_idx - 1], # type: ignore[attr-defined]
  973. )
  974. # Converts q_idx / kv_idx from [0, total_length) -> [0, S), where S refers
  975. # to the sequence length for each sequence in the NJT, for use in given
  976. # score_mod. This allows the user to write a score_mod as if it were
  977. # operating on a single sequence and the "stacked sequence" is split
  978. # automatically into individual sequences for them.
  979. if is_score_mod:
  980. def nt_score_mod(score, b, h, q_idx, kv_idx):
  981. b_nested = q_seq_idx[q_idx]
  982. q_nested = q_idx - q_offsets[q_seq_idx[q_idx]]
  983. kv_nested = kv_idx - kv_offsets[kv_seq_idx[kv_idx]]
  984. is_same_sequence = q_seq_idx[q_idx] == kv_seq_idx[kv_idx]
  985. return torch.where(
  986. is_same_sequence,
  987. orig_mod_func(score, b_nested, h, q_nested, kv_nested), # type: ignore[call-arg]
  988. # don't allow inter-sequence attention
  989. float("-inf"),
  990. )
  991. return nt_score_mod
  992. else:
  993. def nt_mask_mod(b, h, q_idx, kv_idx):
  994. b_nested = q_seq_idx[q_idx]
  995. q_nested = q_idx - q_offsets[q_seq_idx[q_idx]]
  996. kv_nested = kv_idx - kv_offsets[kv_seq_idx[kv_idx]]
  997. # don't allow inter-sequence attention
  998. is_same_sequence = q_seq_idx[q_idx] == kv_seq_idx[kv_idx]
  999. return orig_mod_func(b_nested, h, q_nested, kv_nested) & is_same_sequence # type: ignore[call-arg]
  1000. return nt_mask_mod
  1001. def create_nested_block_mask(
  1002. mask_mod: _mask_mod_signature,
  1003. B: Optional[int],
  1004. H: Optional[int],
  1005. q_nt: torch.Tensor,
  1006. kv_nt: Optional[torch.Tensor] = None,
  1007. BLOCK_SIZE: Union[int, tuple[int, int]] = _DEFAULT_SPARSE_BLOCK_SIZE,
  1008. _compile=False,
  1009. ) -> BlockMask:
  1010. r"""This function creates a nested tensor compatible block mask tuple from a mask_mod
  1011. function. The returned BlockMask will be on the device specified by the input nested tensor.
  1012. Args:
  1013. mask_mod (Callable): mask_mod function. This is a callable that defines the
  1014. masking pattern for the attention mechanism. It takes four arguments:
  1015. b (batch size), h (number of heads), q_idx (query index), and kv_idx (key/value index).
  1016. It should return a boolean tensor indicating which attention connections are allowed
  1017. (True) or masked out (False).
  1018. B (int): Batch size.
  1019. H (int): Number of query heads.
  1020. q_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
  1021. structure for query. The block mask will be constructed to operate on a "stacked
  1022. sequence" of length ``sum(S)`` for sequence length ``S`` from the NJT.
  1023. kv_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
  1024. structure for key / value, allowing for cross attention. The block mask will be
  1025. constructed to operate on a "stacked sequence" of length ``sum(S)`` for sequence
  1026. length ``S`` from the NJT. If this is None, ``q_nt`` is used to define the structure
  1027. for key / value as well. Default: None
  1028. BLOCK_SIZE (int or tuple[int, int]): Block size for the block mask. If a single int is
  1029. provided it is used for both query and key/value.
  1030. Returns:
  1031. BlockMask: A BlockMask object that contains the block mask information.
  1032. Example Usage:
  1033. .. code-block:: python
  1034. # shape (B, num_heads, seq_len*, D) where seq_len* varies across the batch
  1035. query = torch.nested.nested_tensor(..., layout=torch.jagged)
  1036. key = torch.nested.nested_tensor(..., layout=torch.jagged)
  1037. value = torch.nested.nested_tensor(..., layout=torch.jagged)
  1038. def causal_mask(b, h, q_idx, kv_idx):
  1039. return q_idx >= kv_idx
  1040. block_mask = create_nested_block_mask(
  1041. causal_mask, 1, 1, query, _compile=True
  1042. )
  1043. output = flex_attention(query, key, value, block_mask=block_mask)
  1044. .. code-block:: python
  1045. # shape (B, num_heads, seq_len*, D) where seq_len* varies across the batch
  1046. query = torch.nested.nested_tensor(..., layout=torch.jagged)
  1047. key = torch.nested.nested_tensor(..., layout=torch.jagged)
  1048. value = torch.nested.nested_tensor(..., layout=torch.jagged)
  1049. def causal_mask(b, h, q_idx, kv_idx):
  1050. return q_idx >= kv_idx
  1051. # cross attention case: pass both query and key/value NJTs
  1052. block_mask = create_nested_block_mask(
  1053. causal_mask, 1, 1, query, key, _compile=True
  1054. )
  1055. output = flex_attention(query, key, value, block_mask=block_mask)
  1056. """
  1057. # use same structure for kv as for q by default
  1058. if kv_nt is None:
  1059. kv_nt = q_nt
  1060. if q_nt.device != kv_nt.device:
  1061. raise ValueError(
  1062. "create_nested_block_mask(): Expected q_nt and kv_nt to be on the same device"
  1063. )
  1064. return create_block_mask(
  1065. _nested_mod_func_adapter(mask_mod, q_nt, kv_nt, is_score_mod=False), # type: ignore[arg-type]
  1066. B,
  1067. H,
  1068. q_nt._values.shape[q_nt._ragged_idx - 1], # type: ignore[attr-defined]
  1069. kv_nt._values.shape[kv_nt._ragged_idx - 1], # type: ignore[attr-defined]
  1070. device=q_nt.device, # type: ignore[arg-type]
  1071. # compile is important so we don't materialize a mask_tensor of
  1072. # shape (1, 1, total_seqlen, total_seqlen)
  1073. BLOCK_SIZE=BLOCK_SIZE,
  1074. _compile=_compile,
  1075. )
  1076. def _apply_kernel_options(
  1077. query: Tensor,
  1078. key: Tensor,
  1079. value: Tensor,
  1080. return_lse: bool,
  1081. kernel_options,
  1082. return_aux: Optional[AuxRequest] = None,
  1083. ):
  1084. kernel_options = {} if kernel_options is None else dict(kernel_options)
  1085. kernel_options.setdefault("PRESCALE_QK", False)
  1086. kernel_options.setdefault("ROWS_GUARANTEED_SAFE", False)
  1087. kernel_options.setdefault("BLOCKS_ARE_CONTIGUOUS", False)
  1088. # This forces all biases grad scatters to be done in the DQ iteration loop of the backwards
  1089. kernel_options.setdefault("WRITE_DQ", True)
  1090. any_inputs_on_cpu_device = (
  1091. query.device.type == "cpu"
  1092. or key.device.type == "cpu"
  1093. or value.device.type == "cpu"
  1094. )
  1095. # Determine what auxiliary outputs are needed
  1096. output_lse = return_lse
  1097. output_max = False
  1098. if return_aux is not None:
  1099. # New API takes precedence over legacy parameters
  1100. output_lse = return_aux.lse
  1101. output_max = return_aux.max_scores
  1102. # If forward kernel needs to return logsumexp is decided by this rule internally.
  1103. assert "OUTPUT_LOGSUMEXP" not in kernel_options
  1104. kernel_options["OUTPUT_LOGSUMEXP"] = True
  1105. if not output_lse:
  1106. # We used to check if q,k,v required grads but since captured buffers can require grad
  1107. # we always write unless in no_grad
  1108. kernel_options["OUTPUT_LOGSUMEXP"] = torch.is_grad_enabled()
  1109. if any_inputs_on_cpu_device:
  1110. # CPU with torch.compile now supports inference, and will not return lse
  1111. # TODO: support CPU for training and return lse
  1112. kernel_options["OUTPUT_LOGSUMEXP"] = False
  1113. # If forward kernel needs to return max is decided by this rule internally.
  1114. assert "OUTPUT_MAX" not in kernel_options
  1115. kernel_options["OUTPUT_MAX"] = output_max
  1116. if any_inputs_on_cpu_device and output_max:
  1117. # CPU doesn't support returning max yet
  1118. # TODO: support CPU for returning max
  1119. raise NotImplementedError("Returning max scores is not supported on CPU.")
  1120. kernel_options["OUTPUT_MAX"] = False
  1121. return kernel_options
  1122. def _validate_embed_dim(query: Tensor, key: Tensor, value: Tensor):
  1123. if query.size(-1) != key.size(-1):
  1124. raise ValueError(
  1125. f"Expect query and key/value to have the same embedding dimension "
  1126. f"but got E={query.size(-1)} and E={key.size(-1)}."
  1127. )
  1128. def _validate_device(query: Tensor, key: Tensor, value: Tensor):
  1129. """TODO: Remove once non cuda/cpu devices support is added
  1130. We only need to check query since we have already that q,k,v are on the same device
  1131. """
  1132. supported_devices = {"cuda", "cpu", "xpu", "hpu"}
  1133. if query.device.type not in supported_devices:
  1134. raise ValueError(
  1135. "FlexAttention is only supported on CUDA, CPU or HPU devices. "
  1136. f"Found input tensors on {query.device.type} device."
  1137. )
  1138. def _validate_nestedness(query: Tensor, key: Tensor, value: Tensor):
  1139. # Currently, inputs can only be all nested or no nested.
  1140. if query.is_nested != key.is_nested or key.is_nested != value.is_nested:
  1141. raise ValueError(
  1142. "FlexAttention does not support mixed nested tensor / non-nested tensor inputs. "
  1143. "Please file an issue requesting this if it is important to you."
  1144. )
  1145. if (
  1146. (query.is_nested and query._lengths is not None) # type: ignore[attr-defined]
  1147. or (key.is_nested and key._lengths is not None) # type: ignore[attr-defined]
  1148. or (value.is_nested and value._lengths is not None) # type: ignore[attr-defined]
  1149. ):
  1150. raise ValueError(
  1151. "FlexAttention does not support nested tensors that are non-contiguous with holes. "
  1152. "Please file an issue requesting this if it is important to you."
  1153. )
  1154. def _enforce_mem_layouts(
  1155. query: Tensor, key: Tensor, value: Tensor
  1156. ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  1157. """
  1158. Enforce memory layouts for query, key, and value tensors.
  1159. For non-FP8 dtypes, no action is taken.
  1160. For FP8 dtypes, we enforce the following memory layouts:
  1161. - Query tensor must be in row-major memory layout, as it will be the left-operand in the FP8 GEMM `q @ k.T`.
  1162. - Key tensor must be in row-major memory layout, as it will be transposed when used as the right-operand
  1163. in the FP8 GEMM `q @ k.T`, meaning it will correctly be in column-major memory layout for the GEMM.
  1164. - Value tensor must be in column-major memory layout, as it will be the right-operand in the FP8 GEMM `softmax_scores @ v`.
  1165. Returns the query, key, and value tensors with the enforced memory layouts.
  1166. """
  1167. def is_row_major(tensor: Tensor) -> bool:
  1168. return tensor.stride()[-1] == 1
  1169. def is_col_major(tensor: Tensor) -> bool:
  1170. return tensor.stride()[-2] == 1
  1171. # These memory layout constraint are only for FP8 GEMMs on NVIDIA GPU architectures >= SM89 and < SM100.
  1172. # This is because GPU arch < SM89 does not not support FP8 GEMMs, and
  1173. # SM100 has support for TN, NT, TT, NN layouts for FP8 GEMMs
  1174. # (i.e., left and right operands can be in row or column major layouts)
  1175. # so this check is only needed for older architectures.
  1176. # See: https://github.com/NVIDIA/cutlass/blob/main/media/docs/cpp/blackwell_functionality.md
  1177. fp8_dtypes = (
  1178. torch.float8_e4m3fn,
  1179. torch.float8_e5m2,
  1180. )
  1181. gemm_precision = query.dtype
  1182. should_enforce_mem_layout = (
  1183. gemm_precision in fp8_dtypes
  1184. and torch.version.cuda is not None
  1185. and torch.cuda.get_device_capability("cuda") >= (8, 9)
  1186. and torch.cuda.get_device_capability("cuda") < (10, 0)
  1187. )
  1188. if not should_enforce_mem_layout:
  1189. return query, key, value
  1190. # Query must be in row-major memory layout as the left-operand in the FP8 GEMM `q @ k.T`
  1191. if not is_row_major(query):
  1192. query = query.contiguous()
  1193. # Key must be in row-major memory layout as it will be transposed when used as the right-operand
  1194. # in the FP8 GEMM `q @ k.T`, meaning it will correctly be in column-major memory layout for the GEMM.
  1195. if not is_row_major(key):
  1196. key = key.contiguous()
  1197. # Value must be in column-major memory layout as the right-operand in the FP8 GEMM `softmax_scores @ v`
  1198. if not is_col_major(value):
  1199. value = value.transpose(-2, -1).contiguous().transpose(-2, -1)
  1200. return query, key, value
  1201. def flex_attention(
  1202. query: Tensor,
  1203. key: Tensor,
  1204. value: Tensor,
  1205. score_mod: Optional[_score_mod_signature] = None,
  1206. block_mask: Optional[BlockMask] = None,
  1207. scale: Optional[float] = None,
  1208. enable_gqa: bool = False,
  1209. return_lse: bool = False,
  1210. kernel_options: Optional[FlexKernelOptions] = None,
  1211. *,
  1212. return_aux: Optional[AuxRequest] = None,
  1213. ) -> Union[Tensor, tuple[Tensor, Tensor], tuple[Tensor, AuxOutput]]:
  1214. r"""This function implements scaled dot product attention with an arbitrary attention score modification function.
  1215. This function computes the scaled dot product attention between query, key, and value tensors with a user-defined
  1216. attention score modification function. The attention score modification function will be applied after the attention
  1217. scores have been calculated between the query and key tensors. The attention scores are calculated as follows:
  1218. The ``score_mod`` function should have the following signature:
  1219. .. code-block:: python
  1220. def score_mod(
  1221. score: Tensor,
  1222. batch: Tensor,
  1223. head: Tensor,
  1224. q_idx: Tensor,
  1225. k_idx: Tensor
  1226. ) -> Tensor:
  1227. Where:
  1228. - ``score``: A scalar tensor representing the attention score,
  1229. with the same data type and device as the query, key, and value tensors.
  1230. - ``batch``, ``head``, ``q_idx``, ``k_idx``: Scalar tensors indicating
  1231. the batch index, query head index, query index, and key/value index, respectively.
  1232. These should have the ``torch.int`` data type and be located on the same device as the score tensor.
  1233. Args:
  1234. query (Tensor): Query tensor; shape :math:`(B, Hq, L, E)`. For FP8 dtypes, should be in row-major memory layout for optimal performance.
  1235. key (Tensor): Key tensor; shape :math:`(B, Hkv, S, E)`. For FP8 dtypes, should be in row-major memory layout for optimal performance.
  1236. value (Tensor): Value tensor; shape :math:`(B, Hkv, S, Ev)`. For FP8 dtypes, should be in column-major memory layout for optimal performance.
  1237. score_mod (Optional[Callable]): Function to modify attention scores. By default no score_mod is applied.
  1238. block_mask (Optional[BlockMask]): BlockMask object that controls the blocksparsity pattern of the attention.
  1239. scale (Optional[float]): Scaling factor applied prior to softmax. If none, the default value is set to :math:`\frac{1}{\sqrt{E}}`.
  1240. enable_gqa (bool): If set to True, enables Grouped Query Attention (GQA) and broadcasts key/value heads to query heads.
  1241. return_lse (bool): Whether to return the logsumexp of the attention scores. Default is False. **Deprecated**: Use ``return_aux=AuxRequest(lse=True)`` instead.
  1242. kernel_options (Optional[FlexKernelOptions]):
  1243. Options to control the behavior of the underlying Triton kernels.
  1244. See :class:`FlexKernelOptions` for available options and usage examples.
  1245. return_aux (Optional[AuxRequest]): Specifies which auxiliary outputs to compute and return.
  1246. If None, only the attention output is returned. Use ``AuxRequest(lse=True, max_scores=True)``
  1247. to request both auxiliary outputs.
  1248. Returns:
  1249. output (Tensor): Attention output; shape :math:`(B, Hq, L, Ev)`.
  1250. When ``return_aux`` is not None:
  1251. aux (AuxOutput): Auxiliary outputs with requested fields populated.
  1252. When ``return_aux`` is None (deprecated paths):
  1253. lse (Tensor): Log-sum-exp of attention scores; shape :math:`(B, Hq, L)`. Only returned if ``return_lse=True``.
  1254. Shape legend:
  1255. - :math:`N: \text{Batch size} ... : \text{Any number of other batch dimensions (optional)}`
  1256. - :math:`S: \text{Source sequence length}`
  1257. - :math:`L: \text{Target sequence length}`
  1258. - :math:`E: \text{Embedding dimension of the query and key}`
  1259. - :math:`Ev: \text{Embedding dimension of the value}`
  1260. .. warning::
  1261. `torch.nn.attention.flex_attention` is a prototype feature in PyTorch.
  1262. Please look forward to a more stable implementation in a future version of PyTorch.
  1263. Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
  1264. """
  1265. # Some basic input validation
  1266. _validate_sdpa_input(query, key, value)
  1267. _validate_embed_dim(query, key, value)
  1268. _validate_device(query, key, value)
  1269. _validate_nestedness(query, key, value)
  1270. query, key, value = _enforce_mem_layouts(query, key, value)
  1271. if query.dim() != 4 or key.dim() != 4 or value.dim() != 4:
  1272. raise NotImplementedError("NYI: query, key, and value must be 4D tensors")
  1273. if (not enable_gqa) and query.size(-3) != key.size(-3):
  1274. raise ValueError(
  1275. f"Expect query and key/value to have the same number of heads "
  1276. f"but got Hq={query.size(-3)} and Hkv={key.size(-3)}. "
  1277. f"Try setting enable_gqa=True for GQA."
  1278. )
  1279. if enable_gqa:
  1280. Hq = query.size(1)
  1281. Hkv = key.size(1)
  1282. if Hq % Hkv != 0:
  1283. raise ValueError(
  1284. f"Expect number of query heads to be a multiple of kv heads for GQA "
  1285. f"but got Hq={Hq} and Hkv={Hkv}."
  1286. )
  1287. if query.size(0) != key.size(0):
  1288. if block_mask is None:
  1289. raise ValueError(
  1290. f"Expect query and key/value to have the same batch size, "
  1291. f"or non-none block_mask, "
  1292. f"but got block_mask=None, Bq={query.size(0)}, and Bkv={key.size(0)}."
  1293. )
  1294. if block_mask.kv_num_blocks.size(0) != query.size(0):
  1295. raise ValueError(
  1296. f"Expect query and key/value to have the same batch size, "
  1297. f"or block_mask and query to have the same batch size, "
  1298. f"but got Bq={query.size(0)}, Bkv={key.size(0)}, B_block_mask={block_mask.kv_num_blocks.size(0)}."
  1299. )
  1300. if score_mod is None:
  1301. score_mod = _identity
  1302. elif query.is_nested:
  1303. # use same NJT if the ragged structures for sequence lengths match between q and kv
  1304. kv = (
  1305. query
  1306. if query.size(query._ragged_idx) == key.size(query._ragged_idx) # type: ignore[attr-defined]
  1307. else key
  1308. )
  1309. score_mod = _nested_mod_func_adapter(score_mod, query, kv, is_score_mod=True) # type: ignore[assignment]
  1310. if block_mask is None:
  1311. block_mask = _create_empty_block_mask(query, key)
  1312. if (
  1313. block_mask.BLOCK_SIZE[0] == _LARGE_SPARSE_BLOCK_SIZE
  1314. and block_mask.BLOCK_SIZE[1] == _LARGE_SPARSE_BLOCK_SIZE
  1315. ):
  1316. # This corresponds to the case where we essentially have a "no-op" block mask.
  1317. pass
  1318. elif query.is_nested:
  1319. if block_mask.shape[-2] != query._values.size(query._ragged_idx - 1): # type: ignore[attr-defined]
  1320. raise RuntimeError(
  1321. f"block_mask of shape {block_mask.shape} is not compatible with nested tensor input "
  1322. f"with total sequence length of {query._values.size(query._ragged_idx - 1)}" # type: ignore[attr-defined]
  1323. )
  1324. else:
  1325. block_mask_q_len = block_mask.shape[-2]
  1326. block_mask_kv_len = block_mask.shape[-1]
  1327. if query.size(-2) > block_mask_q_len or key.size(-2) > block_mask_kv_len:
  1328. raise ValueError(
  1329. f"block_mask was created for block_mask.shape={block_mask.shape} but got q_len={query.size(-2)} and kv_len={key.size(-2)}. "
  1330. "As the block mask was created for a smaller length than you're using it for, you likely need to create a new block mask."
  1331. )
  1332. elif (
  1333. query.size(-2) < block_mask_q_len and key.size(-2) <= block_mask_kv_len
  1334. ) or (query.size(-2) <= block_mask_q_len and key.size(-2) < block_mask_kv_len):
  1335. raise ValueError(
  1336. f"block_mask was created for block_mask.shape={block_mask.shape} but got q_len={query.size(-2)} and kv_len={key.size(-2)}. "
  1337. "As the block mask was created for a larger length than you're using it for, you can either 1. create a new block mask with the correct length, or 2. 'adjust' the existing block mask to the correct length by calling block_mask._adjust(q_len, kv_len). This essentially 'crops' the block mask to the upper left corner, which does not work for all mask_mods!"
  1338. )
  1339. assert query.size(-2) == block_mask_q_len
  1340. assert key.size(-2) == block_mask_kv_len
  1341. if scale is None:
  1342. scale = 1.0 / math.sqrt(query.size(-1))
  1343. if query.device != block_mask.kv_num_blocks.device: # type: ignore[union-attr]
  1344. raise RuntimeError(
  1345. f"Expect q/k/v and block_mask to be on the same device "
  1346. f"but got {query.device} and {block_mask.kv_num_blocks.device}." # type: ignore[union-attr]
  1347. )
  1348. # Handle deprecation warnings for old parameters
  1349. if return_lse and return_aux is not None:
  1350. raise ValueError(
  1351. "Cannot specify both return_lse and return_aux. "
  1352. "return_lse is deprecated, please use return_aux=AuxRequest(lse=True) instead."
  1353. )
  1354. elif return_lse and return_aux is None:
  1355. _warn_once(
  1356. "deprecated_return_lse",
  1357. "return_lse is deprecated and will be removed in v2.10. "
  1358. "Please use return_aux=AuxRequest(lse=True) instead.",
  1359. category=FutureWarning,
  1360. )
  1361. kernel_options = _apply_kernel_options(
  1362. query,
  1363. key,
  1364. value,
  1365. return_lse,
  1366. kernel_options,
  1367. return_aux,
  1368. )
  1369. def _finalize_outputs(
  1370. out,
  1371. lse,
  1372. max_scores,
  1373. *,
  1374. return_aux: Optional[AuxRequest],
  1375. return_lse: bool,
  1376. ):
  1377. """Normalize stats and build return value (aux-aware, legacy-compatible)."""
  1378. ln2 = math.log(2.0)
  1379. return_lse = return_lse or return_aux is not None and return_aux.lse
  1380. return_max = return_aux is not None and return_aux.max_scores
  1381. lse_scaled = lse * ln2 if (return_lse and lse.numel() > 0) else None
  1382. max_scaled = (
  1383. max_scores * ln2 if (return_max and max_scores.numel() > 0) else None
  1384. )
  1385. if return_aux is not None:
  1386. return out, AuxOutput(
  1387. lse=lse_scaled,
  1388. max_scores=max_scaled,
  1389. )
  1390. if return_lse:
  1391. return out, lse_scaled
  1392. return out
  1393. if torch.compiler.is_dynamo_compiling():
  1394. # mark head_dim and number of heads to be static
  1395. for x in [query, key, value]:
  1396. torch._dynamo.mark_static(x, -3)
  1397. torch._dynamo.mark_static(x, -1)
  1398. out, lse, max_scores = flex_attention_hop(
  1399. query,
  1400. key,
  1401. value,
  1402. score_mod,
  1403. block_mask.as_tuple(),
  1404. scale,
  1405. kernel_options, # type: ignore[union-attr]
  1406. )
  1407. return _finalize_outputs(
  1408. out, lse, max_scores, return_aux=return_aux, return_lse=return_lse
  1409. )
  1410. if not _FLEX_ATTENTION_DISABLE_COMPILE_DEBUG:
  1411. _warn_once(
  1412. warning_id="flex_attention_performance",
  1413. message=(
  1414. "flex_attention called without torch.compile() - this will use an unfused implementation that materializes the full scores matrix instead of generating a fused kernel.\n\n"
  1415. "SOLUTION: Use torch.compile(flex_attention)(...)\n\n"
  1416. "If you want to debug your score_mod/mask_mod, you can set:\n"
  1417. "torch.nn.attention.flex_attention._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True\n\n"
  1418. "This will allow you to use print statements or breakpoints. Note: This doesn't work with the backwards pass and may produce incorrect results."
  1419. ),
  1420. )
  1421. if not torch._dynamo.is_dynamo_supported():
  1422. raise RuntimeError("flex_attention requires dynamo support")
  1423. from torch._dynamo.backends.debugging import (
  1424. make_eager_backend_with_torch_function_mode,
  1425. )
  1426. # Dynamo is expecting a callable with "__code__" attribute.
  1427. # We cannot directly pass hop to it. So we wrap it in a dummy function.
  1428. def _flex_attention_hop_wrapper(*args, **kwargs):
  1429. return flex_attention_hop(*args, **kwargs)
  1430. with _set_compilation_env():
  1431. with torch._dynamo.utils.disable_cache_limit():
  1432. with _temp_remove_pre_dispatch_torch_function_mode():
  1433. with _temp_remove_metadata_torch_function_mode() as metadata_mode:
  1434. if metadata_mode:
  1435. backend: Union[str, Callable[..., Any]] = (
  1436. make_eager_backend_with_torch_function_mode(metadata_mode)
  1437. )
  1438. else:
  1439. backend = "eager"
  1440. if _FLEX_ATTENTION_DISABLE_COMPILE_DEBUG:
  1441. flex_fn = _flex_attention_hop_wrapper
  1442. else:
  1443. flex_fn = torch.compile(
  1444. _flex_attention_hop_wrapper, backend=backend, fullgraph=True
  1445. )
  1446. out, lse, max_scores = flex_fn(
  1447. query,
  1448. key,
  1449. value,
  1450. score_mod,
  1451. block_mask.as_tuple(), # type: ignore[union-attr]
  1452. scale,
  1453. kernel_options,
  1454. )
  1455. return _finalize_outputs(
  1456. out, lse, max_scores, return_aux=return_aux, return_lse=return_lse
  1457. )