Skip to content
Open
Show file tree
Hide file tree
Changes from all 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 @@ -100,6 +100,7 @@
from cutlass.cute.nvgpu import OperandMajorMode, cpasync, tcgen05
from cutlass.cute.runtime import make_ptr
from cutlass.cutlass_dsl import T, dsl_user_op
from cutlass.experimental import primitives as prims

from ..k3r_comm import k3_lamport_ar
from .k3_latent_fp8_gemm import (
Expand Down Expand Up @@ -1789,7 +1790,8 @@ def epilogue(
cute.arch.mbarrier_arrive_and_expect_tx(
mbox_full, my_chunks * ((S - 1) * MMA_M * 16)
)
cute.arch.mbarrier_wait(mbox_full, 0)
# The peers' st.async complete-tx releases at cluster scope.
_mbar_wait_cluster_acquire(mbox_full, 0)
for c in cutlass.range_constexpr(nchunks):
_, col0 = tTR_cAcc[4 * c]
if col0 < m:
Expand Down Expand Up @@ -2103,6 +2105,23 @@ def _st_async_v4_f32(local_addr, v0, v1, v2, v3, local_mbar, peer, *, loc=None,
)


@cute.jit
def _mbar_wait_cluster_acquire(mbar_ptr: cute.Pointer, phase: Int32):
"""Wait for ``phase`` of this CTA's mbarrier at ``mbar_ptr``, acquiring at cluster scope.

``cute.arch.mbarrier_wait`` acquires at CTA scope. The peers' ``st.async ...
mbarrier::complete_tx`` that completes this barrier releases at cluster scope, and only a
cluster-scope acquire orders their payload before the reads that follow the wait: a relaxed
cluster-scope try_wait loop and an acquire fence restricted to shared::cluster (the ISA's
acquire pattern for it; unlike ``.acquire.cluster`` on the wait it adds no L1 invalidate).
"""
while not prims.mbarrier_try_wait_parity(
mbar_ptr, phase, scope=prims.MBarrierScope.CLUSTER, order=prims.MemOrder.RELAXED
):
pass
prims.fence_sync_restrict(prims.MemOrder.ACQUIRE)


@dsl_user_op
def _sts_u16(addr, value, *, loc=None, ip=None):
_asm(
Expand Down Expand Up @@ -2921,7 +2940,8 @@ def epilogue(
cute.arch.mbarrier_arrive_and_expect_tx(
storage.mbox_full, my_chunks * ((S - 1) * MMA_M * 16)
)
cute.arch.mbarrier_wait(storage.mbox_full, 0)
# The peers' st.async complete-tx releases at cluster scope.
_mbar_wait_cluster_acquire(storage.mbox_full, 0)
for i in cutlass.range_constexpr(self.chunks_cap):
if i < my_chunks:
acc = [rOwn[i * 4 + v] for v in range(4)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
_ldg_v4_b32,
_lds_v4_b32,
_lds_v4_f32,
_mbar_wait_cluster_acquire,
_mbarrier_arrive_remote,
_quant_bf16x8_to_e4m3,
_s2t_partition_sf,
Expand Down Expand Up @@ -1141,7 +1142,8 @@ def epilogue(
cute.arch.mbarrier_arrive_and_expect_tx(
storage.mbox_full, my_chunks * ((S - 1) * MMA_M * 16)
)
cute.arch.mbarrier_wait(storage.mbox_full, 0)
# The peers' st.async complete-tx releases at cluster scope.
_mbar_wait_cluster_acquire(storage.mbox_full, 0)
for i in cutlass.range_constexpr(self.chunks_cap):
if i < my_chunks:
acc = [rOwn[i * 4 + v] for v in range(4)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from cutlass.cute.nvgpu import tcgen05
from cutlass.cute.runtime import from_dlpack
from cutlass.cutlass_dsl import T, dsl_user_op
from cutlass.experimental import primitives as prims

#: Per-CTA SMEM capacity reported by CuTeDSL on SM100/SM103.
_SMEM_CAPACITY_BYTES = utils.get_smem_capacity_in_bytes("sm_100")
Expand Down Expand Up @@ -318,6 +319,38 @@ def _store_shared_remote_v4(
)


@dsl_user_op
def _mbarrier_wait_acquire_cluster(
mbar_ptr: "cute.Pointer",
phase: "Int32",
*,
loc=None,
ip=None,
) -> None:
"""``cute.arch.mbarrier_wait`` with ``.acquire.cluster`` semantics.

The peers' ``st.async`` complete-tx operations release at cluster scope; the
default ``.acquire.cta`` wait does not synchronize with other CTAs' threads.
"""
llvm.inline_asm(
None,
[
mbar_ptr.toint(loc=loc, ip=ip).ir_value(),
phase.ir_value(loc=loc, ip=ip),
],
"{\n\t.reg .pred P1;\n\tLAB_WAIT:\n\t"
"mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 "
"P1, [$0], $1, 10000000;\n\t"
"@P1 bra DONE;\n\tbra LAB_WAIT;\n\tDONE:\n\t}",
"r,r,~{memory}",
has_side_effects=True,
is_align_stack=False,
asm_dialect=llvm.AsmDialect.AD_ATT,
loc=loc,
ip=ip,
)


#: Rank that gathers partials and stores the output.
OWNER_RANK = 0

Expand Down Expand Up @@ -642,6 +675,8 @@ def mma_warp(
):
num_tmem_cols = 256
cute.arch.alloc_tmem(num_tmem_cols, tmem_base_ptr, is_two_cta=False)
# Order the allocation before the arrive that publishes the TMEM base pointer.
prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC)
cute.arch.mbarrier_arrive(bar_tmem_alloc)
cute.arch.relinquish_tmem_alloc_permit(is_two_cta=False)

Expand All @@ -652,6 +687,7 @@ def mma_warp(
for k_tile in cutlass.range(k_tile_count, unroll=1):
stage = k_tile % self.num_ab_stage
cute.arch.mbarrier_wait(bar_full + stage, full_phase)
prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC)
for k_block in range(mma_inst_tile_k):
if k_block == 0:
mma_atom.set(tcgen05.Field.ACCUMULATE, k_tile != 0)
Expand All @@ -670,8 +706,15 @@ def mma_warp(

with cute.arch.elect_one():
tcgen05.commit(bar_mma_epilog, None, self.cta_group)
# The release arrival must land in phase 1. Made while phase 0 is still
# open, it counts toward phase 0, and the parity-1 wait can then pass
# before the epilogue has read TMEM.
cute.arch.mbarrier_wait(bar_tmem_alloc, 0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Would it make sense to bring over the handoff fences from FlashInfer #7443 for BF16 and DSpark as well? In particular, after_thread_sync after the MMA wait and before_thread_sync after wait::ld, before signaling that TMEM can be freed.

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.

Agreed, done in 6223b45 for both the BF16 split-K GEMM and the DSpark push GEMM that derives from it, mirroring the hand-off fences of FlashInfer #7443: tcgen05.fence::after_thread_sync after the alloc-barrier wait and after the MMA-completion wait in the epilogue, tcgen05.fence::before_thread_sync after wait::ld before the arrive that hands TMEM back, before_thread_sync after the allocation before it is published, and after_thread_sync in the MMA warp after each full-barrier wait and after the final wait before dealloc. Spelled through cutlass.experimental.primitives.tcgen05_fence.

cute.arch.mbarrier_arrive(bar_tmem_alloc)
cute.arch.mbarrier_wait(bar_tmem_alloc, 1)
# Order the epilogue's completed TMEM loads (published through the arrive
# above) before the deallocation.
prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC)
cute.arch.dealloc_tmem(tmem_ptr, num_tmem_cols, is_two_cta=False)

@cute.experimental.jit
Expand All @@ -694,6 +737,7 @@ def epilog_warp(
# Wait until MMA publishes the TMEM base pointer.
cute.arch.mbarrier_arrive(bar_tmem_alloc)
cute.arch.mbarrier_wait(bar_tmem_alloc, 0)
prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC)

acc_view = cute.make_tensor(
cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_ptr),
Expand Down Expand Up @@ -757,9 +801,13 @@ def epilog_warp(
rBiasAcc.store(rBias.load().to(self.acc_dtype))

cute.arch.mbarrier_wait(bar_mma_epilog, 0)
# Order the MMA's completion (observed through the commit) before the loads.
prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC)
cute_ext.partition_and_copy(thr_t2r, acc_view, rAcc)
# Make tcgen05.ld visible before TMEM release and RMEM use.
# Make tcgen05.ld visible before TMEM release and RMEM use, and order the
# completed loads before the arrive that hands TMEM back for deallocation.
cute.arch.fence_view_async_tmem_load()
prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC)
cute.arch.mbarrier_arrive(bar_tmem_alloc)

# Peers publish FP32 partials; only rank 0 reduces and stores.
Expand Down Expand Up @@ -788,7 +836,7 @@ def epilog_warp(
cute.arch.mbarrier_arrive_and_expect_tx(
bar_reduce, self.expected_transaction_bytes
)
cute.arch.mbarrier_wait(bar_reduce, 0)
_mbarrier_wait_acquire_cluster(bar_reduce, Int32(0))
for peer in cutlass.range_constexpr(self.split_k - 1):
for value_idx in cutlass.range_constexpr(values_per_thread):
rAcc[value_idx] = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
if_generate,
new_from_mlir_values,
)
from cutlass.experimental import primitives as prims
from cutlass.pipeline import (
Agent,
CooperativeGroup,
Expand All @@ -73,6 +74,69 @@
# ============================================================================


@cute.jit
def _mbar_wait_cluster_acquire(mbar_ptr: cute.Pointer, phase: cutlass.Int32):
"""Wait for ``phase`` of this CTA's mbarrier at ``mbar_ptr``, acquiring at cluster scope.

``cute.arch.mbarrier_wait`` acquires at CTA scope. The peers' ``st.async ...
mbarrier::complete_tx`` that completes this barrier releases at cluster scope, and only a
cluster-scope acquire orders their payload before the reads that follow the wait: a relaxed
cluster-scope try_wait loop and an acquire fence restricted to shared::cluster (the ISA's
acquire pattern for it; unlike ``.acquire.cluster`` on the wait it adds no L1 invalidate).
"""
while not prims.mbarrier_try_wait_parity(
mbar_ptr, phase, scope=prims.MBarrierScope.CLUSTER, order=prims.MemOrder.RELAXED
):
pass
prims.fence_sync_restrict(prims.MemOrder.ACQUIRE)


@cute.jit
def _clc_consumer_release_cluster(
pipe: pipeline.PipelineClcFetchAsync, state: pipeline.PipelineState
):
"""``consumer_release`` for a scheduler response slot the leader CTA will overwrite.

Arrives on the leader's empty barrier for ``state`` with ``.release.cluster`` semantics,
so this CTA's read of the response slot is ordered before the leader's next ``st.async``
into it. The pipeline's own release arrives at CTA scope, which does not synchronize
with a thread of another CTA.
"""
cute.arch.mbarrier_arrive(
pipe.sync_object_empty.get_barrier(state.index),
cutlass.Int32(0),
scope=nvvm.MemScopeKind.CLUSTER,
)


@cute.jit
def _clc_producer_acquire_cluster(
pipe: pipeline.PipelineClcFetchAsync, state: pipeline.PipelineState
):
"""``producer_acquire`` for a scheduler response slot that peer CTAs release.

Waits on the leader's empty barrier for ``state`` with cluster-scope acquire semantics,
so the next ``st.async`` into the slot is ordered after every peer's cluster-scope
release, then runs the pipeline's own ``producer_acquire`` with its CTA-scope wait
skipped (``try_acquire_token=True``), which leaves the arrive with transaction count on
every CTA's full barrier.
"""
_mbar_wait_cluster_acquire(pipe.sync_object_empty.get_barrier(state.index), state.phase)
pipe.producer_acquire(state, try_acquire_token=True)


@cute.jit
def _clc_producer_tail_cluster(pipe: pipeline.PipelineClcFetchAsync, state: pipeline.PipelineState):
"""``producer_tail`` for a scheduler response slot that peer CTAs release.

Drains every stage's empty barrier before the leader exits, as the pipeline's own
``producer_tail`` does, with cluster-scope acquire waits to match the peers' releases.
"""
for _ in cutlass.range_constexpr(pipe.num_stages):
_mbar_wait_cluster_acquire(pipe.sync_object_empty.get_barrier(state.index), state.phase)
state.advance()


@dataclass(frozen=True)
class Fc12TaskShape:
"""Exact per-M task counts for the two GEMM phases."""
Expand Down Expand Up @@ -3455,18 +3519,31 @@ def kernel(
if cutlass.const_expr(self.use_l2_atomic_scheduler):
if cutlass.const_expr(self.use_cluster_scheduler_response):
if is_scheduler_leader_cta:
fc1_scheduler_pipeline.producer_acquire(
fc1_scheduler_producer_state
# The peers' releases of this slot arrive at cluster scope:
# acquire at cluster scope before refilling it.
_clc_producer_acquire_cluster(
fc1_scheduler_pipeline, fc1_scheduler_producer_state
)
fc1_tile_sched.publish_next_work(
fc1_scheduler_pipeline.producer_get_barrier(
fc1_scheduler_producer_state
)
)
fc1_scheduler_producer_state.advance()
fc1_scheduler_pipeline.consumer_wait(fc1_scheduler_consumer_state)
# The leader's st.async into this CTA's response slot releases
# at cluster scope: acquire at cluster scope before reading it.
_mbar_wait_cluster_acquire(
fc1_scheduler_pipeline.sync_object_full.get_barrier(
fc1_scheduler_consumer_state.index
),
fc1_scheduler_consumer_state.phase,
)
work_tile = fc1_tile_sched.get_published_work()
fc1_scheduler_pipeline.consumer_release(fc1_scheduler_consumer_state)
# Release the slot to the leader at cluster scope, so the read
# above is ordered before the leader's next st.async into it.
_clc_consumer_release_cluster(
fc1_scheduler_pipeline, fc1_scheduler_consumer_state
)
fc1_scheduler_consumer_state.advance()
elif cutlass.const_expr(self.use_die_scheduler):
work_tile, die_queue = self._die_local_claim(
Expand All @@ -3490,7 +3567,7 @@ def kernel(
self.use_l2_atomic_scheduler and self.use_cluster_scheduler_response
):
if is_scheduler_leader_cta:
fc1_scheduler_pipeline.producer_tail(fc1_scheduler_producer_state)
_clc_producer_tail_cluster(fc1_scheduler_pipeline, fc1_scheduler_producer_state)

# FC2 owns an independent work-ID stream. There is deliberately no
# grid-wide phase fence: a fast cluster may start claiming FC2 as
Expand Down Expand Up @@ -3569,18 +3646,31 @@ def kernel(
if cutlass.const_expr(self.use_l2_atomic_scheduler):
if cutlass.const_expr(self.use_cluster_scheduler_response):
if is_scheduler_leader_cta:
fc2_scheduler_pipeline.producer_acquire(
fc2_scheduler_producer_state
# The peers' releases of this slot arrive at cluster scope:
# acquire at cluster scope before refilling it.
_clc_producer_acquire_cluster(
fc2_scheduler_pipeline, fc2_scheduler_producer_state
)
fc2_tile_sched.publish_next_work(
fc2_scheduler_pipeline.producer_get_barrier(
fc2_scheduler_producer_state
)
)
fc2_scheduler_producer_state.advance()
fc2_scheduler_pipeline.consumer_wait(fc2_scheduler_consumer_state)
# The leader's st.async into this CTA's response slot releases
# at cluster scope: acquire at cluster scope before reading it.
_mbar_wait_cluster_acquire(
fc2_scheduler_pipeline.sync_object_full.get_barrier(
fc2_scheduler_consumer_state.index
),
fc2_scheduler_consumer_state.phase,
)
fc2_work_tile = fc2_tile_sched.get_published_work()
fc2_scheduler_pipeline.consumer_release(fc2_scheduler_consumer_state)
# Release the slot to the leader at cluster scope, so the read
# above is ordered before the leader's next st.async into it.
_clc_consumer_release_cluster(
fc2_scheduler_pipeline, fc2_scheduler_consumer_state
)
fc2_scheduler_consumer_state.advance()
elif cutlass.const_expr(self.use_die_scheduler):
fc2_work_tile, die_queue = self._die_local_claim(
Expand All @@ -3604,7 +3694,7 @@ def kernel(
self.use_l2_atomic_scheduler and self.use_cluster_scheduler_response
):
if is_scheduler_leader_cta:
fc2_scheduler_pipeline.producer_tail(fc2_scheduler_producer_state)
_clc_producer_tail_cluster(fc2_scheduler_pipeline, fc2_scheduler_producer_state)

tile_info_pipeline.producer_acquire(tile_info_producer_state)
with cute.arch.elect_one():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from cutlass.cute.nvgpu import cpasync
from cutlass.cute.runtime import make_ptr
from cutlass.cutlass_dsl import T, dsl_user_op
from cutlass.experimental import primitives as prims

from .k3_fused_router import (
_EVICT_FIRST,
Expand Down Expand Up @@ -111,6 +112,23 @@ def _st_async_v4_f32(local_addr, v0, v1, v2, v3, local_mbar, peer, *, loc=None,
)


@cute.jit
def _mbar_wait_cluster_acquire(mbar_ptr: cute.Pointer, phase: Int32):
"""Wait for ``phase`` of this CTA's mbarrier at ``mbar_ptr``, acquiring at cluster scope.

``cute.arch.mbarrier_wait`` acquires at CTA scope. The peers' ``st.async ...
mbarrier::complete_tx`` that completes this barrier releases at cluster scope, and only a
cluster-scope acquire orders their payload before the reads that follow the wait: a relaxed
cluster-scope try_wait loop and an acquire fence restricted to shared::cluster (the ISA's
acquire pattern for it; unlike ``.acquire.cluster`` on the wait it adds no L1 invalidate).
"""
while not prims.mbarrier_try_wait_parity(
mbar_ptr, phase, scope=prims.MBarrierScope.CLUSTER, order=prims.MemOrder.RELAXED
):
pass
prims.fence_sync_restrict(prims.MemOrder.ACQUIRE)


@dsl_user_op
def _ldg_v4_b32_if(valid, addr, *, loc=None, ip=None):
"""16 bytes of global memory as four 32-bit words if ``valid != 0``, else zeros."""
Expand Down Expand Up @@ -323,7 +341,8 @@ def kernel(
off = tidx * 16
tot = [Float32(0.0)] * 4
if rank == 1:
cute.arch.mbarrier_wait(mbox_full, 0)
# CTA 0's st.async complete-tx releases at cluster scope.
_mbar_wait_cluster_acquire(mbox_full, 0)
tot = list(_lds_v4_f32(mbox_base + off))
for w in cutlass.range_constexpr(NUM_WARPS):
v = _lds_v4_f32(red_base + w * _FRAG_BYTES + off)
Expand Down
Loading
Loading