-
Notifications
You must be signed in to change notification settings - Fork 89
Add forward LSE output to FlyDSL flash attention kernels #844
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
amd-wsung102
wants to merge
1
commit into
ROCm:main
Choose a base branch
from
amd-wsung102:forward_lse
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+372
−9
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -66,6 +66,7 @@ def build_flash_attn_dualwave_swp_module( | |
| cross_seqlen=False, | ||
| paged=False, | ||
| kv_cache_layout="linear", | ||
| return_lse=False, | ||
| ): | ||
| """Build an DUALWAVE_SWP flash_attn launcher for D=64/128 bf16/f16 on gfx950. | ||
|
|
||
|
|
@@ -194,6 +195,11 @@ class SharedStorage: | |
| DUALWAVE_SWP_SETPRIO = bool(dualwave_swp_setprio) | ||
| DUALWAVE_SWP_DEBUG_LAZY_COUNTS = bool(dualwave_swp_debug_lazy_counts) | ||
| DUALWAVE_SWP_ENABLE_STAGGER = bool(dualwave_swp_enable_stagger) | ||
| # Emit per-row log-sum-exp (LSE). Convention (A1<->A3 contract): natural log, | ||
| # softmax scale folded in, i.e. LSE_i = ln(sum_j exp(sm_scale * (q_i . k_j))). | ||
| # Output is fp32 [batch, num_heads, seq_len]. For split-K the LSE is finalized | ||
| # in the combine kernel from the per-split (m, l). See docs/flash_attn_lse_contract.md. | ||
| RETURN_LSE = bool(return_lse) | ||
| VARLEN = bool(varlen) | ||
| # Cross-length (seqlen_q != seqlen_kv): emit the extra in-loop v_s_1 causal mask | ||
| # so a diagonal kv-tile landing on the v_s_1 slot is masked. Off by default so | ||
|
|
@@ -218,6 +224,7 @@ def flash_attn_dualwave_swp_gfx950_kernel( | |
| K: fx.Tensor, | ||
| V: fx.Tensor, | ||
| O: fx.Tensor, # noqa: E741 | ||
| LSE: fx.Tensor, | ||
| DebugCounts: fx.Tensor, | ||
| CuSeqQ: fx.Tensor, | ||
| CuSeqKv: fx.Tensor, | ||
|
|
@@ -543,6 +550,7 @@ def _buffer_store_128(pack_i32_vec, elem_index): | |
| c_zero_i = fx.Int32(0) | ||
| head_dim_f32 = fx.Float32(fx.Int32(head_dim_runtime)) | ||
| c_log2e_f = fx.Float32(_LOG2E) | ||
| c_ln2_f = fx.Float32(1.0 / _LOG2E) | ||
| c_sm_scale_log2e = fx.Float32( | ||
| arith.mulf( | ||
| _raw(fmath.rsqrt(head_dim_f32, fastmath=fm_fast)), | ||
|
|
@@ -2064,6 +2072,26 @@ def _swap_halves(dw): | |
| o_pack = Vec.from_elements([fx.Int32(w0), fx.Int32(w1), fx.Int32(w2), fx.Int32(w3)], fx.Int32) | ||
| o_global = o_base + (dc * D_CHUNK + 2 * g * 8) | ||
| _buffer_store_128(o_pack, o_global) | ||
|
|
||
| if const_expr(RETURN_LSE): | ||
| # LSE = m_row * ln2 + ln(l_row); natural log, scale folded (m_row is | ||
| # already sm_scale*log2e-scaled). fp32 [batch, num_heads, seq_len]; | ||
| # per-batch descriptor folds the batch offset into the 48-bit base. | ||
| _lse_base_i64 = fx.Int64(fx.ptrtoint(fx.get_iter(LSE))) | ||
| _lse_per_batch_elems = fx.Index(NUM_HEADS_Q) * seq_len_v | ||
| _lse_per_batch_bytes = _lse_per_batch_elems * fx.Index(4) | ||
| _lse_rsrc = buffer_ops.create_buffer_resource_from_addr( | ||
| _raw(_lse_base_i64 + fx.Int64(batch_idx * _lse_per_batch_bytes)), | ||
| num_records_bytes=_raw(fx.Int64(_lse_per_batch_bytes)), | ||
| ) | ||
| _lse_val = _fadd(_fmul(m_row, c_ln2_f), fmath.log(_raw(l_row), fastmath=fm_fast)) | ||
| _lse_local = q_head_idx * seq_len_v + q_row | ||
| # One writer per row (low half-wave); partial-tile OOB rows and the | ||
| # high half-wave redirect to the sentinel offset (== num records), | ||
| # which the buffer bound drops. | ||
| _lse_off_row = ArithValue(q_row < seqlen_q_v).select(_lse_local, _lse_per_batch_elems) | ||
| _lse_off = fx.Index(ArithValue(lane < fx.Index(32)).select(_lse_off_row, _lse_per_batch_elems)) | ||
| _ws_store_f32(_lse_val, _lse_off, _lse_rsrc) | ||
| else: | ||
| # Split-K stores normalized O_partial plus this row's fp32 m/l. | ||
| # Per-split descriptors fold split offsets into the 48-bit base. | ||
|
|
@@ -2142,12 +2170,14 @@ def _swap_halves(dw): | |
| def flash_attn_splitk_combine_kernel( | ||
| O: fx.Tensor, # noqa: E741 | ||
| WS: fx.Tensor, | ||
| LSE: fx.Tensor, | ||
| batch_size: fx.Int32, | ||
| seq_len: fx.Int32, | ||
| stride_q_n: fx.Int32, | ||
| ): | ||
| elem_dtype = dtype_to_elem_type(dtype_str) | ||
| fm_fast = fx.arith.FastMathFlags.fast | ||
| c_ln2_f = fx.Float32(1.0 / _LOG2E) | ||
| seq_v = fx.Index(seq_len) | ||
| stride_v = fx.Index(stride_q_n) | ||
| bs_v = fx.Index(batch_size) | ||
|
|
@@ -2245,6 +2275,24 @@ def _accum_split(acc, den): | |
|
|
||
| acc, den = _accum_split(acc, den) | ||
|
|
||
| if const_expr(RETURN_LSE): | ||
| # Combined LSE = m_max * ln2 + ln(den); den = sum_s 2^(m_s - m_max) * l_s is | ||
| # the global base-2 denominator relative to m_max, so ln(den) completes the | ||
| # natural-log, scale-folded LSE. One lane per (b,h,s) row (col == 0) writes; | ||
| # others redirect to the sentinel offset dropped by the buffer bound. | ||
| _lse_base_i64_c = fx.Int64(fx.ptrtoint(fx.get_iter(LSE))) | ||
| _lse_per_batch_elems_c = fx.Index(NUM_HEADS_Q) * seq_v | ||
| _lse_per_batch_bytes_c = _lse_per_batch_elems_c * fx.Index(4) | ||
| _lse_rsrc_c = buffer_ops.create_buffer_resource_from_addr( | ||
| _raw(_lse_base_i64_c + fx.Int64(b * _lse_per_batch_bytes_c)), | ||
| num_records_bytes=_raw(fx.Int64(_lse_per_batch_bytes_c)), | ||
| ) | ||
| _lse_val_c = _fadd(_fmul(m_max, c_ln2_f), fmath.log(_raw(den), fastmath=fm_fast)) | ||
| _lse_off_c = fx.Index( | ||
| ArithValue(col == fx.Index(0)).select(local_ml_idx_c, _lse_per_batch_elems_c) | ||
| ) | ||
| buffer_ops.buffer_store(_raw(fx.Float32(_lse_val_c)), _lse_rsrc_c, _raw(fx.Int32(_lse_off_c))) | ||
|
|
||
| inv_rcp = rocdl.rcp(T.f32, den) | ||
| inv = ArithValue(fx.Float32(den) > fx.Float32(0.0)).select(inv_rcp, fx.Float32(0.0)) | ||
| inv4 = Vec.from_elements([fx.Float32(inv)], fx.Float32).broadcast_to(4) | ||
|
|
@@ -2273,6 +2321,7 @@ def launch_flash_attn_dualwave_swp( | |
| K: fx.Tensor, | ||
| V: fx.Tensor, | ||
| O: fx.Tensor, # noqa: E741 | ||
| LSE: fx.Tensor, | ||
| DebugCounts: fx.Tensor, | ||
| CuSeqQ: fx.Tensor, | ||
| CuSeqKv: fx.Tensor, | ||
|
|
@@ -2308,6 +2357,7 @@ def launch_flash_attn_dualwave_swp( | |
| K, | ||
| V, | ||
| O, | ||
| LSE, | ||
| DebugCounts, | ||
| CuSeqQ, | ||
| CuSeqKv, | ||
|
|
@@ -2330,7 +2380,7 @@ def launch_flash_attn_dualwave_swp( | |
| ) | ||
| if const_expr(SPLITK): | ||
| combine_rows = bs_idx * NUM_HEADS_Q * sl_idx | ||
| flash_attn_splitk_combine_kernel(O, DebugCounts, batch_size, seq_len, stride_q_n).launch( | ||
| flash_attn_splitk_combine_kernel(O, DebugCounts, LSE, batch_size, seq_len, stride_q_n).launch( | ||
| grid=(combine_rows // COMBINE_ROWS_PER_BLOCK, 1, 1), | ||
| block=(COMBINE_BLOCK, 1, 1), | ||
| stream=stream, | ||
|
|
@@ -2363,6 +2413,7 @@ def _launch( | |
| cu_seqlens_kv=None, | ||
| block_table=None, | ||
| block_table_stride=None, | ||
| lse=None, | ||
| stream=None, | ||
| ): | ||
| if stride_kv_n is None: | ||
|
|
@@ -2392,13 +2443,17 @@ def _launch( | |
| block_table = O | ||
| if block_table_stride is None: | ||
| block_table_stride = 0 | ||
| # LSE is only written under const_expr(RETURN_LSE); O placeholder otherwise. | ||
| if lse is None: | ||
| lse = O | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Blocker: same issue here. If |
||
| with CompilationContext.compile_hints(_dualwave_swp_compile_hints): | ||
| if stream is None: | ||
| return launch_flash_attn_dualwave_swp( | ||
| Q, | ||
| K, | ||
| V, | ||
| O, | ||
| lse, | ||
| debug_counts, | ||
| cu_seqlens_q, | ||
| cu_seqlens_kv, | ||
|
|
@@ -2416,6 +2471,7 @@ def _launch( | |
| K, | ||
| V, | ||
| O, | ||
| lse, | ||
| debug_counts, | ||
| cu_seqlens_q, | ||
| cu_seqlens_kv, | ||
|
|
@@ -2448,6 +2504,7 @@ def _compile( | |
| cu_seqlens_kv=None, | ||
| block_table=None, | ||
| block_table_stride=None, | ||
| lse=None, | ||
| stream=None, | ||
| ): | ||
| if stride_kv_n is None: | ||
|
|
@@ -2472,13 +2529,16 @@ def _compile( | |
| block_table = O | ||
| if block_table_stride is None: | ||
| block_table_stride = 0 | ||
| if lse is None: | ||
| lse = O | ||
| with CompilationContext.compile_hints(_dualwave_swp_compile_hints): | ||
| return flyc.compile( | ||
| launch_flash_attn_dualwave_swp, | ||
| Q, | ||
| K, | ||
| V, | ||
| O, | ||
| lse, | ||
| debug_counts, | ||
| cu_seqlens_q, | ||
| cu_seqlens_kv, | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Blocker: when this builder is created with
return_lse=Truebut the caller omitslse, this falls back toOut. SinceRETURN_LSEstores fp32 LSE, that can overwrite the output buffer or write through an incompatible layout. Please raiseValueErrorwhenRETURN_LSEandlse is Noneinstead of usingOutas the fallback.