Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ def __init__(
barrier_id=8,
num_threads=(self.num_reduce_warps + 1) * self.threads_per_warp,
)
# TMEM dealloc (compute warp 0) must be ordered after the reduce
# warps' final dKV T2R has drained; otherwise a successor CTA can

@Jie-Fang Jie-Fang Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there's no successor CTA in our kernel. 1 CTA/SM is in this kernel so that there's no issue even if deallocating tmem early. Could you modify the comments to not make readers confused?

But I agree that we need to add a namedbarrier to ensure the dealloc tmem happens after the store dKV.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review! You're right that this kernel is 1 CTA/SM, so there is no successor CTA and the old wording was misleading. I've reworded the two comments (the tmem_dealloc_barrier definition and the dealloc_tmem site) to attribute the barrier to the intra-CTA ordering instead: compute warp 0's dealloc_tmem must happen after the reduce warps have drained their final dKV T2R reads (the reads that feed store_dKV), otherwise the dealloc would race those in-flight T2R loads within the same CTA. The successor-CTA framing is removed. The barrier and all logic are unchanged — comment-only in 18c0277.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good, thank you!

# re-allocate the columns while T2R is still in flight. Participants:
# num_reduce_warps (arrive) + compute warp 0 (arrive_and_wait).
self.tmem_dealloc_barrier = pipeline.NamedBarrier(
barrier_id=9,
num_threads=(self.num_reduce_warps + 1) * self.threads_per_warp,
)

self.tmem_S_offset = 0
self.tmem_dP_offset = 0
Expand Down Expand Up @@ -343,7 +351,7 @@ def __call__(
dOT_smem_layout_staged = sm100_utils.make_smem_layout_a(dOP_tiled_mma, self.dOP_cta_tiler, self.element_dtype, self.load_mma_QdO_stage)
P_smem_layout_staged = sm100_utils.make_smem_layout_b(dOP_tiled_mma, self.dOP_mma_tiler, self.element_dtype, self.compute_mma_P_stage)
P_smem_layout_store_staged = sm100_utils.make_smem_layout_epi(
self.element_dtype, utils.LayoutEnum.COL_MAJOR, self.QK_mma_tiler[:2], self.load_mma_K_stage
self.element_dtype, utils.LayoutEnum.COL_MAJOR, self.QK_mma_tiler[:2], self.compute_mma_P_stage
)
K_smem_layout_staged_2 = sm100_utils.make_smem_layout_a(KdS_tiled_mma, self.KdS_cta_tiler, self.element_dtype, self.load_mma_K_stage)
if cutlass.const_expr(not self.same_hdim_kv):
Expand All @@ -364,7 +372,7 @@ def __call__(
QT_tail_smem_layout_staged = None
dS_smem_layout_staged = sm100_utils.make_smem_layout_b(QdS_tiled_mma, self.QdS_mma_tiler, self.element_dtype, self.compute_mma_dS_stage)
dS_smem_layout_store_staged = sm100_utils.make_smem_layout_epi(
self.element_dtype, utils.LayoutEnum.COL_MAJOR, self.dOV_mma_tiler[:2], self.load_mma_K_stage
self.element_dtype, utils.LayoutEnum.COL_MAJOR, self.dOV_mma_tiler[:2], self.compute_mma_dS_stage
)

dQ_smem_layout_staged = sm100_utils.make_smem_layout_epi(
Expand Down Expand Up @@ -1028,6 +1036,10 @@ def bwd(
)

if warp_idx == self.compute_warp_id[0]:
# Wait until every reduce warp has finished (and fenced) its
# final dKV T2R before freeing the TMEM columns for successor
# CTAs.
self.tmem_dealloc_barrier.arrive_and_wait()
cute.arch.dealloc_tmem(tmem_ptr_base, self.num_tmem_alloc_cols)

elif warp_idx in self.reduce_warp_id:
Expand All @@ -1048,6 +1060,11 @@ def bwd(
topk,
mma_reduce_dKV_pipeline,
)
# All T2R reads issued by this warp are complete here (each
# store_dKV / T2R block fences before its pipeline release);
# signal compute warp 0 that TMEM dealloc is now safe.
# arrive() only -- the reduce warps need not stall.
self.tmem_dealloc_barrier.arrive()

elif warp_idx in self.load_KV_warp_id:
cute.arch.setmaxregister_decrease(self.num_regs_load_KV)
Expand Down Expand Up @@ -1776,13 +1793,13 @@ def compute(
thr_t2r_dP = tiled_t2r_dP.get_slice(tidx % 128)

tTR_cS = thr_t2r_S.partition_D(cS)
tTR_sS = thr_t2r_S.partition_D(sP_store[None, None, compute_mma_P_producer_state.index])
tTR_sS = thr_t2r_S.partition_D(sP_store[None, None, 0])
tTR_rS = cute.make_rmem_tensor(tTR_sS.shape, self.acc_dtype)

tTR_tS = thr_t2r_S.partition_S(tStS)

tTR_cdP = thr_t2r_dP.partition_D(cdP)
tTR_sdP = thr_t2r_dP.partition_D(sdS_store[None, None, compute_mma_dS_producer_state.index])
tTR_sdP = thr_t2r_dP.partition_D(sdS_store[None, None, 0])
tTR_rdP = cute.make_rmem_tensor(tTR_sdP.shape, self.acc_dtype)

tTR_tdP = thr_t2r_dP.partition_S(tdPtdP)
Expand All @@ -1799,15 +1816,15 @@ def compute(
)
smem_store_p = cute.make_tiled_copy_D(smem_store_atom, tiled_t2r_S)
thr_smem_store_p = smem_store_p.get_slice(tidx % 128)
sP_store_slice = sP_store[None, None, compute_mma_P_producer_state.index]
tRS_sP = thr_smem_store_p.partition_D(sP_store_slice)
tRS_rP = cute.make_rmem_tensor(tRS_sP.shape, self.element_dtype)
# Keep the stage mode: the store slot must follow the producer state
# when compute_mma_P_stage > 1 (slot selection happens at the copy).
tRS_sP = thr_smem_store_p.partition_D(sP_store)
tRS_rP = cute.make_rmem_tensor(tRS_sP[None, None, None, 0].shape, self.element_dtype)

smem_store_ds = cute.make_tiled_copy_D(smem_store_atom, tiled_t2r_dP)
thr_smem_store_ds = smem_store_ds.get_slice(tidx % 128)
sdS_store_slice = sdS_store[None, None, compute_mma_dS_producer_state.index]
tRS_sdS = thr_smem_store_ds.partition_D(sdS_store_slice)
tRS_rdS = cute.make_rmem_tensor(tRS_sdS.shape, self.element_dtype)
tRS_sdS = thr_smem_store_ds.partition_D(sdS_store)
tRS_rdS = cute.make_rmem_tensor(tRS_sdS[None, None, None, 0].shape, self.element_dtype)

tile_index = tile_count - 1
while tile_index >= 0:
Expand Down Expand Up @@ -1838,7 +1855,10 @@ def compute(

# ======= stsm ============
tRS_rP.store(smem_store_p.retile(tTR_rS_f16).load())
cute.copy(smem_store_p, tRS_rP, tRS_sP)
if cutlass.const_expr(self.compute_mma_P_stage == 1):
cute.copy(smem_store_p, tRS_rP, tRS_sP[None, None, None, 0])
else:
cute.copy(smem_store_p, tRS_rP, tRS_sP[None, None, None, compute_mma_P_producer_state.index])

# Fence for shared memory
cute.arch.fence_proxy(
Expand Down Expand Up @@ -1883,7 +1903,10 @@ def compute(
mma_compute_dP_consumer_state.advance()

tRS_rdS.store(smem_store_ds.retile(tTR_rdP_f16).load())
cute.copy(smem_store_ds, tRS_rdS, tRS_sdS)
if cutlass.const_expr(self.compute_mma_dS_stage == 1):
cute.copy(smem_store_ds, tRS_rdS, tRS_sdS[None, None, None, 0])
else:
cute.copy(smem_store_ds, tRS_rdS, tRS_sdS[None, None, None, compute_mma_dS_producer_state.index])

# self.compute_sync_barrier.arrive_and_wait()

Expand Down
86 changes: 86 additions & 0 deletions test/python/fe_api/dsa/test_DSA_sparse_attention_backward.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,89 @@ def fail_on_pad(*args, **kwargs):
atol=5e-2,
rtol=5e-2,
)


@pytest.mark.L0
@torch_fork_set_rng(seed=0)
def test_DSA_sparse_attention_backward_staged_store():
"""Regression test for the staged P/dS store paths of the SM100 kernel.

The compute->MMA smem handoff for P and dS must stay correct when
compute_mma_P_stage / compute_mma_dS_stage are raised above 1: the
store-side layouts and the per-iteration store slot have to follow the
producer pipeline state. This test deepens both pipelines to 2 and
requires dq to match the stage-1 baseline bitwise (dq is written by TMA
with a single writer per element, hence deterministic; dkv/d_sink are
fp32 atomic reductions, so they are only gated on NaN and relative
parity).
"""
try:
from cudnn import DSA
from cudnn.deepseek_sparse_attention.sparse_attention_backward import (
api as _dsa_bwd_api,
_interface_sm100 as _dsa_bwd_iface,
dsa_bwd_sm100 as _dsa_bwd_kmod,
)
except ImportError:
pytest.skip("Environment not supported: cudnn[cutedsl] not installed")

major, minor = torch.cuda.get_device_capability()
if major * 10 + minor < 100:
pytest.skip("staged-store regression test targets the SM100 kernel")

s_q = s_kv = 512
h, d, topk = 64, 512, 256 # topk/64 = 4 tiles -> the pipelines really cycle
device = "cuda"
q = torch.randn(s_q, h, d, dtype=torch.bfloat16, device=device) / 10
kv = torch.randn(s_kv, d, dtype=torch.bfloat16, device=device) / 10
attn_sink = torch.randn(h, dtype=torch.float32, device=device)
topk_idxs = torch.stack([torch.randperm(s_kv, device=device)[:topk] for _ in range(s_q)]).to(torch.int32)
topk_length = torch.full((s_q,), topk, dtype=torch.int32, device=device)
softmax_scale = 1.0 / math.sqrt(d)

out, lse = ref_sparse_attention_forward(q, kv, attn_sink, topk_idxs, topk_length=topk_length, softmax_scale=softmax_scale)
dout = torch.randn_like(out)

orig_setup = _dsa_bwd_kmod.FlashAttentionDSABackwardSm100._setup_attributes

def run(stage_overrides):
def patched(self):
orig_setup(self)
for name, value in stage_overrides.items():
setattr(self, name, value)

_dsa_bwd_kmod.FlashAttentionDSABackwardSm100._setup_attributes = patched
_dsa_bwd_iface.flash_attn_bwd_sm100.compile_cache.clear()
_dsa_bwd_api._cache_of_SparseAttentionBackwardObjects.clear()
try:
result = DSA.sparse_attention_backward_wrapper(
q,
kv,
out,
dout,
lse,
attn_sink,
topk_idxs,
softmax_scale=softmax_scale,
topk_length=topk_length,
)
torch.cuda.synchronize()
return result["dq"], result["dkv"], result["d_sink"]
finally:
_dsa_bwd_kmod.FlashAttentionDSABackwardSm100._setup_attributes = orig_setup
_dsa_bwd_iface.flash_attn_bwd_sm100.compile_cache.clear()
_dsa_bwd_api._cache_of_SparseAttentionBackwardObjects.clear()

dq_ref, dkv_ref, d_sink_ref = run({})
assert not torch.isnan(dq_ref).any(), "stage-1 baseline produced NaN"

dq, dkv, d_sink = run({"compute_mma_P_stage": 2, "compute_mma_dS_stage": 2})

assert not torch.isnan(dq).any() and not torch.isnan(dkv).any() and not torch.isnan(d_sink).any(), "staged store paths produced NaN gradients"
assert torch.equal(dq, dq_ref), "dq must be bitwise-identical between stage 1 and stage 2"

def rel_l2(a, b):
return ((a.float() - b.float()).norm() / b.float().norm().clamp_min(1e-30)).item()

assert rel_l2(dkv, dkv_ref) < 1e-4, "dkv parity vs stage-1 baseline"
assert rel_l2(d_sink, d_sink_ref) < 1e-4, "d_sink parity vs stage-1 baseline"