qsa_fa_fallback.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """SM121 (DGX Spark / GB10) fallback varlen attention for Qwen sparse attention.
  2. Upstream `qwen_sparse_attn_backend._resolve_flash_attn_varlen_func` prefers
  3. classic FA2 and otherwise falls back to flash-attn-4's CuTe DSL interface.
  4. FA4's cute kernels do not compile on SM121 (MLIR layout-congruence error),
  5. so this module provides a drop-in `flash_attn_varlen_func` backed by a Triton
  6. FlashDecoding-style kernel specialized for the QSA call contract:
  7. * every "sequence" has exactly ONE query row (cu_seqlens_q = arange),
  8. * variable numbers of gathered KV rows per sequence (<= topk),
  9. * GQA (num_q_heads a multiple of num_kv_heads),
  10. * cu_seqlens_* are read on-device, so the kernel is CUDA-graph replay safe
  11. (the QSA backend rewrites cu_seqlens_k contents during graph replay).
  12. """
  13. from __future__ import annotations
  14. import torch
  15. import triton
  16. import triton.language as tl
  17. @triton.jit
  18. def _varlen_one_q_attn_kernel(
  19. q_ptr, k_ptr, v_ptr, o_ptr,
  20. cu_seqlens_q_ptr, cu_seqlens_k_ptr,
  21. sm_scale,
  22. HQ: tl.constexpr, HKV: tl.constexpr,
  23. D: tl.constexpr, D_PAD: tl.constexpr,
  24. BLOCK_KV: tl.constexpr,
  25. q_stride_t: tl.constexpr, q_stride_h: tl.constexpr,
  26. k_stride_t: tl.constexpr, k_stride_h: tl.constexpr,
  27. v_stride_t: tl.constexpr, v_stride_h: tl.constexpr,
  28. o_stride_t: tl.constexpr, o_stride_h: tl.constexpr,
  29. ):
  30. """One program per (query row, q head): online-softmax attention over the
  31. gathered KV rows of that query, 1-token query, causal is a no-op."""
  32. row = tl.program_id(0)
  33. head = tl.program_id(1)
  34. # QSA always emits one query per varlen sequence.
  35. q_start = tl.load(cu_seqlens_q_ptr + row)
  36. k_start = tl.load(cu_seqlens_k_ptr + row)
  37. k_end = tl.load(cu_seqlens_k_ptr + row + 1)
  38. offs_d = tl.arange(0, D_PAD)
  39. mask_d = offs_d < D
  40. q = tl.load(
  41. q_ptr + (q_start * q_stride_t) + (head * q_stride_h) + offs_d,
  42. mask=mask_d, other=0.0,
  43. ).to(tl.float32)
  44. kh = head // (HQ // HKV)
  45. m_i = -float("inf")
  46. l_i = 0.0
  47. acc = tl.zeros([D_PAD], dtype=tl.float32)
  48. for k0 in range(k_start, k_end, BLOCK_KV):
  49. offs_kv = k0 + tl.arange(0, BLOCK_KV)
  50. mask_kv = offs_kv < k_end
  51. kv_ptrs = (offs_kv * k_stride_t) + (kh * k_stride_h)
  52. k_blk = tl.load(
  53. k_ptr + kv_ptrs[:, None] + offs_d[None, :],
  54. mask=mask_kv[:, None] & mask_d[None, :], other=0.0,
  55. ).to(tl.float32)
  56. scores = tl.sum(q[None, :] * k_blk, axis=1) * sm_scale
  57. scores = tl.where(mask_kv, scores, -float("inf"))
  58. m_new = tl.maximum(m_i, tl.max(scores, axis=0))
  59. alpha = tl.exp(m_i - m_new)
  60. p = tl.exp(scores - m_new)
  61. l_i = l_i * alpha + tl.sum(p, axis=0)
  62. acc = acc * alpha
  63. v_ptrs = (offs_kv * v_stride_t) + (kh * v_stride_h)
  64. v_blk = tl.load(
  65. v_ptr + v_ptrs[:, None] + offs_d[None, :],
  66. mask=mask_kv[:, None] & mask_d[None, :], other=0.0,
  67. ).to(tl.float32)
  68. acc += tl.sum(p[:, None] * v_blk, axis=0)
  69. m_i = m_new
  70. out = acc / tl.where(l_i > 0.0, l_i, 1.0)
  71. tl.store(
  72. o_ptr + (row * o_stride_t) + (head * o_stride_h) + offs_d,
  73. out.to(o_ptr.dtype.element_ty),
  74. mask=mask_d,
  75. )
  76. def _next_pow2(n: int) -> int:
  77. return triton.next_power_of_2(max(n, 16))
  78. def triton_varlen_attn_func(
  79. q: torch.Tensor,
  80. k: torch.Tensor,
  81. v: torch.Tensor,
  82. cu_seqlens_q: torch.Tensor,
  83. cu_seqlens_k: torch.Tensor,
  84. max_seqlen_q: int = 1,
  85. max_seqlen_k: int = 0,
  86. softmax_scale: float = 1.0,
  87. causal: bool = True,
  88. **kwargs,
  89. ) -> torch.Tensor:
  90. """Drop-in replacement for flash_attn.flash_attn_varlen_func (QSA calls).
  91. Supports the exact shape the QSA sparse backend issues: one query row per
  92. varlen sequence, GQA, matching q/k/v dtypes (bf16/fp16), any head_dim.
  93. """
  94. if not q.is_cuda:
  95. raise RuntimeError("qsa_fa_fallback requires CUDA tensors")
  96. if q.dim() != 3 or k.dim() != 3 or v.dim() != 3:
  97. raise RuntimeError(f"expected 3D q/k/v, got {q.shape}/{k.shape}/{v.shape}")
  98. if k.dtype != q.dtype or v.dtype != q.dtype:
  99. raise RuntimeError(
  100. f"qsa_fa_fallback: q/k/v dtypes must match "
  101. f"({q.dtype}/{k.dtype}/{v.dtype}); keep KV cache in model dtype"
  102. )
  103. if q.dtype not in (torch.bfloat16, torch.float16):
  104. raise RuntimeError(f"qsa_fa_fallback: unsupported dtype {q.dtype}")
  105. total_q, hq, d = q.shape
  106. total_k, hkv, dk = k.shape
  107. if dk != d or v.shape[2] != d:
  108. raise RuntimeError("head_dim mismatch")
  109. if hq % hkv != 0:
  110. raise RuntimeError(f"GQA mismatch: {hq} q heads vs {hkv} kv heads")
  111. num_seqs = total_q
  112. if cu_seqlens_k.numel() != num_seqs + 1:
  113. raise RuntimeError("cu_seqlens_k size mismatch")
  114. # Host-side syncs (torch.equal) are illegal inside CUDA graph capture;
  115. # the eager path has already validated the one-query-per-sequence contract
  116. # before any graph is captured, so skip the check while capturing.
  117. if not torch.cuda.is_current_stream_capturing():
  118. q_lens_ok = bool(
  119. torch.equal(
  120. cu_seqlens_q[1:] - cu_seqlens_q[:-1],
  121. torch.ones_like(cu_seqlens_q[1:]),
  122. )
  123. )
  124. if not q_lens_ok:
  125. raise RuntimeError(
  126. "qsa_fa_fallback only supports q_len==1 per varlen sequence "
  127. "(the QSA backend's only call shape)"
  128. )
  129. if cu_seqlens_q.dtype != torch.int32:
  130. cu_seqlens_q = cu_seqlens_q.to(torch.int32)
  131. if cu_seqlens_k.dtype != torch.int32:
  132. cu_seqlens_k = cu_seqlens_k.to(torch.int32)
  133. q_c = q if q.is_contiguous() else q.contiguous()
  134. k_c = k if k.is_contiguous() else k.contiguous()
  135. v_c = v if v.is_contiguous() else v.contiguous()
  136. out = torch.empty_like(q_c)
  137. BLOCK_KV = 64
  138. grid = (num_seqs, hq)
  139. _varlen_one_q_attn_kernel[grid](
  140. q_c, k_c, v_c, out,
  141. cu_seqlens_q,
  142. cu_seqlens_k,
  143. softmax_scale,
  144. HQ=hq, HKV=hkv,
  145. D=d, D_PAD=_next_pow2(d),
  146. BLOCK_KV=BLOCK_KV,
  147. q_stride_t=q_c.stride(0), q_stride_h=q_c.stride(1),
  148. k_stride_t=k_c.stride(0), k_stride_h=k_c.stride(1),
  149. v_stride_t=v_c.stride(0), v_stride_h=v_c.stride(1),
  150. o_stride_t=out.stride(0), o_stride_h=out.stride(1),
  151. num_warps=4,
  152. )
  153. return out