diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-07-02 19:44:08 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-07-02 19:44:08 +0200 |
| commit | 6a10d3577232f1fd646a20f22a4a1ab4ec29f28a (patch) | |
| tree | e4a077b064876ddb39144935fa256a4ab0692488 /deps/cudnn-frontend/include/cudnn_frontend/generated | |
| parent | 98a713e86c23bc6098bf7a5558507a9f27a7a1c1 (diff) | |
| download | ffwd-6a10d3577232f1fd646a20f22a4a1ab4ec29f28a.tar.gz ffwd-6a10d3577232f1fd646a20f22a4a1ab4ec29f28a.zip | |
cuda: add cuDNN fused attention path with runtime fallback
Diffstat (limited to 'deps/cudnn-frontend/include/cudnn_frontend/generated')
6 files changed, 12996 insertions, 0 deletions
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h new file mode 100644 index 0000000..77b5dd7 --- /dev/null +++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h @@ -0,0 +1,468 @@ +// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: MIT +#pragma once + +// Auto-generated from ln_fwd_silu_kernel.cu +// Do not edit manually. + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverlength-strings" +#endif + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4068) +#endif + +namespace cudnn_frontend::experimental::generated { + +inline constexpr const char ln_fwd_silu_kernel_source[] = + R"KERNEL( +constexpr int mxfp8_block_size = 32; +constexpr int nvfp4_block_size = 16; + +template <typename _Traits> +struct LnFwdShared { + using Traits = _Traits; + static constexpr int32_t SMEM_STATS_ELEMENTS = ((Traits::Stats::SMEM_BYTES > 0) ? Traits::Stats::SMEM_BYTES : 1); + static constexpr int32_t SMEM_BAR_ELEMENTS = ((Traits::USE_CLUSTER && Traits::CTAS_PER_ROW > 1) + ? (Traits::WARPS_M + 1 + Traits::WARPS_M * Traits::CTAS_PER_ROW) + : 1); + static constexpr int32_t SMEM_MXFP8_ELEMENTS = + ((isBlockScale_1D2X2X && !useBlockScaleColwiseKernel) + ? ((mxfp8_block_size * Traits::NUM_ELTS + (Traits::NUM_ELTS - 1)) * (mxfp8_block_size + 1)) + : 1); + static constexpr int32_t GAMMA_ELEMENTS = + ((Traits::hasGamma && Traits::USE_GAMMA_SMEM) + ? (Traits::BATCH_SIZE * Traits::LDGS * Traits::THREADS_PER_ROW * Traits::NUM_ELTS) + : 1); + static constexpr int32_t BETA_ELEMENTS = + ((Traits::hasBeta && Traits::USE_GAMMA_SMEM) + ? (Traits::BATCH_SIZE * Traits::LDGS * Traits::THREADS_PER_ROW * Traits::NUM_ELTS) + : 1); + + __align__(16) char smem_stats[SMEM_STATS_ELEMENTS]; + __align__(16) uint64_t smem_bar[SMEM_BAR_ELEMENTS]; + __align__(16) typename Traits::weight_t smem_gamma[GAMMA_ELEMENTS]; + __align__(16) typename Traits::weight_t smem_beta[BETA_ELEMENTS]; + __align__(16) float smem_mxfp8[SMEM_MXFP8_ELEMENTS]; +}; + +extern "C" __global__ +__launch_bounds__(Ktraits::THREADS_PER_CTA, DESIRED_OCCUPANCY) void ln_fwd_kernel( + PersistentLnFwdParams params, + reduced_divisor divisor) { // divisor is div_batch if it is batch-first case, else it is div_seqLen + enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; + enum { WARPS_N = Ktraits::WARPS_N }; + enum { WARPS_M = Ktraits::WARPS_M }; + enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; + enum { VEC_COLS_PER_LDG = Ktraits::VEC_COLS_PER_LDG }; + enum { VEC_COLS = Ktraits::VEC_COLS }; + enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; + enum { LDGS = Ktraits::LDGS }; + enum { NUM_ELTS = Ktraits::NUM_ELTS }; + enum { THREADS_PER_WARP = Ktraits::THREADS_PER_WARP }; + enum { CTAS_PER_ROW = Ktraits::CTAS_PER_ROW }; + enum { COLS = Ktraits::COLS }; + enum { COLS_PER_LDG = Ktraits::VEC_COLS_PER_LDG * Ktraits::NUM_ELTS }; + enum { COLS_PER_LDG_PER_CTA = COLS_PER_LDG / Ktraits::CTAS_PER_ROW }; + enum { VEC_COLS_PER_LDG_PER_CTA = VEC_COLS_PER_LDG / Ktraits::CTAS_PER_ROW }; + enum { USE_GAMMA_SMEM = Ktraits::USE_GAMMA_SMEM }; + enum { BATCH_SIZE = Ktraits::BATCH_SIZE }; + enum { isAdaLN = Ktraits::isAdaLN }; + enum { isBatchFirst = Ktraits::isBatchFirst }; + + using output_t = typename Ktraits::output_t; + using weight_t = typename Ktraits::weight_t; + using index_t = typename Ktraits::index_t; + using compute_t = typename Ktraits::compute_t; + using norm_output_t = typename Ktraits::norm_output_t; + using Ivec = typename Ktraits::Ivec; + using Ovec = typename Ktraits::Ovec; + using Wvec = typename Ktraits::Wvec; + using Cvec = typename Ktraits::Cvec; + using NormOvec = typename Ktraits::NormOvec; + + using Stats = typename Ktraits::Stats; + using stats_t = typename Stats::stats_t; + +#ifdef USE_STATIC_SMEM_VALUE + __shared__ __align__(16) char smem_base_[USE_STATIC_SMEM_VALUE]; +#else + extern __shared__ char smem_base_[]; +#endif + + LnFwdShared<Ktraits> *shared = reinterpret_cast<LnFwdShared<Ktraits> *>(smem_base_); + + uint64_t *smemBar = shared->smem_bar; +#if LN_USE_CLUSTER + if (CTAS_PER_ROW > 1) { +#if (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080) + // Init the empty bars for each warp + if (threadIdx.x < WARPS_M) { + cuda::ptx::mbarrier_init(&smemBar[threadIdx.x], CTAS_PER_ROW * WARPS_N * THREADS_PER_WARP); + } + // Init the full bar (shared by the CTA) + if (threadIdx.x == 0) { + cuda::ptx::mbarrier_init(&smemBar[WARPS_M], 1); + cuda::ptx::fence_mbarrier_init(cuda::ptx::sem_release, cuda::ptx::scope_cluster); + } + cuda::ptx::barrier_cluster_arrive(cuda::ptx::sem_relaxed); + cuda::ptx::barrier_cluster_wait(); +#else + static_assert(true, "Cluster enabled on host side but not available on device"); +#endif // (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080) + } +#endif // LN_USE_CLUSTER + + const index_t tidx = threadIdx.x; + const index_t bidn = blockIdx.x % CTAS_PER_ROW; + const index_t bidm = blockIdx.x / CTAS_PER_ROW; + const index_t lane = tidx % THREADS_PER_WARP; + const index_t warp = tidx / THREADS_PER_WARP; + const index_t warp_m = warp / WARPS_N; + const index_t warp_n = warp % WARPS_N; + + const index_t r = bidm * ROWS_PER_CTA + warp_m; + + const index_t col_in_tile = warp_n * THREADS_PER_WARP + lane; + const index_t c = bidn * THREADS_PER_ROW + col_in_tile; + + Stats stats(params, bidm, bidn, warp_m, warp_n, tidx, lane, shared->smem_stats, smemBar); + + // Unused when USE_GAMMA_SMEM is true and will be optimized out + [[maybe_unused]] Wvec gamma_regs[BATCH_SIZE][LDGS]; + [[maybe_unused]] Wvec beta_regs[BATCH_SIZE][LDGS]; + weight_t *gamma_smem = nullptr, *beta_smem = nullptr; + if constexpr (USE_GAMMA_SMEM) { + static constexpr int32_t SMEM_BYTES_GAMMA = THREADS_PER_ROW * BATCH_SIZE * LDGS * sizeof(Wvec); + if constexpr (Ktraits::hasGamma) { + gamma_smem = shared->smem_gamma; + } + if constexpr (Ktraits::hasBeta) { + beta_smem = shared->smem_beta; + } + } + + // If we are mxfp8 output type, we need shared memory for amax calculations across warps + // 2d1x1x (not yet implemented) requires 1 (1 for a 32x32 block) + // 1d1x1x requires 0 (since it reduces over a row which can be done with warp reduce) + // 1d2x2x requires 32x(32+1)xNUM_ELTS, more details as follows: + constexpr int block_scale_size = isFP4Out ? nvfp4_block_size : mxfp8_block_size; + BlockScaleRowHelper<Cvec, Ovec, block_scale_size> rowwise_scale_helper{}; + BlockScaleColHelper<Cvec, Ovec, mxfp8_block_size> colwise_scale_helper{shared->smem_mxfp8}; + compute_t *mu_ptr = static_cast<compute_t *>(params.mu); + compute_t *rs_ptr = static_cast<compute_t *>(params.rs); + + constexpr compute_t rn = 1.f / compute_t(Ktraits::COLS); + + index_t idx = c; + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 + asm volatile("griddepcontrol.wait;\n"); +#endif + + // Load gamma and beta into shared memory or registers +#pragma unroll + for (int b = 0; b < BATCH_SIZE; b++) { +// CL-14115: The unroll factor 128 for LDGS was chosen based on the compilation/perf results for APEX LN_fwd engines +#pragma unroll 128 + for (int it = 0; it < LDGS; it++) { + if constexpr (USE_GAMMA_SMEM) { + if (warp_m == 0) { + const index_t cur_gamma_smem_base_idx = + (b * LDGS + it) * THREADS_PER_ROW * NUM_ELTS + warp_n * THREADS_PER_WARP * NUM_ELTS + lane; + if constexpr (Ktraits::hasGamma) { + Wvec cur_gamma_vec; + cur_gamma_vec.load_from(params.gamma, idx); +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + const index_t cur_gamma_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP; + gamma_smem[cur_gamma_smem_idx] = cur_gamma_vec.data.elt[jt]; + } + } + if constexpr (Ktraits::hasBeta) { + Wvec cur_beta_vec; + cur_beta_vec.load_from(params.beta, idx); +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + const index_t cur_beta_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP; + beta_smem[cur_beta_smem_idx] = cur_beta_vec.data.elt[jt]; + } + } + } + } else if constexpr (!GAMMA_ON_DEMAND) { + if constexpr (Ktraits::hasGamma) { + gamma_regs[b][it].load_from(params.gamma, idx); + } + if constexpr (Ktraits::hasBeta) { + beta_regs[b][it].load_from(params.beta, idx); + } + } + idx += VEC_COLS_PER_LDG; + } + } + + if constexpr (USE_GAMMA_SMEM) { + __syncthreads(); + } + + // Initialize scale and bias for FP8 output + compute_t scale = 1.f; + if constexpr (isFP8Out) { + scale = __ldg(params.scale); + } + compute_t amax = 0; + + index_t remaining_rows = params.rows - bidm * ROWS_PER_CTA; + int row_increment_step = params.ctas_per_col * ROWS_PER_CTA; + int batch_idx = 0, remainder = 0; + int batch_increment_step = 0, step_remainder = 0; + if constexpr (isAdaLN) { + if constexpr (isBatchFirst) { + divisor.divmod(r, batch_idx, remainder); // row = batch_idx * seqLen + remainder; (remainder < + // seqLen) batch_idx = r/seqLen + divisor.divmod(row_increment_step, batch_increment_step, step_remainder); // row_increment_step = + // batch_increment_step * seqLen + + // step_remainder (remainder < + // seqLen) + } else { + batch_idx = divisor.mod(r); // batch_idx = row % BATCH_SIZE; + batch_increment_step = + divisor.mod(row_increment_step); // batch_increment_step = row_increment_step % BATCH_SIZE; + } + } + + for (int row = r; row < params.rows; + row += row_increment_step, batch_idx += batch_increment_step, remainder += step_remainder) { + index_t idx = static_cast<index_t>(row) * VEC_COLS + c; + + // Load x and convert to compute type per row per thread + compute_t xf[LDGS * NUM_ELTS]; +#pragma unroll 128 + for (int it = 0; it < LDGS; it++) { + Ivec x_it{}; + x_it.load_from(params.x, idx); +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + compute_t x_ij = compute_t(x_it.data.elt[jt]); + xf[it * NUM_ELTS + jt] = x_ij; + } + idx += VEC_COLS_PER_LDG; + } + + // Compute mean and variance per row per thread + // How many rows current CTA will handle for this iteration + int rows_per_cta = remaining_rows >= ROWS_PER_CTA ? ROWS_PER_CTA : remaining_rows; + stats_t s = stats.compute<Ktraits::isRMSNorm, LDGS, NUM_ELTS>(xf, rn, rows_per_cta); + remaining_rows -= params.ctas_per_col * ROWS_PER_CTA; // for next iteration + compute_t mu = Get<0>::of<stats_t, compute_t>(s); + compute_t m2 = Get<1>::of<stats_t, compute_t>(s); + if constexpr (!Ktraits::isRMSNorm) { + if (bidn == 0 && warp_n == 0 && lane == 0) { + mu_ptr[row] = mu; + } + } + compute_t rs = rsqrtf(rn * m2 + params.epsilon); + + if (bidn == 0 && warp_n == 0 && lane == 0) { + rs_ptr[row] = rs; + } + + idx = row * VEC_COLS + c; + + if constexpr (isAdaLN) { + if constexpr (isBatchFirst) { + if (remainder >= params.seqLen) { + batch_idx += 1; + remainder -= params.seqLen; + } + } else { + if (batch_idx >= BATCH_SIZE) { + batch_idx -= BATCH_SIZE; + } + } + } + index_t gamma_idx = c + (batch_idx * LDGS) * VEC_COLS_PER_LDG; +#pragma unroll 128 + for (int it = 0; it < LDGS; it++) { + Cvec z_math; + [[maybe_unused]] Wvec g_wt; + [[maybe_unused]] Wvec b_wt; + if constexpr (GAMMA_ON_DEMAND && Ktraits::hasGamma && !USE_GAMMA_SMEM) { + g_wt.load_from(params.gamma, gamma_idx); + + if constexpr (Ktraits::hasBeta) { + b_wt.load_from(params.beta, gamma_idx); + } + } +#pragma unroll + // Compute output per ldg per row per thread + for (int jt = 0; jt < NUM_ELTS; jt++) { + compute_t y_ij = rs * (xf[it * NUM_ELTS + jt] - mu); + + if constexpr (Ktraits::hasGamma) { + weight_t g_ij_wt{}; + const int32_t cur_gamma_smem_base_idx = (batch_idx * LDGS + it) * THREADS_PER_ROW * NUM_ELTS + + warp_n * THREADS_PER_WARP * NUM_ELTS + lane; + const int32_t cur_gamma_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP; + if constexpr (USE_GAMMA_SMEM) { + g_ij_wt = gamma_smem[cur_gamma_smem_idx]; + } else if constexpr (GAMMA_ON_DEMAND) { + g_ij_wt = g_wt.data.elt[jt]; + } else { + g_ij_wt = gamma_regs[batch_idx][it].data.elt[jt]; + } + compute_t g_ij = static_cast<compute_t>(g_ij_wt); + if constexpr (isZeroCenteredGamma) { + if constexpr (isZeroCenteredGammaCastBeforeAdd) { + g_ij = static_cast<compute_t>(g_ij_wt) + static_cast<compute_t>(1.f); + } else { + g_ij = static_cast<compute_t>(g_ij_wt + static_cast<weight_t>(1.f)); + } + } + if constexpr (Ktraits::hasBeta) { + compute_t b_ij{}; + const int32_t cur_beta_smem_idx = cur_gamma_smem_base_idx + jt * THREADS_PER_WARP; + if constexpr (USE_GAMMA_SMEM) { + b_ij = beta_smem[cur_beta_smem_idx];)KERNEL" + R"KERNEL( } else if constexpr (GAMMA_ON_DEMAND) { + b_ij = static_cast<compute_t>(b_wt.data.elt[jt]); + } else { + b_ij = beta_regs[batch_idx][it].data.elt[jt]; + } + y_ij = g_ij * y_ij + b_ij; + } else { + y_ij = g_ij * y_ij; + } + } + + // SiLU activation: y = y * sigmoid(y) = y / (1 + exp(-y)) + // Applied after norm + gamma [+ beta], before FP8/block-scale quantization. + y_ij = __fdividef(y_ij, 1.0f + __expf(-y_ij)); + + if constexpr (isFP8Out) { + if (hasAmax) { + __builtin_assume(amax >= 0); + amax = fmaxf(amax, fabsf(y_ij)); + } + y_ij *= scale; + } + z_math.data.elt[jt] = y_ij; + } // NUM_ELTS + + if constexpr (isBlockScaleOut) { + static_assert(!isBlockScaleOut || + (Ktraits::COLS % mxfp8_block_size == 0)); // ensure cols divisable by 32 + + index_t sf_row_idx = idx / mxfp8_block_size; + [[maybe_unused]] NormOvec z_intermediate; + if constexpr (std::is_same<compute_t, norm_output_t>::value) { + rowwise_scale_helper.blockQuantizeStore(z_math, params.scale_row, sf_row_idx, params.z, idx); + } else { + z_math.to(z_intermediate); + rowwise_scale_helper.blockQuantizeStore( + z_intermediate, params.scale_row, sf_row_idx, params.z, idx); + } + if constexpr (isBlockScale_1D2X2X) { + if constexpr (useBlockScaleColwiseKernel) { + // Store the temporary z_math values in workspace and launch a separate kernel to compute the + // colwise scaling results + if constexpr (std::is_same<compute_t, norm_output_t>::value) { + z_math.store_to(params.z_math, idx); + } else { + z_intermediate.store_to(params.z_math, idx); + } + } else { + if constexpr (std::is_same<compute_t, norm_output_t>::value) { + colwise_scale_helper.initTile(z_math, THREADS_PER_ROW * WARPS_M); + // static_assert(!std::is_same<compute_t, norm_output_t>::value); + } else { + colwise_scale_helper.initTile(z_intermediate, THREADS_PER_ROW * WARPS_M); + } + index_t sf_col_row_idx = 0; + index_t sf_col_col_idx = 0; + index_t sf_col_row_width = 0; + index_t z_col_idx = 0; + index_t z_row_offset = row - row % mxfp8_block_size; + if constexpr (!isBlockScale_1D2X2X_Transpose) { + sf_col_row_idx = row / mxfp8_block_size; + sf_col_col_idx = it * VEC_COLS_PER_LDG + bidn * VEC_COLS_PER_LDG_PER_CTA + warp; + sf_col_row_width = VEC_COLS; + z_col_idx = (z_row_offset + lane) * VEC_COLS + sf_col_col_idx; + } else { + constexpr index_t group_size = mxfp8_block_size / NUM_ELTS; + sf_col_row_idx = it * COLS_PER_LDG + bidn * COLS_PER_LDG_PER_CTA + warp * NUM_ELTS; + sf_col_col_idx = row / mxfp8_block_size; + sf_col_row_width = params.rows / mxfp8_block_size; + z_col_idx = (sf_col_row_idx + lane / group_size) * params.rows / NUM_ELTS + + z_row_offset / NUM_ELTS + (lane % group_size); + } + colwise_scale_helper.blockQuantizeStore<isBlockScale_1D2X2X_Transpose>( + params.scale_col, + sf_col_row_idx, + sf_col_col_idx, + sf_col_row_width, + params.z_col, + z_col_idx, + THREADS_PER_ROW * WARPS_M); + } + } + } else { + Ovec z; + z_math.to(z); + z.store_to(params.z, idx); + } + idx += VEC_COLS_PER_LDG; + gamma_idx += VEC_COLS_PER_LDG; + } // LDGS + } // grid stride loop + + // Write scale_inv before launch_dependents - consumer needs it to dequantize FP8 output + if constexpr (isFP8Out) { + if (hasScaleInv && blockIdx.x == 0 && threadIdx.x == 0) { + *reinterpret_cast<compute_t *>(params.scale_inv) = __fdividef(1.f, scale); + } + } + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 + asm volatile("griddepcontrol.launch_dependents;\n"); +#endif + + // amax can be after launch_dependents - only needed for delayed scaling (next iteration) + if constexpr (isFP8Out) { + if constexpr (hasAmax) { + amax = reduce_max<WARPS_M * WARPS_N>(amax, warp, threadIdx.x); + if (threadIdx.x == 0) { + atomicMaxFloat(reinterpret_cast<compute_t *>(params.amax), amax); + } + } + } +} + +)KERNEL"; +inline constexpr size_t ln_fwd_silu_kernel_source_len = sizeof(ln_fwd_silu_kernel_source) - 1; + +} // namespace cudnn_frontend::experimental::generated + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +namespace cudnn_frontend::experimental::generated { + +inline constexpr const char ln_fwd_silu_kernel_flags[] = R"FLAGS(--gpu-architecture=sm_100a +--std=c++17 +-w +--define-macro=__CUDACC_RTC__ +-default-device +--use_fast_math +)FLAGS"; +inline constexpr size_t ln_fwd_silu_kernel_flags_len = sizeof(ln_fwd_silu_kernel_flags) - 1; + +} // namespace cudnn_frontend::experimental::generated diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h new file mode 100644 index 0000000..59bac63 --- /dev/null +++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/rms_norm_silu/sm100/ln_headers.h @@ -0,0 +1,2043 @@ +// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: MIT +#pragma once +// Auto-generated — do not edit manually. +// Lightweight LN headers (~3K lines) replacing the 151K-line embedded version. +// Uses #include directives for CUDA TK headers (requires --include-path at NVRTC compile time). + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverlength-strings" +#endif + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4068) +#endif + +namespace cudnn_frontend { +namespace experimental { +namespace generated { + +inline constexpr const char ln_headers_source[] = + R"KERNEL( +#pragma once +// Auto-generated lightweight LN kernel header. +// Replaces the 151K-line persistent_ln_headers_13.0.h with: +// - Standard CUDA TK #include directives (resolved via --include-path at NVRTC compile time) +// - ~2900 lines of cuDNN-authored LN-specific code extracted from the original +// +// CGA/cluster support (USE_CLUSTER) is disabled: +// - #include <cuda/ptx> and cooperative_groups are NOT included +// - All if constexpr (USE_CLUSTER) branches changed to if constexpr(USE_CLUSTER) so dead code is not compiled +// +// Requires CUDA Toolkit headers available at the --include-path location. +// Generated by step3b_extract_ln_headers.py — do not edit manually. + +// ============================================================ +// Standard CUDA Toolkit headers (resolved via --include-path) +// ============================================================ + +// Minimal std stubs needed by NVRTC (no standard library available) +#if __cplusplus >= 201103L +namespace std { +template<bool B, class T = void> struct enable_if {}; +template<class T> struct enable_if<true, T> { typedef T type; }; +#if __cplusplus >= 201402L +template< bool B, class T = void > using enable_if_t = typename enable_if<B,T>::type; +#endif + +struct true_type { enum { value = true }; operator bool() const { return true; } }; +struct false_type { enum { value = false }; operator bool() const { return false; } }; + +template<typename T> struct is_floating_point : false_type {}; +template<> struct is_floating_point<float> : true_type {}; +template<> struct is_floating_point<double> : true_type {}; + +template<typename T> struct is_integral : false_type {}; +template<> struct is_integral<bool> : true_type {}; +template<> struct is_integral<char> : true_type {}; +template<> struct is_integral<short> : true_type {}; +template<> struct is_integral<int> : true_type {}; +template<> struct is_integral<long> : true_type {}; +template<> struct is_integral<long long> : true_type {}; +template<> struct is_integral<unsigned char> : true_type {}; +template<> struct is_integral<unsigned short> : true_type {}; +template<> struct is_integral<unsigned int> : true_type {}; +template<> struct is_integral<unsigned long> : true_type {}; +template<> struct is_integral<unsigned long long> : true_type {}; + +template<typename T, typename U> struct is_same : false_type {}; +template<typename T> struct is_same<T, T> : true_type {}; +} +#endif + +// CUDA numeric type headers +#include <cuda_fp16.h> +#include <cuda_bf16.h> +#include <cuda_fp8.h> +#include <cuda_fp4.h> + +// NOTE: #include <cuda/ptx> and <cooperative_groups.h> are intentionally omitted. +// They are only needed for CGA/cluster support (USE_CLUSTER=true), which this +// OSS engine does not use. All USE_CLUSTER code paths are guarded with +// "if constexpr" so dead branches are not compiled. + +// ============================================================ +// Fixed-width integer typedefs for NVRTC (no <cstdint> available) +// ============================================================ +constexpr int THREADS_PER_WARP = 32; + +#ifndef __CUDACC_RTC__ +#include <stdint.h> +#else +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; +#endif + +// ============================================================ +// cuDNN-authored LN kernel utilities +// Extracted from persistent_ln_headers_13.0.h +// ============================================================ + + +// cuDNN type aliases for FP8 types (from after inlined cuda_fp8.h) +typedef __nv_fp8_e4m3 nv_fp8_e4m3; +typedef __nv_fp8x2_e4m3 nv_fp8x2_e4m3; +typedef __nv_fp8_e5m2 nv_fp8_e5m2; +typedef __nv_fp8x2_e5m2 nv_fp8x2_e5m2; + +// cuDNN type aliases for FP4 types (from after inlined cuda_fp4.h) +typedef __nv_fp4_e2m1 nv_fp4_e2m1; +typedef __nv_fp4x2_e2m1 nv_fp4x2_e2m1; +typedef __nv_fp4x4_e2m1 nv_fp4x4_e2m1; + +// Pointer typedefs for NVRTC (from original Jitify stubs) +typedef int64_t intptr_t; +typedef uint64_t uintptr_t; +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + +// Large vector types for 64-byte and 32-byte loads +struct uint16 { + uint4 u; + uint4 v; + uint4 s; + uint4 t; +}; + +struct uint8 { + uint4 u; + uint4 v; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Datatype helpers + +template <int BYTES> +struct BytesToType {}; + +template <> +struct BytesToType<64> { + using Type = uint16; +}; + +template <> +struct BytesToType<32> { + using Type = uint8; +}; + +template <> +struct BytesToType<16> { + using Type = uint4; +}; + +template <> +struct BytesToType<8> { + using Type = uint64_t; +}; + +template <> +struct BytesToType<4> { + using Type = uint32_t; +}; + +template <> +struct BytesToType<2> { + using Type = uint16_t; +}; + +template <> +struct BytesToType<1> { + using Type = uint8_t; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <typename T> +struct TypeToVec2 {}; + +template <> +struct TypeToVec2<float> { + using Type = float2; +}; + +template <> +struct TypeToVec2<half> { + using Type = half2; +}; + +template <> +struct TypeToVec2<nv_bfloat16> { + using Type = nv_bfloat162; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <int INDEX> +struct Get { + template <typename T, typename R> + static inline __device__ R + of(const T& vec); +}; + +template <> +template <typename T, typename R> +inline __device__ R +Get<0>::of(const T& vec) { + return vec.x; +} + +template <> +template <typename T, typename R> +inline __device__ R +Get<1>::of(const T& vec) { + return vec.y; +} + +template <> +template <typename T, typename R> +inline __device__ R +Get<2>::of(const T& vec) { + return vec.z; +} + +template <> +template <typename T, typename R> +inline __device__ R +Get<3>::of(const T& vec) { + return vec.w; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <typename Src, typename Dst> +struct Converter { + static inline __device__ Dst + convert(const Src& from) { + return Dst(from); + } +}; + +template <> +struct Converter<float2, half2> { + static inline __device__ half2 + convert(const float2& x) { + return __float22half2_rn(x); + } +}; + +template <> +struct Converter<float2, nv_bfloat162> { + static inline __device__ nv_bfloat162 + convert(const float2& x) { +#if __CUDA_ARCH__ >= 800 + return __float22bfloat162_rn(x); +#else + union { + nv_bfloat162 raw; + nv_bfloat16 x; + nv_bfloat16 y; + } tmp; + tmp.x = __float2bfloat16_rn(x.x); + tmp.y = __float2bfloat16_rn(x.y); + return tmp.raw; +#endif + } +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <typename T> +struct Zeros { + static inline __device__ T + get() { + return T(0.f); + } +}; + +template <> +struct Zeros<float2> { + static inline __device__ float2 + get() { + return make_float2(0.f, 0.f); + } +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +__device__ __inline__ uint8_t +float_to_e8m0(float val) { + // CL-15277: use rounding-up mode for float -> e8m0 conversion +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && \ + (defined(__CUDA_ARCH_FEAT_SM100_ALL) || defined(__CUDA_ARCH_FEAT_SM101_ALL) || defined(__CUDA_ARCH_FEAT_SM110_ALL) || \ + defined(__CUDA_ARCH_FEAT_SM120_ALL)) + uint16_t out; + asm volatile( + "{\n" + "cvt.rp.satfinite.ue8m0x2.f32 %0, 0.0, %1;\n" + "}" + : "=h"(out) + : "f"(val)); + return *reinterpret_cast<uint8_t*>(&out); +#else +#if CUDART_VERSION >= 12080 + // Use explicit round-up mode to match the SM_100+ hardware instruction + return __nv_cvt_float_to_e8m0(val, __NV_SATFINITE, cudaRoundPosInf); +#else + if (isnan(val) || isinf(val)) { + return 0xFF; + } + uint32_t val_u32 = __float_as_uint(val); + uint8_t exponent = (val_u32 >> 23) & 0xFF; + uint32_t mantissa = val_u32 & 0x7FFFFF; + if ((mantissa > 0) && (exponent != 0xFE)) { // exp can only be < 0xFE here + exponent++; + } + return exponent; +#endif +#endif +} + +__device__ __inline__ float +e8m0_to_float(uint8_t val) { +#if CUDART_VERSION >= 12080 + __nv_fp8_e8m0 e8m0; + e8m0.__x = val; + return static_cast<float>(e8m0); +#else + return __uint_as_float(static_cast<uint32_t>(val) << 23); +#endif + +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Vectorization data structures +template <typename ELT_TYPE, uint32_t NUM_ELT> +struct Vec { + using Elt_type = ELT_TYPE; + + enum { BYTES = NUM_ELT * sizeof(Elt_type) }; + using Vec_type = typename BytesToType<BYTES>::Type; + + using Alias_type = union { + Vec_type vec; + Elt_type elt[NUM_ELT]; + }; + + Alias_type data; + + template <typename S> + inline __device__ void + to(Vec<S, NUM_ELT>& other) { +#pragma unroll + for (int it = 0; it < NUM_ELT; it++) { + other.data.elt[it] = S(this->data.elt[it]); + } + } + + template <typename Op> + inline __device__ void + assign(const Op& op) { +#pragma unroll + for (int it = 0; it < NUM_ELT; it++) { + this->data.elt[it] = op(it); + } + } + + inline __device__ void + load_from(const void* base_ptr, const size_t idx) { + this->data.vec = static_cast<const Vec_type*>(base_ptr)[idx]; + } + + inline __device__ void + store_to(void* base_ptr, const size_t idx) { + static_cast<Vec_type*>(base_ptr)[idx] = this->data.vec; + } + + inline __device__ void + operator+=(const Vec<ELT_TYPE, NUM_ELT>& rhs) { +#pragma unroll + for (int it = 0; it < NUM_ELT; it++) { + this->data.elt[it] += rhs.data.elt[it]; + } + } +}; + +inline __device__ float2 +operator+(const float2& a, const float2& b) { + return {a.x + b.x, a.y + b.y}; +} + +inline __device__ void +operator+=(float2& a, const float2& b) { + a.x += b.x; + a.y += b.y; +} + +template <typename T> +struct Sum { + inline __device__ + Sum() {} + inline __device__ T + operator()(const T& a, const T& b) { + return a + b; + } +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +inline __device__ void +__nv_ptx_builtin_ocg_fence_view_async_shared(void) { + asm volatile("fence.proxy.async.shared::cta;\n"); +} + +extern "C" { +__device__ uint32_t +__nvvm_get_smem_pointer(void* ptr); +//__device__ void +//__nv_ptx_builtin_ocg_fence_view_async_shared(void); +__device__ void +__nv_ptx_builtin_ocg_write_async_shared_b32(uint32_t dstAddr, uint32_t mbarrierAddr, uint32_t b0); +__device__ void +__nv_ptx_builtin_ocg_write_async_shared_b64(uint32_t dstAddr, uint32_t mbarrierAddr, uint64_t b0); +__device__ void +__nv_ptx_builtin_ocg_write_async_shared_v2_b32(uint32_t dstAddr, uint32_t mbarrierAddr, uint32_t b0, uint32_t b1); +__device__ void +__nv_ptx_builtin_ocg_write_async_shared_v4_b32(uint32_t dstAddr, + uint32_t mbarrierAddr, + uint32_t b0, + uint32_t b1, + uint32_t b2, + uint32_t b3); +} + +namespace utils { + +////////////////////////////////////////////////////////////////////////////////////////////////// +//// Shuffle syncronization helpers +template <typename T> +inline __device__ T +warp_shuffle_xor(const T& x, uint32_t idx) { + return __shfl_xor_sync(uint32_t(-1), x, idx); +} + +template <> +inline __device__ float2 +warp_shuffle_xor<float2>(const float2& x, uint32_t idx) { + return {warp_shuffle_xor(x.x, idx), warp_shuffle_xor(x.y, idx)};)KERNEL" + R"KERNEL(} + +template <typename T> +inline __device__ T +warp_shuffle_down(const T& x, uint32_t idx) { + return __shfl_down_sync(uint32_t(-1), x, idx); +} + +template <> +inline __device__ float2 +warp_shuffle_down<float2>(const float2& x, uint32_t idx) { + return {warp_shuffle_down(x.x, idx), warp_shuffle_down(x.y, idx)}; +} + +// This is a helper function to support __shfl_sync(float2) +template <typename T> +__device__ inline static T +shfl_sync_helper(unsigned mask, T var, int srcLane) { + return __shfl_sync(mask, var, srcLane); +} + +// specialize for float2 +template <> +__device__ inline float2 +shfl_sync_helper<float2>(unsigned mask, float2 var, int srcLane) { + double ret = __shfl_sync(mask, *reinterpret_cast<double*>(&var), srcLane); // cast to double + return *reinterpret_cast<float2*>(&ret); +} + +////////////////////////////////////////////////////////////////////////////////////////////////// +__device__ __forceinline__ void +namedBarrierSync(int name, int numThreads) { + asm volatile("bar.sync %0, %1;" : : "r"(name), "r"(numThreads) : "memory"); +} + +} // namespace utils + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Atomics +static inline __device__ void +atomicMaxFloat(float* addr, const float value) { + atomicMax(reinterpret_cast<int*>(addr), __float_as_int(value)); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Warp reduction functions +template <int GROUP_SIZE> +static inline __device__ float +warp_reduce_max(const float m, unsigned int mask = 0xFFFFFFFF) { + static constexpr int WARP_SIZE = 32; + static_assert(GROUP_SIZE > 0 && GROUP_SIZE <= WARP_SIZE, "group size must be less than or equal to warp size"); + + float max_val = m; +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && defined(__CUDA_ARCH_FEAT_SM100_ALL) + // Only enable the credux instruction for reduction on the full warp, as we saw perf regression for GROUP_SIZE < 32, + // where we need to iterate over #(WARP_SIZE/GROUP_SIZE) groups in the warp + if constexpr (GROUP_SIZE == WARP_SIZE) { + // For sm_100a arch, we can use redux.sync.op{.abs.}{.NaN}.f32 instruction to reduce the min/max value + // https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-redux-sync + asm volatile("redux.sync.max.f32 %0, %1, %2;" : "=f"(max_val) : "f"(m), "r"(mask)); + return max_val; + } +#endif +#pragma unroll + for (int delta = GROUP_SIZE / 2; delta > 0; delta /= 2) { + const float other_m = __shfl_down_sync(mask, max_val, delta); + __builtin_assume(max_val >= 0); + __builtin_assume(other_m >= 0); + max_val = fmaxf(max_val, other_m); + } + return max_val; +} + +template <int num_warps, typename compute_t> +static inline __device__ compute_t +reduce_max(const compute_t m, const int warpid) { + __shared__ float staging[num_warps]; + constexpr int warp_size = 32; + const float my_max = m; + const float my_warp_max = warp_reduce_max<warp_size>(my_max); + if (threadIdx.x % 32 == 0) { + staging[warpid] = my_warp_max; + } + __syncthreads(); + compute_t result = 0; + if (warpid == 0) { + const float my_max = threadIdx.x < num_warps ? staging[threadIdx.x] : 0; + result = warp_reduce_max<warp_size>(my_max); + } + return result; +} + +template <int num_warps, typename compute_t> +static inline __device__ compute_t +reduce_max(const compute_t m, const int warpid, int tidx) { + __shared__ float staging[num_warps]; + constexpr int warp_size = 32; + const float my_max = m; + const float my_warp_max = warp_reduce_max<warp_size>(my_max); + if (tidx % 32 == 0) { + staging[warpid] = my_warp_max; + } + utils::namedBarrierSync(1, num_warps * warp_size); + compute_t result = 0; + if (warpid == 0) { + const float my_max = tidx < num_warps ? staging[tidx] : 0; + result = warp_reduce_max<warp_size>(my_max); + } + return result; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Misc +constexpr __device__ int32_t +find_largest_divisor(int32_t n, int32_t divisor_upper_bound) { + if (n <= divisor_upper_bound) { + return n; + } + for (int32_t i = divisor_upper_bound; i >= 1; --i) { + if (n % i == 0) { + return i; // found the largest divisor + } + } + return divisor_upper_bound; // fallback +} + +constexpr __device__ bool +is_power_of_2(unsigned int n) { + return (n > 0) && ((n & (n - 1)) == 0); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Cooperative groups related +//// !!!! Keep this block at the end of the file - start !!!! + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Runtime parameters + +struct PersistentLnParamsBase { + // For Multi-CTA, number of different CTA groups; otherwise same as gridDim.x. + int ctas_per_col = 0; + + // Input is interpreted as matrix and we normalize across columns. + int rows = 0; + int cols = 0; + int batchSize = 1; // For AdaLN + int seqLen = 1; // For AdaLN + + // Common data pointers for forward and backward passes. + void *x = nullptr; + void *mu = nullptr; + void *rs = nullptr; + void *gamma = nullptr; + + // Multi-CTA workspace in gmem. + void *workspace = nullptr; + + // Multi-CTA sync barriers in gmem. + int *barrier = nullptr; + + bool isRMSNorm = false; + bool noScale = false; + bool noBias = false; + bool isAdaLN = false; + bool isBatchFirst = true; +}; + +struct PersistentLnFwdParams : public PersistentLnParamsBase { + // Output of LN FWD. + void *z = nullptr; + + void *beta = nullptr; + float epsilon = 0.f; + + // FP8 support + bool fp8_out = false; + float *scale = nullptr; + float *scale_inv = nullptr; + float *amax = nullptr; + + // Reuse z for row scaled output (or block scaled output if we use 2d1x1x) + void *scale_row = nullptr; + void *scale_col = nullptr; // only used in 1d2x2x + void *z_col = nullptr; // only used in 1d2x2x + void *z_math = nullptr; // only used when enabling the 1d2x2x colwise kernel +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Inter-CTA synchronization +template <uint32_t CTAS_PER_ROW> +struct InterCTASync { + template <typename Params> + inline __device__ + InterCTASync(Params ¶ms, uint32_t bidm, uint32_t bidn, uint32_t tidx) + : phase_counter_(0), + b0_(params.barrier + bidm) // The barrier for this group of CTAs. + , + b1_(params.barrier + bidm + params.ctas_per_col) // The barrier for this group of CTAs. + , + tidx_(tidx) { + // BARRIERS ARE ASSUMED TO BE INITIALIZED TO 0! + } + + inline __device__ void + spin_wait_(int *barrier, int step, int expected) { + asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(barrier), "r"(step)); + for (int found = -1; found != expected;) { + asm volatile("ld.global.acquire.gpu.b32 %0, [%1];" : "=r"(found) : "l"(barrier)); + } + } + + inline __device__ void + sync(uint32_t threads_per_cta) { + // ALL THREADS MUST ENTER! + + // We switch barrier every iteration. + int *barrier = phase_counter_ & 0x1 ? b1_ : b0_; + // We decrement every other iteration. + bool dec = phase_counter_ & 0x2; + int step = dec ? -1 : 1; + int expected = dec ? 0 : CTAS_PER_ROW; + // There are only 4 phases: up/down for b0/b1. + phase_counter_ = (phase_counter_ + 1) & 0x3; + + if (0 == tidx_) { + spin_wait_(barrier, step, expected); + } + + // CTA waits for thread 0 + utils::namedBarrierSync(0, threads_per_cta); + } + + int phase_counter_; + int *b0_; + int *b1_; + uint32_t tidx_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// LayerNorm Reduction and stats computation +// NOTE: WHOLE_CTA means if we'll use one empty mbarrier for inter-CTA sync using cluster. +// In the TMA LN engines it should be "true" since we're syncing the whole CTA with one empty mbarrier, while in the +// APEX LN engines it should be "false" as there's one empty mbarrier per warp m (and therefore WARPS_M empty mbarriers +// in total) +template <typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA> +struct Reducer : public Reducer<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA> { + using InterCTASync = InterCTASync<CTAS_PER_ROW>; + using Base = Reducer<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>; + using Type = typename Base::Type; + + enum { SMEM_BYTES = Base::SMEM_BYTES }; + + enum { WS_BARRIER_BYTES = 2 * sizeof(int) }; + enum { WS_DATA_BYTES = WARPS_M * CTAS_PER_ROW * sizeof(T) }; + + // size of the barriers + temporary result per CTA (multiply with CTAS_PER_ROW to get total) + enum { WORKSPACE_BYTES_PER_GROUP = Base::WORKSPACE_BYTES_PER_GROUP + WS_BARRIER_BYTES + WS_DATA_BYTES }; + + template <typename Params> + inline __device__ + Reducer(Params ¶ms, + uint32_t bidm, + uint32_t bidn, + uint32_t warp_m, + uint32_t warp_n, + uint32_t tidx, + uint32_t lane, + void *smem, + uint64_t *smem_bar) + : Base(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar), + inter_cta_(params, bidm, bidn, tidx), + bidn_(bidn), // CTA id within the group. + warp_m_(warp_m), + w0_(static_cast<T *>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW), + w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW), + smem_bar_(smem_bar), + parity_(0) { + // the first several elements are the barriers + smem_cga_ = reinterpret_cast<T *>(&smem_bar[WHOLE_CTA? 2: (WARPS_M + 1)]); + } + + template <typename Op> + inline __device__ T + allreduce(T data, Op &op, int32_t warps_m) { + data = Base::reduce(data, op, warps_m); + + if constexpr (USE_CLUSTER) { +#if (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080) + auto cluster = cooperative_groups::this_cluster(); + + // NOTE: right now only lane 0 has the valid value so that a intra-warp broadcast is required here. + // This issue is not in fwd (struct Stats) which does it earlier inside warp_chan_upd_dynamic(). + data = utils::shfl_sync_helper(uint32_t(-1), data, 0); + + // Broadcast local results to other CTAs inside the CGA + // Size of smem_cga_: [WARPS_M][CTAS_PER_ROW] + // Thread 0 sends to block 0, Thread 1 sends to block 1, etc... + if ((this->warp_n_ == 0) && (this->lane_ < CTAS_PER_ROW)) { + st_async_remote(&smem_cga_[warp_m_ * CTAS_PER_ROW + bidn_], data, this->lane_, &smem_bar_[WHOLE_CTA? 0: WARPS_M]); + } + + // Leader thread arrives on local barrier to indicate expected tx count + // We can't use (threadIdx.x == 0) directly here because it won't work for TMA + if ((this->warp_n_ == 0) && (warp_m_ == 0) && (this->lane_ == 0)) { + // It's possible that not all warp_m are active here, therefore, we can't use WARPS_M directly + uint32_t expected_tx_count = sizeof(data) * CTAS_PER_ROW * warps_m; + utils::mbarrier_arrive_expect_tx_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], expected_tx_count); + } + + // Wait on local barrier + while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], parity_)) {} + utils::fence_acquire_smem(); // Ensure we can read local smem values that are released by barrier flip + + T total = Zeros<T>::get(); + if (this->lane_ < CTAS_PER_ROW) { + total = smem_cga_[warp_m_ * CTAS_PER_ROW + this->lane_]; + } + utils::fence_release_smem(); // Ensure read of buffer remains ordered before smem_bar.arrive.relaxed +)KERNEL" + R"KERNEL( // Signal barrier is empty. + // Each thread must arrive on all the barriers (like an arrive broadcast). + // NOTE: here we only let each warp m arrive on the remote barriers of the same warp m (i.e. the same row), + // because if we have one empty barrier for the entire CTA, there's a difficulty how to init the count of + // the barrier (since some warps could be disabled here). The downside is we'll need a __syncthreads() here, + // which doesn't have obvious perf impact though. + // TODO: we could probably have one full bar per row (same as the empty bar) to get rid of the CTA sync, + // while the downside is more smem (mbarriers) will be needed. + if (!WHOLE_CTA) { + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + } + for (int other_block_rank = 0; other_block_rank < CTAS_PER_ROW; ++other_block_rank) { + uint64_t *remote_bar_empty = cluster.map_shared_rank(&smem_bar_[WHOLE_CTA? 1: warp_m_], other_block_rank); + utils::mbarrier_arrive_relaxed_cluster(remote_bar_empty); + } + + total = Reducer<T, 1, 1, 1, USE_CLUSTER, WHOLE_CTA>::allreduce_(total, op); + + // Wait for remote buffer to be writable again by waiting on local barrier: + while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 1: warp_m_], parity_)) {} + utils::fence_acquire_smem(); // Order wrt st_async_remote + + // Flip parity bit for next iteration + parity_ ^= 1; + + return total; +#else + static_assert(true, "Cluster enabled on host side but not available on device"); +#endif + } else { + // We switch workspace every iteration. + T *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_; + + // Warp leaders 0 hold the CTA-local results. + if (this->warp_n_ == 0 && this->lane_ == 0) { + workspace[bidn_] = data; + } + + // We need to check for the case where we are using CTA > 1 and WARP_M > 1 and N == 1 + // Because in this case we cannot rely on the __syncThreads in template<typename T, uint32_t WARPS_M, + // uint32_t WARPS_N>::compute (because we will use the specialized template <typename T, uint32_t + // WARPS_M>::compute which does not have a sync) + if (CTAS_PER_ROW > 1 && WARPS_M > 1 && WARPS_N == 1) { + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + } + + // Wait for all CTAS_PER_ROW CTAS in the group to have written their result. + inter_cta_.sync(warps_m * WARPS_N * 32); + + T total = Zeros<T>::get(); + + // Every warp does the final reduction locally. + if constexpr (CTAS_PER_ROW <= THREADS_PER_WARP) { + if (this->lane_ < CTAS_PER_ROW) { + total = workspace[this->lane_]; + } + } else { + static constexpr int32_t LOOP_PER_THREAD = (CTAS_PER_ROW + THREADS_PER_WARP - 1) / THREADS_PER_WARP; + + // Collect stats for the current lane from ctas (#bidn % THREADS_PER_WARP == #lane) and then do the + // intra-warp reduction + total = workspace[this->lane_]; +#pragma unroll + for (int32_t loop_in_thread = 1; loop_in_thread < LOOP_PER_THREAD; ++loop_in_thread) { + const int32_t lane_in_loop = this->lane_ + loop_in_thread * THREADS_PER_WARP; + if (lane_in_loop < CTAS_PER_ROW) { + total = op(total, workspace[lane_in_loop]); + } + } + } + + total = Reducer<T, 1, 1, 1, false, false>::allreduce_(total, op); + + return total; + } + } + + InterCTASync inter_cta_; + T *w0_; + T *w1_; + int bidn_; + int warp_m_; + + private: + T *smem_cga_; + uint64_t *smem_bar_; + int parity_; +}; + +template <typename T, uint32_t WARPS_M, bool USE_CLUSTER, bool WHOLE_CTA> +struct Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA> { + using Type = T; + enum { SMEM_BYTES = 0 }; + enum { WORKSPACE_BYTES_PER_GROUP = 0 }; + enum { THREADS_PER_WARP = 32 }; + + template <typename Params> + inline __device__ + Reducer(Params ¶ms, + uint32_t bidm, + uint32_t bidn, + uint32_t warp_m, + uint32_t warp_n, + uint32_t /*tidx*/, + uint32_t lane, + void *smem, + uint64_t *smem_bar) + : warp_n_(warp_n), lane_(lane) {} + + template <typename Op> + static inline __device__ T + allreduce_(T data, Op &op) { +#pragma unroll + for (int it = 1; it < THREADS_PER_WARP; it *= 2) { + data = op(data, utils::warp_shuffle_xor(data, it)); + } + return data; + } + + template <typename Op> + inline __device__ T + allreduce(T data, Op &op, int32_t warps_m) { + return allreduce_(data, op); + } + + protected: + template <typename Op> + inline __device__ T + reduce(T data, Op &op, int32_t warps_m) { +// only lane 0 holds the result! +#pragma unroll + for (int it = THREADS_PER_WARP / 2; it > 0; it /= 2) { + data = op(data, utils::warp_shuffle_down(data, it)); + } + return data; + } + + public: + int warp_n_; + int lane_; +}; + +template <typename T, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA> +struct Reducer<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA> : public Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA> { + using Base = Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA>; + using Type = T; + + enum { SMEM_BYTES = Base::SMEM_BYTES + WARPS_M * WARPS_N * sizeof(T) * 2 }; + enum { WORKSPACE_BYTES_PER_GROUP = 0 }; + enum { THREADS_PER_WARP = 32 }; + + template <typename Params> + inline __device__ + Reducer(Params ¶ms, + uint32_t bidm, + uint32_t bidn, + uint32_t warp_m, + uint32_t warp_n, + uint32_t tidx, + uint32_t lane, + void *smem, + uint64_t *smem_bar) + : Base(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar), use0_(true) { + smem0_ = &static_cast<T *>(smem)[warp_m * WARPS_N]; + smem1_ = smem0_ + WARPS_M * WARPS_N; + } + + template <typename Op> + inline __device__ T + allreduce(T data, Op &op, int32_t warps_m) { + T *smem = use0_ ? smem0_ : smem1_; + use0_ = !use0_; + data = Base::reduce(data, op, warps_m); + if (this->lane_ == 0) { + smem[this->warp_n_] = data; + } + // The number matters here. 0 will only use one barrier per block. "1" will use 2 according to ncu. + // We should use 0 unless it is absolutely necessary to use seperate barriers. + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + T out = Zeros<T>::get(); +#pragma unroll + for (int it = 0; it < WARPS_N; it++) { + out = op(out, smem[it]); + } + return out; + } + + protected: + template <typename Op> + inline __device__ T + reduce(T data, Op &op, int32_t warps_m) { + T *smem = use0_ ? smem0_ : smem1_; + use0_ = !use0_; + // only intra-CTA group leader holds the result! + data = Base::reduce(data, op, warps_m); + if (this->lane_ == 0) { + smem[this->warp_n_] = data; + } + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + T out = Zeros<T>::get(); + if (this->warp_n_ == 0 && this->lane_ == 0) { +#pragma unroll + for (int it = 0; it < WARPS_N; it++) { + out = op(out, smem[it]); + } + } + return out; + } + + private: + T *smem0_; + T *smem1_; + bool use0_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +template <bool isRMSNorm, typename T, bool handleNan = false> +inline __device__ void +update_norm_stats(T &m_a, T &m2_a, T &n_a, T m_b, T m2_b, T n_b) { + const T n_ab = n_a + n_b; + + if constexpr (!isRMSNorm) { + const T rn_ab = (handleNan && (n_ab == Zeros<T>::get())) ? Zeros<T>::get() : (1.f / n_ab); + const T delta = m_a - m_b; + const float m2_ab = m2_a + m2_b + delta * delta * n_a * n_b * rn_ab; + const float m_ab = (n_a * m_a + n_b * m_b) * rn_ab; + n_a = n_ab; + m_a = m_ab; + m2_a = m2_ab; + } else { + const float m2_ab = m2_a + m2_b; + n_a = n_ab; + m_a = Zeros<T>::get(); + m2_a = m2_ab; + } +} + +template <bool isRMSNorm, typename T, bool handleNan = false> +inline __device__ void +warp_chan_upd_dynamic(T &m_a, T &m2_a, T &n_a, int num_active) { + // Assume at least leftmost is valid and init: step = next_pow2(num_active) / 2 (might get NaN otherwise) + int highest_bit_set = (8 * sizeof(num_active)) - __clz(num_active - 1); + +#pragma unroll + for (int step = (1 << (highest_bit_set - 1)); step > 0; step /= 2) { + // Exchange + T n_b = utils::warp_shuffle_down(n_a, step); + T m_b = (!isRMSNorm ? utils::warp_shuffle_down(m_a, step) : Zeros<T>::get()); + T m2_b = utils::warp_shuffle_down(m2_a, step); + update_norm_stats<isRMSNorm, T, handleNan>(m_a, m2_a, n_a, m_b, m2_b, n_b); + } + // Intra-warp broadcast (only lane 0 has valid stats). + m_a = __shfl_sync(uint32_t(-1), m_a, 0); + m2_a = __shfl_sync(uint32_t(-1), m2_a, 0); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// NOTE: WHOLE_CTA means if we'll use one empty mbarrier for inter-CTA sync using cluster. +// In the TMA LN engines it should be "true" since we're syncing the whole CTA with one empty mbarrier, while in the +// APEX LN engines it should be "false" as there's one empty mbarrier per warp m (and therefore WARPS_M empty mbarriers +// in total) +template <typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA> +struct Stats { + // This could be done generically with the Reducer. But then we would have to exchange 3 instead of 2 fields. + + using InterCTASync = InterCTASync<CTAS_PER_ROW>; + using BlockStats = Stats<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>; + using stats_t = typename BlockStats::stats_t; + + enum { SMEM_BYTES = BlockStats::SMEM_BYTES }; + + template <typename Params> + inline __device__ + Stats(Params ¶ms, + uint32_t bidm, + uint32_t bidn, + uint32_t warp_m, + uint32_t warp_n, + uint32_t tidx, + uint32_t lane, + void *smem, + uint64_t *smem_bar) + : inter_cta_(params, bidm, bidn, tidx), + block_stats_(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar), + bidn_(bidn), // CTA id within the group. + w0_(static_cast<stats_t *>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW), + w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW), + warp_n_(warp_n), + warp_m_(warp_m), + lane_(lane), + smem_bar_(smem_bar), + parity_(0) { + // the first several elements are the barriers + smem_cga_ = reinterpret_cast<stats_t *>(&smem_bar[WHOLE_CTA? 2: (WARPS_M + 1)]); + } + + template <bool isRMSNorm, uint32_t LDGS, uint32_t NUM_ELTS> + inline __device__ stats_t + compute(const T (&elts)[LDGS * NUM_ELTS], const T rn, int32_t warps_m) { + static constexpr uint32_t N = LDGS * NUM_ELTS; + constexpr T ELTS_PER_ROW_PER_CTA = N * WARPS_N * THREADS_PER_WARP; + // TODO rn is not really needed here.. + constexpr T block_rn = 1.f / T(ELTS_PER_ROW_PER_CTA); + stats_t block_stats = block_stats_.template compute<isRMSNorm, LDGS, NUM_ELTS>(elts, block_rn, warps_m); + + if constexpr (USE_CLUSTER) { +#if (__CUDA_ARCH__ >= 900) && (CUDART_VERSION >= 12080) + auto cluster = cooperative_groups::this_cluster(); + + // Broadcast local results to other CTAs inside the CGA + // Size of smem_cga_: [WARPS_M][CTAS_PER_ROW] + // Thread 0 sends to block 0, Thread 1 sends to block 1, etc... + if ((warp_n_ == 0) && (lane_ < CTAS_PER_ROW)) { + st_async_remote(&smem_cga_[warp_m_ * CTAS_PER_ROW + bidn_], block_stats, lane_, &smem_bar_[WHOLE_CTA? 0: WARPS_M]); + } + + // Leader thread arrives on local barrier to indicate expected tx count + // We can't use (threadIdx.x == 0) directly here because it won't work for TMA + if ((warp_n_ == 0) && (warp_m_ == 0) && (lane_ == 0)) { + // It's possible that not all warp_m are active here, therefore, we can't use WARPS_M directly + uint32_t expected_tx_count = sizeof(block_stats) * CTAS_PER_ROW * warps_m; + utils::mbarrier_arrive_expect_tx_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], expected_tx_count); + } + + // Wait on local barrier + while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 0: WARPS_M], parity_)) {} + utils::fence_acquire_smem(); // Ensure we can read local smem values that are released by barrier flip + + T n = Zeros<T>::get(); + T m = Zeros<T>::get(); + T m2 = Zeros<T>::get(); + if (lane_ < CTAS_PER_ROW) { + stats_t result = smem_cga_[warp_m_ * CTAS_PER_ROW + lane_]; + n = ELTS_PER_ROW_PER_CTA; + m = Get<0>::of<stats_t, T>(result); // should be 0 for RMSNorm + m2 = Get<1>::of<stats_t, T>(result); + } + utils::fence_release_smem(); // Ensure read of buffer remains ordered before smem_bar.arrive.relaxed +)KERNEL" + R"KERNEL( // Signal barrier is empty. + // Each thread must arrive on all the barriers (like an arrive broadcast). + // NOTE: here we only let each warp m arrive on the remote barriers of the same warp m (i.e. the same row), + // because if we have one empty barrier for the entire CTA, there's a difficulty how to init the count of + // the barrier (since some warps could be disabled here). The downside is we'll need a __syncthreads() here, + // which doesn't have obvious perf impact though. + // TODO: we could probably have one full bar per row (same as the empty bar) to get rid of the CTA sync, + // while the downside is more smem (mbarriers) will be needed. + if (!WHOLE_CTA) { + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + } + for (int other_block_rank = 0; other_block_rank < CTAS_PER_ROW; ++other_block_rank) { + uint64_t *remote_bar_empty = cluster.map_shared_rank(&smem_bar_[WHOLE_CTA? 1: warp_m_], other_block_rank); + utils::mbarrier_arrive_relaxed_cluster(remote_bar_empty); + } + + warp_chan_upd_dynamic<isRMSNorm, T, !is_power_of_2(CTAS_PER_ROW)>(m, m2, n, CTAS_PER_ROW); + + // Wait for remote buffer to be writable again by waiting on local barrier: + while (!utils::mbarrier_try_wait_parity_relaxed_cluster(&smem_bar_[WHOLE_CTA? 1: warp_m_], parity_)) {} + utils::fence_acquire_smem(); // Order wrt st_async_remote + + // Flip parity bit for next iteration + parity_ ^= 1; + + return {m, m2}; +#else + static_assert(true, "Cluster enabled on host side but not available on device"); +#endif + } else { + // We switch workspace every iteration. + stats_t *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_; + + // Warp leaders 0 hold the CTA-local results. + if (warp_n_ == 0 && lane_ == 0) { + workspace[bidn_] = block_stats; + } + + // We need to check for the case where we are using CTA > 1 and WARP_M > 1 and N == 1 + // Because in this case we cannot rely on the __syncThreads in template<typename T, uint32_t WARPS_M, + // uint32_t WARPS_N>::compute (because we will use the specialized template <typename T, uint32_t + // WARPS_M>::compute which does not have a sync) + // Bug 5221388: For WARPS_M > 1 and WARPS_N > 1, we also need the sync here, otherwise the stats received in + // `workspace[lane_]` may be NaN (as if some stats from the other CTAs are not initialized). + // Reason unknown yet and tracked in CL-16775. + if (CTAS_PER_ROW > 1 && WARPS_M > 1) { + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + } + + // Wait for all CTAS_PER_ROW CTAS in the group to have written their result. + inter_cta_.sync(warps_m * WARPS_N * 32); + + T n = Zeros<T>::get(); + T m = Zeros<T>::get(); + T m2 = Zeros<T>::get(); + + // Every warp does the final reduction locally. + if constexpr (CTAS_PER_ROW <= THREADS_PER_WARP) { + if (lane_ < CTAS_PER_ROW) { + stats_t result = workspace[lane_]; + n = ELTS_PER_ROW_PER_CTA; + m = Get<0>::of<stats_t, T>(result); // should be 0 for RMSNorm + m2 = Get<1>::of<stats_t, T>(result); + } + warp_chan_upd_dynamic<isRMSNorm, T, !is_power_of_2(CTAS_PER_ROW)>(m, m2, n, CTAS_PER_ROW); + } else { + static constexpr int32_t LOOP_PER_THREAD = (CTAS_PER_ROW + THREADS_PER_WARP - 1) / THREADS_PER_WARP; + + stats_t curr = workspace[lane_]; + n = ELTS_PER_ROW_PER_CTA; + m = Get<0>::of<stats_t, T>(curr); // should be 0 for RMSNorm + m2 = Get<1>::of<stats_t, T>(curr); + + // Collect stats for the current lane from ctas (#bidn % THREADS_PER_WARP == #lane) and then do the + // intra-warp reduction +#pragma unroll + for (int32_t loop_in_thread = 1; loop_in_thread < LOOP_PER_THREAD; ++loop_in_thread) { + const int32_t lane_in_loop = lane_ + loop_in_thread * THREADS_PER_WARP; + if (lane_in_loop < CTAS_PER_ROW) { + curr = workspace[lane_in_loop]; + T m_b = Get<0>::of<stats_t, T>(curr); + T m2_b = Get<1>::of<stats_t, T>(curr); + update_norm_stats<isRMSNorm>(m, m2, n, m_b, m2_b, ELTS_PER_ROW_PER_CTA); + } + } + warp_chan_upd_dynamic<isRMSNorm>(m, m2, n, THREADS_PER_WARP); + } + + return {m, m2}; + } + } + + InterCTASync inter_cta_; + BlockStats block_stats_; + + stats_t *w0_; + stats_t *w1_; + int bidn_; + int warp_n_; + int warp_m_; + int lane_; + + private: + stats_t *smem_cga_; + uint64_t *smem_bar_; + int parity_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <typename T, uint32_t WARPS_M, uint32_t WARPS_N, bool USE_CLUSTER, bool WHOLE_CTA> +struct Stats<T, 1, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA> { + using WarpStats = Stats<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA>; + using stats_t = typename WarpStats::stats_t; + + enum { SMEM_BYTES = WARPS_M * WARPS_N * sizeof(stats_t) * 2 }; + + template <typename Params> + inline __device__ + Stats(Params ¶ms, + uint32_t bidm, + uint32_t bidn, + uint32_t warp_m, + uint32_t warp_n, + uint32_t tidx, + uint32_t lane, + void *smem, + uint64_t *smem_bar) + : warp_stats_(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar), use0_(true) { + smem0_ = static_cast<stats_t *>(smem) + warp_m * WARPS_N; + smem1_ = smem0_ + WARPS_M * WARPS_N; + } + + template <bool isRMSNorm, uint32_t LDGS, uint32_t NUM_ELTS> + inline __device__ stats_t + compute(const T (&elts)[LDGS * NUM_ELTS], const T rn, int32_t warps_m) { + stats_t *smem = use0_ ? smem0_ : smem1_; + use0_ = !use0_; + // Compute warp local for all WARPS_N + static constexpr uint32_t N = LDGS * NUM_ELTS; + constexpr T warp_rn = 1.f / T(N * THREADS_PER_WARP); + stats_t warp_stats = warp_stats_.template compute<isRMSNorm, LDGS, NUM_ELTS>(elts, warp_rn, warps_m); + + // Each warp warp leader stores its stats + const auto warp_n = warp_stats_.reducer_.warp_n_; + const auto lane = warp_stats_.reducer_.lane_; + if (lane == 0) { + smem[warp_n] = warp_stats; + } + utils::namedBarrierSync(0, warps_m * WARPS_N * 32); + + T n = Zeros<T>::get(); + T m = Zeros<T>::get(); + T m2 = Zeros<T>::get(); + + if (lane < WARPS_N) { + stats_t result = smem[lane]; + n = N * THREADS_PER_WARP; + m = Get<0>::of<stats_t, T>(result); // should be 0 for RMSNorm + m2 = Get<1>::of<stats_t, T>(result); + } + + warp_chan_upd_dynamic<isRMSNorm>(m, m2, n, WARPS_N); + + return {m, m2}; + } + + WarpStats warp_stats_; + stats_t *smem0_; + stats_t *smem1_; + bool use0_; +}; + +template <typename T, uint32_t WARPS_M, bool USE_CLUSTER, bool WHOLE_CTA> +struct Stats<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA> { + using stats_t = typename TypeToVec2<T>::Type; + // The simple Warp reducer. + using Reducer = Reducer<T, 1, WARPS_M, 1, USE_CLUSTER, WHOLE_CTA>; + + enum { SMEM_BYTES = 0 }; + + template <typename Params> + inline __device__ + Stats(Params ¶ms, + uint32_t bidm, + uint32_t bidn, + uint32_t warp_m, + uint32_t warp_n, + uint32_t tidx, + uint32_t lane, + void *smem, + uint64_t *smem_bar) + : reducer_(params, bidm, bidn, warp_m, warp_n, tidx, lane, smem, smem_bar) {} + + template <bool isRMSNorm, uint32_t LDGS, uint32_t NUM_ELTS> + inline __device__ stats_t + compute(const T (&elts)[LDGS * NUM_ELTS], const T rn, int32_t warps_m) { + static constexpr uint32_t N = LDGS * NUM_ELTS; + auto sum = Sum<T>(); + + T m = Zeros<T>::get(); + if (!isRMSNorm) { +// CL-14115: The unroll factor 128 for LDGS was chosen based on the compilation/perf results for APEX LN_fwd engines +#pragma unroll(128 * NUM_ELTS) + for (int it = 0; it < N; it++) { + m += elts[it]; + } + m = reducer_.allreduce(m, sum, warps_m) * rn; + } + + T m2 = Zeros<T>::get(); +#pragma unroll(128 * NUM_ELTS) + for (int it = 0; it < N; it++) { + T diff = (elts[it] - m); + m2 = __fmaf_ieee_rn(diff, diff, m2); + } + m2 = reducer_.allreduce(m2, sum, warps_m); + + return {m, m2}; + } + + Reducer reducer_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//// Fast division helpers + +// Count leading zeros - start from most significant bit. +static int +clz(int32_t x) { + for (int32_t i = 31; i >= 0; --i) + if (((1 << i) & x) != 0) { + return 31 - i; + } + return 32; +} + +static int32_t +find_log_2(int32_t x, bool round_up = false) { + int32_t a = 31 - clz(x); + if (round_up) { + a += !(0 == (x & (x - 1))); + } + return a; +} + +static void +find_divisor(int32_t denom, uint32_t &mul_coeff, uint32_t &shift_coeff) { + if (denom == 0) { + return; + } + if (denom == 1) { + // if dividing by 1, reduced math doesn't work because mul_coeff would + // need to be 2^32, which doesn't fit into unsigned int. the div() + // routine handles this special case separately. + mul_coeff = 0; + shift_coeff = 0; + return; + } + // To express the division N/D in terms of a multiplication, what we first + // imagine is simply N*(1/D). However, 1/D will always evaluate to 0 (for D>1), + // so we need another way. There's nothing that says we have to use exactly + // the fraction 1/D; instead it could be any X/Y that reduces to 1/D (i.e., + // Y=X*D), or at least to "close enough" to it. If we pick Y that is a power + // of two, then the N*(X/Y) can be N*X followed by a right-shift by some amount. + // The power of two we should pick should be at least 2^32, because in the + // div() routine we'll use umulhi(), which returns only the upper 32 bits -- + // this being equivalent to a right-shift by 32. But we might want a higher + // power of two for better accuracy depending on the magnitude of the denominator. + // Once we've picked Y, then X [our mul_coeff value] is simply Y/D, rounding up, + // and we save shift_coeff as whatever further shift we have to do beyond + // what the umulhi() implies. + uint32_t p = 31 + find_log_2(denom, true); + uint32_t m = ((1ull << p) + static_cast<uint32_t>(denom - 1)) / static_cast<uint32_t>(denom); + mul_coeff = m; + shift_coeff = p - 32; +} + +__device__ __forceinline__ uint32_t +umulhi(uint32_t x, uint32_t y) { +#if defined(__CUDA_ARCH__) + return __umulhi(x, y); +#else + uint64_t z = static_cast<uint64_t>(x) * y; + return static_cast<uint32_t>(z >> 32); +#endif +} + +class reduced_divisor { + public: + reduced_divisor() {} + __forceinline__ + reduced_divisor(int32_t _y) + : y(_y) { + mul_coeff = 0U; + shift_coeff = 0U; + find_divisor(y, mul_coeff, shift_coeff); + } + __device__ __forceinline__ + reduced_divisor(uint32_t _mul_coeff, uint32_t _shift_coeff, int32_t _y) + : mul_coeff(_mul_coeff), shift_coeff(_shift_coeff), y(_y) {} + __device__ __forceinline__ int32_t + div(int32_t x) const { + // if dividing by 1, then find_divisor wouldn't have worked because + // mul_coeff would have had to be 2^32, which can't be represented, + // so we have to special case that one. + return (y != 1) ? umulhi(static_cast<uint32_t>(x), mul_coeff) >> shift_coeff : x; + } + __device__ __forceinline__ int32_t + mod(int32_t x) const { + return x - (div(x) * y); + } + __device__ __forceinline__ void + divmod(int32_t x, int32_t &q, int32_t &mod) const { + q = div(x); + mod = x - (q * y); + } + __device__ __forceinline__ int32_t + get() const { + return y; + } + + protected: + uint32_t mul_coeff; + uint32_t shift_coeff; + int32_t y; +}; + + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <uint32_t HIDDEN_SIZE_, + typename weight_t_, + typename input_t_, + typename output_t_, + typename compute_t_, + typename index_t_, + uint32_t THREADS_PER_CTA_> +struct Kernel_traits_base { + using weight_t = weight_t_; + using input_t = input_t_; + using output_t = output_t_; + using compute_t = compute_t_; + using index_t = index_t_; + + enum { HIDDEN_SIZE = HIDDEN_SIZE_ }; + enum { THREADS_PER_CTA = THREADS_PER_CTA_ }; + enum { THREADS_PER_WARP = 32 }; +};)KERNEL" + R"KERNEL( + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +template <typename weight_t_, + typename input_t_, + typename output_t_, + typename compute_t_, + typename norm_output_t_, + typename index_t_, + uint32_t HIDDEN_SIZE_, + uint32_t BATCH_SIZE_, + uint32_t CTAS_PER_ROW_, + uint32_t WARPS_M_, + uint32_t WARPS_N_, + uint32_t BYTES_PER_LDG_ = 16, + bool isRMSNorm_ = false, + bool isAdaLN_ = false, + bool isBatchFirst_ = true, + bool hasGamma_ = true, + bool hasBeta_ = true, + bool useGammaSmem_ = true, // for FWD kernels it denotes the use of shmem for both gamma and beta + bool useCluster_ = false, + bool wholeCTA_ = false, + uint32_t ROWS_PER_WARP_ = 1, + typename Base = Kernel_traits_base<HIDDEN_SIZE_, + weight_t_, + input_t_, + output_t_, + compute_t_, + index_t_, + WARPS_M_ * WARPS_N_ * THREADS_PER_WARP> > +struct Kernel_traits : public Base { + using input_t = typename Base::input_t; + using weight_t = typename Base::weight_t; + using compute_t = typename Base::compute_t; + using output_t = typename Base::output_t; + using index_t = typename Base::index_t; + using norm_output_t = norm_output_t_; + enum { isRMSNorm = isRMSNorm_ }; + enum { isAdaLN = isAdaLN_ }; + enum { isBatchFirst = isBatchFirst_ }; + enum { hasGamma = hasGamma_ }; + enum { hasBeta = hasBeta_ }; + enum { CTAS_PER_ROW = CTAS_PER_ROW_ }; + enum { WARPS_M = WARPS_M_ }; + enum { WARPS_N = WARPS_N_ }; + enum { COLS = HIDDEN_SIZE_ }; + enum { HIDDEN_SIZE = HIDDEN_SIZE_ }; + enum { BATCH_SIZE = BATCH_SIZE_ }; + enum { BYTES_PER_LDG = BYTES_PER_LDG_ }; + enum { NUM_ELTS = BYTES_PER_LDG / sizeof(input_t) }; + enum { USE_GAMMA_SMEM = useGammaSmem_ }; + enum { USE_CLUSTER = useCluster_ }; + enum { WHOLE_CTA = wholeCTA_ }; + enum { THREADS_PER_ROW = WARPS_N * THREADS_PER_WARP }; + enum { THREADS_PER_CTA = WARPS_M * THREADS_PER_ROW }; + enum { ROWS_PER_WARP = ROWS_PER_WARP_ }; + enum { ROWS_PER_CTA = WARPS_M * ROWS_PER_WARP }; + + enum { BYTES_PER_ROW = COLS * sizeof(input_t) }; + enum { BYTES_PER_ROW_PER_CTA = THREADS_PER_ROW * BYTES_PER_LDG }; + // Multi-row per CTA not supported for multi-CTA => no smem for WGRAD needed + enum { SMEM_BYTES_WGRAD = ROWS_PER_CTA == 1 ? 0 : BATCH_SIZE * ROWS_PER_CTA * COLS * sizeof(compute_t) }; + + using reduce_t = typename TypeToVec2<compute_t>::Type; + using RMSReducer = Reducer<compute_t, CTAS_PER_ROW, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>; + using Reducer = Reducer<reduce_t, CTAS_PER_ROW, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>; + + enum { SMEM_BYTES_DGRAD = Reducer::SMEM_BYTES }; + enum { SMEM_BYTES = SMEM_BYTES_DGRAD + SMEM_BYTES_WGRAD }; + + using Ivec = Vec<input_t, NUM_ELTS>; + using Ovec = Vec<output_t, NUM_ELTS>; + using Wvec = Vec<weight_t, NUM_ELTS>; + using Cvec = Vec<compute_t, NUM_ELTS>; + using NormOvec = Vec<norm_output_t, NUM_ELTS>; + enum { ELTS_PER_LDG = BYTES_PER_LDG / sizeof(input_t) }; + + // Assume that each thread can handle the same number of elements in the output and weights as in the input. + // The number of columns fetched per load from input: one per thread. + enum { VEC_COLS_PER_LDG = CTAS_PER_ROW * THREADS_PER_ROW }; + // The total number of vectorized loads/stores per hidden vector. + enum { VEC_COLS = COLS / ELTS_PER_LDG }; + // The number of loads per thread for the input. + enum { LDGS = VEC_COLS / VEC_COLS_PER_LDG }; + + using Stats = Stats<compute_t, CTAS_PER_ROW, WARPS_M, WARPS_N, USE_CLUSTER, WHOLE_CTA>; + enum { SMEM_BYTES_FWD = Stats::SMEM_BYTES }; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// + + +constexpr float CUDNN_FLT_MIN = 1.17549435082228750796873653722224568e-38F; // Minimum positive normalized float value +/** + * Base class to provide common block scaling utilities, private to `BlockScaleHelper` + */ +template <typename Cvec, typename Ovec, int32_t BlockSize> +class BlockScaleHelperBase; + +/** + * Base class to provide common block scaling utilities, for nvfp4 + */ +template <typename Cvec, typename Ovec> +class BlockScaleHelperBase<Cvec, Ovec, 16> { + public: + using scale_t = nv_fp8_e4m3; + + protected: + using compute_t = typename Cvec::Elt_type; + using output_t = typename Ovec::Elt_type; + + using index_t = uint32_t; + + static constexpr int32_t THREADS_PER_WARP = 32; + static constexpr int32_t BLOCK_SIZE = 16; + static constexpr int32_t NUM_ELTS = sizeof(Cvec) / sizeof(compute_t); + static constexpr int32_t GROUP_SIZE = BLOCK_SIZE / NUM_ELTS; + static constexpr int32_t SF_COUNT = THREADS_PER_WARP / GROUP_SIZE; + + static __device__ compute_t + scale(const compute_t value) { + constexpr compute_t nvfp4_max = 6.0f; + compute_t result = value / nvfp4_max; + // Clamp to CUDNN_FLT_MIN to match reference implementation and avoid 0 scaling factors + return fmaxf(result, CUDNN_FLT_MIN); + } + + static __device__ scale_t + fp32ToE4M3(float value) { + return scale_t(value); + } + + static __device__ Vec<uint8_t, NUM_ELTS> + vecDivideAndCast(const Cvec &input, compute_t scale) { + // Construct the nv_fp4x2_e2m1 outputs. + // If NUM_ELTS == 1, nv_fp4(ele1,0) + // If NUM_ELTS % 2 == 0; f2_i=nv_fp4(ele_i, ele_i+1) --> out[i/2] + // Per cuda_fp4.h and cuda_fp8.h + // The data type of __nv_fp4x2_storage_t is __nv_fp8_storage_t + // The data type of __nv_fp8_storage_t is unsigned char: + // typedef unsigned char __nv_fp8_storage_t; + // The reason why we use unsigned char is that the __shfl_xor_sync don't support nv_fp4 data type + Vec<uint8_t, NUM_ELTS> output; +#pragma unroll + for (int i = 0; i < NUM_ELTS; i += 2) { + float2 f2 = + make_float2((input.data.elt[i] / scale), (i + 1 < NUM_ELTS ? (input.data.elt[i + 1] / scale) : 0)); + output.data.elt[i / 2] = static_cast<uint8_t>(nv_fp4x2_e2m1(f2).__x); + } + return output; + } +}; + +/** + * Base class to provide common block scaling utilities, for mxfp8 + */ +template <typename Cvec, typename Ovec> +class BlockScaleHelperBase<Cvec, Ovec, 32> { + public: + using lne8m0_t = uint8_t; + using scale_t = lne8m0_t; + + protected: + using compute_t = typename Cvec::Elt_type; + using output_t = typename Ovec::Elt_type; + using index_t = uint32_t; + + static constexpr int32_t THREADS_PER_WARP = 32; + static constexpr int32_t BLOCK_SIZE = 32; + static constexpr int32_t NUM_ELTS = sizeof(Cvec) / sizeof(compute_t); + static constexpr int32_t GROUP_SIZE = BLOCK_SIZE / NUM_ELTS; + + static __device__ compute_t + scale(const compute_t value) { + static constexpr float FP8_MAX = std::is_same<output_t, nv_fp8_e5m2>::value ? 57344.f : 448.f; + compute_t result = value / FP8_MAX; + // Clamp to CUDNN_FLT_MIN to match reference implementation and avoid 0 scaling factors + return fmaxf(result, CUDNN_FLT_MIN); + } + + template <typename IOvec> + static __device__ Ovec + vecDivideAndCast(const IOvec &input, compute_t scale) { + Ovec output; +#pragma unroll + for (int32_t i = 0; i < NUM_ELTS; ++i) { + output.data.elt[i] = output_t((compute_t(input.data.elt[i]) / scale)); + } + return output; + }; +}; + +/** + * Helper class to define the block scale operations + */ +template <typename Cvec, typename Ovec, int32_t BlockSize> +class BlockScaleRowHelper; + +template <typename Cvec, typename Ovec, int32_t BlockSize> +class BlockScaleColHelper; + +/** + * Specialization for MXFP8 rowwise scaling + */ +template <typename Cvec, typename Ovec> +class BlockScaleRowHelper<Cvec, Ovec, 32> : private BlockScaleHelperBase<Cvec, Ovec, 32> { + private: + using Base = BlockScaleHelperBase<Cvec, Ovec, 32>; + using Base::BLOCK_SIZE; + using Base::GROUP_SIZE; + using Base::NUM_ELTS; + using Base::THREADS_PER_WARP; + using typename Base::compute_t; + using typename Base::index_t; + using typename Base::scale_t; + + public: + __device__ + BlockScaleRowHelper() = default; + + template <typename IOvec> + __device__ void + blockQuantizeStore(const IOvec &z_math, void *sf_ptr, index_t sf_idx, void *z_ptr, index_t z_idx) { + const index_t group_id = lane / GROUP_SIZE; + + // 1. compute scaling factor + compute_t sf = 0; +#pragma unroll + // compute the amax across NUM_ELTS elements + for (int jt = 0; jt < NUM_ELTS; jt++) { + sf = fmaxf(sf, fabsf(compute_t(z_math.data.elt[jt]))); + } + +// Currently disabled for rowwise block scaling as perf regression observed +#if 0 && (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && defined(__CUDA_ARCH_FEAT_SM100_ALL) +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + if (group_id == jt) { + asm volatile("redux.sync.max.f32 %0, %1, %2;" : "=f"(sf) : "f"(sf), "r"(__activemask())); + } + } +#else + // warp reduce (binary reduction) starting from GROUP_SIZE / 2 to aggregate + // a total of NUM_ELTS * GROUP_SIZE = BLOCK_SIZE number of z values in sf +#pragma unroll + for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2) { + sf = fmaxf(sf, __shfl_down_sync(0xffffffff, sf, offset)); + } + + // broadcast from the lane with the valid values to the other threads in the group + sf = __shfl_sync(0xffffffff, sf, group_id * GROUP_SIZE); +#endif + // scale the row amax to get the scaling factor + sf = Base::scale(sf); + + // 2. store scaling factor + // Warp orchestration to compute scale_row: + // e.g. for NUM_ELTS == 2: + // | W0SF0 W0SF1 | W0SF0 W0SF1 | ... | W0SF0 W0SF1 | W0SF0 W0SF1 |... + // | W1SF0 W1SF1 | W1SF0 W1SF1 | ... | W1SF0 W1SF1 | W1SF0 W1SF1 |... + // | ... | ... | ... | ... | ... |... + // | W31SF0 W31SF1 | W31SF0 W31SF1 | ... | W31SF0 W31SF1 | W31SF0 W31SF1 |... + // |---------------|---------------|-----|--------------------------|---------------|... + // |----- CTA0 ----|----- CTA1 ----| ... |--- CTA<ctas_per_row-1> --|----- CTA0 ----|... + // | | + // |-------------------------------LDG0-----------------------------|-------LDG1-----... + Vec<scale_t, NUM_ELTS> sf_out; + // only correct for group_id == 0, but it's ok because only lane == 0 is storing sf_out + sf_out.data.elt[0] = float_to_e8m0(sf); +#pragma unroll + for (int jt = 1; jt < NUM_ELTS; jt++) { + sf_out.data.elt[jt] = float_to_e8m0(__shfl_sync(0xffffffff, sf, jt * GROUP_SIZE)); + } + if (lane == 0) { + sf_out.store_to(sf_ptr, sf_idx); + } + // No need to check for 0x00 - scale() now clamps to FLT_MIN which converts to 0x01 + float scale = e8m0_to_float(sf_out.data.elt[0]); + Ovec z_row_scaled = Base::vecDivideAndCast(z_math, scale); + z_row_scaled.store_to(z_ptr, z_idx); + } + + private: + const index_t lane = threadIdx.x % THREADS_PER_WARP; +}; + +/** + * Specialization for MXFP8 colwise scaling in 1D2X2X + */ +template <typename Cvec, typename Ovec> +class BlockScaleColHelper<Cvec, Ovec, 32> : private BlockScaleHelperBase<Cvec, Ovec, 32> { + private: + using Base = BlockScaleHelperBase<Cvec, Ovec, 32>; + using Base::BLOCK_SIZE; + using Base::GROUP_SIZE; + using Base::NUM_ELTS; + using Base::THREADS_PER_WARP; + using typename Base::compute_t; + using typename Base::index_t; + using typename Base::output_t; + using typename Base::scale_t; + + public: + __device__ + BlockScaleColHelper(float *mxfp8_tile) + : mxfp8_tile_(mxfp8_tile) {} + + template <typename IOvec> + __device__ void + initTile(const IOvec &z_math, int num_threads) {)KERNEL" + R"KERNEL( return initTile(z_math, warp, num_threads); + } + + template <typename IOvec> + __device__ void + initTile(const IOvec &z_math, index_t row_in_tile, int num_threads) { + constexpr int entry_barrier_arbitrary = 5; + utils::namedBarrierSync(entry_barrier_arbitrary, num_threads); +#pragma unroll + for (index_t jt = 0; jt < NUM_ELTS; jt++) { + index_t idx_in_mxfp8_smem = + (jt * (BLOCK_SIZE + /*padding row*/ 1) + row_in_tile) * MXFP8_1D2X2X_SMEM_COLS + lane; + mxfp8_tile_[idx_in_mxfp8_smem] = float(z_math.data.elt[jt]); + } + } + + template <bool Transpose> + __device__ void + blockQuantizeStore(void *sf_ptr, + index_t sf_row_idx, + index_t sf_col_idx, + index_t sf_row_width, + void *z_ptr, + index_t z_idx, + int num_threads) { + return blockQuantizeStore<Transpose>( + sf_ptr, sf_row_idx, sf_col_idx, sf_row_width, z_ptr, z_idx, num_threads, warp); + } + + template <bool Transpose> + __device__ void + blockQuantizeStore(void *sf_ptr, + index_t sf_row_idx, + index_t sf_col_idx, + index_t sf_row_width, + void *z_ptr, + index_t z_idx, + int num_threads, + index_t row_in_tile) { + // Ensure all temp outputs have been written to mxfp8 smem for the current ldg + constexpr int entry_barrier_arbitrary = 4; + utils::namedBarrierSync(entry_barrier_arbitrary, num_threads); + const index_t group_id = lane / GROUP_SIZE; + +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000) && defined(__CUDA_ARCH_FEAT_SM100_ALL) + // For sm_100a arch, we can use redux.sync.op{.abs.}{.NaN}.f32 instruction to reduce the min/max value + // https://docs.nvidia.com/cuda/parallel-thread-execution/#parallel-synchronization-and-communication-instructions-redux-sync + compute_t amax_vals[NUM_ELTS]; +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + const index_t idx_in_mxfp8_smem = jt * NEXT_COL_SMEM_OFFSET + lane * MXFP8_1D2X2X_SMEM_COLS + row_in_tile; + asm volatile("redux.sync.max.abs.f32 %0, %1, 0xffffffff;" + : "=f"(amax_vals[jt]) + : "f"(mxfp8_tile_[idx_in_mxfp8_smem])); + } + compute_t sf = amax_vals[group_id]; +#else + // 1. compute scaling factor + compute_t sf = 0; +#pragma unroll + // compute the amax across NUM_ELTS elements in the same col (in shared memory, adjacent rows) + for (int jt = 0; jt < NUM_ELTS * MXFP8_1D2X2X_SMEM_COLS; jt += MXFP8_1D2X2X_SMEM_COLS) { + const index_t idx_in_mxfp8_smem = ROW_SMEM_OFFSET + jt + row_in_tile; + sf = fmaxf(sf, fabsf(mxfp8_tile_[idx_in_mxfp8_smem])); + } + + // warp reduce (binary reduction) starting from GROUP_SIZE / 2 to aggregate + // a total of NUM_ELTS * GROUP_SIZE = BLOCK_SIZE number of z values in sf +#pragma unroll + for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2) { + sf = fmaxf(sf, __shfl_down_sync(0xffffffff, sf, offset)); + } + + // broadcast from the lane with the valid values to the other threads in the group + sf = __shfl_sync(0xffffffff, sf, group_id * GROUP_SIZE); +#endif + + // scale the col amax to get the scaling factor + sf = Base::scale(sf); + + // Warp orchestration to compute scale_col: + // e.g. for NUM_ELTS == 2: + // | W0SF0 W0SF1 W1SF0 W1SF1 ... W31SF0 W31SF1 | W0SF0 W0SF1 ... W31SF0 W31SF1 |... + // |----warp0---|---warp1--| ... |----warp31---|----warp0---|... |----warp31---|... + // |--------------------CTA0-------------------|---------------CTA1------------|... + // |------------------------------------------LDG0------------------------------... + Ovec z_col_scaled; + if constexpr (!Transpose) { + // 2. store scaling factor + // different columns require different sf, so all threads must exchange sf + Vec<scale_t, NUM_ELTS> sf_out; +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + sf_out.data.elt[jt] = float_to_e8m0(__shfl_sync(0xffffffff, sf, jt * GROUP_SIZE)); + } + if (lane == 0) { + sf_out.store_to(sf_ptr, sf_row_idx * sf_row_width + sf_col_idx); + } + + // 3. scale and store output +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + // iterate over NUM_ELTS elements in a row (in shared memory, every other NUM_ELTS in a column) + index_t z_idx_in_mxfp8_smem = jt * NEXT_COL_SMEM_OFFSET + lane * MXFP8_1D2X2X_SMEM_COLS + row_in_tile; + // No need to check for 0x00 - scale() now clamps to FLT_MIN which converts to 0x01 + float scale = e8m0_to_float(sf_out.data.elt[jt]); + z_col_scaled.data.elt[jt] = + output_t(mxfp8_tile_[z_idx_in_mxfp8_smem] / scale); + } + } else { + // 2. store scaling factor + uint8_t sf_e8m0 = float_to_e8m0(sf); + // No need to check for 0x00 - scale() now clamps to FLT_MIN which converts to 0x01 + if (lane % GROUP_SIZE == 0) { + static_cast<scale_t *>(sf_ptr)[(sf_row_idx + group_id) * sf_row_width + sf_col_idx] = sf_e8m0; + } + + // 3. scale and store output + float scale = e8m0_to_float(sf_e8m0); + // No need to check for 0.0f - scale() now clamps to FLT_MIN +#pragma unroll + for (int jt = 0; jt < NUM_ELTS; jt++) { + // iterate over NUM_ELTS elements in a column (in shared memory, adjacent NUM_ELTS rows) + index_t z_idx_in_mxfp8_smem = ROW_SMEM_OFFSET + jt * MXFP8_1D2X2X_SMEM_COLS + row_in_tile; + z_col_scaled.data.elt[jt] = output_t(mxfp8_tile_[z_idx_in_mxfp8_smem] / scale); + } + } + z_col_scaled.store_to(z_ptr, z_idx); + + } + + private: + static constexpr index_t MXFP8_1D2X2X_SMEM_ROWS = BLOCK_SIZE * NUM_ELTS + /*padding rows between*/ (NUM_ELTS - 1); + static constexpr index_t MXFP8_1D2X2X_SMEM_COLS = BLOCK_SIZE + /*padding col*/ 1; + static constexpr index_t NEXT_COL_SMEM_OFFSET = (BLOCK_SIZE + /*padding row*/ 1) * MXFP8_1D2X2X_SMEM_COLS; + // For MXFP8 1d2x2x, we store the 32x32xNUM_ELTS tile in shared memory to compute the col amax for scaling within + // the current CTA + // e.g. for NUM_ELTS == 2, the shared memory layout for 1d2x2x is as follows: + // + // col0 col2 col4 col6 ... col62 + // ↓ ↓ ↓ ↓ ↓ + // |-------------------------------------------| + // | T0V0 | T1V0 | T2V0 | T3V0 |...| T31V0 | 0 | <-- warp0 to store at jt=0 + // | T0V0 | T1V0 | T2V0 | T3V0 |...| T31V0 | 0 | <-- warp1 to store at jt=0 + // | .. | .. | .. | .. |...| ... | 0 | <-- ... + // | T0V0 | T1V0 | T2V0 | T3V0 |...| T31V0 | 0 | <-- warp31 to store at jt=0 + // |--------------------|------|---|-------|---| + // | 0 | 0 | 0 | 0 |...| 0 | 0 | <-- padding row between to avoid bank conflicts when col-scaling + // |--------------------|------|---|-------|---| + // | T0V1 | T1V1 | T2V1 | T3V1 |...| T31V1 | 0 | <-- warp0 to store at jt=1 + // | T0V1 | T1V1 | T2V1 | T3V1 |...| T31V1 | 0 | <-- warp1 to store at jt=1 + // | .. | .. | .. | .. |...| ... | 0 | <-- ... + // | T0V1 | T1V1 | T2V1 | T3V1 |...| T31V1 | 0 | <-- warp31 to store at jt=1 + // |-------------------------------------------| + // ↑ ↑ ↑ ↑ ↑ ↑ + // col1 col3 col5 col7 ... col63 padding col to avoid bank conflicts when computing col-scale factors + // + // ↑ ↑ ↑ ↑ ↑ + // warp0 warp1 warp2 warp3 ... warp31 + // to compute and apply the col-scale factors + float *mxfp8_tile_ = nullptr; + + const index_t lane = threadIdx.x % THREADS_PER_WARP; + const index_t warp = threadIdx.x / THREADS_PER_WARP; + + const index_t ROW_SMEM_OFFSET = ((lane * NUM_ELTS) + /*padding rows*/ (lane / GROUP_SIZE)) * MXFP8_1D2X2X_SMEM_COLS; +}; + +/** + * Specialization for NVFP4 rowwise scaling + */ +template <typename Cvec, typename Ovec> +class BlockScaleRowHelper<Cvec, Ovec, 16> : private BlockScaleHelperBase<Cvec, Ovec, 16> { + using Base = BlockScaleHelperBase<Cvec, Ovec, 16>; + using Base::BLOCK_SIZE; + using Base::GROUP_SIZE; + using Base::NUM_ELTS; + using Base::SF_COUNT; + using Base::THREADS_PER_WARP; + using typename Base::compute_t; + using typename Base::index_t; + using typename Base::output_t; + using typename Base::scale_t; + + public: + __device__ + BlockScaleRowHelper() = default; + + __device__ void + blockQuantizeStore(const Cvec &z_math, void *sf_ptr, index_t sf_idx, void *z_ptr, index_t z_idx) { + // 1. compute scaling factor + compute_t sf = 0; +#pragma unroll + // compute the amax across NUM_ELTS elements + for (int jt = 0; jt < NUM_ELTS; jt++) { + sf = fmaxf(sf, fabsf(z_math.data.elt[jt])); + } + + // warp reduce (binary reduction) starting from GROUP_SIZE / 2 to aggregate + // a total of NUM_ELTS * GROUP_SIZE = BLOCK_SIZE number of z values in sf +#pragma unroll + for (int offset = GROUP_SIZE / 2; offset > 0; offset /= 2) { + sf = fmaxf(sf, __shfl_down_sync(0xffffffff, sf, offset)); + } + + // broadcast from the lane with the valid values to the other threads in the group + const index_t group_id = lane / GROUP_SIZE; + sf = __shfl_sync(0xffffffff, sf, group_id * GROUP_SIZE); + + // scale the row amax to get the scaling factor + sf = Base::scale(sf); + + // 2. store scaling factor + Vec<scale_t, SF_COUNT> sf_out; + // only correct for group_id == 0, but it's ok because only lane == 0 is storing sf_out + sf_out.data.elt[0] = Base::fp32ToE4M3(sf); +#pragma unroll + for (int jt = 1; jt < SF_COUNT; jt++) { + sf_out.data.elt[jt] = Base::fp32ToE4M3(__shfl_sync(0xffffffff, sf, jt * GROUP_SIZE)); + } + if (lane == 0) { + sf_out.store_to(sf_ptr, sf_idx); + } + + // TODO: can consider doing something like the following to remove the need for a shuffle loop + // template <int32_t N> + // struct UintContainer { + // using type = std::conditional_t<N == 1, uint8_t, + // std::conditional_t<N == 2, uint16_t, + // std::conditional_t<N == 4, uint32_t, + // std::conditional_t<N == 8, uint64_t, + // void>>>>; // void for unsupported sizes + // }; + // Base::vecDivideAndCast returns Vec<UintContainer<NUM_ELTS / 2>, 2> + // 3. scale and store output + auto z_row_scaled = Base::vecDivideAndCast(z_math, sf); +#pragma unroll + // Consturct z_row_scaled by combining the adjacent thread's z_row_scaled + // Vec<uint8_t, NUM_ELTS> z_row_scaled + for (int i = 0; i < NUM_ELTS / 2; i++) { + uint8_t adjacent_val = __shfl_xor_sync(0xffffffff, z_row_scaled.data.elt[i], 1); + z_row_scaled.data.elt[i + NUM_ELTS / 2] = adjacent_val; + } + if (NUM_ELTS == 1) { + uint8_t adjacent_val = __shfl_xor_sync(0xffffffff, z_row_scaled.data.elt[0], 1); + z_row_scaled.data.elt[0] |= adjacent_val << 4U; + } + if (lane % 2 == 0) { + z_row_scaled.store_to(z_ptr, z_idx / 2); + } + } + + private: + const index_t lane = threadIdx.x % THREADS_PER_WARP; +}; + +)KERNEL"; +inline constexpr size_t ln_headers_source_len = sizeof(ln_headers_source) - 1; + +} // namespace generated +} // namespace experimental +} // namespace cudnn_frontend + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h new file mode 100644 index 0000000..ee3664a --- /dev/null +++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h @@ -0,0 +1,3479 @@ +// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: MIT +#pragma once +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverlength-strings" +#endif +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4068) +#endif +namespace cudnn_frontend { +namespace experimental { +namespace generated { +inline constexpr const char sm100_d128_fprop_source[] = + R"KERNEL( + +// receive_op 0 includes +typedef unsigned long long uint64_t; +typedef unsigned int uint32_t; +typedef unsigned short uint16_t; +typedef unsigned char uint8_t; +typedef long long int64_t; +typedef int int32_t; +typedef short int16_t; +typedef signed char int8_t; +typedef unsigned int r32; + +struct CUtensorMap { + alignas(64) uint64_t opaque[16]; +}; + +#define __FLT_MIN__ 1.17549435082228750796873653722224568e-38F +#define __FLT_MAX__ 3.40282346638528859811704183484516925e+38F + +#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__ + +namespace fort { +static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul); +static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT; +static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF; + +#define NAN __int_as_float(0x7fffffff) +#define POS_INFINITY __int_as_float(0x7f800000) +#define NEG_INFINITY __int_as_float(0xff800000) + +typedef uint16_t bfloat16_t; + +#define FORT_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define FORT_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define FORT_DIV_UP(a, b) (((a) + (b) - 1) / (b)) +#define FORT_ROUND_UP(a, b) ((((a) + (b) - 1) / (b)) * (b)) + +typedef struct tensor_descriptor { + static const int MAX_DIMS = 12; + + int64_t num_dims; + int64_t dims[MAX_DIMS]; + int64_t strides[MAX_DIMS]; +} tensor_descriptor; + +typedef struct FastDivisor { + uint32_t val, shr, mul; +} FastDivisor_t; + +inline __device__ void fastDivMod(const FastDivisor_t &d, uint32_t val, + uint32_t &div, uint32_t &mod) { + div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr; + mod = val - div * d.val; +} + +inline __device__ char *get_smem_loc_epilogue_swizzle_128b( + char *smem_addr, int local_block_id, int tid, int local_row, int column, + size_t element_size, int block_size, int row_per_tile) { + if (element_size * block_size == 256) { + // Case 1: 2 * swizzle tile size = block size -> half block per swizzle tile + int swizzle_col = local_row ^ (column % 8); + + // (local_block_id * 2 + (column / 8)) * row_per_tile * 128: gives offset of + // corresponding swizzle tile tid * 128: tid gives number of loads in block + // swizzle_col * 16B: swizzle_col gives transformed column + return smem_addr + + (local_block_id * 2 + (column / 8)) * row_per_tile * 128 + + tid * 128 + swizzle_col * 16; + } else if (element_size * block_size == 128) { + // Case 2: swizzle tile size = block size -> one block per swizzle tile + int swizzle_col = local_row ^ (column % 8); + + // local_block_id * row_per_tile * 128: gives offset of corresponding + // swizzle tile tid * 128: tid gives number of loads in block swizzle_col * + // 16B: swizzle_col gives transformed column + return smem_addr + local_block_id * row_per_tile * 128 + tid * 128 + + swizzle_col * 16; + } else { + // Case 3: swizzle tile size / 2 = block size -> two blocks per swizzle tile + int swizzle_col = local_row ^ ((column + local_block_id * 4) % 8); + + // (local_block_id / 2) * row_per_tile * 128: gives offset of corresponding + // swizzle tile tid * 128: tid gives number of loads in block swizzle_col * + // 16B: swizzle_col gives transformed column + return smem_addr + (local_block_id / 2) * row_per_tile * 128 + tid * 128 + + swizzle_col * 16; + } +} + +inline __device__ static void get_next_block_id(uint32_t result, + uint32_t mbar) { +#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300 + asm volatile("{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::" + "complete_tx::bytes.b128 [%0], [%1];}\n\t" ::"r"(result), + "r"(mbar)); +#else + asm volatile( + "{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::complete_" + "tx::bytes.multicast::cluster::all.b128 [%0], [%1];}\n\t" ::"r"(result), + "r"(mbar)); +#endif +} + +inline __device__ float2 ffma2(const float2 &a, const float2 &b, + const float2 &c) { + uint64_t d; + asm volatile("fma.rn.f32x2 %0, %1, %2, %3;\n" + : "=l"(d) + : "l"(reinterpret_cast<const uint64_t &>(a)), + "l"(reinterpret_cast<const uint64_t &>(b)), + "l"(reinterpret_cast<const uint64_t &>(c))); + return reinterpret_cast<float2 &>(d); +} + +inline __device__ float2 fadd2(const float2 &a, const float2 &b) { + uint64_t c; + asm volatile("add.f32x2 %0, %1, %2;\n" + : "=l"(c) + : "l"(reinterpret_cast<const uint64_t &>(a)), + "l"(reinterpret_cast<const uint64_t &>(b))); + return reinterpret_cast<float2 &>(c); +} + +inline __device__ float2 fmul2(const float2 &a, const float2 &b) { + uint64_t c; + asm volatile("mul.f32x2 %0, %1, %2;\n" + : "=l"(c) + : "l"(reinterpret_cast<const uint64_t &>(a)), + "l"(reinterpret_cast<const uint64_t &>(b))); + return reinterpret_cast<float2 &>(c); +} + +inline __device__ float fmax3(float a, float b, float c) { +#if (__CUDACC_VER_MAJOR__ >= 13) + float d; + asm volatile("max.ftz.f32 %0, %1, %2, %3;\n" + : "=f"(d) + : "f"((a)), "f"((b)), "f"((c))); + return d; +#else + #error "This kernel is not supported for CUDA toolkit version < 13.0" + return 0.0f; +#endif +} + +inline __device__ float row_max_reduction_128_elems(uint32_t reg[128]) { + float tmp_max_0[42]; + float tmp_max_1[14]; + float tmp_max_2[5]; + float tmp_max_3[2]; + +#pragma unroll + for (int i = 0; i < 126; i += 3) { + tmp_max_0[i / 3] = fmax3(reinterpret_cast<float &>(reg[i + 0]), + reinterpret_cast<float &>(reg[i + 1]), + reinterpret_cast<float &>(reg[i + 2])); + } +#pragma unroll + for (int i = 0; i < 42; i += 3) { + tmp_max_1[i / 3] = + fmax3(tmp_max_0[i + 0], tmp_max_0[i + 1], tmp_max_0[i + 2]); + } +#pragma unroll + for (int i = 0; i < 12; i += 3) { + tmp_max_2[i / 3] = + fmax3(tmp_max_1[i + 0], tmp_max_1[i + 1], tmp_max_1[i + 2]); + } + tmp_max_2[4] = + fmax3(tmp_max_1[12], tmp_max_1[13], reinterpret_cast<float &>(reg[126])); + tmp_max_3[0] = fmax3(tmp_max_2[0], tmp_max_2[1], tmp_max_2[2]); + tmp_max_3[1] = + fmax3(tmp_max_2[3], tmp_max_2[4], reinterpret_cast<float &>(reg[127])); + + return fmax3(tmp_max_3[0], tmp_max_3[1], tmp_max_3[1]); +} + +#if __CUDA_ARCH__ >= 900 + +inline __device__ uint32_t elect_one_sync() { + uint32_t pred = 0; + uint32_t laneid = 0; + asm volatile("{\n" + ".reg .b32 %%rx;\n" + ".reg .pred %%px;\n" + " elect.sync %%rx|%%px, %2;\n" + "@%%px mov.s32 %1, 1;\n" + " mov.s32 %0, %%rx;\n" + "}\n" + : "+r"(laneid), "+r"(pred) + : "r"(0xFFFFFFFF)); + return pred; +} + +template <int TARGET_REG_COUNT> inline __device__ void reg_alloc() { + // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's + // VALUE together): 224, 232, 208, 216 + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" + : + : "n"(TARGET_REG_COUNT)); +} + +template <int TARGET_REG_COUNT> inline __device__ void reg_dealloc() { + // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72 + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n" + : + : "n"(TARGET_REG_COUNT)); +} + +inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID, + uint32_t NUM_THREADS) { + asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS)); +} + +inline __device__ void named_barrier_wait(uint32_t BARRIER_ID, + uint32_t NUM_THREADS) { + asm volatile("bar.sync %0, %1;" ::"r"(BARRIER_ID), "r"(NUM_THREADS)); +} + +inline __device__ void tmastg_arrive() { + asm volatile("cp.async.bulk.commit_group;"); +} + +template <int Count> inline __device__ void tmastg_wait_count() { + asm volatile("cp.async.bulk.wait_group.read %0;" : : "n"(Count) : "memory"); +} + +#endif + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 +inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;\n" ::"r"(smem_ptr), + "r"(thread_count)); +} + +inline __device__ void +smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes, + uint32_t pred = 0) { + asm volatile("{\n\t.reg .pred p;" + " \n\tsetp.eq.u32 p, %2, 1;" + " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" + " \n\t}" ::"r"(smem_ptr), + "r"(expected_copy_bytes), "r"(pred)); +} + +inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr, + uint32_t bar_phase) { + uint32_t bar_phase_out; + asm volatile("{\n\t.reg .pred P1;" + " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;" + " \n\tselp.b32 %0, 1, 0, P1; \n\t}" + : "=r"(bar_phase_out) + : "r"(smem_ptr), "r"(bar_phase)); + return bar_phase_out; +} + +inline __device__ void +wait_barrier(uint32_t smem_int_ptr, + int phase_bit) // Current phase bit the barrier waiting to flip +{ + asm volatile("{\n" + ".reg .pred P1;\n" + "LAB_WAIT:\n" + "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n" + "@P1 bra.uni DONE;\n" + "bra.uni LAB_WAIT;\n" + "DONE:\n" + "}\n" ::"r"(smem_int_ptr), + "r"(phase_bit)); +} + +// Barrier arrive on local smem +inline __device__ void arrive_barrier(uint32_t smem_addr) { + asm volatile("{\n\t" + "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t" + "}" + : + : "r"(smem_addr)); +} + +#endif + +// Circular Buffer Index + Associated Phase +// Assumes only one operation possible - i.e., ++ +template <uint32_t Stages_> struct PipelineState { +public: + static constexpr int Stages = Stages_; + + inline __device__ PipelineState(int index, int state) + : state_(state), index_(index) {} + + inline __device__ int phase() const { return state_; } + + inline __device__ int index() const { return index_; } + + inline __device__ void operator++() { + if (Stages > 1) { + ++index_; + if (index_ == Stages) { + index_ = 0; + state_ ^= 1; + } + } else { + state_ ^= 1; + } + } + + int state_; + int index_; +}; + +template <uint64_t MAX_SHIFT_FOR_WS, uint64_t UTCMMA_M, uint64_t UTCMMA_N, + uint64_t B_TRANSPOSE, uint64_t A_TRANSPOSE, uint64_t B_NEGATE, + uint64_t A_NEGATE, uint64_t SRC_B_TYPE, uint64_t SRC_A_TYPE, + uint64_t SPARSE_METADATA_FORMAT, uint64_t ACC_TYPE, + uint64_t SATURATE_ENABLED, uint64_t SPARSE_ENABLED, + uint64_t SPARSE_METADATA_ID2> +inline __device__ constexpr uint64_t build_utcmma_instruction_desc() { + return (static_cast<uint64_t>(0) | (MAX_SHIFT_FOR_WS << 30) | + ((UTCMMA_M >> 5) << 25) | ((UTCMMA_N >> 3) << 17) | + (B_TRANSPOSE << 16) | (A_TRANSPOSE << 15) | (B_NEGATE << 14) | + (A_NEGATE << 13) | (SRC_B_TYPE << 10) | (SRC_A_TYPE << 7) | + (SPARSE_METADATA_FORMAT << 6) | (ACC_TYPE << 4) | + (SATURATE_ENABLED << 3) | (SPARSE_ENABLED << 2) | + (SPARSE_METADATA_ID2 << 0)) + << 32; +} +)KERNEL" + R"KERNEL( + +class Smem_utcmma_descriptor { +public: + inline __device__ Smem_utcmma_descriptor(uint64_t SWIZZLE_MODE, + uint64_t BASE_OFFSET, + uint64_t DESC_VERSION, + uint64_t BYTES_PER_LEADING_DIM, + uint64_t BYTES_PER_STRIDE_DIM) { + // ------------------------------------ + // Setup smem descriptor for operand A: + // ------------------------------------ + // Note 1: SWIZZLE_NONE = 0, SWIZZLE_128B = 2, SWIZZLE_64B = 4, SWIZZLE_32B + // = 6, SWIZZLE_128B_ATOM32B = 1, N/A = 3, N/A = 5, N/A = 7 + const uint64_t SWIZZLE_MODE_IN_BIT_LOCATION = SWIZZLE_MODE + << 61; // bits: 63-61 + + // Note 2: Base offset. Valid only for matrix descriptor 1, 2 or 3, 4 + const uint64_t BASE_OFFSET_IN_BIT_LOCATION = BASE_OFFSET + << 49; // bits 51-49 + + // Note 3: Descriptor version, needs to be set to 1. ??? + const uint64_t DESC_VERSION_IN_BIT_LOCATION = DESC_VERSION + << 46; // bits 48-46 + + // Note 4: Stride dimension byte offset, 16 byte aligned, 4 LSBs not + // included + const uint64_t STRIDE_DIM_BYTE_OFFSET = BYTES_PER_STRIDE_DIM >> 4; + const uint64_t STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION = + STRIDE_DIM_BYTE_OFFSET << 32; // bits 45-32 + + // Note 5: Leading dimension byte offset, 16 byte aligned, 4 LSBs not + // included + const uint64_t LEADING_DIM_BYTE_OFFSET = BYTES_PER_LEADING_DIM >> 4; + const uint64_t LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION = + LEADING_DIM_BYTE_OFFSET << 16; // bits 29-16 + + desc = + (SWIZZLE_MODE_IN_BIT_LOCATION | BASE_OFFSET_IN_BIT_LOCATION | + DESC_VERSION_IN_BIT_LOCATION | STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION | + LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION); + } + template <int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void set_smem(uint32_t smem) { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4); + + int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc); + tmp_initial.x = tmp.x; + + max_desc = tmp.x + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1); + } + + template <int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void increment_smem_buffer() { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x += (tmp.x >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1) + : (BYTES_PER_BUFFER >> 4); + } + + template <int BYTES_PER_BUFFER> + inline __device__ void stage_increment_smem_buffer(int stage) { + int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc); + int2 &tmp = reinterpret_cast<int2 &>(desc); + + tmp.x = tmp_initial.x + (BYTES_PER_BUFFER >> 4) * stage; + } + + template <int BYTES_OFFSET> inline __device__ void add_smem_offset() { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x += (BYTES_OFFSET >> 4); + } + + uint64_t initial_desc; + uint64_t desc; + uint32_t max_desc; +}; + +// cta1 utcmma with A and B from smem and C stored in tmem, scale denotes if we +// want to accumulate C or not Something like: Accumulate or overwrite C. 1: +// read C, 0: ignore C [clear accumulators] +inline __device__ void +utcmma_asmem_bsmem_h_cta1(uint64_t sdescA, uint64_t sdescB, uint32_t tmemC, + uint64_t idescE, uint32_t scaleC) { + uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means, + // CUTLASS hardcodes to all zeros + asm volatile("{\n\t" + ".reg .pred p;\n\t" + "setp.ne.b32 p, %4, 0;\n\t" + "tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, {%5, %6, " + "%7, %8}, p; \n\t" + "}\n" + : + : "r"(tmemC), "l"(sdescA), "l"(sdescB), + "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]), + "r"(mask[1]), "r"(mask[2]), "r"(mask[3])); +} + +// cta1 utcmma with A from tmem and B from smem and C stored in tmem, scale +// denotes if we want to accumulate C or not Something like: Accumulate or +// overwrite C. 1: read C, 0: ignore C [clear accumulators] +inline __device__ void +utcmma_atmem_bsmem_h_cta1(uint32_t tmemA, uint64_t sdescB, uint32_t tmemC, + uint64_t idescE, uint32_t scaleC) { + uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means, + // CUTLASS hardcodes to all zeros + asm volatile("{\n\t" + ".reg .pred p;\n\t" + "setp.ne.b32 p, %4, 0;\n\t" + "tcgen05.mma.cta_group::1.kind::f16 [%0], [%1], %2, %3, {%5, " + "%6, %7, %8}, p; \n\t" + "}\n" + : + : "r"(tmemC), "r"(tmemA), "l"(sdescB), + "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]), + "r"(mask[1]), "r"(mask[2]), "r"(mask[3])); +} + +// Check for the utcmma to finish +inline __device__ void umma_arrive(uint32_t bar_intptr) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::" + "cluster.b64 [%0];" ::"r"(bar_intptr)); +} + +inline __device__ uint32_t cast_smem_ptr_to_uint(void const *const ptr) { + return static_cast<uint32_t>(__cvta_generic_to_shared(ptr)); +} + +inline __device__ void fence_view_async_shared(void) { + asm volatile("fence.proxy.async.shared::cta;\n"); +} + +inline __device__ void sts_128(r32 dst, r32 src[4]) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};\n" ::"r"(dst), + "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3])); +} + +inline __device__ void lds_128(r32 dst[4], r32 src) { + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];\n" + : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]) + : "r"(src)); +} + +inline __device__ void lds_32(r32 dst[1], r32 src) { + asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src)); +} + +inline __device__ void stg_32(void *ptr, r32 val[1]) { + uint32_t *p = reinterpret_cast<uint32_t *>(ptr); + p[0] = val[0]; +} + +inline __device__ void stg_8(void *ptr, r32 val[1]) { + uint8_t *p = reinterpret_cast<uint8_t *>(ptr); + p[0] = reinterpret_cast<const uint8_t &>(val[0]); +} + +inline __device__ void ldg_16(r32 dst[1], const void *ptr, bool pred = true) { + if (pred) { + *reinterpret_cast<uint16_t *>(dst) = + *reinterpret_cast<const uint16_t *>(ptr); + } else { + *reinterpret_cast<uint16_t *>(dst) = 0; + } +} + +inline __device__ void ldg_8(r32 dst[1], const void *ptr, bool pred = true) { + if (pred) { + *reinterpret_cast<uint8_t *>(dst) = *reinterpret_cast<const uint8_t *>(ptr); + } else { + *reinterpret_cast<uint8_t *>(dst) = 0; + } +} + +inline __device__ void ldg_16_reg(r32 dst[1], const void *ptr, + bool pred = true) { + if (pred) { + uint16_t tmp = *reinterpret_cast<const uint16_t *>(ptr); + asm volatile("{\nmov.b32 %0, {%1, %1};\n}\n" : "=r"(dst[0]) : "h"(tmp)); + } else { + dst[0] = 0; + } +} + +inline __device__ void ldg_8_reg(r32 dst[1], const void *ptr, + bool pred = true) { + if (pred) { + uint8_t tmp_val = *reinterpret_cast<const uint8_t *>(ptr); + uint8_t *tmp_ptr = reinterpret_cast<uint8_t *>(dst); + tmp_ptr[0] = tmp_ptr[1] = tmp_ptr[2] = tmp_ptr[3] = tmp_val; + } else { + dst[0] = 0; + } +} + +// Forward (non-ReLU) Activations +// Backward (non-ReLU) Activations +// Forward ReLU activations +// Relu helper function: clip the lower part +// Relu helper function: clip the upper part +// Forward ReLU: clip only lower part +// Forward ReLU: clip lower part and upper part +// Forward ReLU: clip only lower part, but add slope to lower clip +// Forward ReLU: clip lower part and upper part, but add slope to lower clip +#if __CUDA_ARCH__ >= 900 +#endif + +// optimization opportunity exists here +inline __device__ void fp32x2_to_fp16x2(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n" + : "=r"(dst[0]) + : "r"(src[1]), "r"(src[0])); +} + +inline __device__ void fp32x2_to_fp16x2_relu(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.relu.f16x2.f32 %0, %1, %2;\n" + : "=r"(dst[0]) + : "r"(src[1]), "r"(src[0])); +} + +inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n" + : "=r"(dst[0]) + : "r"(src[1]), "r"(src[0])); +} + +// mma_pipeline_op 1 includes +typedef struct AttentionDescriptor { + // Input parameters + // b - batch + // q_h - num heads of q/dq/o/do + // k_h - num heads of k/dk + // v_h - num heads of v/dv + // s_q - max sequence length of q + // s_kv - max sequence length of kv + // d - hidden dim (head dim) + uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v; + uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv; +} AttentionDescriptor_t; + + +inline __device__ void fence_view_async_tmem_load() { + asm volatile("{\n\ttcgen05.wait::ld.sync.aligned; \n}" ::); +} + +inline __device__ void fence_view_async_tmem_store() { + asm volatile("{\n\ttcgen05.wait::st.sync.aligned; \n}" ::); +} + +inline __device__ void tmem_allocate_1sm(uint32_t num_columns, + uint32_t smem_addr) { + asm volatile( + "tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"( + smem_addr), + "r"(num_columns)); +} + +inline __device__ void tmem_free_1sm(uint32_t num_columns, uint32_t tmem_addr) { + asm volatile( + "{\n\ttcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1; \n\t}" ::"r"( + tmem_addr), + "r"(num_columns)); +} + +inline __device__ void tmem_release_allocation_lock_1sm() { +)KERNEL" + R"KERNEL( + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::); +} + +///////////////////////////////// +/// TMEM STTM related instructions +///////////////////////////////// + +// 32 data path lanes, 32-bit pattern, repeated 128 times +// 32 data path lanes, 32-bit pattern, repeated 64 times +// 32 data path lanes, 32-bit pattern, repeated 32 times +inline __device__ void sttm_32dp32bit_x32(uint32_t dst, r32 src[32]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x32.b32" + "[%0]," + "{%1, %2, %3, %4," + "%5, %6, %7, %8," + "%9, %10, %11, %12," + "%13, %14, %15, %16," + "%17, %18, %19, %20," + "%21, %22, %23, %24," + "%25, %26, %27, %28," + "%29, %30, %31, %32};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]), + "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]), + "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]), + "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15]), + "r"(src[16]), "r"(src[17]), "r"(src[18]), "r"(src[19]), + "r"(src[20]), "r"(src[21]), "r"(src[22]), "r"(src[23]), + "r"(src[24]), "r"(src[25]), "r"(src[26]), "r"(src[27]), + "r"(src[28]), "r"(src[29]), "r"(src[30]), "r"(src[31])); +} + +// 32 data path lanes, 32-bit pattern, repeated 16 times +inline __device__ void sttm_32dp32bit_x16(uint32_t dst, r32 src[16]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x16.b32" + "[%0]," + "{%1, %2, %3, %4," + "%5, %6, %7, %8," + "%9, %10, %11, %12," + "%13, %14, %15, %16};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]), + "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]), + "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]), + "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15])); +} + +// 32 data path lanes, 32-bit pattern, repeated 8 times +inline __device__ void sttm_32dp32bit_x8(uint32_t dst, r32 src[8]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x8.b32" + "[%0]," + "{%1, %2, %3, %4," + "%5, %6, %7, %8};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]), + "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7])); +} + +// 32 data path lanes, 32-bit pattern, repeated 4 times +// 32 data path lanes, 32-bit pattern, repeated 2 times +inline __device__ void sttm_32dp32bit_x2(uint32_t dst, r32 src[2]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x2.b32" + "[%0]," + "{%1, %2};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1])); +} + +// 32 data path lanes, 32-bit pattern, repeated 1 times +inline __device__ void sttm_32dp32bit_x1(uint32_t dst, r32 src[1]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x1.b32" + "[%0]," + "{%1};\n" + : + : "r"(dst), "r"(src[0])); +} + +///////////////////////////////// +/// TMEM LDTM related instructions +///////////////////////////////// + +// 32 data path lanes, 32-bit pattern, repeated 128 times +// 32 data path lanes, 32-bit pattern, repeated 64 times +// 32 data path lanes, 32-bit pattern, repeated 32 times +inline __device__ void ldtm_32dp32bit_x32(r32 dst[32], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x32.b32" + "{%0, %1, %2, %3," + "%4, %5, %6, %7," + "%8, %9, %10, %11," + "%12, %13, %14, %15," + "%16, %17, %18, %19," + "%20, %21, %22, %23," + "%24, %25, %26, %27," + "%28, %29, %30, %31}," + "[%32];\n" + : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]), + "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7]), + "=r"(dst[8]), "=r"(dst[9]), "=r"(dst[10]), "=r"(dst[11]), + "=r"(dst[12]), "=r"(dst[13]), "=r"(dst[14]), "=r"(dst[15]), + "=r"(dst[16]), "=r"(dst[17]), "=r"(dst[18]), "=r"(dst[19]), + "=r"(dst[20]), "=r"(dst[21]), "=r"(dst[22]), "=r"(dst[23]), + "=r"(dst[24]), "=r"(dst[25]), "=r"(dst[26]), "=r"(dst[27]), + "=r"(dst[28]), "=r"(dst[29]), "=r"(dst[30]), "=r"(dst[31]) + : "r"(src_addr)); +} + +// 32 data path lanes, 32-bit pattern, repeated 16 times +// 32 data path lanes, 32-bit pattern, repeated 8 times +inline __device__ void ldtm_32dp32bit_x8(r32 dst[8], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32" + "{%0, %1, %2, %3," + "%4, %5, %6, %7}," + "[%8];\n" + : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]), + "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7]) + : "r"(src_addr)); +} + +// 32 data path lanes, 32-bit pattern, repeated 4 times +// 32 data path lanes, 32-bit pattern, repeated 2 times +inline __device__ void ldtm_32dp32bit_x2(r32 dst[2], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x2.b32" + "{%0, %1}," + "[%2];\n" + : "=r"(dst[0]), "=r"(dst[1]) + : "r"(src_addr)); +} + +// 32 data path lanes, 32-bit pattern, repeated 1 times +inline __device__ void ldtm_32dp32bit_x1(r32 dst[1], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x1.b32" + "{%0}," + "[%1];\n" + : "=r"(dst[0]) + : "r"(src_addr)); +} + +// CUtensorMap, when issued using bulk copy async functions, are cached in +// constant cache. But the producer kernel may have directly written to global +// memory, without invalidating this constant cache. This acquire fence, +// invalidates the memory address in constant cache, using UTMACCTL.IV. +inline __device__ void tma_descriptor_fence_acquire(CUtensorMap const *p_desc) { +#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123) + uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc); + asm volatile("fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n" + : + : "l"(gmem_int_desc) + : "memory"); + asm volatile("cvta.global.u64 %0, %0;\n" + : + : "l"(gmem_int_desc), "l"(gmem_int_desc) + : "memory"); +#endif +} + +inline __device__ void +utmaldg_4d_tiled(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { +#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300 + asm volatile( + "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::" + "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"( + urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc) + : "memory"); +#else + asm volatile( + "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::" + "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"( + urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc) + : "memory"); +#endif + } +} + +inline __device__ void +utmaldg_4d_tiled_multicast(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint16_t mcast_mask, const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::" + "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], " + "[%1, {%2, %3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1), "h"(mcast_mask), "l"(mem_desc) + : "memory"); + } +} + +#if (__CUDA_ARCH__ >= 1000) && (CUDACC_VERSION >= 128) +inline __device__ void +utmaldg_4d_tiled_2cta(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile("cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global." + "mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, " + "%3, %4, %5}], [%6], %7;\n" ::"r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK), + "l"(mem_desc) + : "memory"); + } +} + +inline __device__ void +utmaldg_4d_tiled_multicast_2cta(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint16_t mcast_mask, + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile( + "cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global.mbarrier::" + "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], [%1, {%2, " + "%3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK), "h"(mcast_mask), + "l"(mem_desc) + : "memory"); + } +} +#endif + +inline __device__ void +utmastg_atomicAdd_4d_tiled(const void *p_desc, uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + const uint32_t elect_one, + uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile( + "cp.reduce.async.bulk.tensor.4d.global.shared::cta.add.bulk_group [%0, " + "{%1, %2, %3, %4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset) + : "memory"); + } +} + +inline __device__ void utmastg_4d_tiled(const void *p_desc, + uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + uint64_t mem_desc = MEM_DESC_DEFAULT) { + asm volatile( + "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, " + "%4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset) + : "memory"); +} + +inline __device__ void utmastg_5d_tiled(const void *p_desc, + uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + int32_t urb4, // lean_tile_id + uint64_t mem_desc = MEM_DESC_DEFAULT) { + asm volatile( + "cp.async.bulk.tensor.5d.global.shared::cta.bulk_group [%0, {%1, %2, %3, " + "%4, %5}], [%6];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(urb4), "r"(smem_offset) + : "memory"); +} + +// mma_loop_op 2 includes + +// global_load_shared_store_op 4 includes + +// shared_load_op 5 includes + +// shared_load_op 6 includes + +// global_load_shared_store_op 7 includes + +// mma_op 8 includes + +// global_load_op 10 includes + +// pointwise_calc_op 9 includes + +// softmax_op 12 includes + +// global_store_op 13 includes + +// global_store_op 14 includes + +// shared_load_op 15 includes + +// global_load_shared_store_op 16 includes + +// mma_op 17 includes + +// global_store_op 20 includes + +// output_loop_op 3 includes + +// shared_store_op 18 includes + +// shared_load_op 19 includes +} // namespace fort +)KERNEL" + R"KERNEL( + +// receive_op 0 types +using namespace fort; + +static constexpr int THREADS_PER_WARP_0 = 32; +static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 512 / THREADS_PER_WARP_0); +static constexpr int THREADS_PER_WARP_GROUP_0 = + THREADS_PER_WARP_0 * WARPS_PER_GROUP_0; +static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint) +static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8; +static constexpr int THREADS_PER_GROUP_0 = + WARPS_PER_GROUP_0 * THREADS_PER_WARP_0; + +// mma_pipeline_op 1 types +static constexpr int BYTES_PER_BANK_1 = 16; +static constexpr int BITS_PER_ELEMENT_1 = 16; +static constexpr int ELEMS_PER_BANK_1 = + BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1; +static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8; +static constexpr int BYTES_PER_FP16_1 = 2; +static constexpr int ELEMS_PER_VECTOR_1 = + BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1; +static constexpr int BITS_PER_ACC_1 = 32; +static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8; +static constexpr int TILE_M_1 = 128; +static constexpr int TILE_N_1 = 128; +static constexpr int TILE_K_1 = 128; +static constexpr int TILE_O_1 = FORT_MIN(TILE_K_1, 128); +static constexpr int TILE_V_1 = TILE_K_1; +static constexpr int TILE_DV_1 = FORT_MIN(TILE_K_1, 128); +static constexpr int WARP_TILE_M_1 = 16; +static constexpr int WARP_TILE_N_1 = 16; +static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1; +static constexpr int WARPS_M_1 = 64 / 16; +static constexpr int WARPS_N_1 = 16 / 16; +static constexpr int WARPS_K_1 = 16 / 16; +static constexpr int STAGES_1 = 1; +static constexpr int GROUPS_M_1 = 1; +static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1; +static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1; +static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1; +static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1; +static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1; +static constexpr int WARP_REGS_1 = TILE_N_1; +static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1; +static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1; +static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1; +static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16; +static constexpr int REGS_dQ_1 = TILE_O_1 / 16; +static constexpr int REGS_O_1 = REGS_K_1 * 1; + +static constexpr int CGA_M_1 = 1; +static constexpr int CGA_N_1 = 1; +static constexpr int CTA_MMA_1 = 1; +static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4; +static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1; + +static constexpr int CTA_TILE_M_1 = TILE_M_1; +static constexpr int CTA_TILE_N_1 = 128; +static constexpr int CTA_TILE_K_1 = 128; + +static constexpr float ln2 = 0.6931471805599453094f; +static constexpr float inv_ln2 = 1.4426950408889634074f; + +static constexpr uint32_t SchedulerPipelineStageCount = 1; +static constexpr uint32_t AccumulatorPipelineStageCount = 1; +static constexpr uint32_t SmemPipelineStageCount = 1; +static constexpr uint32_t num_columns_per_tmem = 512; +static constexpr uint32_t columns_per_allocation_slice = 32; +static constexpr int stages_q = 2; +static constexpr int stages_kv = 2 * CTA_MMA_1; +static constexpr int Tiles_Q = 2; + +static constexpr int SoftmaxWarpGroups = 2; +static constexpr int CorrectionWarpGroups = 1; +static constexpr int SoftmaxWarps = SoftmaxWarpGroups * 4; +static constexpr int CorrectionWarps = 4; + +static constexpr int MmaWarpRegs = 40; // warp 12 +static constexpr int TmaldgWarpRegs = 40; // warp 13 +static constexpr int TmastgWarpRegs = 40; // warp 14 +static constexpr int SchedulerWarpRegs = 40; // warp 15 +static constexpr int CorrectionWarpRegs = 88; // warps 8-11 +static constexpr int SoftmaxWarpRegs = 192; // warps 0-7 + +static constexpr int threads_per_warp = 32; +static constexpr int warps_per_group = 4; +static constexpr int threads_per_group = threads_per_warp * warps_per_group; +static constexpr int threads_per_cta = + threads_per_warp * (warps_per_group + SoftmaxWarps + CorrectionWarps); + +static constexpr int BUFFERS_Q = stages_q; +static constexpr int BUFFERS_K = stages_kv; +static constexpr int BUFFERS_V = stages_kv; +static constexpr int BUFFERS_S = stages_kv; + +using ElementQ = fort::bfloat16_t; +using ElementK = fort::bfloat16_t; +using ElementV = fort::bfloat16_t; +using ElementS = fort::bfloat16_t; +using ElementO = fort::bfloat16_t; +using ElementAccumulator = float; + +static constexpr int BYTES_PER_ELEMENT = 2; +static constexpr int BYTES_PER_ACC = 4; + +static constexpr int BMM1_TILE_M = TILE_M_1; +static constexpr int BMM1_TILE_N = 128; +static constexpr int BMM1_TILE_K = 128; + +static constexpr int BMM2_TILE_M = TILE_M_1; +static constexpr int BMM2_TILE_N = 128; +static constexpr int BMM2_TILE_K = 128; + +static constexpr uint32_t qBufferElems = BMM1_TILE_M * BMM1_TILE_K; +static constexpr uint32_t kBufferElems = BMM1_TILE_N * BMM1_TILE_K / CTA_MMA_1; +static constexpr uint32_t vBufferElems = BMM2_TILE_N * BMM2_TILE_K / CTA_MMA_1; +static constexpr uint32_t oBufferElems = + FORT_MAX(8, BMM2_TILE_M) * (BMM2_TILE_N + 0); +static constexpr uint32_t sBufferElems = FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N; + +static constexpr uint32_t qTmaTransactionBytes = + qBufferElems * sizeof(ElementQ) * CTA_MMA_1; +static constexpr uint32_t kTmaTransactionBytes = + kBufferElems * sizeof(ElementK) * CTA_MMA_1; +static constexpr uint32_t vTmaTransactionBytes = + vBufferElems * sizeof(ElementV) * CTA_MMA_1; + +static constexpr int UTCMMA_TILE_M = 128; +static constexpr int UTCMMA_TILE_N = 128; +static constexpr int UTCMMA_TILE_K = 32 / BYTES_PER_ELEMENT; + +static constexpr int BMM1_XMMAS_K = BMM1_TILE_K / UTCMMA_TILE_K; +static constexpr int BMM2_XMMAS_K = BMM2_TILE_K / UTCMMA_TILE_K; +static constexpr int BYTES_PER_MMA_K = UTCMMA_TILE_K * BYTES_PER_ELEMENT; + +static constexpr int SMEM_BUFFER_SIZE_Q = + BMM1_TILE_M * BMM1_TILE_K * BYTES_PER_ELEMENT; +static constexpr int SMEM_BUFFER_SIZE_K = + BMM1_TILE_N * BMM1_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1; +static constexpr int SMEM_BUFFER_SIZE_V = + BMM2_TILE_N * BMM2_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1; +static constexpr int SMEM_BUFFER_SIZE_S = + FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N * BYTES_PER_ELEMENT; + +static constexpr int SOFTMAX_BARRIER = 1; +static constexpr int BAND_BIAS_BARRIER = 5; +static constexpr int TMEM_ALLOC_SOFTMAX_BARRIER = 6; +static constexpr int TMEM_ALLOC_CORRECTION_BARRIER = 7; + +struct SharedStorage { + alignas(1024) ElementQ smem_Q[qBufferElems * stages_q]; + alignas(1024) ElementK smem_K[kBufferElems * stages_kv]; + alignas(1024) ElementV smem_V[vBufferElems * stages_kv]; + alignas(1024) ElementO smem_O[oBufferElems]; + + alignas(16) uint64_t tma_o_0_empty_mbar[1]; + + alignas(16) uint64_t tma_k_empty_mbar[stages_kv]; + alignas(16) uint64_t tma_k_full_mbar[stages_kv]; + + alignas(16) uint64_t tma_v_empty_mbar[stages_kv]; + alignas(16) uint64_t tma_v_full_mbar[stages_kv]; + + alignas(16) uint64_t tma_q_empty_mbar[stages_q]; + alignas(16) uint64_t tma_q_full_mbar[stages_q]; + + alignas(16) uint64_t bmm2_tile0_done_mbar[1]; + alignas(16) uint64_t bmm2_tile0_ready_mbar[2]; + + alignas(16) uint64_t stat_tile0_full_mbar[1]; + alignas(16) uint64_t stat_tile0_empty_mbar[1]; + alignas(16) uint64_t final_stat_tile0_empty_mbar[1]; + alignas(16) uint64_t + tma_o_0_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)]; + alignas(16) uint64_t + tma_o_1_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)]; + + alignas(16) uint64_t epilogue_done_mbar[1]; + alignas(16) uint64_t tmaldg_tile_started_mbar[1]; + + alignas(16) uint64_t bmm1_tile0_done_mbar[1]; + alignas(16) uint64_t bmm1_tile1_done_mbar[1]; + + alignas(16) uint64_t bmm2_tile1_done_mbar[1]; + alignas(16) uint64_t bmm2_tile1_ready_mbar[2]; + + alignas(16) uint64_t stat_tile1_full_mbar[1]; + alignas(16) uint64_t stat_tile1_empty_mbar[1]; + alignas(16) uint64_t final_stat_tile1_empty_mbar[1]; + + alignas(16) uint64_t empty_mainloop_mbar[1]; + + alignas(16) uint64_t scheduler_mbar[SchedulerPipelineStageCount]; + alignas(16) uint64_t read_tile_id_done_mbar[SchedulerPipelineStageCount]; + alignas(16) uint64_t tmem_dealloc_smem_bar[1]; + + uint32_t tmem_base_ptrs; + + alignas(16) uint32_t tile_id[8 * SchedulerPipelineStageCount]; +}; + +// global_load_shared_store_op 4 types +static constexpr int BITS_PER_ELEMENT_4 = 16; +static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8; +static constexpr int BYTES_PER_ACCESS_4 = 16; +static constexpr int TILE_M_4 = 128; +static constexpr int TILE_N_4 = 128; +static constexpr int BYTES_PER_SMEM_4 = + TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4; + +// shared_load_op 5 types +static constexpr int BITS_PER_ELEMENT_5 = 16; +static constexpr int BYTES_PER_ELEMENT_5 = 2; +static constexpr int BYTES_PER_QUAD_5 = 16; +static constexpr int WARP_TILE_M_5 = 16; +static constexpr int WARP_TILE_N_5 = 16; +static constexpr int TILE_M_5 = 128; +static constexpr int TILE_N_5 = 128; +static constexpr int BYTES_PER_SMEM_5 = + TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5; +static constexpr int WARPS_M_5 = 4; +static constexpr int WARPS_N_5 = 1; +static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5; +static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5; +static constexpr int THREADS_PER_WARP_TILE_M_5 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_5 = 4; +static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5; +static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5; +static constexpr int BYTES_PER_LD_5 = 128; +static constexpr int SWIZZLE_SCALE_5 = + FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4); + +// shared_load_op 6 types +static constexpr int BITS_PER_ELEMENT_6 = 16; +static constexpr int BYTES_PER_ELEMENT_6 = 2; +static constexpr int BYTES_PER_QUAD_6 = 16; +static constexpr int WARP_TILE_M_6 = 16; +static constexpr int WARP_TILE_N_6 = 16; +static constexpr int TILE_M_6 = 128; +static constexpr int TILE_N_6 = 128; +static constexpr int BYTES_PER_SMEM_6 = + TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6; +static constexpr int WARPS_M_6 = 1; +static constexpr int WARPS_N_6 = 1; +static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6; +static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6; +static constexpr int THREADS_PER_WARP_TILE_M_6 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_6 = 4; +static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6; +static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6; +static constexpr int BYTES_PER_LD_6 = 128; +static constexpr int SWIZZLE_SCALE_6 = + FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4); + +// global_load_shared_store_op 7 types +static constexpr int BITS_PER_ELEMENT_7 = 16; +static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8; +static constexpr int BYTES_PER_ACCESS_7 = 16; +static constexpr int TILE_M_7 = 128; +static constexpr int TILE_N_7 = 128; +static constexpr int BYTES_PER_SMEM_7 = + TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7; + +// mma_op 8 types +static constexpr int ROWS_PER_CORE_MATRIX_A_8 = 8; +static constexpr int COLS_PER_CORE_MATRIX_A_8 = 8; +static constexpr int ROWS_PER_CORE_MATRIX_B_8 = 8; +static constexpr int COLS_PER_CORE_MATRIX_B_8 = 8; + +// global_load_op 10 types +static constexpr int BITS_PER_ELEMENT_10 = 32; +static constexpr int BYTES_PER_ELEMENT_10 = 4; +static constexpr int REGISTERS_PER_VECTOR_10 = 1; +static constexpr int REGISTERS_PER_ACCESS_10 = 1; + +// pointwise_calc_op 9 types +static constexpr int WARP_TILE_M_9 = 16; +static constexpr int WARP_TILE_N_9 = 16; +static constexpr int TILE_M_9 = 128; +static constexpr int TILE_N_9 = 128; +static constexpr int WARPS_M_9 = 4; +static constexpr int WARPS_N_9 = 1; +static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9; +static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9; +static constexpr int WARP_REGS_9 = WARP_REGS_1; +static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9; +static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9; + +// mha_mask_op 11 types +static constexpr int WARP_TILE_M_11 = 16; +static constexpr int WARP_TILE_N_11 = 16; +static constexpr int TILE_M_11 = 128; +static constexpr int TILE_N_11 = 128; +static constexpr int WARPS_M_11 = 4; +static constexpr int WARPS_N_11 = 1; +static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11; +static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11; +static constexpr int WARP_REGS_11 = 8; +static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11; +static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11; +inline __device__ bool compute_diagonal_band_mask_11( +)KERNEL" + R"KERNEL( + const int row, const int col, const int actual_seqlen_kv, + const int actual_seqlen_q, const int shift_right_bound, + const int left_bound) { + constexpr bool is_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_right_bound = true; + constexpr bool is_left_bound = false; + constexpr bool need_oob_check = false; + + const int diag = is_bottom_right_alignment + ? row + (actual_seqlen_kv - actual_seqlen_q) + : row; + const int shifted_right_bound = + is_shift_right_bound ? diag + shift_right_bound : diag; + const bool right_bound_mask = + is_right_bound ? col <= shifted_right_bound : true; + const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true; + const bool oob_check = + need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true; + return right_bound_mask && left_bound_mask && oob_check; +} + +// softmax_op 12 types +static constexpr int BYTES_PER_ELEMENT_12 = 2; +static constexpr int WARP_TILE_M_12 = 16; +static constexpr int WARP_TILE_N_12 = 16; +static constexpr int TILE_M_12 = 128; +static constexpr int TILE_N_12 = 128; +static constexpr int WARPS_M_12 = 4; +static constexpr int WARPS_N_12 = 1; +static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12; +static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12; +static constexpr int THREADS_PER_WARP_TILE_M_12 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_12 = 4; +static constexpr int WARP_REGS_12 = 8; +static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12; +static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12; +static constexpr int ROWS_PER_THREAD_12 = + TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12; + +// global_store_op 13 types +static constexpr int BYTES_PER_ELEMENT_13 = 4; +static constexpr int WARP_TILE_M_13 = 16; +static constexpr int WARP_TILE_N_13 = 16; +static constexpr int TILE_M_13 = 128; +static constexpr int TILE_N_13 = 128; +static constexpr int WARPS_M_13 = 4; +static constexpr int WARPS_N_13 = 1; +static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13; +static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13; +static constexpr int THREADS_PER_WARP_TILE_M_13 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_13 = 4; +static constexpr int ROWS_PER_THREAD_13 = + TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13; + +// global_store_op 14 types +static constexpr int BYTES_PER_ELEMENT_14 = 4; +static constexpr int WARP_TILE_M_14 = 16; +static constexpr int WARP_TILE_N_14 = 16; +static constexpr int TILE_M_14 = 128; +static constexpr int TILE_N_14 = 128; +static constexpr int WARPS_M_14 = 4; +static constexpr int WARPS_N_14 = 1; +static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14; +static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14; +static constexpr int THREADS_PER_WARP_TILE_M_14 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_14 = 4; +static constexpr int ROWS_PER_THREAD_14 = + TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14; + +// shared_load_op 15 types +static constexpr int BITS_PER_ELEMENT_15 = 16; +static constexpr int BYTES_PER_ELEMENT_15 = 2; +static constexpr int BYTES_PER_QUAD_15 = 16; +static constexpr int WARP_TILE_M_15 = 16; +static constexpr int WARP_TILE_N_15 = 16; +static constexpr int TILE_M_15 = 128; +static constexpr int TILE_N_15 = 128; +static constexpr int BYTES_PER_SMEM_15 = + TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15; +static constexpr int WARPS_M_15 = 1; +static constexpr int WARPS_N_15 = 1; +static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15; +static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15; +static constexpr int THREADS_PER_WARP_TILE_M_15 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_15 = 4; +static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15; +static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15; +static constexpr int BYTES_PER_LD_15 = 128; +static constexpr int SWIZZLE_SCALE_15 = + FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4); + +// global_load_shared_store_op 16 types +static constexpr int BITS_PER_ELEMENT_16 = 16; +static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8; +static constexpr int BYTES_PER_ACCESS_16 = 16; +static constexpr int TILE_M_16 = 128; +static constexpr int TILE_N_16 = 128; +static constexpr int BYTES_PER_SMEM_16 = + TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16; + +// mma_op 17 types +static constexpr int ROWS_PER_CORE_MATRIX_A_17 = 8; +static constexpr int COLS_PER_CORE_MATRIX_A_17 = 8; +static constexpr int ROWS_PER_CORE_MATRIX_B_17 = 8; +static constexpr int COLS_PER_CORE_MATRIX_B_17 = 8; + +// global_store_op 20 types + +// mma_loop_op 2 types +inline __device__ int2 compute_kv_loop_bounds( + const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE, + const int actual_seqlen_kv, const int actual_seqlen_q, + const int shift_right_bound, const int left_bound) { + constexpr bool is_right_bound = true; + constexpr bool is_right_bound_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_left_bound = false; + constexpr bool is_left_bound_bottom_right_alignment = false; + + const int right_bound_diagonal = + is_right_bound_bottom_right_alignment + ? row_coord + (actual_seqlen_kv - actual_seqlen_q) + : row_coord; + const int shifted_right_bound_diagonal = + is_shift_right_bound ? right_bound_diagonal + shift_right_bound + : right_bound_diagonal; + const int left_bound_diagonal = + is_left_bound_bottom_right_alignment + ? row_coord + (actual_seqlen_kv - actual_seqlen_q) + : row_coord; + + const int kv_loop_left_bound = + is_left_bound + ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE) + : 0; + const int kv_loop_right_bound = + is_right_bound + ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE, + COL_TILE_SIZE), + FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE)) + : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE); + return make_int2(kv_loop_left_bound, kv_loop_right_bound); +} + +// output_loop_op 3 types +static constexpr int BYTES_PER_BANK_3 = 16; +static constexpr int ELEMENTS_PER_VECTOR_3 = + FORT_MIN(64, CTA_TILE_N_1 / N_TILES_PER_OUTPUT_TILE_1); + +// shared_store_op 18 types + +// shared_load_op 19 types +static constexpr int BITS_PER_ELEMENT_19 = 32 * 1; +static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8; +static constexpr int BITS_PER_VECTOR_19 = + BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3; +static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8; +static constexpr int REGISTERS_PER_VECTOR_19 = + BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0; + +// receive_op 0 code + +extern "C" __global__ +__launch_bounds__(512, 1) void cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x128_4x1x1_cga1x1x1_kernel0_0( + const AttentionDescriptor_t attnDesc, const FastDivisor_t num_head_divmod, + const FastDivisor_t l2_minor_divmod, const FastDivisor_t l2_major_divmod, + const FastDivisor_t l2_minor_residual_divmod, const int num_hb_quotient, + const int num_block, const int total_blocks, + __grid_constant__ const CUtensorMap tma_tensor_3, + __grid_constant__ const CUtensorMap tma_tensor_2, float tensor_4, + float tensor_13, void *tensor_7, fort::tensor_descriptor desc_7, + void *tensor_6, fort::tensor_descriptor desc_6, + __grid_constant__ const CUtensorMap tma_tensor_1, + __grid_constant__ const CUtensorMap tma_tensor_5) { + asm volatile(".pragma \"global knob ForceLateCommoning=1\";\n" ::: "memory"); + asm volatile(".pragma \"global knob HoistLate=3\";\n" ::: "memory"); + + extern __shared__ char smem_[]; + SharedStorage &shared_storage = *reinterpret_cast<SharedStorage *>(smem_); + + // receive_op 0 decls + + // mma_pipeline_op 1 decls + const int tid = threadIdx.x % threads_per_group; + const int wid = threadIdx.x / 32; + const int tiw = threadIdx.x % 32; + + const uint32_t elect_one = elect_one_sync(); + + if (wid == 0 && elect_one) { + smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]), + /* 1 tmastg */ 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]), + /* 4 epilogue */ warps_per_group * 32 * CTA_MMA_1); + +#pragma unroll + for (int q_stage = 0; q_stage < stages_q; q_stage++) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + /* 1 tma */ 1); + } + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]), + /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile0_empty_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.final_stat_tile0_empty_mbar[0]), + /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1); + +#pragma unroll + for (int i = 0; i < TILE_O_1 * sizeof(ElementO); i += 128) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]), + /* 1 correction */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]), + /* 1 correction */ warps_per_group * 32); + } + smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]), + /* 1 tmastg */ 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]), 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]), + /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[1]), + /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[1]), + /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile1_empty_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.final_stat_tile1_empty_mbar[0]), + /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1); + + smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]), + /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1); + +#pragma unroll + for (int sched_steps = 0; sched_steps < SchedulerPipelineStageCount; + sched_steps++) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.scheduler_mbar[sched_steps]), + /* 1 sched */ 1); + smem_bar_init(cast_smem_ptr_to_uint( + &shared_storage.read_tile_id_done_mbar[sched_steps]), + (SoftmaxWarps + CorrectionWarps + 1 + 1) * CGA_M_1 * + CGA_N_1 + + CGA_M_1 * CGA_N_1 / CTA_MMA_1); + } + +#pragma unroll + for (int kv_stages = 0; kv_stages < stages_kv; kv_stages++) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[kv_stages]), + /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stages]), + /* 1 tma/32 ldgsts */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stages]), + /* 1 tma/32 ldgsts */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[kv_stages]), + /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1); + } + } + __syncthreads(); + +)KERNEL" + R"KERNEL( + // mma_pipeline_op 1 code + + // mma_loop_op 2 code + uint32_t tile_id_and_coord[8] = {0}; + + int actual_seqlen_kv_1 = attnDesc.s_kv; + int actual_seqlen_q_1 = attnDesc.s_q; + int q_row_coord = 0; + int kv_loop_right_bound, kv_loop_left_bound; + + const int left_bound = 0; + const int shift_right_bound = 0; + + uint32_t tile_idx = blockIdx.x; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + tile_id_and_coord[0] = head_idx; + tile_id_and_coord[1] = batch_idx; + tile_id_and_coord[2] = block; + tile_id_and_coord[3] = 1; + + int head_coord_q_offset_1 = 0; + uint32_t head_coord_1, head_coord_k_1, head_coord_v_1; + uint32_t blocked_row_coord = tile_id_and_coord[2]; + uint32_t head_coord_from_grid_1 = tile_id_and_coord[0]; + uint32_t batch_coord_1 = tile_id_and_coord[1]; + uint32_t lean_tile_id = tile_id_and_coord[0]; + + uint32_t is_valid_tile = true; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + + PipelineState<SchedulerPipelineStageCount> sched_state(0, 0); // index, state + + // thread_specialize_op 21 code + if (wid >= 0 && wid < SoftmaxWarps) { + // Softmax + reg_alloc<SoftmaxWarpRegs>(); + + const uint32_t softmax_gid = wid / 4; + const uint32_t softmax_gid_s_offset = softmax_gid * BMM1_TILE_N; + + uint32_t base_tmem_addr; + named_barrier_wait(TMEM_ALLOC_SOFTMAX_BARRIER, + threads_per_warp * (SoftmaxWarps + 1)); + lds_32(&base_tmem_addr, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + uint32_t tmem_fp32_S = base_tmem_addr + 0 + softmax_gid_s_offset; + uint32_t tmem_fp16_S = + base_tmem_addr + BMM1_TILE_N / 2 + softmax_gid_s_offset; + uint32_t tmem_Stats = base_tmem_addr + 0 + softmax_gid_s_offset; + + r32 reg_8_0[BMM1_TILE_N]; + r32 fp32_stats[2]; + + // Memory barrier states + uint32_t bmm_mbar_state = 0; + uint32_t stat_mbar_state = 0; + uint32_t epilogue_state = 0; + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + int p_row_1 = q_row_coord + softmax_gid * TILE_M_1 + tid; + + // global_load_op 10 decls + r32 reg_10_0[1]; + reg_10_0[0] = reinterpret_cast<const r32 &>(tensor_4); + const int oob_M_10 = 1; + const int oob_N_10 = 1; + + // pointwise_calc_op 9 decls + + // mha_mask_op 11 decls + + // softmax_op 12 decls + r32 reg_12_0[32]; + float2 total_sum = {0.0f, 0.0f}; + float2 local_sum = {0.0f, 0.0f}; + float total_max = NEG_INFINITY; + float actual_total_max = NEG_INFINITY; + static constexpr float inv_ln2_12 = 1.4426950408889634074f; + float total_max_scale_12 = inv_ln2_12; + const float bmm_scale = reinterpret_cast<const float &>(tensor_4); + total_max_scale_12 *= bmm_scale; + + uint64_t &bmm1_mbar = softmax_gid == 0 + ? shared_storage.bmm1_tile0_done_mbar[0] + : shared_storage.bmm1_tile1_done_mbar[0]; + uint64_t &stat_empty_mbar = softmax_gid == 0 + ? shared_storage.stat_tile0_empty_mbar[0] + : shared_storage.stat_tile1_empty_mbar[0]; + uint64_t *bmm2_mbar = softmax_gid == 0 + ? &(shared_storage.bmm2_tile0_ready_mbar[0]) + : &(shared_storage.bmm2_tile1_ready_mbar[0]); + uint64_t *stat_full_mbar = + softmax_gid == 0 ? &(shared_storage.stat_tile0_full_mbar[0]) + : &(shared_storage.stat_tile1_full_mbar[0]); + + epilogue_state ^= 1; + wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]), + epilogue_state); + stat_mbar_state ^= 1; + wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), stat_mbar_state); + +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound; + kv_loop < + kv_loop_right_bound - + FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N); + kv_loop += 1) { + int p_col_1 = kv_loop * TILE_N_1; + { + + wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state); + + r32 stat_reg[BMM1_TILE_N / 64]; +#pragma unroll + for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) { + ldtm_32dp32bit_x32(®_8_0[32 * ldtm_step], + tmem_fp32_S + ldtm_step * 32); + } + constexpr bool use_ldtm_stat_max = false; + + // global_load_op 10 code + + // softmax_op 12 code + float current_max = + row_max_reduction_128_elems(reg_8_0) * total_max_scale_12; + + // Update total max + float total_max_tmp = fmaxf(current_max, total_max); + current_max = total_max; + total_max = total_max_tmp; + + float2 bmm_scale_x_ln2_x2 = + make_float2(total_max_scale_12, total_max_scale_12); + float total_max_scaled = + (total_max == NEG_INFINITY) ? 0.0f : total_max; + float2 minus_scaled_max_x2 = + make_float2(-total_max_scaled, -total_max_scaled); + + static constexpr int kMulPipeCount = 14; // must be multiple of 2 + static constexpr int kSubtractPipeCount = 12; // must be multiple of 2 + static constexpr int kFmaPipeCount = 12; // must be multiple of 2 + static constexpr int kConvertPipeCount = 8; // must be multiple of 2 + static constexpr int kReleasePipeCount = 4; // must be multiple of 2 + static constexpr int kDropoutPipeCount = + 6; // must be multiple of 2 and less than or equal + // kConvertPipeCount + static constexpr int kAddPipeCount = + 4; // must be multiple of 2 and less than kDropoutPipeCount + + // To better overlap EX2 MUFU and emulation, we need to have last + // kE2eRes of every kE2eFreq elements in a row to use emulation while + // the rest go to MUFU. Also, we need to avoid using emulation after + // kE2eLimit elements as it would delay the execution of row sum of + // another softmax warpgroup because of resource contention + static constexpr int kE2eFreq = 16; + static constexpr int kE2eRes = 8; + static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9; + +#pragma unroll + for (int i = 0; i < kFmaPipeCount; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y; + } + + // Optimized version of alpha = __expf(current_max - total_max); + float exp_input = (total_max == NEG_INFINITY) + ? NEG_INFINITY + : (current_max - total_max); + float alpha = exp2f(exp_input); + + // Send stats to correction warp + reinterpret_cast<float &>(fp32_stats[0]) = alpha; + + // STTM + sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar)); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + if (i - kConvertPipeCount == 32) { + sttm_32dp32bit_x16(tmem_fp16_S, ®_12_0[0]); + } + if (i - kConvertPipeCount == 64) { + sttm_32dp32bit_x16(tmem_fp16_S + 16, ®_12_0[16]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0)); + } + + if (i >= kConvertPipeCount) { + fp32x2_to_bf16x2( + ®_12_0[((i - kConvertPipeCount) / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i - kConvertPipeCount])); + } + + reinterpret_cast<float &>(reg_8_0[i + 0]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 0])); + + + if (i + kFmaPipeCount < BMM1_TILE_N) { + float2 in = make_float2( + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]), + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y; + } + + reinterpret_cast<float &>(reg_8_0[i + 1]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 1])); + + if (i == kE2eLimit) { + if (softmax_gid == 1) { + named_barrier_arrive(SOFTMAX_BARRIER, 256); + named_barrier_wait(SOFTMAX_BARRIER + 1, 256); + } + } + } + +#pragma unroll + for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N; + i += 2) { + fp32x2_to_bf16x2(®_12_0[(i / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i])); + } + sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16, + ®_12_0[((BMM1_TILE_N / 64) % 2) * 16]); + fence_view_async_tmem_store(); + arrive_barrier( + cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1))); + + stat_mbar_state ^= 1; + if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state)) { + wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state); + } + + float2 alpha2 = make_float2(alpha, alpha); + float local_row_sum_0 = 0.0f; + total_sum = fmul2(alpha2, total_sum); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + total_sum = fadd2(total_sum, in); + } + if (softmax_gid == 0) { + named_barrier_arrive(SOFTMAX_BARRIER + 1, 256); + named_barrier_wait(SOFTMAX_BARRIER, 256); + } + named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128); + } + bmm_mbar_state ^= 1; + } // End of mainloop +#pragma unroll 1 + for (int kv_loop = FORT_MAX( + kv_loop_right_bound - + FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N), + kv_loop_left_bound); + kv_loop < kv_loop_right_bound; kv_loop += 1) { + int p_col_1 = kv_loop * TILE_N_1; + { + + wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state); + + r32 stat_reg[BMM1_TILE_N / 64]; +#pragma unroll + for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) { + ldtm_32dp32bit_x32(®_8_0[32 * ldtm_step], + tmem_fp32_S + ldtm_step * 32); + } + constexpr bool use_ldtm_stat_max = false; + +)KERNEL" + R"KERNEL( + // global_load_op 10 code + + // mha_mask_op 11 code + + { +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i++) { + int row = p_row_1; + int col = p_col_1 + i; + bool mask = compute_diagonal_band_mask_11( + row, col, actual_seqlen_kv_1, actual_seqlen_q_1, + shift_right_bound, left_bound); + if (!mask) { + reinterpret_cast<float &>(reg_8_0[i]) = tensor_13; + } + } + } + + // softmax_op 12 code + float current_max = + row_max_reduction_128_elems(reg_8_0) * total_max_scale_12; + + // Update total max + float total_max_tmp = fmaxf(current_max, total_max); + current_max = total_max; + total_max = total_max_tmp; + + float2 bmm_scale_x_ln2_x2 = + make_float2(total_max_scale_12, total_max_scale_12); + float total_max_scaled = + (total_max == NEG_INFINITY) ? 0.0f : total_max; + float2 minus_scaled_max_x2 = + make_float2(-total_max_scaled, -total_max_scaled); + + static constexpr int kMulPipeCount = 14; // must be multiple of 2 + static constexpr int kSubtractPipeCount = 12; // must be multiple of 2 + static constexpr int kFmaPipeCount = 12; // must be multiple of 2 + static constexpr int kConvertPipeCount = 8; // must be multiple of 2 + static constexpr int kReleasePipeCount = 4; // must be multiple of 2 + static constexpr int kDropoutPipeCount = + 6; // must be multiple of 2 and less than or equal + // kConvertPipeCount + static constexpr int kAddPipeCount = + 4; // must be multiple of 2 and less than kDropoutPipeCount + + // To better overlap EX2 MUFU and emulation, we need to have last + // kE2eRes of every kE2eFreq elements in a row to use emulation while + // the rest go to MUFU. Also, we need to avoid using emulation after + // kE2eLimit elements as it would delay the execution of row sum of + // another softmax warpgroup because of resource contention + static constexpr int kE2eFreq = 16; + static constexpr int kE2eRes = 8; + static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9; + +#pragma unroll + for (int i = 0; i < kFmaPipeCount; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y; + } + + // Optimized version of alpha = __expf(current_max - total_max); + float exp_input = (total_max == NEG_INFINITY) + ? NEG_INFINITY + : (current_max - total_max); + float alpha = exp2f(exp_input); + + // Send stats to correction warp + reinterpret_cast<float &>(fp32_stats[0]) = alpha; + + // STTM + sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar)); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + if (i - kConvertPipeCount == 32) { + sttm_32dp32bit_x16(tmem_fp16_S, ®_12_0[0]); + } + if (i - kConvertPipeCount == 64) { + sttm_32dp32bit_x16(tmem_fp16_S + 16, ®_12_0[16]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0)); + } + + if (i >= kConvertPipeCount) { + fp32x2_to_bf16x2( + ®_12_0[((i - kConvertPipeCount) / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i - kConvertPipeCount])); + } + + reinterpret_cast<float &>(reg_8_0[i + 0]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 0])); + + + if (i + kFmaPipeCount < BMM1_TILE_N) { + float2 in = make_float2( + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]), + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y; + } + + reinterpret_cast<float &>(reg_8_0[i + 1]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 1])); + + if (i == kE2eLimit) { + if (softmax_gid == 1) { + named_barrier_arrive(SOFTMAX_BARRIER, 256); + named_barrier_wait(SOFTMAX_BARRIER + 1, 256); + } + } + } + +#pragma unroll + for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N; + i += 2) { + fp32x2_to_bf16x2(®_12_0[(i / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i])); + } + sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16, + ®_12_0[((BMM1_TILE_N / 64) % 2) * 16]); + fence_view_async_tmem_store(); + arrive_barrier( + cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1))); + + stat_mbar_state ^= 1; + if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state)) { + wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state); + } + + float2 alpha2 = make_float2(alpha, alpha); + float local_row_sum_0 = 0.0f; + total_sum = fmul2(alpha2, total_sum); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + total_sum = fadd2(total_sum, in); + } + if (softmax_gid == 0) { + named_barrier_arrive(SOFTMAX_BARRIER + 1, 256); + named_barrier_wait(SOFTMAX_BARRIER, 256); + } + named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128); + } + bmm_mbar_state ^= 1; + } // End of mainloop + + float final_total_sum = total_sum.x + total_sum.y; + + reinterpret_cast<float &>(fp32_stats[0]) = total_max; + reinterpret_cast<float &>(fp32_stats[1]) = final_total_sum; + // STTM + sttm_32dp32bit_x2(tmem_Stats, &fp32_stats[0]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar)); + + // This portion of the code may seem strange, please read the + // Function: work_tile_info_from_workid_response, load_query_response + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } // end of persistent loop + } + + // thread_specialize_op 22 code + else if (wid >= SoftmaxWarps && wid < SoftmaxWarps + CorrectionWarps) { + // Correction + reg_dealloc<CorrectionWarpRegs>(); + uint32_t base_tmem_addr; + named_barrier_wait(TMEM_ALLOC_CORRECTION_BARRIER, + threads_per_warp * (CorrectionWarps + 1)); + lds_32(&base_tmem_addr, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + uint32_t tmem_fp32_O_0 = base_tmem_addr + 256; + uint32_t tmem_fp32_O_1 = base_tmem_addr + 384; + uint32_t tmem_Stats_0 = base_tmem_addr + 0; + uint32_t tmem_Stats_1 = base_tmem_addr + 0 + BMM1_TILE_N; + + static constexpr int local_correction_block_size = 16; + static constexpr int local_epilogue_block_size = + 128 / sizeof(ElementO); // hack as only K=128/64 supported. Both can do + // 128B TMASTG. + +)KERNEL" + R"KERNEL( + float amax_s_1 = 0.f; + float amax_o_1 = 0.f; + + // Registers + uint32_t fp32_stats[2]; + uint32_t fp32_O[local_correction_block_size]; + + // Memory barrier states + uint32_t epilogue_state = 0; + uint32_t bmm_mbar_state = 0; + uint32_t stat_mbar_state = 0; + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + + if (kv_loop_left_bound < kv_loop_right_bound) { + // No correction for iter 0 + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile0_ready_mbar[0]))); + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile1_ready_mbar[0]))); + + { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]), + stat_mbar_state); + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.stat_tile0_empty_mbar[0]))); + } + { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]), + stat_mbar_state); + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.stat_tile1_empty_mbar[0]))); + } + stat_mbar_state ^= 1; + } else { + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.empty_mainloop_mbar[0]))); + } + +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound; + kv_loop += 1) { +#pragma unroll + for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) { + uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1; + uint32_t tmem_fp32_O = + sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1; + + uint64_t &stat_full_mbar = + sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0] + : shared_storage.stat_tile1_full_mbar[0]; + uint64_t &bmm_done_mbar = + sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0] + : shared_storage.bmm2_tile1_done_mbar[0]; + uint64_t *stat_empty_mbar = + sub_tile_id == 0 ? &(shared_storage.stat_tile0_empty_mbar[0]) + : &(shared_storage.stat_tile1_empty_mbar[0]); + uint64_t *bmm_ready_mbar = + sub_tile_id == 0 ? &(shared_storage.bmm2_tile0_ready_mbar[0]) + : &(shared_storage.bmm2_tile1_ready_mbar[0]); + + wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state); + ldtm_32dp32bit_x1(&fp32_stats[0], tmem_Stats); + + float alpha = reinterpret_cast<float &>(fp32_stats[0]); + fence_view_async_tmem_load(); + arrive_barrier(cast_smem_ptr_to_uint(stat_empty_mbar)); + + bool alpha_is_one = (alpha == 1.0f); + bool all_alpha_one = __all_sync(0xFFFFFFFF, alpha_is_one); + + float2 alpha2 = make_float2(alpha, alpha); + + wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state); + + if (!all_alpha_one) { +#pragma unroll + for (int block = 0; block < TILE_O_1 / local_correction_block_size; + block++) { +// LDTM +#pragma unroll + for (int ldtm_step = 0; + ldtm_step < local_correction_block_size / 8; ldtm_step++) { + ldtm_32dp32bit_x8(&fp32_O[8 * ldtm_step], + tmem_fp32_O + + block * local_correction_block_size + + ldtm_step * 8); + } + +#pragma unroll + for (int i = 0; i < local_correction_block_size; i += 2) { + float2 in = + make_float2(reinterpret_cast<float &>(fp32_O[i + 0]), + reinterpret_cast<float &>(fp32_O[i + 1])); + float2 out = fmul2(alpha2, in); + reinterpret_cast<float &>(fp32_O[i + 0]) = out.x; + reinterpret_cast<float &>(fp32_O[i + 1]) = out.y; + } + +#pragma unroll + for (int sttm_step = 0; + sttm_step < local_correction_block_size / 8; sttm_step++) { + sttm_32dp32bit_x8(tmem_fp32_O + + block * local_correction_block_size + + sttm_step * 8, + &fp32_O[8 * sttm_step]); + } + } + } + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(bmm_ready_mbar)); + } + stat_mbar_state ^= 1; + bmm_mbar_state ^= 1; + } // End of mainloop + + // Epilogue + { + epilogue_state ^= 1; + + static constexpr int stg_step = 16 / sizeof(ElementO); + const int local_row = (tid % 8) / 1; + + // global_store_op 13 decls + int oob_M_13 = desc_7.dims[2]; + int row_13 = 0; + char *ptr_13 = + reinterpret_cast<char *>(tensor_7) + + batch_coord_1 * desc_7.strides[0] * BYTES_PER_ELEMENT_13 + + head_coord_1 * desc_7.strides[1] * BYTES_PER_ELEMENT_13 + + row_13 * desc_7.strides[2] * BYTES_PER_ELEMENT_13; + + // global_store_op 14 decls + int oob_M_14 = desc_6.dims[2]; + int row_14 = 0; + char *ptr_14 = + reinterpret_cast<char *>(tensor_6) + + batch_coord_1 * desc_6.strides[0] * BYTES_PER_ELEMENT_14 + + head_coord_1 * desc_6.strides[1] * BYTES_PER_ELEMENT_14 + + row_14 * desc_6.strides[2] * BYTES_PER_ELEMENT_14; + +#pragma unroll + for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) { + const int row_coord = q_row_coord + sub_tile_id * TILE_M_1 + tid; + ElementO *smem_O = (sub_tile_id == 0) ? shared_storage.smem_O + : shared_storage.smem_V; + + uint32_t fp32_reg_O[local_epilogue_block_size]; + uint32_t reg_O[local_epilogue_block_size / (4 / sizeof(ElementO))]; + + uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1; + uint32_t tmem_fp32_O = + sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1; + + uint64_t &stat_full_mbar = + sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0] + : shared_storage.stat_tile1_full_mbar[0]; + uint64_t &bmm_done_mbar = + sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0] + : shared_storage.bmm2_tile1_done_mbar[0]; + uint64_t &stat_empty_mbar = + sub_tile_id == 0 ? shared_storage.stat_tile0_empty_mbar[0] + : shared_storage.stat_tile1_empty_mbar[0]; + uint64_t &final_stat_empty_mbar = + sub_tile_id == 0 ? shared_storage.final_stat_tile0_empty_mbar[0] + : shared_storage.final_stat_tile1_empty_mbar[0]; + + wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state); + ldtm_32dp32bit_x2(&fp32_stats[0], tmem_Stats); + + float total_max = reinterpret_cast<float &>(fp32_stats[0]) * ln2; + float total_sum = reinterpret_cast<float &>(fp32_stats[1]); + fence_view_async_tmem_load(); + arrive_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar)); + arrive_barrier(cast_smem_ptr_to_uint(&final_stat_empty_mbar)); + + float softmax_stats = + total_sum == 0.f ? NEG_INFINITY : total_max + __logf(total_sum); + + // global_store_op 13 code + if (row_coord < actual_seqlen_q_1) { + stg_32(ptr_13 + + row_coord * desc_7.strides[2] * BYTES_PER_ELEMENT_13, + &(reinterpret_cast<uint32_t &>(total_max))); + } + + // global_store_op 14 code + if (row_coord < actual_seqlen_q_1) { + stg_32(ptr_14 + + row_coord * desc_6.strides[2] * BYTES_PER_ELEMENT_14, + &(reinterpret_cast<uint32_t &>(total_sum))); + } + + float threshold_beta = (total_sum == 0.f) ? 0.f : 1.f / total_sum; + float beta = threshold_beta; + + float2 beta2 = make_float2(threshold_beta, threshold_beta); + + wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state); + + if (sub_tile_id == 0) { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]), + epilogue_state); + } +#pragma unroll + for (int block = 0; block < TILE_O_1 / local_epilogue_block_size; + block++) { + { +#pragma unroll + for (int ldtm_step = 0; + ldtm_step < local_epilogue_block_size / 32; ldtm_step++) { + ldtm_32dp32bit_x32(&fp32_reg_O[32 * ldtm_step], + tmem_fp32_O + + block * local_epilogue_block_size + + ldtm_step * 32); + } + } + +#pragma unroll + for (int i = 0; i < local_epilogue_block_size; i += 2) { + float2 in = + make_float2(reinterpret_cast<float &>(fp32_reg_O[i + 0]), + reinterpret_cast<float &>(fp32_reg_O[i + 1])); + float2 out = fmul2(beta2, in); + reinterpret_cast<float &>(fp32_reg_O[i + 0]) = out.x; + reinterpret_cast<float &>(fp32_reg_O[i + 1]) = out.y; + } + +// general_data_type_cast code +#pragma unroll + for (int i = 0; i < local_epilogue_block_size; i += 2) { + fp32x2_to_bf16x2(®_O[i / 2], &fp32_reg_O[i]); + } + +#pragma unroll + for (int i = 0; i < local_epilogue_block_size / stg_step; i++) { + char *smem_loc = get_smem_loc_epilogue_swizzle_128b( + reinterpret_cast<char *>(smem_O), block, tid, local_row, i, + sizeof(ElementO), local_epilogue_block_size, TILE_M_1); +)KERNEL" + R"KERNEL( + sts_128(cast_smem_ptr_to_uint(smem_loc), + reinterpret_cast<r32 *>(®_O[i * 4])); + } + + uint64_t *tma_o_full_mbar = + sub_tile_id == 0 ? &(shared_storage.tma_o_0_full_mbar[block]) + : &(shared_storage.tma_o_1_full_mbar[block]); + fence_view_async_shared(); + arrive_barrier(cast_smem_ptr_to_uint(tma_o_full_mbar)); + } + } + stat_mbar_state ^= 1; + bmm_mbar_state ^= 1; + } // Epilogue end + + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } // end of persistent loop + arrive_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0])); + } + + // thread_specialize_op 23 code + else if (wid == SoftmaxWarps + CorrectionWarps) { + // MMA + reg_dealloc<MmaWarpRegs>(); + tmem_allocate_1sm(num_columns_per_tmem, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + tmem_release_allocation_lock_1sm(); + __syncwarp(); + named_barrier_arrive(TMEM_ALLOC_SOFTMAX_BARRIER, + threads_per_warp * (SoftmaxWarps + 1)); + named_barrier_arrive(TMEM_ALLOC_CORRECTION_BARRIER, + threads_per_warp * (CorrectionWarps + 1)); + uint32_t base_tmem_addr; + lds_32(&base_tmem_addr, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + + uint32_t tmem_S_acc_0 = base_tmem_addr + 0; + uint32_t tmem_S_acc_1 = base_tmem_addr + BMM1_TILE_N; + + uint32_t tmem_S_bmm2_0 = base_tmem_addr + BMM1_TILE_N / 2; + uint32_t tmem_S_bmm2_1 = base_tmem_addr + 3 * BMM1_TILE_N / 2; + + uint32_t tmem_O_0 = base_tmem_addr + 256; + uint32_t tmem_O_1 = base_tmem_addr + 384; + + // Memory barrier states + uint32_t bmm_mbar_state = 0; + uint32_t final_stat_mbar_state = 1; + uint32_t empty_mainloop_mbar_state = 0; + + PipelineState<stages_kv> kv_mbar_state(0, 0); // index, state + PipelineState<stages_q> q_mbar_state(0, 0); // index, state + + // mma_op 8 decls + constexpr uint64_t utcmma_instruction_desc_8 = + build_utcmma_instruction_desc<0, // max shift for WS + TILE_M_1 * CTA_MMA_1, TILE_N_1, + 0, // Transpose for B + 0, // Transpose for A + 0, // Negate for B + 0, // Negate for A + 1, // Data type B + 1, // Data type A + 0, // sparse meta data format + 1, // Acc type fp32 + 0, // saturate disable + 0, // sparse disable + 0 // sparse meta data id2 ??? + >(); + // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k + Smem_utcmma_descriptor utcmma_smem_desc_Q_0(2, 0, 1, 16, + ROWS_PER_CORE_MATRIX_A_8 * 128); + Smem_utcmma_descriptor utcmma_smem_desc_K(2, 0, 1, 16, + ROWS_PER_CORE_MATRIX_B_8 * 128); + + utcmma_smem_desc_Q_0.set_smem<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>( + cast_smem_ptr_to_uint(shared_storage.smem_Q)); + utcmma_smem_desc_K.set_smem<SMEM_BUFFER_SIZE_K, BUFFERS_K>( + cast_smem_ptr_to_uint(shared_storage.smem_K)); + + // mma_op 17 decls + constexpr uint64_t utcmma_instruction_desc_17 = + build_utcmma_instruction_desc<0, // max shift for WS + TILE_M_1 * CTA_MMA_1, TILE_O_1, + 1, // Transpose for B + 0, // Transpose for A + 0, // Negate for B + 0, // Negate for A + 1, // Data type B + 1, // Data type A + 0, // sparse meta data format + 1, // Acc type fp32 + 0, // saturate disable + 0, // sparse disable + 0 // sparse meta data id2 ??? + >(); + // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k + Smem_utcmma_descriptor utcmma_smem_desc_V( + 2, 0, 1, TILE_O_1 / ROWS_PER_CORE_MATRIX_B_17 <= 8 ? 0 : TILE_N_1 * 128, + COLS_PER_CORE_MATRIX_B_17 * 128); + + utcmma_smem_desc_V.set_smem<SMEM_BUFFER_SIZE_V, BUFFERS_V>( + cast_smem_ptr_to_uint(shared_storage.smem_V)); + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + //---------------------------------------------------------// + //------------------- MMA Pipeline Begin ------------------// + //---------------------------------------------------------// + + if (kv_loop_left_bound < kv_loop_right_bound) { + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.final_stat_tile0_empty_mbar[0]), + final_stat_mbar_state); + + const int kv_stage = kv_mbar_state.index(); + const int kv_state = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stage]), + kv_state); + + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Q * K matmul for sub-tile 0 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_0; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0])); + } // elect_one + } // if (kv_loop_left_bound < kv_loop_right_bound) + if (kv_loop_left_bound < kv_loop_right_bound) { + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.final_stat_tile1_empty_mbar[0]), + final_stat_mbar_state); + + const int kv_stage = kv_mbar_state.index(); + const int kv_state = kv_mbar_state.phase(); + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Q * K matmul for sub-tile 1 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_1; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, +)KERNEL" + R"KERNEL( + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for K + utcmma_smem_desc_K + .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + const int kv_stage = kv_mbar_state.index(); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_k_empty_mbar[kv_stage])); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0])); + } // elect_one + } + +// Mainloop +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound; + kv_loop += 1) { + const int kv_stage = kv_mbar_state.index(); + const uint32_t kv_state = kv_mbar_state.phase(); + + ++kv_mbar_state; + + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]), + kv_state); + + // S * V matmul for sub-tile 0 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]); + uint32_t tmem_O = tmem_O_0; + uint32_t tmem_S = tmem_S_bmm2_0; + uint32_t scaleC = kv_loop > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0])); + } + + wait_barrier( + cast_smem_ptr_to_uint( + &shared_storage.tma_k_full_mbar[kv_mbar_state.index()]), + kv_mbar_state.phase()); + + // Q * K matmul for sub-tile 0 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_0; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0])); + } // elect_one + + // S * V matmul for sub-tile 1 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]); + uint32_t tmem_O = tmem_O_1; + uint32_t tmem_S = tmem_S_bmm2_1; + uint32_t scaleC = kv_loop > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0])); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_v_empty_mbar[kv_stage])); + // Change the buffer for V + utcmma_smem_desc_V + .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>(); + } + bmm_mbar_state ^= 1; + + // Q * K matmul for sub-tile 1 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_1; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for K + utcmma_smem_desc_K + .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + const int kv_stage = kv_mbar_state.index(); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_k_empty_mbar[kv_stage])); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0])); + } // elect_one + } + if (kv_loop_left_bound < kv_loop_right_bound) { + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[1])); + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[0])); + } + const int kv_stage = kv_mbar_state.index(); + const uint32_t kv_state = kv_mbar_state.phase(); + ++kv_mbar_state; + + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]), + kv_state); + + // S * V matmul for sub-tile 0 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]); + uint32_t tmem_O = tmem_O_0; + uint32_t tmem_S = tmem_S_bmm2_0; + uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + +)KERNEL" + R"KERNEL( + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0])); + } + // S * V matmul for sub-tile 1 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]); + uint32_t tmem_O = tmem_O_1; + uint32_t tmem_S = tmem_S_bmm2_1; + uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0])); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_v_empty_mbar[kv_stage])); + // Change the buffer for V + utcmma_smem_desc_V + .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>(); + } + bmm_mbar_state ^= 1; + } else { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]), + empty_mainloop_mbar_state); + empty_mainloop_mbar_state ^= 1; + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0])); + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0])); + } + } + final_stat_mbar_state ^= 1; + __syncwarp(); + + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]), 0); + tmem_free_1sm(num_columns_per_tmem, shared_storage.tmem_base_ptrs); + } + + // thread_specialize_op 24 code + else if (wid == SoftmaxWarps + CorrectionWarps + 1) { + // TMALDG Q, K, V + reg_dealloc<TmaldgWarpRegs>(); + + // Memory barrier states + uint32_t epilogue_state = 1; + PipelineState<stages_q> q_mbar_state(0, 1); // index, state + PipelineState<stages_kv> kv_mbar_state(0, 1); // index, state + PipelineState<2> sts_page_buffer_state(0, 0); // index, state + PipelineState<2> lds_page_buffer_state(0, 0); // index, state + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + + // global_load_shared_store_op 4 decls + + // global_load_shared_store_op 7 decls + + // global_load_shared_store_op 16 decls + if (kv_loop_left_bound < kv_loop_right_bound) { + int kv_loop = kv_loop_left_bound; + + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Load Q sub-tile 0 + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + qTmaTransactionBytes, elect_one); + } + { + uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q + + q_stage * qBufferElems); + uint32_t local_smem_bar_tma_q = + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]); + const uint32_t row_coord = q_row_coord; + + // global_load_shared_store_op 4 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1, + local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1, + row_coord, head_coord_1 + 0, batch_coord_1, + elect_one); + } + } + + // Load K + const int k_stage = kv_mbar_state.index(); + const int k_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]), + k_phase); + + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]), + kTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K + + k_stage * kBufferElems); + uint32_t local_smem_bar_tma_k = + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 7 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1, + local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_k_1, batch_coord_1, + elect_one); + } + } + } // if (kv_loop_left_bound < kv_loop_right_bound) + + if (kv_loop_left_bound < kv_loop_right_bound) { + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Load Q sub-tile 1 + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + qTmaTransactionBytes, elect_one); + } + { + uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q + + q_stage * qBufferElems); + uint32_t local_smem_bar_tma_q = + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]); + const uint32_t row_coord = q_row_coord + TILE_M_1; + + // global_load_shared_store_op 4 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1, + local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1, + row_coord, head_coord_1 + 0, batch_coord_1, + elect_one); + } + } + } // if (kv_loop_left_bound < kv_loop_right_bound) + wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]), + epilogue_state); + epilogue_state ^= 1; + if (kv_loop_left_bound < kv_loop_right_bound) { + int kv_loop = kv_loop_left_bound; + // Load V + const int v_stage = kv_mbar_state.index(); + const int v_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]), + v_phase); + ++kv_mbar_state; + + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]), + vTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V + + v_stage * vBufferElems); + uint32_t local_smem_bar_tma_v = + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 16 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; + i += 128 * CTA_MMA_1) { + utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1, + local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_v_1, batch_coord_1, + elect_one); + } + } + } // if (kv_loop_left_bound < kv_loop_right_bound) + arrive_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0])); + +// Mainloop to load K and V +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound; + kv_loop += 1) { + + // Load K + const int k_stage = kv_mbar_state.index(); + const int k_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]), + k_phase); + +)KERNEL" + R"KERNEL( + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]), + kTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K + + k_stage * kBufferElems); + uint32_t local_smem_bar_tma_k = + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 7 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1, + local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_k_1, batch_coord_1, + elect_one); + } + } + if (kv_loop + 1 < kv_loop_right_bound) { + } + + // Load V + const int v_stage = kv_mbar_state.index(); + const int v_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]), + v_phase); + ++kv_mbar_state; + + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]), + vTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V + + v_stage * vBufferElems); + uint32_t local_smem_bar_tma_v = + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 16 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; + i += 128 * CTA_MMA_1) { + utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1, + local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_v_1, batch_coord_1, + elect_one); + } + } + + ++lds_page_buffer_state; + } + if (kv_loop_left_bound < kv_loop_right_bound) { + ++lds_page_buffer_state; + ++sts_page_buffer_state; + } + __syncwarp(); + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } + } + + // thread_specialize_op 25 code + else if (wid == SoftmaxWarps + CorrectionWarps + 2) { + // TMASTG (epilogue) + reg_dealloc<TmastgWarpRegs>(); + + ElementO *smem_O_0 = shared_storage.smem_O; + ElementO *smem_O_1 = shared_storage.smem_V; + // Memory barrier states + uint32_t epilogue_state = 0; + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]), + epilogue_state); + + // global_store_op 20 decls + +// TMASTG for sub-tile 0 +#pragma unroll + for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]), + epilogue_state); + const uint32_t row_coord = q_row_coord; + uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_0) + i * BMM2_TILE_M; + if (actual_seqlen_q_1 > 0) { + + // global_store_op 20 code + utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO), + row_coord, head_coord_1 + 0, batch_coord_1); + } + } + + tmastg_arrive(); + +// TMASTG for sub-tile 1 +#pragma unroll + for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]), + epilogue_state); + const uint32_t row_coord = q_row_coord + TILE_M_1; + uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_1) + i * BMM2_TILE_M; + if (actual_seqlen_q_1 > 0) { + + // global_store_op 20 code + utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO), + row_coord, head_coord_1 + 0, batch_coord_1); + } + } + tmastg_arrive(); + + tmastg_wait_count<1>(); + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.tma_o_0_empty_mbar[0]))); + + tmastg_wait_count<0>(); + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.epilogue_done_mbar[0]))); + + epilogue_state ^= 1; + + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } // end of persistent loop + } + + // thread_specialize_op 26 code + else if (wid == SoftmaxWarps + CorrectionWarps + 3) { + // Scheduler + reg_dealloc<SchedulerWarpRegs>(); + +#pragma unroll 1 + while (is_valid_tile) { + wait_barrier( + cast_smem_ptr_to_uint( + &shared_storage.read_tile_id_done_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + 16, elect_one); + + if (elect_one) { + get_next_block_id( + tile_id_smem_int_ptr, + cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()])); + } + __syncwarp(); + + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + is_valid_tile = tile_id_and_coord[2] & 1; + } + } +} +)KERNEL"; +inline constexpr size_t sm100_d128_fprop_source_len = sizeof(sm100_d128_fprop_source) - 1; + +inline constexpr const char sm100_d128_fprop_flags[] = R"FLAGS( +--gpu-architecture=sm_100a +--std=c++17 +-w +--define-macro=__CUDACC_RTC__ +-default-device +--use_fast_math +-Xptxas=-maxrregcount=128 +-DCUDA_ENABLE_TENSOR_MEMORY_INTRINSICS=1 +-DCUDA_ENABLE_VIRTCOUNT_INTRINSICS=1 +-DCUDA_ENABLE_TMEM_MANAGEMENT_INTRINSICS=1 +-DCUDA_BLACKWELL_TMA_SWIZZLE_ENABLED=1 +-DCUDA_ENABLE_FLEXIBLE_CLUSTER=1 +-DCUDA_PTX_TCMMA_V2_SUPPORTED=1 +-DCUDA_PTX_TMEM_MANAGEMENT_SUPPORTED=1 +-DCUDA_ENABLE_CLUSTER_MMA_INTRINSICS=1 +-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1 +-DCUTLASS_ENABLE_EXTENDED_PTX=1 +-DCUTLASS_ENABLE_INTERNAL_NVVM=1 +-DCUTLASS_CUDA_INTERNAL_L2_PREFETCH_ENABLED=1 +-DCUTLASS_CUDA_RP2RP_ENABLED=1 +-DCUTLASS_ENABLE_COMPILER_KNOBS=1 +-DCUTLASS_TEST_LEVEL=0 +-DCUTLASS_TEST_ENABLE_CACHED_RESULTS=1 +-DCUTLASS_CONV_UNIT_TEST_RIGOROUS_SIZE_ENABLED=1 +-DCUTLASS_DEBUG_TRACE_LEVEL=0 +-DCUTLASS_VERSIONS_GENERATED +)FLAGS"; +inline constexpr size_t sm100_d128_fprop_flags_len = sizeof(sm100_d128_fprop_flags) - 1; + +} // namespace generated +} // namespace experimental +} // namespace cudnn_frontend +#if defined(_MSC_VER) +#pragma warning(pop) +#endif +#if defined(__clang__) +#pragma clang diagnostic pop +#endif
\ No newline at end of file diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h new file mode 100644 index 0000000..33b9ef2 --- /dev/null +++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h @@ -0,0 +1,3481 @@ +// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: MIT +#pragma once +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverlength-strings" +#endif +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4068) +#endif +namespace cudnn_frontend { +namespace experimental { +namespace generated { +inline constexpr const char sm100_d64_fprop_source[] = + R"KERNEL( + +// receive_op 0 includes +typedef unsigned long long uint64_t; +typedef unsigned int uint32_t; +typedef unsigned short uint16_t; +typedef unsigned char uint8_t; +typedef long long int64_t; +typedef int int32_t; +typedef short int16_t; +typedef signed char int8_t; +typedef unsigned int r32; + +struct CUtensorMap { + alignas(64) uint64_t opaque[16]; +}; + +#define __FLT_MIN__ 1.17549435082228750796873653722224568e-38F +#define __FLT_MAX__ 3.40282346638528859811704183484516925e+38F + +#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__ + +namespace fort { +static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul); +static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT; +static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF; + +#define NAN __int_as_float(0x7fffffff) +#define POS_INFINITY __int_as_float(0x7f800000) +#define NEG_INFINITY __int_as_float(0xff800000) + +typedef uint16_t bfloat16_t; + +#define FORT_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define FORT_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define FORT_DIV_UP(a, b) (((a) + (b) - 1) / (b)) +#define FORT_ROUND_UP(a, b) ((((a) + (b) - 1) / (b)) * (b)) + +typedef struct tensor_descriptor { + static const int MAX_DIMS = 12; + + int64_t num_dims; + int64_t dims[MAX_DIMS]; + int64_t strides[MAX_DIMS]; +} tensor_descriptor; + +typedef struct FastDivisor { + uint32_t val, shr, mul; +} FastDivisor_t; + +inline __device__ void fastDivMod(const FastDivisor_t &d, uint32_t val, + uint32_t &div, uint32_t &mod) { + div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr; + mod = val - div * d.val; +} + +inline __device__ char *get_smem_loc_epilogue_swizzle_128b( + char *smem_addr, int local_block_id, int tid, int local_row, int column, + size_t element_size, int block_size, int row_per_tile) { + if (element_size * block_size == 256) { + // Case 1: 2 * swizzle tile size = block size -> half block per swizzle tile + int swizzle_col = local_row ^ (column % 8); + + // (local_block_id * 2 + (column / 8)) * row_per_tile * 128: gives offset of + // corresponding swizzle tile tid * 128: tid gives number of loads in block + // swizzle_col * 16B: swizzle_col gives transformed column + return smem_addr + + (local_block_id * 2 + (column / 8)) * row_per_tile * 128 + + tid * 128 + swizzle_col * 16; + } else if (element_size * block_size == 128) { + // Case 2: swizzle tile size = block size -> one block per swizzle tile + int swizzle_col = local_row ^ (column % 8); + + // local_block_id * row_per_tile * 128: gives offset of corresponding + // swizzle tile tid * 128: tid gives number of loads in block swizzle_col * + // 16B: swizzle_col gives transformed column + return smem_addr + local_block_id * row_per_tile * 128 + tid * 128 + + swizzle_col * 16; + } else { + // Case 3: swizzle tile size / 2 = block size -> two blocks per swizzle tile + int swizzle_col = local_row ^ ((column + local_block_id * 4) % 8); + + // (local_block_id / 2) * row_per_tile * 128: gives offset of corresponding + // swizzle tile tid * 128: tid gives number of loads in block swizzle_col * + // 16B: swizzle_col gives transformed column + return smem_addr + (local_block_id / 2) * row_per_tile * 128 + tid * 128 + + swizzle_col * 16; + } +} + +inline __device__ static void get_next_block_id(uint32_t result, + uint32_t mbar) { +#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300 + asm volatile("{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::" + "complete_tx::bytes.b128 [%0], [%1];}\n\t" ::"r"(result), + "r"(mbar)); +#else + asm volatile( + "{clusterlaunchcontrol.try_cancel.async.shared::cta.mbarrier::complete_" + "tx::bytes.multicast::cluster::all.b128 [%0], [%1];}\n\t" ::"r"(result), + "r"(mbar)); +#endif +} + +inline __device__ float2 ffma2(const float2 &a, const float2 &b, + const float2 &c) { + uint64_t d; + asm volatile("fma.rn.f32x2 %0, %1, %2, %3;\n" + : "=l"(d) + : "l"(reinterpret_cast<const uint64_t &>(a)), + "l"(reinterpret_cast<const uint64_t &>(b)), + "l"(reinterpret_cast<const uint64_t &>(c))); + return reinterpret_cast<float2 &>(d); +} + +inline __device__ float2 fadd2(const float2 &a, const float2 &b) { + uint64_t c; + asm volatile("add.f32x2 %0, %1, %2;\n" + : "=l"(c) + : "l"(reinterpret_cast<const uint64_t &>(a)), + "l"(reinterpret_cast<const uint64_t &>(b))); + return reinterpret_cast<float2 &>(c); +} + +inline __device__ float2 fmul2(const float2 &a, const float2 &b) { + uint64_t c; + asm volatile("mul.f32x2 %0, %1, %2;\n" + : "=l"(c) + : "l"(reinterpret_cast<const uint64_t &>(a)), + "l"(reinterpret_cast<const uint64_t &>(b))); + return reinterpret_cast<float2 &>(c); +} + +inline __device__ float fmax3(float a, float b, float c) { +#if (__CUDACC_VER_MAJOR__ >= 13) + float d; + asm volatile("max.ftz.f32 %0, %1, %2, %3;\n" + : "=f"(d) + : "f"((a)), "f"((b)), "f"((c))); + return d; +#else + #error "This kernel is not supported for CUDA toolkit version < 13.0" + return 0.0f; +#endif +} + +inline __device__ float row_max_reduction_128_elems(uint32_t reg[128]) { + float tmp_max_0[42]; + float tmp_max_1[14]; + float tmp_max_2[5]; + float tmp_max_3[2]; + +#pragma unroll + for (int i = 0; i < 126; i += 3) { + tmp_max_0[i / 3] = fmax3(reinterpret_cast<float &>(reg[i + 0]), + reinterpret_cast<float &>(reg[i + 1]), + reinterpret_cast<float &>(reg[i + 2])); + } +#pragma unroll + for (int i = 0; i < 42; i += 3) { + tmp_max_1[i / 3] = + fmax3(tmp_max_0[i + 0], tmp_max_0[i + 1], tmp_max_0[i + 2]); + } +#pragma unroll + for (int i = 0; i < 12; i += 3) { + tmp_max_2[i / 3] = + fmax3(tmp_max_1[i + 0], tmp_max_1[i + 1], tmp_max_1[i + 2]); + } + tmp_max_2[4] = + fmax3(tmp_max_1[12], tmp_max_1[13], reinterpret_cast<float &>(reg[126])); + tmp_max_3[0] = fmax3(tmp_max_2[0], tmp_max_2[1], tmp_max_2[2]); + tmp_max_3[1] = + fmax3(tmp_max_2[3], tmp_max_2[4], reinterpret_cast<float &>(reg[127])); + + return fmax3(tmp_max_3[0], tmp_max_3[1], tmp_max_3[1]); +} + +#if __CUDA_ARCH__ >= 900 + +inline __device__ uint32_t elect_one_sync() { + uint32_t pred = 0; + uint32_t laneid = 0; + asm volatile("{\n" + ".reg .b32 %%rx;\n" + ".reg .pred %%px;\n" + " elect.sync %%rx|%%px, %2;\n" + "@%%px mov.s32 %1, 1;\n" + " mov.s32 %0, %%rx;\n" + "}\n" + : "+r"(laneid), "+r"(pred) + : "r"(0xFFFFFFFF)); + return pred; +} + +template <int TARGET_REG_COUNT> inline __device__ void reg_alloc() { + // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's + // VALUE together): 224, 232, 208, 216 + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" + : + : "n"(TARGET_REG_COUNT)); +} + +template <int TARGET_REG_COUNT> inline __device__ void reg_dealloc() { + // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72 + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n" + : + : "n"(TARGET_REG_COUNT)); +} + +inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID, + uint32_t NUM_THREADS) { + asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS)); +} + +inline __device__ void named_barrier_wait(uint32_t BARRIER_ID, + uint32_t NUM_THREADS) { + asm volatile("bar.sync %0, %1;" ::"r"(BARRIER_ID), "r"(NUM_THREADS)); +} + +inline __device__ void tmastg_arrive() { + asm volatile("cp.async.bulk.commit_group;"); +} + +template <int Count> inline __device__ void tmastg_wait_count() { + asm volatile("cp.async.bulk.wait_group.read %0;" : : "n"(Count) : "memory"); +} + +#endif + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 +inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;\n" ::"r"(smem_ptr), + "r"(thread_count)); +} + +inline __device__ void +smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes, + uint32_t pred = 0) { + asm volatile("{\n\t.reg .pred p;" + " \n\tsetp.eq.u32 p, %2, 1;" + " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" + " \n\t}" ::"r"(smem_ptr), + "r"(expected_copy_bytes), "r"(pred)); +} + +inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr, + uint32_t bar_phase) { + uint32_t bar_phase_out; + asm volatile("{\n\t.reg .pred P1;" + " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;" + " \n\tselp.b32 %0, 1, 0, P1; \n\t}" + : "=r"(bar_phase_out) + : "r"(smem_ptr), "r"(bar_phase)); + return bar_phase_out; +} + +inline __device__ void +wait_barrier(uint32_t smem_int_ptr, + int phase_bit) // Current phase bit the barrier waiting to flip +{ + asm volatile("{\n" + ".reg .pred P1;\n" + "LAB_WAIT:\n" + "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n" + "@P1 bra.uni DONE;\n" + "bra.uni LAB_WAIT;\n" + "DONE:\n" + "}\n" ::"r"(smem_int_ptr), + "r"(phase_bit)); +} + +// Barrier arrive on local smem +inline __device__ void arrive_barrier(uint32_t smem_addr) { + asm volatile("{\n\t" + "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t" + "}" + : + : "r"(smem_addr)); +} + +#endif + +// Circular Buffer Index + Associated Phase +// Assumes only one operation possible - i.e., ++ +template <uint32_t Stages_> struct PipelineState { +public: + static constexpr int Stages = Stages_; + + inline __device__ PipelineState(int index, int state) + : state_(state), index_(index) {} + + inline __device__ int phase() const { return state_; } + + inline __device__ int index() const { return index_; } + + inline __device__ void operator++() { + if (Stages > 1) { + ++index_; + if (index_ == Stages) { + index_ = 0; + state_ ^= 1; + } + } else { + state_ ^= 1; + } + } + + int state_; + int index_; +}; + +template <uint64_t MAX_SHIFT_FOR_WS, uint64_t UTCMMA_M, uint64_t UTCMMA_N, + uint64_t B_TRANSPOSE, uint64_t A_TRANSPOSE, uint64_t B_NEGATE, + uint64_t A_NEGATE, uint64_t SRC_B_TYPE, uint64_t SRC_A_TYPE, + uint64_t SPARSE_METADATA_FORMAT, uint64_t ACC_TYPE, + uint64_t SATURATE_ENABLED, uint64_t SPARSE_ENABLED, + uint64_t SPARSE_METADATA_ID2> +inline __device__ constexpr uint64_t build_utcmma_instruction_desc() { + return (static_cast<uint64_t>(0) | (MAX_SHIFT_FOR_WS << 30) | + ((UTCMMA_M >> 5) << 25) | ((UTCMMA_N >> 3) << 17) | + (B_TRANSPOSE << 16) | (A_TRANSPOSE << 15) | (B_NEGATE << 14) | + (A_NEGATE << 13) | (SRC_B_TYPE << 10) | (SRC_A_TYPE << 7) | + (SPARSE_METADATA_FORMAT << 6) | (ACC_TYPE << 4) | + (SATURATE_ENABLED << 3) | (SPARSE_ENABLED << 2) | + (SPARSE_METADATA_ID2 << 0)) + << 32; +} +)KERNEL" + R"KERNEL( + +class Smem_utcmma_descriptor { +public: + inline __device__ Smem_utcmma_descriptor(uint64_t SWIZZLE_MODE, + uint64_t BASE_OFFSET, + uint64_t DESC_VERSION, + uint64_t BYTES_PER_LEADING_DIM, + uint64_t BYTES_PER_STRIDE_DIM) { + // ------------------------------------ + // Setup smem descriptor for operand A: + // ------------------------------------ + // Note 1: SWIZZLE_NONE = 0, SWIZZLE_128B = 2, SWIZZLE_64B = 4, SWIZZLE_32B + // = 6, SWIZZLE_128B_ATOM32B = 1, N/A = 3, N/A = 5, N/A = 7 + const uint64_t SWIZZLE_MODE_IN_BIT_LOCATION = SWIZZLE_MODE + << 61; // bits: 63-61 + + // Note 2: Base offset. Valid only for matrix descriptor 1, 2 or 3, 4 + const uint64_t BASE_OFFSET_IN_BIT_LOCATION = BASE_OFFSET + << 49; // bits 51-49 + + // Note 3: Descriptor version, needs to be set to 1. ??? + const uint64_t DESC_VERSION_IN_BIT_LOCATION = DESC_VERSION + << 46; // bits 48-46 + + // Note 4: Stride dimension byte offset, 16 byte aligned, 4 LSBs not + // included + const uint64_t STRIDE_DIM_BYTE_OFFSET = BYTES_PER_STRIDE_DIM >> 4; + const uint64_t STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION = + STRIDE_DIM_BYTE_OFFSET << 32; // bits 45-32 + + // Note 5: Leading dimension byte offset, 16 byte aligned, 4 LSBs not + // included + const uint64_t LEADING_DIM_BYTE_OFFSET = BYTES_PER_LEADING_DIM >> 4; + const uint64_t LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION = + LEADING_DIM_BYTE_OFFSET << 16; // bits 29-16 + + desc = + (SWIZZLE_MODE_IN_BIT_LOCATION | BASE_OFFSET_IN_BIT_LOCATION | + DESC_VERSION_IN_BIT_LOCATION | STRIDE_DIM_BYTE_OFFSET_IN_BIT_LOCATION | + LEADING_DIM_BYTE_OFFSET_IN_BIT_LOCATION); + } + template <int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void set_smem(uint32_t smem) { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4); + + int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc); + tmp_initial.x = tmp.x; + + max_desc = tmp.x + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1); + } + + template <int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void increment_smem_buffer() { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x += (tmp.x >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1) + : (BYTES_PER_BUFFER >> 4); + } + + template <int BYTES_PER_BUFFER> + inline __device__ void stage_increment_smem_buffer(int stage) { + int2 &tmp_initial = reinterpret_cast<int2 &>(initial_desc); + int2 &tmp = reinterpret_cast<int2 &>(desc); + + tmp.x = tmp_initial.x + (BYTES_PER_BUFFER >> 4) * stage; + } + + template <int BYTES_OFFSET> inline __device__ void add_smem_offset() { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x += (BYTES_OFFSET >> 4); + } + + uint64_t initial_desc; + uint64_t desc; + uint32_t max_desc; +}; + +// Adapted from : +// cta1 utcmma with A and B from smem and C stored in tmem, scale denotes if we +// want to accumulate C or not Something like: Accumulate or overwrite C. 1: +// read C, 0: ignore C [clear accumulators] +inline __device__ void +utcmma_asmem_bsmem_h_cta1(uint64_t sdescA, uint64_t sdescB, uint32_t tmemC, + uint64_t idescE, uint32_t scaleC) { + uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means, + // CUTLASS hardcodes to all zeros + asm volatile("{\n\t" + ".reg .pred p;\n\t" + "setp.ne.b32 p, %4, 0;\n\t" + "tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, {%5, %6, " + "%7, %8}, p; \n\t" + "}\n" + : + : "r"(tmemC), "l"(sdescA), "l"(sdescB), + "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]), + "r"(mask[1]), "r"(mask[2]), "r"(mask[3])); +} + +// cta1 utcmma with A from tmem and B from smem and C stored in tmem, scale +// denotes if we want to accumulate C or not Something like: Accumulate or +// overwrite C. 1: read C, 0: ignore C [clear accumulators] +inline __device__ void +utcmma_atmem_bsmem_h_cta1(uint32_t tmemA, uint64_t sdescB, uint32_t tmemC, + uint64_t idescE, uint32_t scaleC) { + uint32_t mask[4] = {0, 0, 0, 0}; // TODO : Figure out what this mask means, + // CUTLASS hardcodes to all zeros + asm volatile("{\n\t" + ".reg .pred p;\n\t" + "setp.ne.b32 p, %4, 0;\n\t" + "tcgen05.mma.cta_group::1.kind::f16 [%0], [%1], %2, %3, {%5, " + "%6, %7, %8}, p; \n\t" + "}\n" + : + : "r"(tmemC), "r"(tmemA), "l"(sdescB), + "r"(uint32_t(idescE >> 32)), "r"(scaleC), "r"(mask[0]), + "r"(mask[1]), "r"(mask[2]), "r"(mask[3])); +} + +// Check for the utcmma to finish +inline __device__ void umma_arrive(uint32_t bar_intptr) { + asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::" + "cluster.b64 [%0];" ::"r"(bar_intptr)); +} + +inline __device__ uint32_t cast_smem_ptr_to_uint(void const *const ptr) { + return static_cast<uint32_t>(__cvta_generic_to_shared(ptr)); +} + +inline __device__ void fence_view_async_shared(void) { + asm volatile("fence.proxy.async.shared::cta;\n"); +} + +inline __device__ void sts_128(r32 dst, r32 src[4]) { + asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};\n" ::"r"(dst), + "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3])); +} + +inline __device__ void lds_128(r32 dst[4], r32 src) { + asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];\n" + : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]) + : "r"(src)); +} + +inline __device__ void lds_32(r32 dst[1], r32 src) { + asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src)); +} + +inline __device__ void stg_32(void *ptr, r32 val[1]) { + uint32_t *p = reinterpret_cast<uint32_t *>(ptr); + p[0] = val[0]; +} + +inline __device__ void stg_8(void *ptr, r32 val[1]) { + uint8_t *p = reinterpret_cast<uint8_t *>(ptr); + p[0] = reinterpret_cast<const uint8_t &>(val[0]); +} + +inline __device__ void ldg_16(r32 dst[1], const void *ptr, bool pred = true) { + if (pred) { + *reinterpret_cast<uint16_t *>(dst) = + *reinterpret_cast<const uint16_t *>(ptr); + } else { + *reinterpret_cast<uint16_t *>(dst) = 0; + } +} + +inline __device__ void ldg_8(r32 dst[1], const void *ptr, bool pred = true) { + if (pred) { + *reinterpret_cast<uint8_t *>(dst) = *reinterpret_cast<const uint8_t *>(ptr); + } else { + *reinterpret_cast<uint8_t *>(dst) = 0; + } +} + +inline __device__ void ldg_16_reg(r32 dst[1], const void *ptr, + bool pred = true) { + if (pred) { + uint16_t tmp = *reinterpret_cast<const uint16_t *>(ptr); + asm volatile("{\nmov.b32 %0, {%1, %1};\n}\n" : "=r"(dst[0]) : "h"(tmp)); + } else { + dst[0] = 0; + } +} + +inline __device__ void ldg_8_reg(r32 dst[1], const void *ptr, + bool pred = true) { + if (pred) { + uint8_t tmp_val = *reinterpret_cast<const uint8_t *>(ptr); + uint8_t *tmp_ptr = reinterpret_cast<uint8_t *>(dst); + tmp_ptr[0] = tmp_ptr[1] = tmp_ptr[2] = tmp_ptr[3] = tmp_val; + } else { + dst[0] = 0; + } +} + +// Forward (non-ReLU) Activations +// Backward (non-ReLU) Activations +// Forward ReLU activations +// Relu helper function: clip the lower part +// Relu helper function: clip the upper part +// Forward ReLU: clip only lower part +// Forward ReLU: clip lower part and upper part +// Forward ReLU: clip only lower part, but add slope to lower clip +// Forward ReLU: clip lower part and upper part, but add slope to lower clip +#if __CUDA_ARCH__ >= 900 +#endif + +// optimization opportunity exists here +inline __device__ void fp32x2_to_fp16x2(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n" + : "=r"(dst[0]) + : "r"(src[1]), "r"(src[0])); +} + +inline __device__ void fp32x2_to_fp16x2_relu(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.relu.f16x2.f32 %0, %1, %2;\n" + : "=r"(dst[0]) + : "r"(src[1]), "r"(src[0])); +} + +inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n" + : "=r"(dst[0]) + : "r"(src[1]), "r"(src[0])); +} + +// mma_pipeline_op 1 includes +typedef struct AttentionDescriptor { + // Input parameters + // b - batch + // q_h - num heads of q/dq/o/do + // k_h - num heads of k/dk + // v_h - num heads of v/dv + // s_q - max sequence length of q + // s_kv - max sequence length of kv + // d - hidden dim (head dim) + uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v; + uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv; +} AttentionDescriptor_t; + + +inline __device__ void fence_view_async_tmem_load() { + asm volatile("{\n\ttcgen05.wait::ld.sync.aligned; \n}" ::); +} + +inline __device__ void fence_view_async_tmem_store() { + asm volatile("{\n\ttcgen05.wait::st.sync.aligned; \n}" ::); +} + +inline __device__ void tmem_allocate_1sm(uint32_t num_columns, + uint32_t smem_addr) { + asm volatile( + "tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"( + smem_addr), + "r"(num_columns)); +} + +inline __device__ void tmem_free_1sm(uint32_t num_columns, uint32_t tmem_addr) { + asm volatile( + "{\n\ttcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1; \n\t}" ::"r"( + tmem_addr), + "r"(num_columns)); +} + +inline __device__ void tmem_release_allocation_lock_1sm() { +)KERNEL" + R"KERNEL( + asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;" ::); +} + +///////////////////////////////// +/// TMEM STTM related instructions +///////////////////////////////// + +// 32 data path lanes, 32-bit pattern, repeated 128 times +// 32 data path lanes, 32-bit pattern, repeated 64 times +// 32 data path lanes, 32-bit pattern, repeated 32 times +inline __device__ void sttm_32dp32bit_x32(uint32_t dst, r32 src[32]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x32.b32" + "[%0]," + "{%1, %2, %3, %4," + "%5, %6, %7, %8," + "%9, %10, %11, %12," + "%13, %14, %15, %16," + "%17, %18, %19, %20," + "%21, %22, %23, %24," + "%25, %26, %27, %28," + "%29, %30, %31, %32};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]), + "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]), + "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]), + "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15]), + "r"(src[16]), "r"(src[17]), "r"(src[18]), "r"(src[19]), + "r"(src[20]), "r"(src[21]), "r"(src[22]), "r"(src[23]), + "r"(src[24]), "r"(src[25]), "r"(src[26]), "r"(src[27]), + "r"(src[28]), "r"(src[29]), "r"(src[30]), "r"(src[31])); +} + +// 32 data path lanes, 32-bit pattern, repeated 16 times +inline __device__ void sttm_32dp32bit_x16(uint32_t dst, r32 src[16]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x16.b32" + "[%0]," + "{%1, %2, %3, %4," + "%5, %6, %7, %8," + "%9, %10, %11, %12," + "%13, %14, %15, %16};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]), + "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7]), + "r"(src[8]), "r"(src[9]), "r"(src[10]), "r"(src[11]), + "r"(src[12]), "r"(src[13]), "r"(src[14]), "r"(src[15])); +} + +// 32 data path lanes, 32-bit pattern, repeated 8 times +inline __device__ void sttm_32dp32bit_x8(uint32_t dst, r32 src[8]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x8.b32" + "[%0]," + "{%1, %2, %3, %4," + "%5, %6, %7, %8};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3]), + "r"(src[4]), "r"(src[5]), "r"(src[6]), "r"(src[7])); +} + +// 32 data path lanes, 32-bit pattern, repeated 4 times +// 32 data path lanes, 32-bit pattern, repeated 2 times +inline __device__ void sttm_32dp32bit_x2(uint32_t dst, r32 src[2]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x2.b32" + "[%0]," + "{%1, %2};\n" + : + : "r"(dst), "r"(src[0]), "r"(src[1])); +} + +// 32 data path lanes, 32-bit pattern, repeated 1 times +inline __device__ void sttm_32dp32bit_x1(uint32_t dst, r32 src[1]) { + asm volatile("tcgen05.st.sync.aligned.32x32b.x1.b32" + "[%0]," + "{%1};\n" + : + : "r"(dst), "r"(src[0])); +} + +///////////////////////////////// +/// TMEM LDTM related instructions +///////////////////////////////// + +// 32 data path lanes, 32-bit pattern, repeated 128 times +// 32 data path lanes, 32-bit pattern, repeated 64 times +// 32 data path lanes, 32-bit pattern, repeated 32 times +inline __device__ void ldtm_32dp32bit_x32(r32 dst[32], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x32.b32" + "{%0, %1, %2, %3," + "%4, %5, %6, %7," + "%8, %9, %10, %11," + "%12, %13, %14, %15," + "%16, %17, %18, %19," + "%20, %21, %22, %23," + "%24, %25, %26, %27," + "%28, %29, %30, %31}," + "[%32];\n" + : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]), + "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7]), + "=r"(dst[8]), "=r"(dst[9]), "=r"(dst[10]), "=r"(dst[11]), + "=r"(dst[12]), "=r"(dst[13]), "=r"(dst[14]), "=r"(dst[15]), + "=r"(dst[16]), "=r"(dst[17]), "=r"(dst[18]), "=r"(dst[19]), + "=r"(dst[20]), "=r"(dst[21]), "=r"(dst[22]), "=r"(dst[23]), + "=r"(dst[24]), "=r"(dst[25]), "=r"(dst[26]), "=r"(dst[27]), + "=r"(dst[28]), "=r"(dst[29]), "=r"(dst[30]), "=r"(dst[31]) + : "r"(src_addr)); +} + +// 32 data path lanes, 32-bit pattern, repeated 16 times +// 32 data path lanes, 32-bit pattern, repeated 8 times +inline __device__ void ldtm_32dp32bit_x8(r32 dst[8], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32" + "{%0, %1, %2, %3," + "%4, %5, %6, %7}," + "[%8];\n" + : "=r"(dst[0]), "=r"(dst[1]), "=r"(dst[2]), "=r"(dst[3]), + "=r"(dst[4]), "=r"(dst[5]), "=r"(dst[6]), "=r"(dst[7]) + : "r"(src_addr)); +} + +// 32 data path lanes, 32-bit pattern, repeated 4 times +// 32 data path lanes, 32-bit pattern, repeated 2 times +inline __device__ void ldtm_32dp32bit_x2(r32 dst[2], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x2.b32" + "{%0, %1}," + "[%2];\n" + : "=r"(dst[0]), "=r"(dst[1]) + : "r"(src_addr)); +} + +// 32 data path lanes, 32-bit pattern, repeated 1 times +inline __device__ void ldtm_32dp32bit_x1(r32 dst[1], uint32_t src_addr) { + asm volatile("tcgen05.ld.sync.aligned.32x32b.x1.b32" + "{%0}," + "[%1];\n" + : "=r"(dst[0]) + : "r"(src_addr)); +} + +// CUtensorMap, when issued using bulk copy async functions, are cached in +// constant cache. But the producer kernel may have directly written to global +// memory, without invalidating this constant cache. This acquire fence, +// invalidates the memory address in constant cache, using UTMACCTL.IV. +inline __device__ void tma_descriptor_fence_acquire(CUtensorMap const *p_desc) { +#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123) + uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc); + asm volatile("fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n" + : + : "l"(gmem_int_desc) + : "memory"); + asm volatile("cvta.global.u64 %0, %0;\n" + : + : "l"(gmem_int_desc), "l"(gmem_int_desc) + : "memory"); +#endif +} + +inline __device__ void +utmaldg_4d_tiled(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { +#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300 + asm volatile( + "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::" + "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"( + urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc) + : "memory"); +#else + asm volatile( + "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::" + "bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" ::"r"( + urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1), "l"(mem_desc) + : "memory"); +#endif + } +} + +inline __device__ void +utmaldg_4d_tiled_multicast(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint16_t mcast_mask, const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::" + "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], " + "[%1, {%2, %3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1), "h"(mcast_mask), "l"(mem_desc) + : "memory"); + } +} + +#if (__CUDA_ARCH__ >= 1000) && (CUDACC_VERSION >= 128) +inline __device__ void +utmaldg_4d_tiled_2cta(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile("cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global." + "mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, " + "%3, %4, %5}], [%6], %7;\n" ::"r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK), + "l"(mem_desc) + : "memory"); + } +} + +inline __device__ void +utmaldg_4d_tiled_multicast_2cta(const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint16_t mcast_mask, + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile( + "cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global.mbarrier::" + "complete_tx::bytes.multicast::cluster.L2::cache_hint [%0], [%1, {%2, " + "%3, %4, %5}], [%6], %7, %8;\n" ::"r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), "r"(urb2), "r"(urb3), + "r"(urb4), "r"(urb5), "r"(urb1 & MMA_PEER_BIT_MASK), "h"(mcast_mask), + "l"(mem_desc) + : "memory"); + } +} +#endif + +inline __device__ void +utmastg_atomicAdd_4d_tiled(const void *p_desc, uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + const uint32_t elect_one, + uint64_t mem_desc = MEM_DESC_DEFAULT) { + if (elect_one) { + asm volatile( + "cp.reduce.async.bulk.tensor.4d.global.shared::cta.add.bulk_group [%0, " + "{%1, %2, %3, %4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset) + : "memory"); + } +} + +inline __device__ void utmastg_4d_tiled(const void *p_desc, + uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + uint64_t mem_desc = MEM_DESC_DEFAULT) { + asm volatile( + "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, " + "%4}], [%5];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(smem_offset) + : "memory"); +} + +inline __device__ void utmastg_5d_tiled(const void *p_desc, + uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + int32_t urb4, // lean_tile_id + uint64_t mem_desc = MEM_DESC_DEFAULT) { + asm volatile( + "cp.async.bulk.tensor.5d.global.shared::cta.bulk_group [%0, {%1, %2, %3, " + "%4, %5}], [%6];\n" ::"l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), "r"(urb1), "r"(urb2), "r"(urb3), "r"(urb4), "r"(smem_offset) + : "memory"); +} + +// mma_loop_op 2 includes + +// global_load_shared_store_op 4 includes + +// shared_load_op 5 includes + +// shared_load_op 6 includes + +// global_load_shared_store_op 7 includes + +// mma_op 8 includes + +// global_load_op 10 includes + +// pointwise_calc_op 9 includes + +// softmax_op 12 includes + +// global_store_op 13 includes + +// global_store_op 14 includes + +// shared_load_op 15 includes + +// global_load_shared_store_op 16 includes + +// mma_op 17 includes + +// global_store_op 20 includes + +// output_loop_op 3 includes + +// shared_store_op 18 includes + +// shared_load_op 19 includes +} // namespace fort +)KERNEL" + R"KERNEL( + +// receive_op 0 types +using namespace fort; + +static constexpr int THREADS_PER_WARP_0 = 32; +static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 512 / THREADS_PER_WARP_0); +static constexpr int THREADS_PER_WARP_GROUP_0 = + THREADS_PER_WARP_0 * WARPS_PER_GROUP_0; +static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint) +static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8; +static constexpr int THREADS_PER_GROUP_0 = + WARPS_PER_GROUP_0 * THREADS_PER_WARP_0; + +// mma_pipeline_op 1 types +static constexpr int BYTES_PER_BANK_1 = 16; +static constexpr int BITS_PER_ELEMENT_1 = 16; +static constexpr int ELEMS_PER_BANK_1 = + BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1; +static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8; +static constexpr int BYTES_PER_FP16_1 = 2; +static constexpr int ELEMS_PER_VECTOR_1 = + BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1; +static constexpr int BITS_PER_ACC_1 = 32; +static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8; +static constexpr int TILE_M_1 = 128; +static constexpr int TILE_N_1 = 128; +static constexpr int TILE_K_1 = 64; +static constexpr int TILE_O_1 = FORT_MIN(TILE_K_1, 128); +static constexpr int TILE_V_1 = TILE_K_1; +static constexpr int TILE_DV_1 = FORT_MIN(TILE_K_1, 128); +static constexpr int WARP_TILE_M_1 = 16; +static constexpr int WARP_TILE_N_1 = 16; +static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1; +static constexpr int WARPS_M_1 = 64 / 16; +static constexpr int WARPS_N_1 = 16 / 16; +static constexpr int WARPS_K_1 = 16 / 16; +static constexpr int STAGES_1 = 1; +static constexpr int GROUPS_M_1 = 1; +static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1; +static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1; +static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1; +static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1; +static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1; +static constexpr int WARP_REGS_1 = TILE_N_1; +static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1; +static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1; +static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1; +static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16; +static constexpr int REGS_dQ_1 = TILE_O_1 / 16; +static constexpr int REGS_O_1 = REGS_K_1 * 1; + +static constexpr int CGA_M_1 = 1; +static constexpr int CGA_N_1 = 1; +static constexpr int CTA_MMA_1 = 1; +static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4; +static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1; + +static constexpr int CTA_TILE_M_1 = TILE_M_1; +static constexpr int CTA_TILE_N_1 = 64; +static constexpr int CTA_TILE_K_1 = 128; + +static constexpr float ln2 = 0.6931471805599453094f; +static constexpr float inv_ln2 = 1.4426950408889634074f; + +static constexpr uint32_t SchedulerPipelineStageCount = 1; +static constexpr uint32_t AccumulatorPipelineStageCount = 1; +static constexpr uint32_t SmemPipelineStageCount = 1; +static constexpr uint32_t num_columns_per_tmem = 512; +static constexpr uint32_t columns_per_allocation_slice = 32; +static constexpr int stages_q = 2; +static constexpr int stages_kv = 2 * CTA_MMA_1; +static constexpr int Tiles_Q = 2; + +static constexpr int SoftmaxWarpGroups = 2; +static constexpr int CorrectionWarpGroups = 1; +static constexpr int SoftmaxWarps = SoftmaxWarpGroups * 4; +static constexpr int CorrectionWarps = 4; + +static constexpr int MmaWarpRegs = 40; // warp 12 +static constexpr int TmaldgWarpRegs = 40; // warp 13 +static constexpr int TmastgWarpRegs = 40; // warp 14 +static constexpr int SchedulerWarpRegs = 40; // warp 15 +static constexpr int CorrectionWarpRegs = 88; // warps 8-11 +static constexpr int SoftmaxWarpRegs = 192; // warps 0-7 + +static constexpr int threads_per_warp = 32; +static constexpr int warps_per_group = 4; +static constexpr int threads_per_group = threads_per_warp * warps_per_group; +static constexpr int threads_per_cta = + threads_per_warp * (warps_per_group + SoftmaxWarps + CorrectionWarps); + +static constexpr int BUFFERS_Q = stages_q; +static constexpr int BUFFERS_K = stages_kv; +static constexpr int BUFFERS_V = stages_kv; +static constexpr int BUFFERS_S = stages_kv; + +using ElementQ = fort::bfloat16_t; +using ElementK = fort::bfloat16_t; +using ElementV = fort::bfloat16_t; +using ElementS = fort::bfloat16_t; +using ElementO = fort::bfloat16_t; +using ElementAccumulator = float; + +static constexpr int BYTES_PER_ELEMENT = 2; +static constexpr int BYTES_PER_ACC = 4; + +static constexpr int BMM1_TILE_M = TILE_M_1; +static constexpr int BMM1_TILE_N = 128; +static constexpr int BMM1_TILE_K = 64; + +static constexpr int BMM2_TILE_M = TILE_M_1; +static constexpr int BMM2_TILE_N = 64; +static constexpr int BMM2_TILE_K = 128; + +static constexpr uint32_t qBufferElems = BMM1_TILE_M * BMM1_TILE_K; +static constexpr uint32_t kBufferElems = BMM1_TILE_N * BMM1_TILE_K / CTA_MMA_1; +static constexpr uint32_t vBufferElems = BMM2_TILE_N * BMM2_TILE_K / CTA_MMA_1; +static constexpr uint32_t oBufferElems = + FORT_MAX(8, BMM2_TILE_M) * (BMM2_TILE_N + 0); +static constexpr uint32_t sBufferElems = FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N; + +static constexpr uint32_t qTmaTransactionBytes = + qBufferElems * sizeof(ElementQ) * CTA_MMA_1; +static constexpr uint32_t kTmaTransactionBytes = + kBufferElems * sizeof(ElementK) * CTA_MMA_1; +static constexpr uint32_t vTmaTransactionBytes = + vBufferElems * sizeof(ElementV) * CTA_MMA_1; + +static constexpr int UTCMMA_TILE_M = 128; +static constexpr int UTCMMA_TILE_N = 128; +static constexpr int UTCMMA_TILE_K = 32 / BYTES_PER_ELEMENT; + +static constexpr int BMM1_XMMAS_K = BMM1_TILE_K / UTCMMA_TILE_K; +static constexpr int BMM2_XMMAS_K = BMM2_TILE_K / UTCMMA_TILE_K; +static constexpr int BYTES_PER_MMA_K = UTCMMA_TILE_K * BYTES_PER_ELEMENT; + +static constexpr int SMEM_BUFFER_SIZE_Q = + BMM1_TILE_M * BMM1_TILE_K * BYTES_PER_ELEMENT; +static constexpr int SMEM_BUFFER_SIZE_K = + BMM1_TILE_N * BMM1_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1; +static constexpr int SMEM_BUFFER_SIZE_V = + BMM2_TILE_N * BMM2_TILE_K * BYTES_PER_ELEMENT / CTA_MMA_1; +static constexpr int SMEM_BUFFER_SIZE_S = + FORT_MAX(8, BMM1_TILE_M) * BMM1_TILE_N * BYTES_PER_ELEMENT; + +static constexpr int SOFTMAX_BARRIER = 1; +static constexpr int BAND_BIAS_BARRIER = 5; +static constexpr int TMEM_ALLOC_SOFTMAX_BARRIER = 6; +static constexpr int TMEM_ALLOC_CORRECTION_BARRIER = 7; + +struct SharedStorage { + alignas(1024) ElementQ smem_Q[qBufferElems * stages_q]; + alignas(1024) ElementK smem_K[kBufferElems * stages_kv]; + alignas(1024) ElementV smem_V[vBufferElems * stages_kv]; + alignas(1024) ElementO smem_O[oBufferElems]; + + alignas(16) uint64_t tma_o_0_empty_mbar[1]; + + alignas(16) uint64_t tma_k_empty_mbar[stages_kv]; + alignas(16) uint64_t tma_k_full_mbar[stages_kv]; + + alignas(16) uint64_t tma_v_empty_mbar[stages_kv]; + alignas(16) uint64_t tma_v_full_mbar[stages_kv]; + + alignas(16) uint64_t tma_q_empty_mbar[stages_q]; + alignas(16) uint64_t tma_q_full_mbar[stages_q]; + + alignas(16) uint64_t bmm2_tile0_done_mbar[1]; + alignas(16) uint64_t bmm2_tile0_ready_mbar[2]; + + alignas(16) uint64_t stat_tile0_full_mbar[1]; + alignas(16) uint64_t stat_tile0_empty_mbar[1]; + alignas(16) uint64_t final_stat_tile0_empty_mbar[1]; + alignas(16) uint64_t + tma_o_0_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)]; + alignas(16) uint64_t + tma_o_1_full_mbar[FORT_DIV_UP(TILE_O_1 * sizeof(ElementO), 128)]; + + alignas(16) uint64_t epilogue_done_mbar[1]; + alignas(16) uint64_t tmaldg_tile_started_mbar[1]; + + alignas(16) uint64_t bmm1_tile0_done_mbar[1]; + alignas(16) uint64_t bmm1_tile1_done_mbar[1]; + + alignas(16) uint64_t bmm2_tile1_done_mbar[1]; + alignas(16) uint64_t bmm2_tile1_ready_mbar[2]; + + alignas(16) uint64_t stat_tile1_full_mbar[1]; + alignas(16) uint64_t stat_tile1_empty_mbar[1]; + alignas(16) uint64_t final_stat_tile1_empty_mbar[1]; + + alignas(16) uint64_t empty_mainloop_mbar[1]; + + alignas(16) uint64_t scheduler_mbar[SchedulerPipelineStageCount]; + alignas(16) uint64_t read_tile_id_done_mbar[SchedulerPipelineStageCount]; + alignas(16) uint64_t tmem_dealloc_smem_bar[1]; + + uint32_t tmem_base_ptrs; + + alignas(16) uint32_t tile_id[8 * SchedulerPipelineStageCount]; +}; + +// global_load_shared_store_op 4 types +static constexpr int BITS_PER_ELEMENT_4 = 16; +static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8; +static constexpr int BYTES_PER_ACCESS_4 = 16; +static constexpr int TILE_M_4 = 128; +static constexpr int TILE_N_4 = 64; +static constexpr int BYTES_PER_SMEM_4 = + TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4; + +// shared_load_op 5 types +static constexpr int BITS_PER_ELEMENT_5 = 16; +static constexpr int BYTES_PER_ELEMENT_5 = 2; +static constexpr int BYTES_PER_QUAD_5 = 16; +static constexpr int WARP_TILE_M_5 = 16; +static constexpr int WARP_TILE_N_5 = 16; +static constexpr int TILE_M_5 = 128; +static constexpr int TILE_N_5 = 64; +static constexpr int BYTES_PER_SMEM_5 = + TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5; +static constexpr int WARPS_M_5 = 4; +static constexpr int WARPS_N_5 = 1; +static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5; +static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5; +static constexpr int THREADS_PER_WARP_TILE_M_5 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_5 = 4; +static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5; +static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5; +static constexpr int BYTES_PER_LD_5 = 128; +static constexpr int SWIZZLE_SCALE_5 = + FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4); + +// shared_load_op 6 types +static constexpr int BITS_PER_ELEMENT_6 = 16; +static constexpr int BYTES_PER_ELEMENT_6 = 2; +static constexpr int BYTES_PER_QUAD_6 = 16; +static constexpr int WARP_TILE_M_6 = 16; +static constexpr int WARP_TILE_N_6 = 16; +static constexpr int TILE_M_6 = 128; +static constexpr int TILE_N_6 = 64; +static constexpr int BYTES_PER_SMEM_6 = + TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6; +static constexpr int WARPS_M_6 = 1; +static constexpr int WARPS_N_6 = 1; +static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6; +static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6; +static constexpr int THREADS_PER_WARP_TILE_M_6 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_6 = 4; +static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6; +static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6; +static constexpr int BYTES_PER_LD_6 = 128; +static constexpr int SWIZZLE_SCALE_6 = + FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4); + +// global_load_shared_store_op 7 types +static constexpr int BITS_PER_ELEMENT_7 = 16; +static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8; +static constexpr int BYTES_PER_ACCESS_7 = 16; +static constexpr int TILE_M_7 = 128; +static constexpr int TILE_N_7 = 64; +static constexpr int BYTES_PER_SMEM_7 = + TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7; + +// mma_op 8 types +static constexpr int ROWS_PER_CORE_MATRIX_A_8 = 8; +static constexpr int COLS_PER_CORE_MATRIX_A_8 = 8; +static constexpr int ROWS_PER_CORE_MATRIX_B_8 = 8; +static constexpr int COLS_PER_CORE_MATRIX_B_8 = 8; + +// global_load_op 10 types +static constexpr int BITS_PER_ELEMENT_10 = 32; +static constexpr int BYTES_PER_ELEMENT_10 = 4; +static constexpr int REGISTERS_PER_VECTOR_10 = 1; +static constexpr int REGISTERS_PER_ACCESS_10 = 1; + +// pointwise_calc_op 9 types +static constexpr int WARP_TILE_M_9 = 16; +static constexpr int WARP_TILE_N_9 = 16; +static constexpr int TILE_M_9 = 128; +static constexpr int TILE_N_9 = 128; +static constexpr int WARPS_M_9 = 4; +static constexpr int WARPS_N_9 = 1; +static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9; +static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9; +static constexpr int WARP_REGS_9 = WARP_REGS_1; +static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9; +static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9; + +// mha_mask_op 11 types +static constexpr int WARP_TILE_M_11 = 16; +static constexpr int WARP_TILE_N_11 = 16; +static constexpr int TILE_M_11 = 128; +static constexpr int TILE_N_11 = 128; +static constexpr int WARPS_M_11 = 4; +static constexpr int WARPS_N_11 = 1; +static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11; +static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11; +static constexpr int WARP_REGS_11 = 8; +static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11; +static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11; +inline __device__ bool compute_diagonal_band_mask_11( +)KERNEL" + R"KERNEL( + const int row, const int col, const int actual_seqlen_kv, + const int actual_seqlen_q, const int shift_right_bound, + const int left_bound) { + constexpr bool is_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_right_bound = true; + constexpr bool is_left_bound = false; + constexpr bool need_oob_check = false; + + const int diag = is_bottom_right_alignment + ? row + (actual_seqlen_kv - actual_seqlen_q) + : row; + const int shifted_right_bound = + is_shift_right_bound ? diag + shift_right_bound : diag; + const bool right_bound_mask = + is_right_bound ? col <= shifted_right_bound : true; + const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true; + const bool oob_check = + need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true; + return right_bound_mask && left_bound_mask && oob_check; +} + +// softmax_op 12 types +static constexpr int BYTES_PER_ELEMENT_12 = 2; +static constexpr int WARP_TILE_M_12 = 16; +static constexpr int WARP_TILE_N_12 = 16; +static constexpr int TILE_M_12 = 128; +static constexpr int TILE_N_12 = 128; +static constexpr int WARPS_M_12 = 4; +static constexpr int WARPS_N_12 = 1; +static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12; +static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12; +static constexpr int THREADS_PER_WARP_TILE_M_12 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_12 = 4; +static constexpr int WARP_REGS_12 = 8; +static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12; +static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12; +static constexpr int ROWS_PER_THREAD_12 = + TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12; + +// global_store_op 13 types +static constexpr int BYTES_PER_ELEMENT_13 = 4; +static constexpr int WARP_TILE_M_13 = 16; +static constexpr int WARP_TILE_N_13 = 16; +static constexpr int TILE_M_13 = 128; +static constexpr int TILE_N_13 = 128; +static constexpr int WARPS_M_13 = 4; +static constexpr int WARPS_N_13 = 1; +static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13; +static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13; +static constexpr int THREADS_PER_WARP_TILE_M_13 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_13 = 4; +static constexpr int ROWS_PER_THREAD_13 = + TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13; + +// global_store_op 14 types +static constexpr int BYTES_PER_ELEMENT_14 = 4; +static constexpr int WARP_TILE_M_14 = 16; +static constexpr int WARP_TILE_N_14 = 16; +static constexpr int TILE_M_14 = 128; +static constexpr int TILE_N_14 = 128; +static constexpr int WARPS_M_14 = 4; +static constexpr int WARPS_N_14 = 1; +static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14; +static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14; +static constexpr int THREADS_PER_WARP_TILE_M_14 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_14 = 4; +static constexpr int ROWS_PER_THREAD_14 = + TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14; + +// shared_load_op 15 types +static constexpr int BITS_PER_ELEMENT_15 = 16; +static constexpr int BYTES_PER_ELEMENT_15 = 2; +static constexpr int BYTES_PER_QUAD_15 = 16; +static constexpr int WARP_TILE_M_15 = 16; +static constexpr int WARP_TILE_N_15 = 16; +static constexpr int TILE_M_15 = 128; +static constexpr int TILE_N_15 = 64; +static constexpr int BYTES_PER_SMEM_15 = + TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15; +static constexpr int WARPS_M_15 = 1; +static constexpr int WARPS_N_15 = 1; +static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15; +static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15; +static constexpr int THREADS_PER_WARP_TILE_M_15 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_15 = 4; +static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15; +static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15; +static constexpr int BYTES_PER_LD_15 = 128; +static constexpr int SWIZZLE_SCALE_15 = + FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4); + +// global_load_shared_store_op 16 types +static constexpr int BITS_PER_ELEMENT_16 = 16; +static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8; +static constexpr int BYTES_PER_ACCESS_16 = 16; +static constexpr int TILE_M_16 = 128; +static constexpr int TILE_N_16 = 64; +static constexpr int BYTES_PER_SMEM_16 = + TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16; + +// mma_op 17 types +static constexpr int ROWS_PER_CORE_MATRIX_A_17 = 8; +static constexpr int COLS_PER_CORE_MATRIX_A_17 = 8; +static constexpr int ROWS_PER_CORE_MATRIX_B_17 = 8; +static constexpr int COLS_PER_CORE_MATRIX_B_17 = 8; + +// global_store_op 20 types + +// mma_loop_op 2 types +inline __device__ int2 compute_kv_loop_bounds( + const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE, + const int actual_seqlen_kv, const int actual_seqlen_q, + const int shift_right_bound, const int left_bound) { + constexpr bool is_right_bound = true; + constexpr bool is_right_bound_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_left_bound = false; + constexpr bool is_left_bound_bottom_right_alignment = false; + + const int right_bound_diagonal = + is_right_bound_bottom_right_alignment + ? row_coord + (actual_seqlen_kv - actual_seqlen_q) + : row_coord; + const int shifted_right_bound_diagonal = + is_shift_right_bound ? right_bound_diagonal + shift_right_bound + : right_bound_diagonal; + const int left_bound_diagonal = + is_left_bound_bottom_right_alignment + ? row_coord + (actual_seqlen_kv - actual_seqlen_q) + : row_coord; + + const int kv_loop_left_bound = + is_left_bound + ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE) + : 0; + const int kv_loop_right_bound = + is_right_bound + ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE, + COL_TILE_SIZE), + FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE)) + : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE); + return make_int2(kv_loop_left_bound, kv_loop_right_bound); +} + +// output_loop_op 3 types +static constexpr int BYTES_PER_BANK_3 = 16; +static constexpr int ELEMENTS_PER_VECTOR_3 = + FORT_MIN(64, CTA_TILE_N_1 / N_TILES_PER_OUTPUT_TILE_1); + +// shared_store_op 18 types + +// shared_load_op 19 types +static constexpr int BITS_PER_ELEMENT_19 = 32 * 1; +static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8; +static constexpr int BITS_PER_VECTOR_19 = + BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3; +static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8; +static constexpr int REGISTERS_PER_VECTOR_19 = + BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0; + +// receive_op 0 code + +extern "C" __global__ +__launch_bounds__(512, 1) void cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x64_4x1x1_cga1x1x1_kernel0_0( + const AttentionDescriptor_t attnDesc, const FastDivisor_t num_head_divmod, + const FastDivisor_t l2_minor_divmod, const FastDivisor_t l2_major_divmod, + const FastDivisor_t l2_minor_residual_divmod, const int num_hb_quotient, + const int num_block, const int total_blocks, + __grid_constant__ const CUtensorMap tma_tensor_3, + __grid_constant__ const CUtensorMap tma_tensor_2, float tensor_4, + float tensor_13, void *tensor_7, fort::tensor_descriptor desc_7, + void *tensor_6, fort::tensor_descriptor desc_6, + __grid_constant__ const CUtensorMap tma_tensor_1, + __grid_constant__ const CUtensorMap tma_tensor_5) { + asm volatile(".pragma \"global knob ForceLateCommoning=1\";\n" ::: "memory"); + asm volatile(".pragma \"global knob HoistLate=3\";\n" ::: "memory"); + + extern __shared__ char smem_[]; + SharedStorage &shared_storage = *reinterpret_cast<SharedStorage *>(smem_); + + // receive_op 0 decls + + // mma_pipeline_op 1 decls + const int tid = threadIdx.x % threads_per_group; + const int wid = threadIdx.x / 32; + const int tiw = threadIdx.x % 32; + + const uint32_t elect_one = elect_one_sync(); + + if (wid == 0 && elect_one) { + smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]), + /* 1 tmastg */ 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]), + /* 4 epilogue */ warps_per_group * 32 * CTA_MMA_1); + +#pragma unroll + for (int q_stage = 0; q_stage < stages_q; q_stage++) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + /* 1 tma */ 1); + } + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]), + /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile0_empty_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.final_stat_tile0_empty_mbar[0]), + /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1); + +#pragma unroll + for (int i = 0; i < TILE_O_1 * sizeof(ElementO); i += 128) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]), + /* 1 correction */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]), + /* 1 correction */ warps_per_group * 32); + } + smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]), + /* 1 tmastg */ 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]), 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]), + /* 4 Softmax */ warps_per_group * 32 * 2 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[1]), + /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[1]), + /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0]), + /* 1 mma */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.stat_tile1_empty_mbar[0]), + /* 4 Softmax */ warps_per_group * 32); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.final_stat_tile1_empty_mbar[0]), + /* 4 Correction */ warps_per_group * 32 * CTA_MMA_1); + + smem_bar_init(cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]), + /* 4 Softmax */ warps_per_group * 32 * 1 * CTA_MMA_1); + +#pragma unroll + for (int sched_steps = 0; sched_steps < SchedulerPipelineStageCount; + sched_steps++) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.scheduler_mbar[sched_steps]), + /* 1 sched */ 1); + smem_bar_init(cast_smem_ptr_to_uint( + &shared_storage.read_tile_id_done_mbar[sched_steps]), + (SoftmaxWarps + CorrectionWarps + 1 + 1) * CGA_M_1 * + CGA_N_1 + + CGA_M_1 * CGA_N_1 / CTA_MMA_1); + } + +#pragma unroll + for (int kv_stages = 0; kv_stages < stages_kv; kv_stages++) { + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[kv_stages]), + /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stages]), + /* 1 tma/32 ldgsts */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stages]), + /* 1 tma/32 ldgsts */ 1); + smem_bar_init( + cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[kv_stages]), + /* 1 mma */ CGA_M_1 / CTA_MMA_1 + CGA_N_1 - 1); + } + } + __syncthreads(); + +)KERNEL" + R"KERNEL( + // mma_pipeline_op 1 code + + // mma_loop_op 2 code + uint32_t tile_id_and_coord[8] = {0}; + + int actual_seqlen_kv_1 = attnDesc.s_kv; + int actual_seqlen_q_1 = attnDesc.s_q; + int q_row_coord = 0; + int kv_loop_right_bound, kv_loop_left_bound; + + const int left_bound = 0; + const int shift_right_bound = 0; + + uint32_t tile_idx = blockIdx.x; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + tile_id_and_coord[0] = head_idx; + tile_id_and_coord[1] = batch_idx; + tile_id_and_coord[2] = block; + tile_id_and_coord[3] = 1; + + int head_coord_q_offset_1 = 0; + uint32_t head_coord_1, head_coord_k_1, head_coord_v_1; + uint32_t blocked_row_coord = tile_id_and_coord[2]; + uint32_t head_coord_from_grid_1 = tile_id_and_coord[0]; + uint32_t batch_coord_1 = tile_id_and_coord[1]; + uint32_t lean_tile_id = tile_id_and_coord[0]; + + uint32_t is_valid_tile = true; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + + PipelineState<SchedulerPipelineStageCount> sched_state(0, 0); // index, state + + // thread_specialize_op 21 code + if (wid >= 0 && wid < SoftmaxWarps) { + // Softmax + reg_alloc<SoftmaxWarpRegs>(); + + const uint32_t softmax_gid = wid / 4; + const uint32_t softmax_gid_s_offset = softmax_gid * BMM1_TILE_N; + + uint32_t base_tmem_addr; + named_barrier_wait(TMEM_ALLOC_SOFTMAX_BARRIER, + threads_per_warp * (SoftmaxWarps + 1)); + lds_32(&base_tmem_addr, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + uint32_t tmem_fp32_S = base_tmem_addr + 0 + softmax_gid_s_offset; + uint32_t tmem_fp16_S = + base_tmem_addr + BMM1_TILE_N / 2 + softmax_gid_s_offset; + uint32_t tmem_Stats = base_tmem_addr + 0 + softmax_gid_s_offset; + + r32 reg_8_0[BMM1_TILE_N]; + r32 fp32_stats[2]; + + // Memory barrier states + uint32_t bmm_mbar_state = 0; + uint32_t stat_mbar_state = 0; + uint32_t epilogue_state = 0; + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + int p_row_1 = q_row_coord + softmax_gid * TILE_M_1 + tid; + + // global_load_op 10 decls + r32 reg_10_0[1]; + reg_10_0[0] = reinterpret_cast<const r32 &>(tensor_4); + const int oob_M_10 = 1; + const int oob_N_10 = 1; + + // pointwise_calc_op 9 decls + + // mha_mask_op 11 decls + + // softmax_op 12 decls + r32 reg_12_0[32]; + float2 total_sum = {0.0f, 0.0f}; + float2 local_sum = {0.0f, 0.0f}; + float total_max = NEG_INFINITY; + float actual_total_max = NEG_INFINITY; + static constexpr float inv_ln2_12 = 1.4426950408889634074f; + float total_max_scale_12 = inv_ln2_12; + const float bmm_scale = reinterpret_cast<const float &>(tensor_4); + total_max_scale_12 *= bmm_scale; + + uint64_t &bmm1_mbar = softmax_gid == 0 + ? shared_storage.bmm1_tile0_done_mbar[0] + : shared_storage.bmm1_tile1_done_mbar[0]; + uint64_t &stat_empty_mbar = softmax_gid == 0 + ? shared_storage.stat_tile0_empty_mbar[0] + : shared_storage.stat_tile1_empty_mbar[0]; + uint64_t *bmm2_mbar = softmax_gid == 0 + ? &(shared_storage.bmm2_tile0_ready_mbar[0]) + : &(shared_storage.bmm2_tile1_ready_mbar[0]); + uint64_t *stat_full_mbar = + softmax_gid == 0 ? &(shared_storage.stat_tile0_full_mbar[0]) + : &(shared_storage.stat_tile1_full_mbar[0]); + + epilogue_state ^= 1; + wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]), + epilogue_state); + stat_mbar_state ^= 1; + wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), stat_mbar_state); + +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound; + kv_loop < + kv_loop_right_bound - + FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N); + kv_loop += 1) { + int p_col_1 = kv_loop * TILE_N_1; + { + + wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state); + + r32 stat_reg[BMM1_TILE_N / 64]; +#pragma unroll + for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) { + ldtm_32dp32bit_x32(®_8_0[32 * ldtm_step], + tmem_fp32_S + ldtm_step * 32); + } + constexpr bool use_ldtm_stat_max = false; + + // global_load_op 10 code + + // softmax_op 12 code + float current_max = + row_max_reduction_128_elems(reg_8_0) * total_max_scale_12; + + // Update total max + float total_max_tmp = fmaxf(current_max, total_max); + current_max = total_max; + total_max = total_max_tmp; + + float2 bmm_scale_x_ln2_x2 = + make_float2(total_max_scale_12, total_max_scale_12); + float total_max_scaled = + (total_max == NEG_INFINITY) ? 0.0f : total_max; + float2 minus_scaled_max_x2 = + make_float2(-total_max_scaled, -total_max_scaled); + + static constexpr int kMulPipeCount = 14; // must be multiple of 2 + static constexpr int kSubtractPipeCount = 12; // must be multiple of 2 + static constexpr int kFmaPipeCount = 12; // must be multiple of 2 + static constexpr int kConvertPipeCount = 8; // must be multiple of 2 + static constexpr int kReleasePipeCount = 4; // must be multiple of 2 + static constexpr int kDropoutPipeCount = + 6; // must be multiple of 2 and less than or equal + // kConvertPipeCount + static constexpr int kAddPipeCount = + 4; // must be multiple of 2 and less than kDropoutPipeCount + + // To better overlap EX2 MUFU and emulation, we need to have last + // kE2eRes of every kE2eFreq elements in a row to use emulation while + // the rest go to MUFU. Also, we need to avoid using emulation after + // kE2eLimit elements as it would delay the execution of row sum of + // another softmax warpgroup because of resource contention + static constexpr int kE2eFreq = 16; + static constexpr int kE2eRes = 8; + static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9; + +#pragma unroll + for (int i = 0; i < kFmaPipeCount; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y; + } + + // Optimized version of alpha = __expf(current_max - total_max); + float exp_input = (total_max == NEG_INFINITY) + ? NEG_INFINITY + : (current_max - total_max); + float alpha = exp2f(exp_input); + + // Send stats to correction warp + reinterpret_cast<float &>(fp32_stats[0]) = alpha; + + // STTM + sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar)); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + if (i - kConvertPipeCount == 32) { + sttm_32dp32bit_x16(tmem_fp16_S, ®_12_0[0]); + } + if (i - kConvertPipeCount == 64) { + sttm_32dp32bit_x16(tmem_fp16_S + 16, ®_12_0[16]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0)); + } + + if (i >= kConvertPipeCount) { + fp32x2_to_bf16x2( + ®_12_0[((i - kConvertPipeCount) / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i - kConvertPipeCount])); + } + + reinterpret_cast<float &>(reg_8_0[i + 0]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 0])); + + + if (i + kFmaPipeCount < BMM1_TILE_N) { + float2 in = make_float2( + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]), + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y; + } + + reinterpret_cast<float &>(reg_8_0[i + 1]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 1])); + + if (i == kE2eLimit) { + if (softmax_gid == 1) { + named_barrier_arrive(SOFTMAX_BARRIER, 256); + named_barrier_wait(SOFTMAX_BARRIER + 1, 256); + } + } + } + +#pragma unroll + for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N; + i += 2) { + fp32x2_to_bf16x2(®_12_0[(i / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i])); + } + sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16, + ®_12_0[((BMM1_TILE_N / 64) % 2) * 16]); + fence_view_async_tmem_store(); + arrive_barrier( + cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1))); + + stat_mbar_state ^= 1; + if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state)) { + wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state); + } + + float2 alpha2 = make_float2(alpha, alpha); + float local_row_sum_0 = 0.0f; + total_sum = fmul2(alpha2, total_sum); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + total_sum = fadd2(total_sum, in); + } + if (softmax_gid == 0) { + named_barrier_arrive(SOFTMAX_BARRIER + 1, 256); + named_barrier_wait(SOFTMAX_BARRIER, 256); + } + named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128); + } + bmm_mbar_state ^= 1; + } // End of mainloop +#pragma unroll 1 + for (int kv_loop = FORT_MAX( + kv_loop_right_bound - + FORT_DIV_UP(BMM1_TILE_M * CGA_M_1 * Tiles_Q, BMM1_TILE_N), + kv_loop_left_bound); + kv_loop < kv_loop_right_bound; kv_loop += 1) { + int p_col_1 = kv_loop * TILE_N_1; + { + + wait_barrier(cast_smem_ptr_to_uint(&bmm1_mbar), bmm_mbar_state); + + r32 stat_reg[BMM1_TILE_N / 64]; +#pragma unroll + for (int ldtm_step = 0; ldtm_step < BMM1_TILE_N / 32; ldtm_step++) { + ldtm_32dp32bit_x32(®_8_0[32 * ldtm_step], + tmem_fp32_S + ldtm_step * 32); + } + constexpr bool use_ldtm_stat_max = false; + +)KERNEL" + R"KERNEL( + // global_load_op 10 code + + // mha_mask_op 11 code + + { +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i++) { + int row = p_row_1; + int col = p_col_1 + i; + bool mask = compute_diagonal_band_mask_11( + row, col, actual_seqlen_kv_1, actual_seqlen_q_1, + shift_right_bound, left_bound); + if (!mask) { + reinterpret_cast<float &>(reg_8_0[i]) = tensor_13; + } + } + } + + // softmax_op 12 code + float current_max = + row_max_reduction_128_elems(reg_8_0) * total_max_scale_12; + + // Update total max + float total_max_tmp = fmaxf(current_max, total_max); + current_max = total_max; + total_max = total_max_tmp; + + float2 bmm_scale_x_ln2_x2 = + make_float2(total_max_scale_12, total_max_scale_12); + float total_max_scaled = + (total_max == NEG_INFINITY) ? 0.0f : total_max; + float2 minus_scaled_max_x2 = + make_float2(-total_max_scaled, -total_max_scaled); + + static constexpr int kMulPipeCount = 14; // must be multiple of 2 + static constexpr int kSubtractPipeCount = 12; // must be multiple of 2 + static constexpr int kFmaPipeCount = 12; // must be multiple of 2 + static constexpr int kConvertPipeCount = 8; // must be multiple of 2 + static constexpr int kReleasePipeCount = 4; // must be multiple of 2 + static constexpr int kDropoutPipeCount = + 6; // must be multiple of 2 and less than or equal + // kConvertPipeCount + static constexpr int kAddPipeCount = + 4; // must be multiple of 2 and less than kDropoutPipeCount + + // To better overlap EX2 MUFU and emulation, we need to have last + // kE2eRes of every kE2eFreq elements in a row to use emulation while + // the rest go to MUFU. Also, we need to avoid using emulation after + // kE2eLimit elements as it would delay the execution of row sum of + // another softmax warpgroup because of resource contention + static constexpr int kE2eFreq = 16; + static constexpr int kE2eRes = 8; + static constexpr int kE2eLimit = BMM1_TILE_N / 16 * 9; + +#pragma unroll + for (int i = 0; i < kFmaPipeCount; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + 1]) = out.y; + } + + // Optimized version of alpha = __expf(current_max - total_max); + float exp_input = (total_max == NEG_INFINITY) + ? NEG_INFINITY + : (current_max - total_max); + float alpha = exp2f(exp_input); + + // Send stats to correction warp + reinterpret_cast<float &>(fp32_stats[0]) = alpha; + + // STTM + sttm_32dp32bit_x1(tmem_Stats, &fp32_stats[0]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar)); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + if (i - kConvertPipeCount == 32) { + sttm_32dp32bit_x16(tmem_fp16_S, ®_12_0[0]); + } + if (i - kConvertPipeCount == 64) { + sttm_32dp32bit_x16(tmem_fp16_S + 16, ®_12_0[16]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(bmm2_mbar + 0)); + } + + if (i >= kConvertPipeCount) { + fp32x2_to_bf16x2( + ®_12_0[((i - kConvertPipeCount) / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i - kConvertPipeCount])); + } + + reinterpret_cast<float &>(reg_8_0[i + 0]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 0])); + + + if (i + kFmaPipeCount < BMM1_TILE_N) { + float2 in = make_float2( + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]), + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1])); + float2 out = ffma2(bmm_scale_x_ln2_x2, in, minus_scaled_max_x2); + + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 0]) = out.x; + reinterpret_cast<float &>(reg_8_0[i + kFmaPipeCount + 1]) = out.y; + } + + reinterpret_cast<float &>(reg_8_0[i + 1]) = + exp2f(reinterpret_cast<float &>(reg_8_0[i + 1])); + + if (i == kE2eLimit) { + if (softmax_gid == 1) { + named_barrier_arrive(SOFTMAX_BARRIER, 256); + named_barrier_wait(SOFTMAX_BARRIER + 1, 256); + } + } + } + +#pragma unroll + for (int i = BMM1_TILE_N - kConvertPipeCount; i < BMM1_TILE_N; + i += 2) { + fp32x2_to_bf16x2(®_12_0[(i / 2) % 32], + reinterpret_cast<r32 *>(®_8_0[i])); + } + sttm_32dp32bit_x32(tmem_fp16_S + BMM1_TILE_N / 64 * 16, + ®_12_0[((BMM1_TILE_N / 64) % 2) * 16]); + fence_view_async_tmem_store(); + arrive_barrier( + cast_smem_ptr_to_uint(bmm2_mbar + (BMM1_TILE_N / 64 - 1))); + + stat_mbar_state ^= 1; + if (!smem_bar_peek(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state)) { + wait_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar), + stat_mbar_state); + } + + float2 alpha2 = make_float2(alpha, alpha); + float local_row_sum_0 = 0.0f; + total_sum = fmul2(alpha2, total_sum); + +#pragma unroll + for (int i = 0; i < BMM1_TILE_N; i += 2) { + float2 in = make_float2(reinterpret_cast<float &>(reg_8_0[i + 0]), + reinterpret_cast<float &>(reg_8_0[i + 1])); + total_sum = fadd2(total_sum, in); + } + if (softmax_gid == 0) { + named_barrier_arrive(SOFTMAX_BARRIER + 1, 256); + named_barrier_wait(SOFTMAX_BARRIER, 256); + } + named_barrier_wait(SOFTMAX_BARRIER + 2 + softmax_gid, 128); + } + bmm_mbar_state ^= 1; + } // End of mainloop + + float final_total_sum = total_sum.x + total_sum.y; + + reinterpret_cast<float &>(fp32_stats[0]) = total_max; + reinterpret_cast<float &>(fp32_stats[1]) = final_total_sum; + // STTM + sttm_32dp32bit_x2(tmem_Stats, &fp32_stats[0]); + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(stat_full_mbar)); + + // This portion of the code may seem strange, please read the + // documentation here: + // Function: work_tile_info_from_workid_response, load_query_response + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } // end of persistent loop + } + + // thread_specialize_op 22 code + else if (wid >= SoftmaxWarps && wid < SoftmaxWarps + CorrectionWarps) { + // Correction + reg_dealloc<CorrectionWarpRegs>(); + uint32_t base_tmem_addr; + named_barrier_wait(TMEM_ALLOC_CORRECTION_BARRIER, + threads_per_warp * (CorrectionWarps + 1)); + lds_32(&base_tmem_addr, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + uint32_t tmem_fp32_O_0 = base_tmem_addr + 256; + uint32_t tmem_fp32_O_1 = base_tmem_addr + 384; + uint32_t tmem_Stats_0 = base_tmem_addr + 0; + uint32_t tmem_Stats_1 = base_tmem_addr + 0 + BMM1_TILE_N; + + static constexpr int local_correction_block_size = 16; + static constexpr int local_epilogue_block_size = + 128 / sizeof(ElementO); // hack as only K=128/64 supported. Both can do + // 128B TMASTG. + +)KERNEL" + R"KERNEL( + float amax_s_1 = 0.f; + float amax_o_1 = 0.f; + + // Registers + uint32_t fp32_stats[2]; + uint32_t fp32_O[local_correction_block_size]; + + // Memory barrier states + uint32_t epilogue_state = 0; + uint32_t bmm_mbar_state = 0; + uint32_t stat_mbar_state = 0; + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + + if (kv_loop_left_bound < kv_loop_right_bound) { + // No correction for iter 0 + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile0_ready_mbar[0]))); + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.bmm2_tile1_ready_mbar[0]))); + + { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.stat_tile0_full_mbar[0]), + stat_mbar_state); + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.stat_tile0_empty_mbar[0]))); + } + { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.stat_tile1_full_mbar[0]), + stat_mbar_state); + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.stat_tile1_empty_mbar[0]))); + } + stat_mbar_state ^= 1; + } else { + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.empty_mainloop_mbar[0]))); + } + +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound; + kv_loop += 1) { +#pragma unroll + for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) { + uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1; + uint32_t tmem_fp32_O = + sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1; + + uint64_t &stat_full_mbar = + sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0] + : shared_storage.stat_tile1_full_mbar[0]; + uint64_t &bmm_done_mbar = + sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0] + : shared_storage.bmm2_tile1_done_mbar[0]; + uint64_t *stat_empty_mbar = + sub_tile_id == 0 ? &(shared_storage.stat_tile0_empty_mbar[0]) + : &(shared_storage.stat_tile1_empty_mbar[0]); + uint64_t *bmm_ready_mbar = + sub_tile_id == 0 ? &(shared_storage.bmm2_tile0_ready_mbar[0]) + : &(shared_storage.bmm2_tile1_ready_mbar[0]); + + wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state); + ldtm_32dp32bit_x1(&fp32_stats[0], tmem_Stats); + + float alpha = reinterpret_cast<float &>(fp32_stats[0]); + fence_view_async_tmem_load(); + arrive_barrier(cast_smem_ptr_to_uint(stat_empty_mbar)); + + bool alpha_is_one = (alpha == 1.0f); + bool all_alpha_one = __all_sync(0xFFFFFFFF, alpha_is_one); + + float2 alpha2 = make_float2(alpha, alpha); + + wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state); + + if (!all_alpha_one) { +#pragma unroll + for (int block = 0; block < TILE_O_1 / local_correction_block_size; + block++) { +// LDTM +#pragma unroll + for (int ldtm_step = 0; + ldtm_step < local_correction_block_size / 8; ldtm_step++) { + ldtm_32dp32bit_x8(&fp32_O[8 * ldtm_step], + tmem_fp32_O + + block * local_correction_block_size + + ldtm_step * 8); + } + +#pragma unroll + for (int i = 0; i < local_correction_block_size; i += 2) { + float2 in = + make_float2(reinterpret_cast<float &>(fp32_O[i + 0]), + reinterpret_cast<float &>(fp32_O[i + 1])); + float2 out = fmul2(alpha2, in); + reinterpret_cast<float &>(fp32_O[i + 0]) = out.x; + reinterpret_cast<float &>(fp32_O[i + 1]) = out.y; + } + +#pragma unroll + for (int sttm_step = 0; + sttm_step < local_correction_block_size / 8; sttm_step++) { + sttm_32dp32bit_x8(tmem_fp32_O + + block * local_correction_block_size + + sttm_step * 8, + &fp32_O[8 * sttm_step]); + } + } + } + fence_view_async_tmem_store(); + arrive_barrier(cast_smem_ptr_to_uint(bmm_ready_mbar)); + } + stat_mbar_state ^= 1; + bmm_mbar_state ^= 1; + } // End of mainloop + + // Epilogue + { + epilogue_state ^= 1; + + static constexpr int stg_step = 16 / sizeof(ElementO); + const int local_row = (tid % 8) / 1; + + // global_store_op 13 decls + int oob_M_13 = desc_7.dims[2]; + int row_13 = 0; + char *ptr_13 = + reinterpret_cast<char *>(tensor_7) + + batch_coord_1 * desc_7.strides[0] * BYTES_PER_ELEMENT_13 + + head_coord_1 * desc_7.strides[1] * BYTES_PER_ELEMENT_13 + + row_13 * desc_7.strides[2] * BYTES_PER_ELEMENT_13; + + // global_store_op 14 decls + int oob_M_14 = desc_6.dims[2]; + int row_14 = 0; + char *ptr_14 = + reinterpret_cast<char *>(tensor_6) + + batch_coord_1 * desc_6.strides[0] * BYTES_PER_ELEMENT_14 + + head_coord_1 * desc_6.strides[1] * BYTES_PER_ELEMENT_14 + + row_14 * desc_6.strides[2] * BYTES_PER_ELEMENT_14; + +#pragma unroll + for (int sub_tile_id = 0; sub_tile_id < 2; ++sub_tile_id) { + const int row_coord = q_row_coord + sub_tile_id * TILE_M_1 + tid; + ElementO *smem_O = (sub_tile_id == 0) ? shared_storage.smem_O + : shared_storage.smem_V; + + uint32_t fp32_reg_O[local_epilogue_block_size]; + uint32_t reg_O[local_epilogue_block_size / (4 / sizeof(ElementO))]; + + uint32_t tmem_Stats = sub_tile_id == 0 ? tmem_Stats_0 : tmem_Stats_1; + uint32_t tmem_fp32_O = + sub_tile_id == 0 ? tmem_fp32_O_0 : tmem_fp32_O_1; + + uint64_t &stat_full_mbar = + sub_tile_id == 0 ? shared_storage.stat_tile0_full_mbar[0] + : shared_storage.stat_tile1_full_mbar[0]; + uint64_t &bmm_done_mbar = + sub_tile_id == 0 ? shared_storage.bmm2_tile0_done_mbar[0] + : shared_storage.bmm2_tile1_done_mbar[0]; + uint64_t &stat_empty_mbar = + sub_tile_id == 0 ? shared_storage.stat_tile0_empty_mbar[0] + : shared_storage.stat_tile1_empty_mbar[0]; + uint64_t &final_stat_empty_mbar = + sub_tile_id == 0 ? shared_storage.final_stat_tile0_empty_mbar[0] + : shared_storage.final_stat_tile1_empty_mbar[0]; + + wait_barrier(cast_smem_ptr_to_uint(&stat_full_mbar), stat_mbar_state); + ldtm_32dp32bit_x2(&fp32_stats[0], tmem_Stats); + + float total_max = reinterpret_cast<float &>(fp32_stats[0]) * ln2; + float total_sum = reinterpret_cast<float &>(fp32_stats[1]); + fence_view_async_tmem_load(); + arrive_barrier(cast_smem_ptr_to_uint(&stat_empty_mbar)); + arrive_barrier(cast_smem_ptr_to_uint(&final_stat_empty_mbar)); + + float softmax_stats = + total_sum == 0.f ? NEG_INFINITY : total_max + __logf(total_sum); + + // global_store_op 13 code + if (row_coord < actual_seqlen_q_1) { + stg_32(ptr_13 + + row_coord * desc_7.strides[2] * BYTES_PER_ELEMENT_13, + &(reinterpret_cast<uint32_t &>(total_max))); + } + + // global_store_op 14 code + if (row_coord < actual_seqlen_q_1) { + stg_32(ptr_14 + + row_coord * desc_6.strides[2] * BYTES_PER_ELEMENT_14, + &(reinterpret_cast<uint32_t &>(total_sum))); + } + + float threshold_beta = (total_sum == 0.f) ? 0.f : 1.f / total_sum; + float beta = threshold_beta; + + float2 beta2 = make_float2(threshold_beta, threshold_beta); + + wait_barrier(cast_smem_ptr_to_uint(&bmm_done_mbar), bmm_mbar_state); + + if (sub_tile_id == 0) { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_o_0_empty_mbar[0]), + epilogue_state); + } +#pragma unroll + for (int block = 0; block < TILE_O_1 / local_epilogue_block_size; + block++) { + { +#pragma unroll + for (int ldtm_step = 0; + ldtm_step < local_epilogue_block_size / 32; ldtm_step++) { + ldtm_32dp32bit_x32(&fp32_reg_O[32 * ldtm_step], + tmem_fp32_O + + block * local_epilogue_block_size + + ldtm_step * 32); + } + } + +#pragma unroll + for (int i = 0; i < local_epilogue_block_size; i += 2) { + float2 in = + make_float2(reinterpret_cast<float &>(fp32_reg_O[i + 0]), + reinterpret_cast<float &>(fp32_reg_O[i + 1])); + float2 out = fmul2(beta2, in); + reinterpret_cast<float &>(fp32_reg_O[i + 0]) = out.x; + reinterpret_cast<float &>(fp32_reg_O[i + 1]) = out.y; + } + +// general_data_type_cast code +#pragma unroll + for (int i = 0; i < local_epilogue_block_size; i += 2) { + fp32x2_to_bf16x2(®_O[i / 2], &fp32_reg_O[i]); + } + +#pragma unroll + for (int i = 0; i < local_epilogue_block_size / stg_step; i++) { + char *smem_loc = get_smem_loc_epilogue_swizzle_128b( + reinterpret_cast<char *>(smem_O), block, tid, local_row, i, + sizeof(ElementO), local_epilogue_block_size, TILE_M_1); +)KERNEL" + R"KERNEL( + sts_128(cast_smem_ptr_to_uint(smem_loc), + reinterpret_cast<r32 *>(®_O[i * 4])); + } + + uint64_t *tma_o_full_mbar = + sub_tile_id == 0 ? &(shared_storage.tma_o_0_full_mbar[block]) + : &(shared_storage.tma_o_1_full_mbar[block]); + fence_view_async_shared(); + arrive_barrier(cast_smem_ptr_to_uint(tma_o_full_mbar)); + } + } + stat_mbar_state ^= 1; + bmm_mbar_state ^= 1; + } // Epilogue end + + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } // end of persistent loop + arrive_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0])); + } + + // thread_specialize_op 23 code + else if (wid == SoftmaxWarps + CorrectionWarps) { + // MMA + reg_dealloc<MmaWarpRegs>(); + tmem_allocate_1sm(num_columns_per_tmem, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + tmem_release_allocation_lock_1sm(); + __syncwarp(); + named_barrier_arrive(TMEM_ALLOC_SOFTMAX_BARRIER, + threads_per_warp * (SoftmaxWarps + 1)); + named_barrier_arrive(TMEM_ALLOC_CORRECTION_BARRIER, + threads_per_warp * (CorrectionWarps + 1)); + uint32_t base_tmem_addr; + lds_32(&base_tmem_addr, + cast_smem_ptr_to_uint(&shared_storage.tmem_base_ptrs)); + + uint32_t tmem_S_acc_0 = base_tmem_addr + 0; + uint32_t tmem_S_acc_1 = base_tmem_addr + BMM1_TILE_N; + + uint32_t tmem_S_bmm2_0 = base_tmem_addr + BMM1_TILE_N / 2; + uint32_t tmem_S_bmm2_1 = base_tmem_addr + 3 * BMM1_TILE_N / 2; + + uint32_t tmem_O_0 = base_tmem_addr + 256; + uint32_t tmem_O_1 = base_tmem_addr + 384; + + // Memory barrier states + uint32_t bmm_mbar_state = 0; + uint32_t final_stat_mbar_state = 1; + uint32_t empty_mainloop_mbar_state = 0; + + PipelineState<stages_kv> kv_mbar_state(0, 0); // index, state + PipelineState<stages_q> q_mbar_state(0, 0); // index, state + + // mma_op 8 decls + constexpr uint64_t utcmma_instruction_desc_8 = + build_utcmma_instruction_desc<0, // max shift for WS + TILE_M_1 * CTA_MMA_1, TILE_N_1, + 0, // Transpose for B + 0, // Transpose for A + 0, // Negate for B + 0, // Negate for A + 1, // Data type B + 1, // Data type A + 0, // sparse meta data format + 1, // Acc type fp32 + 0, // saturate disable + 0, // sparse disable + 0 // sparse meta data id2 ??? + >(); + // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k + Smem_utcmma_descriptor utcmma_smem_desc_Q_0(2, 0, 1, 16, + ROWS_PER_CORE_MATRIX_A_8 * 128); + Smem_utcmma_descriptor utcmma_smem_desc_K(2, 0, 1, 16, + ROWS_PER_CORE_MATRIX_B_8 * 128); + + utcmma_smem_desc_Q_0.set_smem<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>( + cast_smem_ptr_to_uint(shared_storage.smem_Q)); + utcmma_smem_desc_K.set_smem<SMEM_BUFFER_SIZE_K, BUFFERS_K>( + cast_smem_ptr_to_uint(shared_storage.smem_K)); + + // mma_op 17 decls + constexpr uint64_t utcmma_instruction_desc_17 = + build_utcmma_instruction_desc<0, // max shift for WS + TILE_M_1 * CTA_MMA_1, TILE_O_1, + 1, // Transpose for B + 0, // Transpose for A + 0, // Negate for B + 0, // Negate for A + 1, // Data type B + 1, // Data type A + 0, // sparse meta data format + 1, // Acc type fp32 + 0, // saturate disable + 0, // sparse disable + 0 // sparse meta data id2 ??? + >(); + // Swizzle mode, base smem offset, desc type, bytes per leading dim, tile k + Smem_utcmma_descriptor utcmma_smem_desc_V( + 2, 0, 1, TILE_O_1 / ROWS_PER_CORE_MATRIX_B_17 <= 8 ? 0 : TILE_N_1 * 128, + COLS_PER_CORE_MATRIX_B_17 * 128); + + utcmma_smem_desc_V.set_smem<SMEM_BUFFER_SIZE_V, BUFFERS_V>( + cast_smem_ptr_to_uint(shared_storage.smem_V)); + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + //---------------------------------------------------------// + //------------------- MMA Pipeline Begin ------------------// + //---------------------------------------------------------// + + if (kv_loop_left_bound < kv_loop_right_bound) { + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.final_stat_tile0_empty_mbar[0]), + final_stat_mbar_state); + + const int kv_stage = kv_mbar_state.index(); + const int kv_state = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[kv_stage]), + kv_state); + + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Q * K matmul for sub-tile 0 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_0; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0])); + } // elect_one + } // if (kv_loop_left_bound < kv_loop_right_bound) + if (kv_loop_left_bound < kv_loop_right_bound) { + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.final_stat_tile1_empty_mbar[0]), + final_stat_mbar_state); + + const int kv_stage = kv_mbar_state.index(); + const int kv_state = kv_mbar_state.phase(); + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Q * K matmul for sub-tile 1 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_1; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, +)KERNEL" + R"KERNEL( + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for K + utcmma_smem_desc_K + .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + const int kv_stage = kv_mbar_state.index(); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_k_empty_mbar[kv_stage])); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0])); + } // elect_one + } + +// Mainloop +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound; + kv_loop += 1) { + const int kv_stage = kv_mbar_state.index(); + const uint32_t kv_state = kv_mbar_state.phase(); + + ++kv_mbar_state; + + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]), + kv_state); + + // S * V matmul for sub-tile 0 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]); + uint32_t tmem_O = tmem_O_0; + uint32_t tmem_S = tmem_S_bmm2_0; + uint32_t scaleC = kv_loop > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0])); + } + + wait_barrier( + cast_smem_ptr_to_uint( + &shared_storage.tma_k_full_mbar[kv_mbar_state.index()]), + kv_mbar_state.phase()); + + // Q * K matmul for sub-tile 0 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_0; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile0_done_mbar[0])); + } // elect_one + + // S * V matmul for sub-tile 1 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]); + uint32_t tmem_O = tmem_O_1; + uint32_t tmem_S = tmem_S_bmm2_1; + uint32_t scaleC = kv_loop > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0])); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_v_empty_mbar[kv_stage])); + // Change the buffer for V + utcmma_smem_desc_V + .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>(); + } + bmm_mbar_state ^= 1; + + // Q * K matmul for sub-tile 1 + { + Smem_utcmma_descriptor &utcmma_smem_desc_Q = utcmma_smem_desc_Q_0; + uint32_t tmem_acc = tmem_S_acc_1; + + // mma_op 8 code +#pragma unroll + for (int k = 0; k < BMM1_XMMAS_K; ++k) { + if (elect_one) + utcmma_asmem_bsmem_h_cta1(utcmma_smem_desc_Q.desc, + utcmma_smem_desc_K.desc, tmem_acc, + utcmma_instruction_desc_8, (k > 0)); + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_Q.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_Q.add_smem_offset<128 * BMM1_TILE_M>(); + } else { + utcmma_smem_desc_Q.add_smem_offset<BYTES_PER_MMA_K>(); + } + if ((k % 4) == ((BMM1_XMMAS_K - 1) % 4)) { + utcmma_smem_desc_K.add_smem_offset<-BYTES_PER_MMA_K *( + (BMM1_XMMAS_K - 1) % 4)>(); + utcmma_smem_desc_K + .add_smem_offset<128 * BMM1_TILE_N / CTA_MMA_1>(); + } else { + utcmma_smem_desc_K.add_smem_offset<BYTES_PER_MMA_K>(); + } + } + utcmma_smem_desc_Q.add_smem_offset<-128 * BMM1_TILE_M * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + utcmma_smem_desc_K.add_smem_offset<-128 * BMM1_TILE_N / CTA_MMA_1 * + FORT_MAX(BMM1_XMMAS_K / 4, 1)>(); + // change the smem buffer for K + utcmma_smem_desc_K + .increment_smem_buffer<SMEM_BUFFER_SIZE_K, BUFFERS_K>(); + // change the smem buffer for Q + utcmma_smem_desc_Q + .increment_smem_buffer<SMEM_BUFFER_SIZE_Q, BUFFERS_Q>(); + const int kv_stage = kv_mbar_state.index(); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_k_empty_mbar[kv_stage])); + } + + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm1_tile1_done_mbar[0])); + } // elect_one + } + if (kv_loop_left_bound < kv_loop_right_bound) { + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[1])); + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[0])); + } + const int kv_stage = kv_mbar_state.index(); + const uint32_t kv_state = kv_mbar_state.phase(); + ++kv_mbar_state; + + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[kv_stage]), + kv_state); + + // S * V matmul for sub-tile 0 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_ready_mbar[0]); + uint32_t tmem_O = tmem_O_0; + uint32_t tmem_S = tmem_S_bmm2_0; + uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + +)KERNEL" + R"KERNEL( + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0])); + } + // S * V matmul for sub-tile 1 + { + uint32_t bmm2_ready_mbar = + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_ready_mbar[0]); + uint32_t tmem_O = tmem_O_1; + uint32_t tmem_S = tmem_S_bmm2_1; + uint32_t scaleC = kv_loop_right_bound > kv_loop_left_bound + 1; + + // mma_op 17 code +#pragma unroll + for (int k = 0; k < BMM2_XMMAS_K; ++k) { + if (k % (BMM2_XMMAS_K / (BMM1_TILE_N / 64)) == 0) { + wait_barrier(bmm2_ready_mbar + + (k / (BMM2_XMMAS_K / (BMM1_TILE_N / 64))) * 8, + bmm_mbar_state); + } + if (elect_one) + utcmma_atmem_bsmem_h_cta1( + tmem_S + k * (UTCMMA_TILE_K / (4 / BYTES_PER_ELEMENT)), + utcmma_smem_desc_V.desc, tmem_O, utcmma_instruction_desc_17, + scaleC || k > 0); + if (k == BMM2_XMMAS_K - 1) { + utcmma_smem_desc_V + .add_smem_offset<-UTCMMA_TILE_K * 128 * (BMM2_XMMAS_K - 1)>(); + } else { + utcmma_smem_desc_V.add_smem_offset<UTCMMA_TILE_K * 128>(); + } + } + if (elect_one) + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0])); + if (elect_one) + umma_arrive(cast_smem_ptr_to_uint( + &shared_storage.tma_v_empty_mbar[kv_stage])); + // Change the buffer for V + utcmma_smem_desc_V + .increment_smem_buffer<SMEM_BUFFER_SIZE_V, BUFFERS_V>(); + } + bmm_mbar_state ^= 1; + } else { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.empty_mainloop_mbar[0]), + empty_mainloop_mbar_state); + empty_mainloop_mbar_state ^= 1; + if (elect_one) { + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile0_done_mbar[0])); + umma_arrive( + cast_smem_ptr_to_uint(&shared_storage.bmm2_tile1_done_mbar[0])); + } + } + final_stat_mbar_state ^= 1; + __syncwarp(); + + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmem_dealloc_smem_bar[0]), 0); + tmem_free_1sm(num_columns_per_tmem, shared_storage.tmem_base_ptrs); + } + + // thread_specialize_op 24 code + else if (wid == SoftmaxWarps + CorrectionWarps + 1) { + // TMALDG Q, K, V + reg_dealloc<TmaldgWarpRegs>(); + + // Memory barrier states + uint32_t epilogue_state = 1; + PipelineState<stages_q> q_mbar_state(0, 1); // index, state + PipelineState<stages_kv> kv_mbar_state(0, 1); // index, state + PipelineState<2> sts_page_buffer_state(0, 0); // index, state + PipelineState<2> lds_page_buffer_state(0, 0); // index, state + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + + // global_load_shared_store_op 4 decls + + // global_load_shared_store_op 7 decls + + // global_load_shared_store_op 16 decls + if (kv_loop_left_bound < kv_loop_right_bound) { + int kv_loop = kv_loop_left_bound; + + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Load Q sub-tile 0 + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + qTmaTransactionBytes, elect_one); + } + { + uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q + + q_stage * qBufferElems); + uint32_t local_smem_bar_tma_q = + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]); + const uint32_t row_coord = q_row_coord; + + // global_load_shared_store_op 4 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1, + local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1, + row_coord, head_coord_1 + 0, batch_coord_1, + elect_one); + } + } + + // Load K + const int k_stage = kv_mbar_state.index(); + const int k_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]), + k_phase); + + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]), + kTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K + + k_stage * kBufferElems); + uint32_t local_smem_bar_tma_k = + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 7 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1, + local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_k_1, batch_coord_1, + elect_one); + } + } + } // if (kv_loop_left_bound < kv_loop_right_bound) + + if (kv_loop_left_bound < kv_loop_right_bound) { + const int q_stage = q_mbar_state.index(); + const int q_phase = q_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_q_empty_mbar[q_stage]), + q_phase); + ++q_mbar_state; + + // Load Q sub-tile 1 + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]), + qTmaTransactionBytes, elect_one); + } + { + uint32_t local_smem_q = cast_smem_ptr_to_uint(shared_storage.smem_Q + + q_stage * qBufferElems); + uint32_t local_smem_bar_tma_q = + cast_smem_ptr_to_uint(&shared_storage.tma_q_full_mbar[q_stage]); + const uint32_t row_coord = q_row_coord + TILE_M_1; + + // global_load_shared_store_op 4 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_3, local_smem_q + i * TILE_M_1, + local_smem_bar_tma_q, i / BYTES_PER_ELEMENT_1, + row_coord, head_coord_1 + 0, batch_coord_1, + elect_one); + } + } + } // if (kv_loop_left_bound < kv_loop_right_bound) + wait_barrier(cast_smem_ptr_to_uint(&shared_storage.epilogue_done_mbar[0]), + epilogue_state); + epilogue_state ^= 1; + if (kv_loop_left_bound < kv_loop_right_bound) { + int kv_loop = kv_loop_left_bound; + // Load V + const int v_stage = kv_mbar_state.index(); + const int v_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]), + v_phase); + ++kv_mbar_state; + + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]), + vTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V + + v_stage * vBufferElems); + uint32_t local_smem_bar_tma_v = + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 16 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; + i += 128 * CTA_MMA_1) { + utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1, + local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_v_1, batch_coord_1, + elect_one); + } + } + } // if (kv_loop_left_bound < kv_loop_right_bound) + arrive_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0])); + +// Mainloop to load K and V +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound + 1; kv_loop < kv_loop_right_bound; + kv_loop += 1) { + + // Load K + const int k_stage = kv_mbar_state.index(); + const int k_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_k_empty_mbar[k_stage]), + k_phase); + +)KERNEL" + R"KERNEL( + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]), + kTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_k = cast_smem_ptr_to_uint(shared_storage.smem_K + + k_stage * kBufferElems); + uint32_t local_smem_bar_tma_k = + cast_smem_ptr_to_uint(&shared_storage.tma_k_full_mbar[k_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 7 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_tensor_2, local_smem_k + i * TILE_N_1, + local_smem_bar_tma_k, i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_k_1, batch_coord_1, + elect_one); + } + } + if (kv_loop + 1 < kv_loop_right_bound) { + } + + // Load V + const int v_stage = kv_mbar_state.index(); + const int v_phase = kv_mbar_state.phase(); + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_v_empty_mbar[v_stage]), + v_phase); + ++kv_mbar_state; + + if (true) { + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]), + vTmaTransactionBytes, elect_one); + } + { + const int lds_page_buffer_state_idx = lds_page_buffer_state.index(); + uint32_t local_smem_v = cast_smem_ptr_to_uint(shared_storage.smem_V + + v_stage * vBufferElems); + uint32_t local_smem_bar_tma_v = + cast_smem_ptr_to_uint(&shared_storage.tma_v_full_mbar[v_stage]); + const uint32_t p_col_coord = kv_loop * TILE_N_1; + + // global_load_shared_store_op 16 code +#pragma unroll + for (int i = 0; i < TILE_O_1 * BYTES_PER_ELEMENT_1; + i += 128 * CTA_MMA_1) { + utmaldg_4d_tiled(&tma_tensor_1, local_smem_v + i * TILE_N_1, + local_smem_bar_tma_v, 0 + i / BYTES_PER_ELEMENT_1, + p_col_coord, head_coord_v_1, batch_coord_1, + elect_one); + } + } + + ++lds_page_buffer_state; + } + if (kv_loop_left_bound < kv_loop_right_bound) { + ++lds_page_buffer_state; + ++sts_page_buffer_state; + } + __syncwarp(); + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } + } + + // thread_specialize_op 25 code + else if (wid == SoftmaxWarps + CorrectionWarps + 2) { + // TMASTG (epilogue) + reg_dealloc<TmastgWarpRegs>(); + + ElementO *smem_O_0 = shared_storage.smem_O; + ElementO *smem_O_1 = shared_storage.smem_V; + // Memory barrier states + uint32_t epilogue_state = 0; + +// Persistent loop over tiles +#pragma unroll 1 + while (is_valid_tile) { + if (elect_one) { + arrive_barrier(cast_smem_ptr_to_uint( + &(shared_storage.read_tile_id_done_mbar[sched_state.index()]))); + } + + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tmaldg_tile_started_mbar[0]), + epilogue_state); + + // global_store_op 20 decls + +// TMASTG for sub-tile 0 +#pragma unroll + for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_o_0_full_mbar[i / 128]), + epilogue_state); + const uint32_t row_coord = q_row_coord; + uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_0) + i * BMM2_TILE_M; + if (actual_seqlen_q_1 > 0) { + + // global_store_op 20 code + utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO), + row_coord, head_coord_1 + 0, batch_coord_1); + } + } + + tmastg_arrive(); + +// TMASTG for sub-tile 1 +#pragma unroll + for (int i = 0; i < BMM2_TILE_N * sizeof(ElementO); i += 128) { + wait_barrier( + cast_smem_ptr_to_uint(&shared_storage.tma_o_1_full_mbar[i / 128]), + epilogue_state); + const uint32_t row_coord = q_row_coord + TILE_M_1; + uint32_t smem_loc = cast_smem_ptr_to_uint(smem_O_1) + i * BMM2_TILE_M; + if (actual_seqlen_q_1 > 0) { + + // global_store_op 20 code + utmastg_4d_tiled(&tma_tensor_5, smem_loc, 0 + i / sizeof(ElementO), + row_coord, head_coord_1 + 0, batch_coord_1); + } + } + tmastg_arrive(); + + tmastg_wait_count<1>(); + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.tma_o_0_empty_mbar[0]))); + + tmastg_wait_count<0>(); + arrive_barrier( + cast_smem_ptr_to_uint(&(shared_storage.epilogue_done_mbar[0]))); + + epilogue_state ^= 1; + + // Get next tile id + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + uint32_t tile_idx = tile_id_and_coord[0]; + uint32_t bidhb, l2_mod; + uint32_t block = 0, bidhb_residual = 0; + + fastDivMod(l2_major_divmod, tile_idx, bidhb, l2_mod); + if (bidhb < num_hb_quotient) { + { + fastDivMod(l2_minor_divmod, l2_mod, block, bidhb_residual); + } + } else { + { + fastDivMod(l2_minor_residual_divmod, l2_mod, block, bidhb_residual); + } + } + + int bidhb_actual = bidhb * l2_minor_divmod.val + bidhb_residual; + uint32_t batch_idx, head_idx; + fastDivMod(num_head_divmod, bidhb_actual, batch_idx, head_idx); + block = num_block - 1 - block; + + lean_tile_id = tile_id_and_coord[0]; + + blocked_row_coord = block + 0; + head_coord_from_grid_1 = (head_idx) + 0; + batch_coord_1 = batch_idx; + is_valid_tile = tile_id_and_coord[2] & 1; + + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + q_row_coord = (blocked_row_coord * Tiles_Q * BMM1_TILE_M); + int2 kv_loop_bounds = compute_kv_loop_bounds( + q_row_coord, BMM1_TILE_M * Tiles_Q * CGA_M_1, TILE_N_1, + actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + kv_loop_left_bound = kv_loop_bounds.x; + kv_loop_right_bound = kv_loop_bounds.y; + if (actual_seqlen_q_1 == 0 || q_row_coord >= actual_seqlen_q_1) { + kv_loop_right_bound = kv_loop_left_bound; + } + } // end of persistent loop + } + + // thread_specialize_op 26 code + else if (wid == SoftmaxWarps + CorrectionWarps + 3) { + // Scheduler + reg_dealloc<SchedulerWarpRegs>(); + +#pragma unroll 1 + while (is_valid_tile) { + wait_barrier( + cast_smem_ptr_to_uint( + &shared_storage.read_tile_id_done_mbar[sched_state.index()]), + sched_state.phase()); + uint32_t tile_id_smem_int_ptr = cast_smem_ptr_to_uint( + &shared_storage.tile_id[sched_state.index() * 8]); + + smem_bar_set_transaction_count( + cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + 16, elect_one); + + if (elect_one) { + get_next_block_id( + tile_id_smem_int_ptr, + cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()])); + } + __syncwarp(); + + wait_barrier(cast_smem_ptr_to_uint( + &shared_storage.scheduler_mbar[sched_state.index()]), + sched_state.phase()); + lds_128(tile_id_and_coord, tile_id_smem_int_ptr); + ++sched_state; + + is_valid_tile = tile_id_and_coord[2] & 1; + } + } +} +)KERNEL"; +inline constexpr size_t sm100_d64_fprop_source_len = sizeof(sm100_d64_fprop_source) - 1; + +inline constexpr const char sm100_d64_fprop_flags[] = R"FLAGS( +--gpu-architecture=sm_100a +--std=c++17 +-w +--define-macro=__CUDACC_RTC__ +-default-device +--use_fast_math +-Xptxas=-maxrregcount=128 +-DCUDA_ENABLE_TENSOR_MEMORY_INTRINSICS=1 +-DCUDA_ENABLE_VIRTCOUNT_INTRINSICS=1 +-DCUDA_ENABLE_TMEM_MANAGEMENT_INTRINSICS=1 +-DCUDA_BLACKWELL_TMA_SWIZZLE_ENABLED=1 +-DCUDA_ENABLE_FLEXIBLE_CLUSTER=1 +-DCUDA_PTX_TCMMA_V2_SUPPORTED=1 +-DCUDA_PTX_TMEM_MANAGEMENT_SUPPORTED=1 +-DCUDA_ENABLE_CLUSTER_MMA_INTRINSICS=1 +-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1 +-DCUTLASS_ENABLE_EXTENDED_PTX=1 +-DCUTLASS_ENABLE_INTERNAL_NVVM=1 +-DCUTLASS_CUDA_INTERNAL_L2_PREFETCH_ENABLED=1 +-DCUTLASS_CUDA_RP2RP_ENABLED=1 +-DCUTLASS_ENABLE_COMPILER_KNOBS=1 +-DCUTLASS_TEST_LEVEL=0 +-DCUTLASS_TEST_ENABLE_CACHED_RESULTS=1 +-DCUTLASS_CONV_UNIT_TEST_RIGOROUS_SIZE_ENABLED=1 +-DCUTLASS_DEBUG_TRACE_LEVEL=0 +-DCUTLASS_VERSIONS_GENERATED +)FLAGS"; +inline constexpr size_t sm100_d64_fprop_flags_len = sizeof(sm100_d64_fprop_flags) - 1; + +} // namespace generated +} // namespace experimental +} // namespace cudnn_frontend +#if defined(_MSC_VER) +#pragma warning(pop) +#endif +#if defined(__clang__) +#pragma clang diagnostic pop +#endif
\ No newline at end of file diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h new file mode 100644 index 0000000..d588ce6 --- /dev/null +++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h @@ -0,0 +1,1762 @@ +// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: MIT +#pragma once +// Suppress clang warning for overlength strings (concatenated result may exceed 65536) +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverlength-strings" +#endif + +// Suppress MSVC warning C4068 (unknown pragma) if clang pragmas are seen +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4068) +#endif + +namespace cudnn_frontend { +namespace experimental { +namespace generated { + +inline constexpr const char d128_fprop_source[] = + R"KERNEL( +//receive_op 0 includes +typedef unsigned long long uint64_t; +typedef unsigned int uint32_t; +typedef unsigned short uint16_t; +typedef unsigned char uint8_t; +typedef long long int64_t; +typedef int int32_t; +typedef short int16_t; +typedef signed char int8_t; +typedef unsigned int r32; + +struct CUtensorMap { + alignas(64) uint64_t opaque[16]; +}; + +#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__ + +namespace fort { + static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul); + static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT; + static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF; + +#define NEG_INFINITY __int_as_float(0xff800000) + + typedef uint16_t half_t; + typedef uint16_t bfloat16_t; + +#define FORT_MIN(a,b) ((a) < (b) ? (a) : (b)) +#define FORT_MAX(a,b) ((a) > (b) ? (a) : (b)) +#define FORT_DIV_UP(a,b) (((a) + (b) - 1) / (b)) +#define FORT_ROUND_UP(a,b) ((((a) + (b) - 1) / (b)) * (b)) + + typedef struct tensor_descriptor { + static const int MAX_DIMS = 12; + + int64_t num_dims; + int64_t dims[MAX_DIMS]; + int64_t strides[MAX_DIMS]; + } tensor_descriptor; + + typedef struct FastDivisor { + uint32_t val, shr, mul; + } FastDivisor_t; + + inline __device__ void + fastDivMod(const FastDivisor_t &d, uint32_t val, uint32_t &div, uint32_t &mod) { + div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr; + mod = val - div * d.val; + } + __device__ __inline__ void cfence() {} + +#if __CUDA_ARCH__ >= 900 + + inline __device__ uint32_t elect_one_sync() { + uint32_t pred = 0; + uint32_t laneid = 0; + asm volatile( + "{\n" + ".reg .b32 %%rx;\n" + ".reg .pred %%px;\n" + " elect.sync %%rx|%%px, %2;\n" + "@%%px mov.s32 %1, 1;\n" + " mov.s32 %0, %%rx;\n" + "}\n" : "+r"(laneid), "+r"(pred) : "r"(0xFFFFFFFF)); + return pred; + } + + template<int TARGET_REG_COUNT> + inline __device__ void reg_alloc() { + // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's VALUE together): 224, 232, 208, 216 + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT)); + } + + template<int TARGET_REG_COUNT> + inline __device__ void reg_dealloc() { + // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72 + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT)); + } + + inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID, uint32_t NUM_THREADS) { + asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS)); + } + + inline __device__ void named_barrier_wait(uint32_t BARRIER_ID, uint32_t NUM_THREADS) { + asm volatile("bar.sync %0, %1;" :: "r"(BARRIER_ID), "r"(NUM_THREADS)); + } + + inline __device__ void tmastg_arrive() { + asm volatile("cp.async.bulk.commit_group;"); + } + + inline __device__ void tmastg_wait() { + asm volatile("cp.async.bulk.wait_group.read %0;" : :"n"(0):"memory"); + } + +#endif + +#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900 + inline __device__ void warpgroup_arrive() { + asm volatile("wgmma.fence.sync.aligned;\n" ::: "memory"); + } + template <int N> inline __device__ void warpgroup_wait() { + asm volatile("wgmma.wait_group.sync.aligned %0;\n" ::"n"(N) : "memory"); + } + inline __device__ void warpgroup_commit() { + asm volatile("wgmma.commit_group.sync.aligned;\n" ::: "memory"); + } + template <typename T> + inline __device__ T &__wgmma_fence_operand(T &®) { + asm volatile("" : "+r"(reg)::"memory"); + return reg; + } +#endif + +#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900 + inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) { + asm volatile ("mbarrier.init.shared::cta.b64 [%0], %1;\n" :: "r"(smem_ptr), "r"(thread_count)); + } + + inline __device__ void smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes, uint32_t pred = 0) { + asm volatile("{\n\t.reg .pred p;" + " \n\tsetp.eq.u32 p, %2, 1;" + " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" + " \n\t}" :: "r"(smem_ptr), "r"(expected_copy_bytes), "r"(pred)); + } + + inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr, uint32_t bar_phase) { + uint32_t bar_phase_out; + asm volatile("{\n\t.reg .pred P1;" + " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;" + " \n\tselp.b32 %0, 1, 0, P1; \n\t}" :"=r" (bar_phase_out):"r"(smem_ptr),"r"(bar_phase)); + return bar_phase_out; + } + + inline __device__ void smem_bar_wait(uint32_t smem_ptr, uint32_t bar_phase) { + + uint32_t large_val = 0x989680; + asm volatile("{\n\t.reg .pred P1;" + " \n\tLAB_WAIT:" + " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1, %2;" + " \n\t@P1 bra.uni DONE;" + " \n\tbra.uni LAB_WAIT;" + " \n\tDONE:" + " \n\t}" :: "r"(smem_ptr),"r"(bar_phase), "r"(large_val)); + + } + + inline __device__ + void + wait_barrier(uint32_t smem_int_ptr, + int phase_bit) // Current phase bit the barrier waiting to flip + { + asm volatile( + "{\n" + ".reg .pred P1;\n" + "LAB_WAIT:\n" + "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n" + "@P1 bra.uni DONE;\n" + "bra.uni LAB_WAIT;\n" + "DONE:\n" + "}\n" + :: "r"(smem_int_ptr), + "r"(phase_bit)); + } + + inline __device__ void smem_bar_arrive(uint32_t smem_ptr) { + asm volatile("{\n\t.reg .b64 state;" + " \n\tmbarrier.arrive.shared::cta.b64 state, [%0];" + " \n\t}" :: "r"(smem_ptr)); + } + + // Barrier arrive on local smem + inline __device__ + void arrive_barrier(uint32_t smem_addr) { + asm volatile( + "{\n\t" + "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t" + "}" + : + : "r"(smem_addr)); + } + +#endif + + extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *ptr); + + inline __device__ uint32_t get_smem_pointer(const void *ptr) { + return __nvvm_get_smem_pointer(const_cast<void *>(ptr)); + } + + extern "C" __device__ inline void *__nv_cvta_shared_to_generic_impl(size_t __ptr) { + return (void *)(void __attribute__((address_space(3))) *)__ptr; + } + inline __device__ void *set_smem_pointer(uint32_t ptr) { + return __nv_cvta_shared_to_generic_impl(ptr); + } + + inline __device__ uint32_t + cast_smem_ptr_to_uint(void const* const ptr) { + return static_cast<uint32_t>(__cvta_generic_to_shared(ptr)); + } + + inline __device__ void stsm_x4(r32 dst, r32 src[4]) { + asm volatile("stmatrix.sync.aligned.m8n8.x4.shared.b16 [%0], {%1, %2, %3, %4};\n" ::"r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3])); + } + + inline __device__ void fence_view_async_shared(void){ + asm volatile ("fence.proxy.async.shared::cta;\n"); + } + + inline __device__ void sts_32(r32 dst, r32 src[1]) { + asm volatile("st.shared.b32 [%0], %1;\n" :: "r"(dst), "r"(src[0])); + } + + inline __device__ void lds_32(r32 dst[1], r32 src) { + asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src)); + } + + inline __device__ void stg_32(void *ptr, r32 val[1]) { + uint32_t *p = reinterpret_cast<uint32_t *>(ptr); + p[0] = val[0]; + } + + // Forward ReLU activations + + inline __device__ uint32_t fp32_exp2(uint32_t in) { + uint32_t out; + asm volatile("ex2.approx.ftz.f32 %0, %1;\n" : "=r"(out) : "r"(in)); + return out; + } + + inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n" : "=r"(dst[0]) : "r"(src[1]), "r"(src[0])); + } + + inline __device__ void bf16x2_to_fp32x2(r32 dst[2], const r32 src[1]) { + asm volatile( \ + "{\n" \ + " .reg .b16 lo, hi;\n" \ + " mov.b32 {lo, hi}, %2;\n" \ + " mov.b32 %0, {0, lo};\n" \ + " mov.b32 %1, {0, hi};\n" \ + "}\n" : "=r"(dst[0]), "=r"(dst[1]) : "r"(src[0])); + } + + //mma_pipeline_op 1 includes + typedef struct AttentionDescriptor { + // Input parameters + // b - batch + // q_h - num heads of q/dq/o/do + // k_h - num heads of k/dk + // v_h - num heads of v/dv + // s_q - max sequence length of q + // s_kv - max sequence length of kv + // d - hidden dim (head dim) + uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v; + uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv; + } AttentionDescriptor_t; + + // CUtensorMap, when issued using bulk copy async functions, are cached in constant cache. + // But the producer kernel may have directly written to global memory, without invalidating this constant cache. + // This acquire fence, invalidates the memory address in constant cache, using UTMACCTL.IV. + inline __device__ void tma_descriptor_fence_acquire( + CUtensorMap const* p_desc + ) { +#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123) + uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc); + asm volatile ( + "fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n" + : + : "l"(gmem_int_desc) + : "memory"); + asm volatile ( + "cvta.global.u64 %0, %0;\n" + : + : "l"(gmem_int_desc), "l"(gmem_int_desc) + : "memory"); +#endif + } + + inline __device__ void utmaldg_4d_tiled ( + const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT + ) { + if (elect_one) { +#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300 + asm volatile( + "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" :: + "r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb2), + "r"(urb3), + "r"(urb4), + "r"(urb5), + "r"(urb1), + "l"(mem_desc) : "memory" + ); +#else + asm volatile( + "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" :: + "r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb2), + "r"(urb3), + "r"(urb4), + "r"(urb5), + "r"(urb1), + "l"(mem_desc) : "memory" + ); +#endif + } + } + + inline __device__ void utmastg_4d_tiled( + const void *p_desc, + uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + uint64_t mem_desc = MEM_DESC_DEFAULT + ) { + asm volatile( + "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, %4}], [%5];\n" :: + "l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), + "r"(urb1), + "r"(urb2), + "r"(urb3), + "r"(smem_offset) : "memory" + ); + } + + inline __device__ void ldgdepbar() { + asm volatile("cp.async.commit_group;\n" ::); + } + + template<int STAGES> + inline __device__ void depbar() { + asm volatile("cp.async.wait_group %0;\n" :: "n"(STAGES)); + } + + //mma_loop_op 2 includes + + //global_load_shared_store_op 4 includes + + // shared_load_op 5 includes + + // shared_load_op 6 includes + + //global_load_shared_store_op 7 includes + + //mma_op 8 includes +)KERNEL" + R"KERNEL( +// === Section: GMMA Operations === + inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) { + __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b); + warpgroup_commit(); + } + + // === Section: GMMA Operations === + inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) { + __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b); + } + +#define BMM_S_GMMA bf16gmma_fp32_64x128x16_TN_asmem_bsmem +#define BMM_S_GMMA_ISB bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb +#define BMM_S_GMMA_C0 bf16gmma_fp32_64x128x16_TN_asmem_bsmem_ignoreC + + //pointwise_calc_op 9 includes + + //global_load_op 10 includes + + //softmax_op 12 includes + + // global_store_op 13 includes + + // global_store_op 14 includes + + // shared_load_op 15 includes + + //global_load_shared_store_op 16 includes + + //mma_op 17 includes + inline __device__ void bf16gmma_fp32_64x128x16_TT_arf_bsmem_isb(const r32 a[4], const uint64_t &desc_b, r32 acc[64]) { + __wgmma_mma_async_bf16(64, 128, 16, false, false, true, false, true, acc, a, desc_b); + warpgroup_commit(); + } + + inline __device__ void bf16gmma_fp32_64x128x16_TT_arf_bsmem(const r32 a[4], const uint64_t &desc_b, r32 acc[64]) { + __wgmma_mma_async_bf16(64, 128, 16, false, false, true, false, true, acc, a, desc_b); + } + +#define BMM_O_GMMA bf16gmma_fp32_64x128x16_TT_arf_bsmem +#define BMM_O_GMMA_ISB bf16gmma_fp32_64x128x16_TT_arf_bsmem_isb +#define BMM_O_GMMA_C0 bf16gmma_fp32_64x128x16_TT_arf_bsmem_ignoreC + + // global_store_op 20 includes + + //output_loop_op 3 includes + + // shared_store_op 18 includes + + // shared_load_op 19 includes +} // namespace fort + +//receive_op 0 types +using namespace fort; + +static constexpr int THREADS_PER_WARP_0 = 32; +static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 384 / THREADS_PER_WARP_0); +static constexpr int THREADS_PER_WARP_GROUP_0 = THREADS_PER_WARP_0 * WARPS_PER_GROUP_0; +static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint) +static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8; +static constexpr int THREADS_PER_GROUP_0 = WARPS_PER_GROUP_0 * THREADS_PER_WARP_0; + +// mma_pipeline_op 1 types +static constexpr int BYTES_PER_BANK_1 = 16; +static constexpr int BITS_PER_ELEMENT_1 = 16; +static constexpr int ELEMS_PER_BANK_1 = BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1; +static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8; +static constexpr int BYTES_PER_FP16_1 = 2; +static constexpr int ELEMS_PER_VECTOR_1 = BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1; +static constexpr int BITS_PER_ACC_1 = 32; +static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8; +static constexpr int TILE_M_1 = 64; +static constexpr int TILE_N_1 = 128; +static constexpr int TILE_K_1 = 128; +static constexpr int TILE_O_1 = 128; +static constexpr int TILE_V_1 = TILE_K_1; +static constexpr int TILE_DV_1 = 128; +static constexpr int WARP_TILE_M_1 = 16; +static constexpr int WARP_TILE_N_1 = 16; +static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1; +static constexpr int WARPS_M_1 = 64 / 16; +static constexpr int WARPS_N_1 = 16 / 16; +static constexpr int WARPS_K_1 = 16 / 16; +static constexpr int STAGES_1 = 1; +static constexpr int GROUPS_M_1 = 1; +static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1; +static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1; +static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1; +static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1; +static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1; +static constexpr int WARP_REGS_1 = 8; +static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1; +static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1; +static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1; +static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16; + +static constexpr int REGS_dQ_1 = TILE_O_1 / 16; +static constexpr int REGS_O_1 = 8; + +static constexpr int CGA_M_1 = 1; +static constexpr int CGA_N_1 = 1; +static constexpr int CTA_MMA_1 = 1; +static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4; +static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1; + +static constexpr int CTA_TILE_M_1 = TILE_M_1 * GROUPS_M_1; +static constexpr int CTA_TILE_N_1 = 128; +static constexpr int CTA_TILE_K_1 = 128; +static constexpr int BUFFERS_Q_1 = 2; +static constexpr int BUFFERS_K_1 = 2; +static constexpr int BUFFERS_V_1 = 2; +static constexpr int BUFFERS_O_1 = 1; +static constexpr int BUFFERS_D_1 = 1; +static constexpr int SMEM_Q_1 = TILE_M_1 * TILE_K_1 * BYTES_PER_ELEMENT_1 * 2; +static constexpr int SMEM_K_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1; +static constexpr int SMEM_V_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1; +static constexpr int SMEM_PAGE_TABLE_1 = FORT_ROUND_UP(TILE_N_1 * 2 * 2 * sizeof(int), 1024); +static constexpr int SMEM_OFFSET_Q_1 = 1024 + (false ? 0 : SMEM_PAGE_TABLE_1); +static constexpr int SMEM_OFFSET_K_1 = SMEM_OFFSET_Q_1 + SMEM_Q_1 * BUFFERS_Q_1; +static constexpr int SMEM_OFFSET_V_1 = SMEM_OFFSET_K_1 + SMEM_K_1 * BUFFERS_K_1; +static constexpr int SMEM_OFFSET_O_1 = SMEM_OFFSET_V_1 + SMEM_V_1 * BUFFERS_V_1; +static constexpr int SMEM_OFFSET_D_1 = SMEM_OFFSET_O_1; +static constexpr int SMEM_OFFSET_BAND_BIAS_1 = SMEM_OFFSET_O_1; + +static constexpr int THREADS_ON_TILE_BARRIER_1 = 256+32+0; +static constexpr int TILE_ID_SYNC_2_BARRIER_1 = 2; +static constexpr int TILE_ID_SYNC_3_BARRIER_1 = 3; +static constexpr int SOFTMAX_1_BARRIER_1 = 4; +static constexpr int SOFTMAX_2_BARRIER_1 = 5; +static constexpr int MATH_WORKGROUP_1 = 6; +static constexpr int TMA_SYNC_BARRIER_1 = 7; + +static constexpr uint32_t BYTES_PER_GMMA_K_1 = GMMA_TILE_K_1 * BYTES_PER_ELEMENT_1; +static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_1 = BYTES_PER_GMMA_K_1 >> 4; +static constexpr uint32_t BYTES_PER_GMMA_K_TRANS_1 = GMMA_TILE_K_1 * 128; +static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 = BYTES_PER_GMMA_K_TRANS_1 >> 4; + +static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1 = 2; +static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1 = 62; // bits 63-62 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 & +((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1)) +<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1; +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 & +((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1)) +<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1; +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 & +((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1)) +<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1; + +static constexpr uint32_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1 = 32; // bits 45-32 +static constexpr uint64_t BYTES_PER_LEADING_DIM_1 = 128; +static constexpr uint64_t STRIDE_BYTE_OFFSET_Q_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2 +static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = STRIDE_BYTE_OFFSET_Q_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1; +static constexpr uint64_t STRIDE_BYTE_OFFSET_K_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2 +static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = STRIDE_BYTE_OFFSET_K_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1; +static constexpr uint64_t STRIDE_BYTE_OFFSET_V_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2 +static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = STRIDE_BYTE_OFFSET_V_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1; + +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1 = 16; // bits 29-16 +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1 = 128 * 64 / 16; // Not used??? +static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1 +<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1; +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1 = 128 * 32 / 16; // Not used??? +static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1 +<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1; +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1 = 128 * TILE_N_1 / 16; +static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1 +<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1; + +inline __device__ constexpr uint64_t create_gmma_desc_q_1() { + return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1) + | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 + | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1; +} + +inline __device__ constexpr uint64_t create_gmma_desc_k_1() { + return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1) + | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1 + | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1; +} + +// === Section: GMMA Descriptors & Mask Helpers === +)KERNEL" + R"KERNEL( +// === Section: GMMA Descriptors & Mask Helpers === +inline __device__ constexpr uint64_t create_gmma_desc_v_1() { + return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1) + | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1 + | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1; +} + +class Gmma_descriptor { + public: + inline __device__ Gmma_descriptor(uint64_t desc_) { + desc = desc_; + } + template<int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void set_smem(uint32_t smem) { + desc |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4); + + max_desc = desc + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1); + } + template<int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void increment_smem_buffer() { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x += (desc >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1) + : (BYTES_PER_BUFFER >> 4); + } + + uint64_t desc; + uint64_t max_desc; +}; + +//global_load_shared_store_op 4 types +static constexpr int BITS_PER_ELEMENT_4 = 16; +static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8; +static constexpr int BYTES_PER_ACCESS_4 = 16; +static constexpr int TILE_M_4 = 64; +static constexpr int TILE_N_4 = 128; +static constexpr int BYTES_PER_SMEM_4 = TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4; + +// shared_load_op 5 types +static constexpr int BITS_PER_ELEMENT_5 = 16; +static constexpr int BYTES_PER_ELEMENT_5 = 2; +static constexpr int BYTES_PER_QUAD_5 = 16; +static constexpr int WARP_TILE_M_5 = 16; +static constexpr int WARP_TILE_N_5 = 16; +static constexpr int TILE_M_5 = 64; +static constexpr int TILE_N_5 = 128; +static constexpr int BYTES_PER_SMEM_5 = TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5; +static constexpr int WARPS_M_5 = 4; +static constexpr int WARPS_N_5 = 1; +static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5; +static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5; +static constexpr int THREADS_PER_WARP_TILE_M_5 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_5 = 4; +static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5; +static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5; +static constexpr int BYTES_PER_LD_5 = 128; +static constexpr int SWIZZLE_SCALE_5 = FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4); + +// shared_load_op 6 types +static constexpr int BITS_PER_ELEMENT_6 = 16; +static constexpr int BYTES_PER_ELEMENT_6 = 2; +static constexpr int BYTES_PER_QUAD_6 = 16; +static constexpr int WARP_TILE_M_6 = 16; +static constexpr int WARP_TILE_N_6 = 16; +static constexpr int TILE_M_6 = 128; +static constexpr int TILE_N_6 = 128; + +static constexpr int BYTES_PER_SMEM_6 = TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6; +static constexpr int WARPS_M_6 = 1; +static constexpr int WARPS_N_6 = 1; +static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6; +static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6; +static constexpr int THREADS_PER_WARP_TILE_M_6 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_6 = 4; +static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6; +static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6; +static constexpr int BYTES_PER_LD_6 = 128; +static constexpr int SWIZZLE_SCALE_6 = FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4); + +//global_load_shared_store_op 7 types +static constexpr int BITS_PER_ELEMENT_7 = 16; +static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8; +static constexpr int BYTES_PER_ACCESS_7 = 16; +static constexpr int TILE_M_7 = 128; +static constexpr int TILE_N_7 = 128; +static constexpr int BYTES_PER_SMEM_7 = TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7; + +//mma_op 8 types +static constexpr int BYTES_PER_ELEMENT_8 = 2; +static constexpr int BYTES_PER_ACC_8 = 4; +static constexpr int WARP_TILE_M_8 = 16; +static constexpr int WARP_TILE_N_8 = 16; +static constexpr int WARP_TILE_K_8 = 16; +static constexpr int TILE_M_8 = 64; +static constexpr int TILE_N_8 = 128; +static constexpr int TILE_K_8 = 128; +static constexpr int WARPS_M_8 = 4; +static constexpr int WARPS_N_8 = 1; +static constexpr int WARP_TILES_M_8 = TILE_M_8 / WARP_TILE_M_8; +static constexpr int WARP_TILES_N_8 = TILE_N_8 / WARP_TILE_N_8; +static constexpr int MMA_STEPS_K_8 = TILE_K_8 / WARP_TILE_K_8; +static constexpr int WARP_REGS_8 = 8; +static constexpr int REGS_M_8 = WARP_TILES_M_8 / WARPS_M_8; +static constexpr int REGS_N_8 = WARP_TILES_N_8 / WARPS_N_8; + +//pointwise_calc_op 9 types +static constexpr int WARP_TILE_M_9 = 16; +static constexpr int WARP_TILE_N_9 = 16; +static constexpr int TILE_M_9 = 64; +static constexpr int TILE_N_9 = 128; +static constexpr int WARPS_M_9 = 4; +static constexpr int WARPS_N_9 = 1; +static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9; +static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9; +static constexpr int WARP_REGS_9 = 8; +static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9; +static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9; + +//global_load_op 10 types +static constexpr int BITS_PER_ELEMENT_10 = 32; +static constexpr int BYTES_PER_ELEMENT_10 = 4; +static constexpr int REGISTERS_PER_VECTOR_10 = 1; +static constexpr int REGISTERS_PER_ACCESS_10 = 1; + +//mha_mask_op 11 types +static constexpr int WARP_TILE_M_11 = 16; +static constexpr int WARP_TILE_N_11 = 16; +static constexpr int TILE_M_11 = 64; +static constexpr int TILE_N_11 = 128; +static constexpr int WARPS_M_11 = 4; +static constexpr int WARPS_N_11 = 1; +static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11; +static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11; +static constexpr int WARP_REGS_11 = 8; +static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11; +static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11; +inline __device__ bool compute_diagonal_band_mask_11(const int row, const int col, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound) { + constexpr bool is_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_right_bound = true; + constexpr bool is_left_bound = false; + constexpr bool need_oob_check = false; + + const int diag = is_bottom_right_alignment ? row + (actual_seqlen_kv - actual_seqlen_q) : row; + const int shifted_right_bound = is_shift_right_bound ? diag + shift_right_bound : diag; + const bool right_bound_mask = is_right_bound ? col <= shifted_right_bound : true; + const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true; + const bool oob_check = need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true; + return right_bound_mask && left_bound_mask && oob_check; +} + +//softmax_op 12 types +static constexpr int BYTES_PER_ELEMENT_12 = 2; +static constexpr int WARP_TILE_M_12 = 16; +static constexpr int WARP_TILE_N_12 = 16; +static constexpr int TILE_M_12 = 64; +static constexpr int TILE_N_12 = 128; +static constexpr int WARPS_M_12 = 4; +static constexpr int WARPS_N_12 = 1; +static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12; + +static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12; +static constexpr int THREADS_PER_WARP_TILE_M_12 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_12 = 4; +static constexpr int WARP_REGS_12 = 8; +static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12; +static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12; +static constexpr int ROWS_PER_THREAD_12 = TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12; + +// global_store_op 13 types +static constexpr int BYTES_PER_ELEMENT_13 = 4; +static constexpr int WARP_TILE_M_13 = 16; +static constexpr int WARP_TILE_N_13 = 16; +static constexpr int TILE_M_13 = 64; +static constexpr int TILE_N_13 = 128; +static constexpr int WARPS_M_13 = 4; +static constexpr int WARPS_N_13 = 1; +static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13; +static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13; +static constexpr int THREADS_PER_WARP_TILE_M_13 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_13 = 4; +static constexpr int ROWS_PER_THREAD_13 = TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13; + +// global_store_op 14 types +static constexpr int BYTES_PER_ELEMENT_14 = 4; +static constexpr int WARP_TILE_M_14 = 16; +static constexpr int WARP_TILE_N_14 = 16; +static constexpr int TILE_M_14 = 64; +static constexpr int TILE_N_14 = 128; +static constexpr int WARPS_M_14 = 4; +static constexpr int WARPS_N_14 = 1; +static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14; +static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14; +static constexpr int THREADS_PER_WARP_TILE_M_14 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_14 = 4; +static constexpr int ROWS_PER_THREAD_14 = TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14; + +// shared_load_op 15 types +static constexpr int BITS_PER_ELEMENT_15 = 16; +static constexpr int BYTES_PER_ELEMENT_15 = 2; +static constexpr int BYTES_PER_QUAD_15 = 16; +static constexpr int WARP_TILE_M_15 = 16; +static constexpr int WARP_TILE_N_15 = 16; +static constexpr int TILE_M_15 = 128; +static constexpr int TILE_N_15 = 128; +static constexpr int BYTES_PER_SMEM_15 = TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15; +static constexpr int WARPS_M_15 = 1; +static constexpr int WARPS_N_15 = 1; +static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15; +static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15; +static constexpr int THREADS_PER_WARP_TILE_M_15 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_15 = 4; +static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15; +static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15; +static constexpr int BYTES_PER_LD_15 = 128; +static constexpr int SWIZZLE_SCALE_15 = FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4); + +//global_load_shared_store_op 16 types +static constexpr int BITS_PER_ELEMENT_16 = 16; +static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8; +static constexpr int BYTES_PER_ACCESS_16 = 16; +static constexpr int TILE_M_16 = 128; +static constexpr int TILE_N_16 = 128; +static constexpr int BYTES_PER_SMEM_16 = TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16; + +//mma_op 17 types +static constexpr int BYTES_PER_ELEMENT_17 = 2; +static constexpr int BYTES_PER_ACC_17 = 4; +static constexpr int WARP_TILE_M_17 = 16; +static constexpr int WARP_TILE_N_17 = 16; +static constexpr int WARP_TILE_K_17 = 16; +static constexpr int TILE_M_17 = 64; +static constexpr int TILE_N_17 = 128; +static constexpr int TILE_K_17 = 128; +static constexpr int WARPS_M_17 = 4; +static constexpr int WARPS_N_17 = 1; +static constexpr int WARP_TILES_M_17 = TILE_M_17 / WARP_TILE_M_17; +static constexpr int WARP_TILES_N_17 = TILE_N_17 / WARP_TILE_N_17; +static constexpr int MMA_STEPS_K_17 = TILE_K_17 / WARP_TILE_K_17; +static constexpr int WARP_REGS_17 = 8; +static constexpr int REGS_M_17 = WARP_TILES_M_17 / WARPS_M_17; +static constexpr int REGS_N_17 = WARP_TILES_N_17 / WARPS_N_17; + +// global_store_op 20 types + +// mma_loop_op 2 types +inline __device__ int2 compute_kv_loop_bounds(const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound) +{ + constexpr bool is_right_bound = true; + constexpr bool is_right_bound_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_left_bound = false; + constexpr bool is_left_bound_bottom_right_alignment = false; + + const int right_bound_diagonal = is_right_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord; + const int shifted_right_bound_diagonal = is_shift_right_bound ? right_bound_diagonal + shift_right_bound : right_bound_diagonal; + const int left_bound_diagonal = is_left_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord; + + const int kv_loop_left_bound = is_left_bound ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE) : 0; + const int kv_loop_right_bound = is_right_bound ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE, COL_TILE_SIZE), FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE)) : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE); + return make_int2(kv_loop_left_bound, kv_loop_right_bound); +} + +// output_loop_op 3 types +static constexpr int BYTES_PER_BANK_3 = 16; +static constexpr int LDS_TILE_M_3 = 16; +static constexpr int LDS_TILE_N_3 = 32; +static constexpr int ACC_CORE_MATRIX_ROWS_3 = 8; // NOTE: fixed due to GMMA design +static constexpr int ACC_CORE_MATRIX_COLS_3 = 8; // NOTE: fixed due to GMMA design +static constexpr int ELEMENTS_PER_VECTOR_3 = 8; +static constexpr int LDS_PER_TILE_3 = ELEMENTS_PER_VECTOR_3 / 2; +static constexpr int LDS_TILES_N_3 = FORT_MAX(CTA_TILE_N_1 / LDS_TILE_N_3, 1); +static constexpr int LDS_TILES_M_3 = FORT_MAX(1, (CTA_TILE_M_1 / GROUPS_M_1) / (LDS_TILE_M_3 * WARPS_PER_GROUP_0)); +static constexpr int VECTORS_PER_LDS_TILES_3 = LDS_TILE_M_3 / ACC_CORE_MATRIX_ROWS_3; +static constexpr int STS_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3; +static constexpr int STSM_X4_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3 / 2; +static constexpr int BANKS_PER_PAD_LINE_3 = BYTES_PER_ACC_1 == 4 ? 1 : 2; + +static constexpr int PADDING_BYTES_3 = BANKS_PER_PAD_LINE_3 * BYTES_PER_BANK_3 * LDS_PER_TILE_3; +)KERNEL" + R"KERNEL( +static constexpr int BYTES_PER_STS_PER_WARP_3= 16 * THREADS_PER_WARP_0; // 16 bytes due to STS_128 +static constexpr int BYTES_PER_LDS_TILE_3 = LDS_TILE_N_3 * LDS_TILE_M_3 * BYTES_PER_ACC_1 + PADDING_BYTES_3; +static constexpr int BYTES_PER_WARP_3 = LDS_TILES_N_3 * BYTES_PER_LDS_TILE_3; + +static constexpr int ELEMS_PER_STS_BLOCK_3 = 16; + +static constexpr int STG_THREADS_PER_TILE_N_3 = LDS_TILE_N_3 / ELEMENTS_PER_VECTOR_3; +static constexpr int EPILOGUE_SMEM_SIZE_PER_XMMA_M_3 = BYTES_PER_WARP_3 * WARPS_PER_GROUP_0; + +// shared_store_op 18 types + +// shared_load_op 19 types +static constexpr int BITS_PER_ELEMENT_19 = 32 * 1; +static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8; +static constexpr int BITS_PER_VECTOR_19 = BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3; +static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8; +static constexpr int REGISTERS_PER_VECTOR_19 = BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0; + +//receive_op 0 code + +// === Section: Kernel Function === +)KERNEL" + R"KERNEL( +// === Section: Kernel Function === +extern "C" __global__ __launch_bounds__(384, 1) +void cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x128_4x1x1_cga1x1x1_kernel0_0(const AttentionDescriptor_t attnDesc +, int num_tiles_1 +, const FastDivisor_t tiles_hr_div_1 +, const FastDivisor_t tiles_r_div_1 +, int32_t* tile_id_counter +, __grid_constant__ const CUtensorMap tma_Q +, __grid_constant__ const CUtensorMap tma_K +, float attn_scale +, float neg_infinity +, void* d_max +, fort::tensor_descriptor desc_max +, void* d_sum_exp +, fort::tensor_descriptor desc_sum_exp +, __grid_constant__ const CUtensorMap tma_V +, __grid_constant__ const CUtensorMap tma_O +) { + extern __shared__ char smem_[]; + uint32_t smem_0 = get_smem_pointer(smem_); + + //receive_op 0 decls + + // mma_pipeline_op 1 decls + const uint32_t tid = threadIdx.x % THREADS_PER_GROUP_0; + const uint32_t gid = threadIdx.x / THREADS_PER_GROUP_0; + const uint32_t wid = threadIdx.x / 32; + const uint32_t tiw = threadIdx.x % 32; + + const uint32_t elect_one = fort::elect_one_sync(); + + uint32_t smem_1 = smem_0; + uint32_t smem_bar_qkv_1 = smem_1; + uint32_t smem_page = smem_1 + 1024; + uint32_t smem_Q = smem_1 + SMEM_OFFSET_Q_1; + uint32_t smem_K = smem_1 + SMEM_OFFSET_K_1; + uint32_t smem_V = smem_1 + SMEM_OFFSET_V_1; + uint32_t smem_O = smem_1 + SMEM_OFFSET_O_1; + uint32_t smem_d_1 = smem_1 + SMEM_OFFSET_D_1; + uint32_t smem_band_bias_1 = smem_1 + SMEM_OFFSET_BAND_BIAS_1; + + uint32_t smem_bar_qkv_tma_1 = smem_bar_qkv_1; + uint32_t smem_bar_qkv_mma_1 = smem_bar_qkv_1 + 1 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); + uint32_t smem_tile_id_1 = smem_bar_qkv_1 + 2 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); + uint32_t smem_bar_tile_id_tma_1 = smem_tile_id_1 + 16; + uint32_t smem_bar_bias_tma_1 = smem_bar_tile_id_tma_1 + 8; + + uint32_t smem_bar_bias_mma_1 = smem_bar_bias_tma_1 + 8 * 2; + + if (elect_one) { + for (int i = wid; i < (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); i+=12) { + smem_bar_init(smem_bar_qkv_tma_1 + i * 8, 1); + smem_bar_init(smem_bar_qkv_mma_1 + i * 8, 2); + } + } + __syncthreads(); + + // mma_pipeline_op 1 code + const int actual_num_tiles_1 = num_tiles_1; + if (gid == 0) { + reg_dealloc<40>(); + const uint32_t local_wid = wid % 4; + + uint32_t tile_id; + uint32_t batch_coord_1 = 0, head_coord_1 = 0, q_row_coord = 0, rows_temp; + uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1; + int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q; + + if (local_wid == 0) { + uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1; + uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1; + + uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1; + uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1; + + uint32_t buffer_id_q = 0; + uint32_t buffer_id_kv = 0; + uint32_t cnt_q = 0; + uint32_t cnt_kv = 0; + + uint32_t sts_page_buffer_id = 0; + uint32_t lds_page_buffer_id = 0; + + int cumulative_tiles = 0; + if (tiw == 0) { + tile_id = atomicAdd(tile_id_counter, 1); + } + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + + named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + sts_32(smem_tile_id_1, &tile_id); + } + named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + + // Persistent loop over output tiles +#pragma unroll 1 + while (tile_id < actual_num_tiles_1) { + fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp); + fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord); + q_row_coord *= TILE_M_1 * 2; + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + const int left_bound = 0; + const int shift_right_bound = 0; + + int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + int kv_loop_left_bound = kv_loop_bounds.x; + int kv_loop_right_bound = kv_loop_bounds.y; + + //global_load_shared_store_op 4 decls + + //global_load_shared_store_op 7 decls + + //global_load_shared_store_op 16 decls + + uint32_t local_smem_q = smem_Q + buffer_id_q * SMEM_Q_1; + uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8; + uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8; + + if (kv_loop_left_bound < kv_loop_right_bound) { + uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 1 : 0; + + cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0; + buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0; + + if (!smem_bar_peek(local_smem_bar_mma_q, smem_bar_phase_q)) { + smem_bar_wait(local_smem_bar_mma_q, smem_bar_phase_q); + } + + smem_bar_set_transaction_count(local_smem_bar_tma_q, SMEM_Q_1, elect_one); + { + const uint32_t row_coord = q_row_coord; + + //global_load_shared_store_op 4 code +#pragma unroll + for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_Q, + local_smem_q + i * TILE_M_1 * 2, + local_smem_bar_tma_q, + i / BYTES_PER_ELEMENT_1, + row_coord, + head_coord_1 + 0, + batch_coord_1, + elect_one); + } + } + } + +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) { + const int p_col_coord = kv_loop * TILE_N_1; + + uint32_t local_smem_k = smem_K + buffer_id_kv * SMEM_K_1; + uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8; + + uint32_t local_smem_v = smem_V + buffer_id_kv * SMEM_V_1; + uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8; + + uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 1 : 0; + + cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0; + buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0; + + uint32_t kv_col_base = (kv_loop + 1) * TILE_N_1; + + if (!smem_bar_peek(local_smem_bar_mma_k, smem_bar_phase_kv)) { + smem_bar_wait(local_smem_bar_mma_k, smem_bar_phase_kv); + } + smem_bar_set_transaction_count(local_smem_bar_tma_k, SMEM_K_1, elect_one); + + //global_load_shared_store_op 7 code +#pragma unroll + for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_K, + local_smem_k + i * TILE_N_1, + local_smem_bar_tma_k, + i / BYTES_PER_ELEMENT_1, + p_col_coord, + head_coord_k_1, + batch_coord_1, + elect_one); + } + if (!smem_bar_peek(local_smem_bar_mma_v, smem_bar_phase_kv)) { + smem_bar_wait(local_smem_bar_mma_v, smem_bar_phase_kv); + } + smem_bar_set_transaction_count(local_smem_bar_tma_v, SMEM_V_1, elect_one); + + //global_load_shared_store_op 16 code +#pragma unroll + for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128 * CTA_MMA_1) { + utmaldg_4d_tiled(&tma_V, + local_smem_v + i * TILE_N_1, + local_smem_bar_tma_v, + 0 + i / BYTES_PER_ELEMENT_1, + p_col_coord, + head_coord_v_1, + batch_coord_1, + elect_one); + } + lds_page_buffer_id ^= 1; + } + if (kv_loop_left_bound < kv_loop_right_bound) { + lds_page_buffer_id ^= 1; + } + + if (tiw == 0) { + tile_id = atomicAdd(tile_id_counter, 1); + } + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + + named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + sts_32(smem_tile_id_1, &tile_id); + } + named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + } + named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + } + reg_dealloc<40>(); + } else { + reg_alloc<232>(); + named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + + const uint32_t local_wid = wid % 4; + const uint32_t local_gid = gid % 2; + + uint32_t tile_id; + uint32_t batch_coord_1, head_coord_1, q_row_coord, rows_temp; + uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1; + int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q; + + uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1; + uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1; + + uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1; + uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1; + + uint32_t buffer_id_q = 0; + uint32_t buffer_id_kv = 0; + uint32_t cnt_q = 0; + uint32_t cnt_kv = 0; + + static constexpr float inv_ln2 = 1.4426950408889634074f; + static constexpr float ln2 = 0.6931471805599453094f; + + Gmma_descriptor gmma_desc_q(create_gmma_desc_q_1()); + Gmma_descriptor gmma_desc_k(create_gmma_desc_k_1()); + Gmma_descriptor gmma_desc_v(create_gmma_desc_v_1()); + + gmma_desc_q.set_smem<SMEM_Q_1, BUFFERS_Q_1>(smem_Q + local_gid * TILE_M_1 * 128); + gmma_desc_k.set_smem<SMEM_K_1, BUFFERS_K_1>(smem_K); + gmma_desc_v.set_smem<SMEM_V_1, BUFFERS_V_1>(smem_V); + + named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + lds_32(&tile_id, smem_tile_id_1); + } + named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + + // Persistent loop over output tiles +#pragma unroll 1 + while (tile_id < actual_num_tiles_1) { + fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp); + fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord); + q_row_coord = q_row_coord * TILE_M_1 * 2; + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + const int left_bound = 0; + const int shift_right_bound = 0; + + int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + int kv_loop_left_bound = kv_loop_bounds.x; + int kv_loop_right_bound = kv_loop_bounds.y; + q_row_coord += local_gid * TILE_M_1; + + const int causal_mask_col = (tiw % 4) * 2; + const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4); + + // mma_loop_op 2 decls + + //global_load_shared_store_op 4 decls + + // shared_load_op 5 decls + + // shared_load_op 6 decls + + //global_load_shared_store_op 7 decls + + //mma_op 8 decls + r32 reg_8_0[REGS_M_8][REGS_N_8][WARP_REGS_8]; + + //pointwise_calc_op 9 decls + + //global_load_op 10 decls + r32 reg_10_0[1]; + reg_10_0[0] = reinterpret_cast<const r32 &>(attn_scale); + const int oob_M_10 = 1; + const int oob_N_10 = 1; + + //mha_mask_op 11 decls + + //softmax_op 12 decls + r32 reg_12_0[REGS_M_12][REGS_N_12][4]; // output for second gemm + r32 reg_12_1[ROWS_PER_THREAD_12]; // acc_max + r32 reg_12_2[ROWS_PER_THREAD_12]; // p_max + r32 reg_12_3[ROWS_PER_THREAD_12]; // acc_sum + r32 reg_12_4[ROWS_PER_THREAD_12]; // p_sum + r32 reg_12_5[ROWS_PER_THREAD_12]; // softmax stats + float beta_12[ROWS_PER_THREAD_12]; + +#pragma unroll + for (int i = 0; i < ROWS_PER_THREAD_12; ++i) { + reinterpret_cast<float &>(reg_12_1[i]) = NEG_INFINITY; + reinterpret_cast<float &>(reg_12_3[i]) = 0.0f; + } + + //global_store_op 13 decls + int oob_M_13 = desc_max.dims[2]; + int row_13 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4); + char *ptr_13 = reinterpret_cast<char *>(d_max) + + batch_coord_1 * desc_max.strides[0] * BYTES_PER_ELEMENT_13 + + head_coord_1 * desc_max.strides[1] * BYTES_PER_ELEMENT_13 + + row_13 * desc_max.strides[2] * BYTES_PER_ELEMENT_13; + + //global_store_op 14 decls + int oob_M_14 = desc_sum_exp.dims[2]; + int row_14 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4); + char *ptr_14 = reinterpret_cast<char *>(d_sum_exp) + + batch_coord_1 * desc_sum_exp.strides[0] * BYTES_PER_ELEMENT_14 +)KERNEL" + R"KERNEL( + + head_coord_1 * desc_sum_exp.strides[1] * BYTES_PER_ELEMENT_14 + + row_14 * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14; + + // shared_load_op 15 decls + + //global_load_shared_store_op 16 decls + + //mma_op 17 decls + + r32 reg_17_0[REGS_M_17][REGS_N_17][WARP_REGS_17]; + + //global_store_op 20 decls + static constexpr int cols_per_step_20 = (TILE_K_1 <= 128) ? TILE_K_1 : 64; + uint32_t smem_20 = smem_O + (local_gid * 4 + local_wid) * 16 * cols_per_step_20 * BYTES_PER_ELEMENT_1; + + const int swizzled_row_20 = (tiw % 16); + const int swizzled_col_20 = (tiw / 16); + constexpr int stsm_per_tile_20 = 128 / (BYTES_PER_BANK_1 * 2); + uint32_t stsm_base_20[stsm_per_tile_20]; + +#pragma unroll + for (int n = 0; n < stsm_per_tile_20; ++n) { + stsm_base_20[n] = smem_20 + ((swizzled_row_20 % 8) ^ (n * 2 + swizzled_col_20)) * BYTES_PER_BANK_1 + swizzled_row_20 * 128; + } + + const int row_20 = q_row_coord + (local_wid % 4) * 16; + + uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8; + uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8; + + if (local_gid == 1) { + named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256); + } + + if (kv_loop_left_bound < kv_loop_right_bound) { + uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 0 : 1; + + cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0; + buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0; + + if (!smem_bar_peek(local_smem_bar_tma_q, smem_bar_phase_q)) { + smem_bar_wait(local_smem_bar_tma_q, smem_bar_phase_q); + } + } + + r32 reg_1_0[REGS_M_1][REGS_O_1][WARP_REGS_1]; + memset(®_1_0[0][0][0], 0, sizeof(reg_1_0)); + + named_barrier_wait(MATH_WORKGROUP_1, 256); +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) { + static constexpr int kMulPipeCount = REGS_M_1 * REGS_N_1 * WARP_REGS_1; + + static constexpr int kSubtractPipeCount = 6; + static constexpr int kConvertPipeCount = 4; + static constexpr int oBlockSize = 1; + + const int p_col_coord = kv_loop * TILE_N_1; + const int causal_mask_col = p_col_coord + (tiw % 4) * 2; + const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4); + + uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8; + + uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8; + + uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 0 : 1; + + cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0; + buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0; + + memset(®_8_0[0][0][0], 0, sizeof(reg_8_0)); + + if (!smem_bar_peek(local_smem_bar_tma_k, smem_bar_phase_kv)) { + smem_bar_wait(local_smem_bar_tma_k, smem_bar_phase_kv); + } + + warpgroup_arrive(); +#pragma unroll + for (int k = 0; k < REGS_K_1; ++k) { + if (k == REGS_K_1 - 1) { + BMM_S_GMMA_ISB(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0])); + } else { + BMM_S_GMMA(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0])); + } + int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc); + tmp_desc_q.x += BYTES_PER_GMMA_K_NO_4LSB_1; + if ((k % 4) == 3) { + tmp_desc_q.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4; + tmp_desc_q.x += ((128*TILE_M_1*2) >> 4); + } + int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc); + tmp_desc_k.x += BYTES_PER_GMMA_K_NO_4LSB_1; + if ((k % 4) == 3) { + tmp_desc_k.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4; + tmp_desc_k.x += ((128*TILE_N_1) >> 4); + } + } + { + int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc); + tmp_desc_q.x -= ((128 * TILE_M_1 * 2) >> 4) * (REGS_K_1 / 4); + int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc); + tmp_desc_k.x -= ((128 * TILE_N_1) >> 4) * (REGS_K_1 / 4); + } + gmma_desc_k.increment_smem_buffer<SMEM_K_1, BUFFERS_K_1>(); + warpgroup_wait<0>(); + + if (local_wid == 0 && elect_one) { + smem_bar_arrive(local_smem_bar_mma_k); + } + + uint32_t wait_v_done = smem_bar_peek(local_smem_bar_tma_v, smem_bar_phase_kv); + + //mha_mask_op 11 code + if (kv_loop >= kv_loop_right_bound - 1) + { +#pragma unroll + for (int m = 0; m < REGS_M_11; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_11; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_11; ++i) { + int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8; + int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8; + bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + if (!mask) { + reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity; + } + } + } + } + } + + //global_load_op 10 code + + //mha_mask_op 11 code + if (kv_loop >= kv_loop_right_bound - 1) + { +#pragma unroll + for (int m = 0; m < REGS_M_11; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_11; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_11; ++i) { + int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8; + int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8; + bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + if (!mask) { + reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity; + } + } + } + } + } + + //softmax_op 12 code + static constexpr float inv_ln2_12 = 1.4426950408889634074f; + float scaled_inv_ln2_12 = inv_ln2_12 * reinterpret_cast<const float &>(reg_10_0[0]); + + r32 *flattened_s = reinterpret_cast<r32 *>(reg_8_0); + r32 *flattened_s_fp16 = reinterpret_cast<r32 *>(reg_12_0); + r32 *flattened_o = reinterpret_cast<r32 *>(reg_1_0); + + float tmp_max_level_0[REGS_N_12][4]; + float tmp_max_level_1[REGS_N_12][2]; + float tmp_max_level_2[REGS_N_12 / 2][2]; +#pragma unroll + for (int m = 0; m < REGS_M_12; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_12; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_12; i+=2) { + tmp_max_level_0[n][i/2] = fmaxf(reinterpret_cast<const float &>(reg_8_0[m][n][i+0]), + reinterpret_cast<const float &>(reg_8_0[m][n][i+1])); + } + } + } + // FMUL +#pragma unroll + for (int i = 0; i < kMulPipeCount; i++) { + reinterpret_cast<float &>(flattened_s[i]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i])); + } + { +#pragma unroll + for (int n = 0; n < REGS_N_12; ++n) { +#pragma unroll + for (int i = 0; i < 2; i++) { + tmp_max_level_1[n][i] = fmaxf(tmp_max_level_0[n][i + 0], + tmp_max_level_0[n][i + 2]); + } + } + } + { +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=2) { + tmp_max_level_2[n/2][0] = fmaxf(tmp_max_level_1[n][0], tmp_max_level_1[n+1][0]); + tmp_max_level_2[n/2][1] = fmaxf(tmp_max_level_1[n][1], tmp_max_level_1[n+1][1]); + } + } + if (TILE_N_1 == 256) { + float tmp_max_level_3[REGS_N_12 / 4][2]; + float tmp_max_level_4[FORT_MAX(1,REGS_N_12 / 8)][2]; +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=4) { + tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]); + tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]); + } +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=8) { + tmp_max_level_4[n/8][0] = fmaxf(tmp_max_level_3[n/4][0], tmp_max_level_3[n/4+1][0]); + tmp_max_level_4[n/8][1] = fmaxf(tmp_max_level_3[n/4][1], tmp_max_level_3[n/4+1][1]); + } + reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_4[0][0], tmp_max_level_4[1][0]); + reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_4[0][1], tmp_max_level_4[1][1]); + } else if (TILE_N_1 == 128) { + float tmp_max_level_3[REGS_N_12 / 4][2]; +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=4) { + tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]); + tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]); + } + reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_3[0][0], tmp_max_level_3[1][0]); + reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_3[0][1], tmp_max_level_3[1][1]); + } else { + reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_2[0][0], tmp_max_level_2[1][0]); + reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_2[0][1], tmp_max_level_2[1][1]); + } + + // Apply the functor for each row inside each group of 4 threads. +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 1); + + reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]), + reinterpret_cast<const float &>(tmp_0)); + + tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 2); + + reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]), + reinterpret_cast<const float &>(tmp_0)) * scaled_inv_ln2_12; + } + + // Update acc_max scale of flash attention +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + r32 curr_max = reg_12_1[m]; + reinterpret_cast<float &>(reg_12_1[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]), + reinterpret_cast<const float &>(curr_max)); + reg_12_2[m] = curr_max; + } + + float alpha_12[ROWS_PER_THREAD_12]; +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + float p_max = reinterpret_cast<const float &>(reg_12_2[m]); + float acc_max = reinterpret_cast<const float &>(reg_12_1[m]); + + // disable FMA for scale * P - max + float tmp = (acc_max == NEG_INFINITY) ? p_max : __fsub_rn(p_max, acc_max); + reinterpret_cast<r32 &>(alpha_12[m]) = fp32_exp2(reinterpret_cast<r32 &>(tmp)); + } + +#pragma unroll + for (int i = 0; i < ROWS_PER_THREAD_12; ++i) { + reinterpret_cast<float &>(reg_12_4[i]) = 0.0f; + } + + // Broadcast scaled_max and alpha + float flattened_scaled_max[REGS_M_12 * REGS_N_12 * WARP_REGS_12]; + float flattened_alpha[REGS_M_12 * REGS_O_1 * WARP_REGS_12]; +#pragma unroll + for (int m = 0; m < REGS_M_12; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_12; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_12; ++i) { + int row_indx = m * 2 + (i / 2) % 2; + float max = reinterpret_cast<const float &>(reg_12_1[row_indx]); + flattened_scaled_max[m * REGS_N_12 * WARP_REGS_12 + n * WARP_REGS_12 + i] = (max == NEG_INFINITY ? 0.0f : max); + } + } + } + +#pragma unroll + for (int m = 0; m < REGS_M_12; ++m) { +#pragma unroll + for (int n = 0; n < REGS_O_1; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_12; ++i) { + int row_indx = m * 2 + (i / 2) % 2; + flattened_alpha[m * REGS_O_1 * WARP_REGS_12 + n * WARP_REGS_12 + i] = alpha_12[row_indx]; + } + } + } + + cfence(); + if (local_gid == 1) { + named_barrier_wait(SOFTMAX_1_BARRIER_1, 256); + } else { + named_barrier_wait(SOFTMAX_2_BARRIER_1, 256); + } + cfence(); + + // FSUB +#pragma unroll + for (int i = 0; i < kSubtractPipeCount; i++) { +)KERNEL" + R"KERNEL( + reinterpret_cast<float &>(flattened_s[i]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i]), flattened_scaled_max[i]); + } +#pragma unroll + + for (int i = 0; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) { + int m_0 = (i-kConvertPipeCount+0) / (REGS_N_12 * WARP_REGS_12); + int ii_0 = (i-kConvertPipeCount+0) % WARP_REGS_12; + int m_1 = (i-kConvertPipeCount+1) / (REGS_N_12 * WARP_REGS_12); + int ii_1 = (i-kConvertPipeCount+1) % WARP_REGS_12; + int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2; + int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2; + // cast and FADD + if (i >= kConvertPipeCount) { + fp32x2_to_bf16x2(&flattened_s_fp16[(i - kConvertPipeCount)/2], &flattened_s[i - kConvertPipeCount]); + reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+0]); + reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+1]); + } + cfence(); + + // exp + flattened_s[i+0] = fp32_exp2(flattened_s[i+0]); + + // O update +#pragma unroll + for (int j = 0; j < oBlockSize; j++) { + if (oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) { + reinterpret_cast<float &>(flattened_o[oBlockSize*i+j]) *= flattened_alpha[oBlockSize*i+j]; + } + } + + // fmul + if (i + kMulPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) { + reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0])); + reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1])); + } + // fsub + + if (i + kSubtractPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) { + reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]), flattened_scaled_max[i+kSubtractPipeCount+0]); + reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]), flattened_scaled_max[i+kSubtractPipeCount+1]); + } + + // exp + flattened_s[i+1] = fp32_exp2(flattened_s[i+1]); + + // O update +#pragma unroll + for (int j = 0; j < oBlockSize; j++) { + if (oBlockSize+oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) { + reinterpret_cast<float &>(flattened_o[oBlockSize+oBlockSize*i+j]) *= flattened_alpha[oBlockSize+oBlockSize*i+j]; + } + } + } + + if (local_gid == 0) { + named_barrier_arrive(SOFTMAX_1_BARRIER_1, 256); + } else { + named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256); + } + cfence(); + +#pragma unroll + for (int i = REGS_M_12 * REGS_N_12 * WARP_REGS_12 - kConvertPipeCount; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) { + int m_0 = (i + 0) / (REGS_N_12 * WARP_REGS_12); + int ii_0 = (i + 0) % WARP_REGS_12; + int m_1 = (i + 1) / (REGS_N_12 * WARP_REGS_12); + int ii_1 = (i + 1) % WARP_REGS_12; + int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2; + int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2; + fp32x2_to_bf16x2(&flattened_s_fp16[i/2], &flattened_s[i]); + reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i+0]); + reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i+1]); + } + + if (!wait_v_done) { + smem_bar_wait(local_smem_bar_tma_v, smem_bar_phase_kv); + } + + warpgroup_arrive(); +#pragma unroll + for (int k = 0; k < TILE_N_1 / GMMA_TILE_K_1; ++k) { + if (k == (TILE_N_1 / GMMA_TILE_K_1) - 1) { + BMM_O_GMMA_ISB(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0])); + } else { + BMM_O_GMMA(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0])); + } + int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc); + tmp_desc_v.x += BYTES_PER_GMMA_K_NO_4LSB_TRANS_1; + } + { + int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc); + tmp_desc_v.x -= BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 * (TILE_N_1 / GMMA_TILE_K_1); + } + gmma_desc_v.increment_smem_buffer<SMEM_V_1, BUFFERS_V_1>(); + + warpgroup_wait<0>(); + if (local_wid == 0 && elect_one) { + smem_bar_arrive(local_smem_bar_mma_v); + } + + // Update acc_sum of flash attention +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + float p_sum = reinterpret_cast<const float &>(reg_12_4[m]); + float acc_sum = reinterpret_cast<const float &>(reg_12_3[m]); + + reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<float &>(alpha_12[m]) * acc_sum + p_sum; + } + } + if (kv_loop_left_bound < kv_loop_right_bound) { + gmma_desc_q.increment_smem_buffer<SMEM_Q_1, BUFFERS_Q_1>(); + + if (local_wid == 0 && elect_one) { + smem_bar_arrive(local_smem_bar_mma_q); + } + } + if (local_gid == 0) { + named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256); + } +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 1); + + reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) + + reinterpret_cast<const float &>(tmp_0); + + tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 2); + + reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) + + reinterpret_cast<const float &>(tmp_0); + + float sum = reinterpret_cast<float &>(reg_12_3[m]); + reinterpret_cast<float &>(reg_12_1[m]) *= ln2; + + reinterpret_cast<float &>(reg_12_5[m]) = (sum == 0.f) ? NEG_INFINITY : reinterpret_cast<const float &>(reg_12_1[m]) + __logf(sum); + + beta_12[m] = (sum == 0.f) ? 0.f : 1.f / sum; + } + +#pragma unroll + for (int m = 0; m < REGS_M_1; ++m) { +#pragma unroll + for (int n = 0; n < REGS_O_1; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_1; ++i) { + int row_indx = m * 2 + (i / 2) % 2; + + reinterpret_cast<float &>(reg_1_0[m][n][i]) *= beta_12[row_indx]; + } + } + } + + //global_store_op 13 code +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_13; ++m) { + const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_13 + (m / 2) * WARPS_M_13 * WARP_TILE_M_13; + + if (row_13 + row_offset < oob_M_13 && (tiw % 4) == 0) { + stg_32(ptr_13 + row_offset * desc_max.strides[2] * BYTES_PER_ELEMENT_13, ®_12_1[m]); + } + } + + //global_store_op 14 code +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_14; ++m) { + const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_14 + (m / 2) * WARPS_M_14 * WARP_TILE_M_14; + + if (row_14 + row_offset < oob_M_14 && (tiw % 4) == 0) { + stg_32(ptr_14 + row_offset * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14, ®_12_3[m]); + } + } + + tmastg_wait(); + + //global_store_op 20 code +#pragma unroll + for (int s = 0; s < TILE_O_1 / 64; ++s) { +#pragma unroll + for (int n = 0; n < stsm_per_tile_20; ++n) { + uint32_t tmp[4]; + fp32x2_to_bf16x2(&tmp[0], ®_1_0[0][s * stsm_per_tile_20 + n][0]); + fp32x2_to_bf16x2(&tmp[1], ®_1_0[0][s * stsm_per_tile_20 + n][2]); + fp32x2_to_bf16x2(&tmp[2], ®_1_0[0][s * stsm_per_tile_20 + n][4]); + fp32x2_to_bf16x2(&tmp[3], ®_1_0[0][s * stsm_per_tile_20 + n][6]); + stsm_x4(stsm_base_20[n] + s * 64 * 16 * BYTES_PER_ELEMENT_1, tmp); + } + } + fence_view_async_shared(); + + int head_coord_loc = 0; + int row = row_20; + int head = head_coord_1; +#pragma unroll + for (int s = 0; s < TILE_K_1 / 64; ++s) { + utmastg_4d_tiled(&tma_O, + smem_20 + s * 64 * 16 * BYTES_PER_ELEMENT_1, + s * 64, + row, + head + head_coord_loc, + batch_coord_1); + } + tmastg_arrive(); + + named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + lds_32(&tile_id, smem_tile_id_1); + } + named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + } + tmastg_wait(); + reg_alloc<232>(); + } +} +)KERNEL"; +inline constexpr size_t d128_fprop_source_len = sizeof(d128_fprop_source) - 1; + +inline constexpr const char d128_fprop_flags[] = R"FLAGS(--gpu-architecture=sm_90a +--std=c++17 +--define-macro=__x86_64__ +-w +--define-macro=__CUDACC_RTC__ +-default-device +--use_fast_math +)FLAGS"; +inline constexpr size_t d128_fprop_flags_len = sizeof(d128_fprop_flags) - 1; + +} // namespace generated +} // namespace experimental +} // namespace cudnn_frontend + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif diff --git a/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h new file mode 100644 index 0000000..92d8d1b --- /dev/null +++ b/deps/cudnn-frontend/include/cudnn_frontend/generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h @@ -0,0 +1,1763 @@ +// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: MIT +#pragma once + +// Suppress clang warning for overlength strings (concatenated result may exceed 65536) +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverlength-strings" +#endif + +// Suppress MSVC warning C4068 (unknown pragma) if clang pragmas are seen +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4068) +#endif + +namespace cudnn_frontend { +namespace experimental { +namespace generated { + +inline constexpr const char d64_fprop_source[] = + R"KERNEL( +//receive_op 0 includes +typedef unsigned long long uint64_t; +typedef unsigned int uint32_t; +typedef unsigned short uint16_t; +typedef unsigned char uint8_t; +typedef long long int64_t; +typedef int int32_t; +typedef short int16_t; +typedef signed char int8_t; +typedef unsigned int r32; + +struct CUtensorMap { + alignas(64) uint64_t opaque[16]; +}; + +#define CUDACC_VERSION __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__ + +namespace fort { + static const uint64_t AMPERE_MEM_DESC_DEFAULT = uint64_t(0x1000000000000000ul); + static const uint64_t MEM_DESC_DEFAULT = AMPERE_MEM_DESC_DEFAULT; + static const uint32_t MMA_PEER_BIT_MASK = 0xFEFFFFFF; + +#define NEG_INFINITY __int_as_float(0xff800000) + + typedef uint16_t half_t; + typedef uint16_t bfloat16_t; + +#define FORT_MIN(a,b) ((a) < (b) ? (a) : (b)) +#define FORT_MAX(a,b) ((a) > (b) ? (a) : (b)) +#define FORT_DIV_UP(a,b) (((a) + (b) - 1) / (b)) +#define FORT_ROUND_UP(a,b) ((((a) + (b) - 1) / (b)) * (b)) + + typedef struct tensor_descriptor { + static const int MAX_DIMS = 12; + + int64_t num_dims; + int64_t dims[MAX_DIMS]; + int64_t strides[MAX_DIMS]; + } tensor_descriptor; + + typedef struct FastDivisor { + uint32_t val, shr, mul; + } FastDivisor_t; + + inline __device__ void + fastDivMod(const FastDivisor_t &d, uint32_t val, uint32_t &div, uint32_t &mod) { + div = __umulhi((uint32_t)2 * val, d.mul) >> d.shr; + mod = val - div * d.val; + } + __device__ __inline__ void cfence() {} + +#if __CUDA_ARCH__ >= 900 + + inline __device__ uint32_t elect_one_sync() { + uint32_t pred = 0; + uint32_t laneid = 0; + asm volatile( + "{\n" + ".reg .b32 %%rx;\n" + ".reg .pred %%px;\n" + " elect.sync %%rx|%%px, %2;\n" + "@%%px mov.s32 %1, 1;\n" + " mov.s32 %0, %%rx;\n" + "}\n" : "+r"(laneid), "+r"(pred) : "r"(0xFFFFFFFF)); + return pred; + } + + template<int TARGET_REG_COUNT> + inline __device__ void reg_alloc() { + // const int TARGET_REG_COUNT = 232; // Example values (use with reg_delloc's VALUE together): 224, 232, 208, 216 + asm volatile("setmaxnreg.inc.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT)); + } + + template<int TARGET_REG_COUNT> + inline __device__ void reg_dealloc() { + // const int TARGET_REG_COUNT = 40; // Exmaple values: 56, 40, 88, 72 + asm volatile("setmaxnreg.dec.sync.aligned.u32 %0;\n" : : "n"(TARGET_REG_COUNT)); + } + + inline __device__ void named_barrier_arrive(uint32_t BARRIER_ID, uint32_t NUM_THREADS) { + asm volatile("bar.arrive %0, %1;" : : "r"(BARRIER_ID), "r"(NUM_THREADS)); + } + + inline __device__ void named_barrier_wait(uint32_t BARRIER_ID, uint32_t NUM_THREADS) { + asm volatile("bar.sync %0, %1;" :: "r"(BARRIER_ID), "r"(NUM_THREADS)); + } + + inline __device__ void tmastg_arrive() { + asm volatile("cp.async.bulk.commit_group;"); + } + + inline __device__ void tmastg_wait() { + asm volatile("cp.async.bulk.wait_group.read %0;" : :"n"(0):"memory"); + } + +#endif + +#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900 + inline __device__ void warpgroup_arrive() { + asm volatile("wgmma.fence.sync.aligned;\n" ::: "memory"); + } + template <int N> inline __device__ void warpgroup_wait() { + asm volatile("wgmma.wait_group.sync.aligned %0;\n" ::"n"(N) : "memory"); + } + inline __device__ void warpgroup_commit() { + asm volatile("wgmma.commit_group.sync.aligned;\n" ::: "memory"); + } + template <typename T> + inline __device__ T &__wgmma_fence_operand(T &®) { + asm volatile("" : "+r"(reg)::"memory"); + return reg; + } +#endif + +#if defined( __CUDA_ARCH__ ) && __CUDA_ARCH__ >= 900 + inline __device__ void smem_bar_init(uint32_t smem_ptr, uint32_t thread_count) { + asm volatile ("mbarrier.init.shared::cta.b64 [%0], %1;\n" :: "r"(smem_ptr), "r"(thread_count)); + } + + inline __device__ void smem_bar_set_transaction_count(uint32_t smem_ptr, uint32_t expected_copy_bytes, uint32_t pred = 0) { + asm volatile("{\n\t.reg .pred p;" + " \n\tsetp.eq.u32 p, %2, 1;" + " \n\t@p mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" + " \n\t}" :: "r"(smem_ptr), "r"(expected_copy_bytes), "r"(pred)); + } + + inline __device__ uint32_t smem_bar_peek(uint32_t smem_ptr, uint32_t bar_phase) { + uint32_t bar_phase_out; + asm volatile("{\n\t.reg .pred P1;" + " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%1], %2;" + " \n\tselp.b32 %0, 1, 0, P1; \n\t}" :"=r" (bar_phase_out):"r"(smem_ptr),"r"(bar_phase)); + return bar_phase_out; + } + + inline __device__ void smem_bar_wait(uint32_t smem_ptr, uint32_t bar_phase) { + uint32_t large_val = 0x989680; + asm volatile("{\n\t.reg .pred P1;" + " \n\tLAB_WAIT:" + " \n\tmbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1, %2;" + " \n\t@P1 bra.uni DONE;" + " \n\tbra.uni LAB_WAIT;" + " \n\tDONE:" + " \n\t}" :: "r"(smem_ptr),"r"(bar_phase), "r"(large_val)); + } + + inline __device__ + void + wait_barrier(uint32_t smem_int_ptr, + int phase_bit) // Current phase bit the barrier waiting to flip + { + asm volatile( + "{\n" + ".reg .pred P1;\n" + "LAB_WAIT:\n" + "mbarrier.try_wait.parity.shared::cta.b64 P1, [%0], %1;\n" + "@P1 bra.uni DONE;\n" + "bra.uni LAB_WAIT;\n" + "DONE:\n" + "}\n" + :: "r"(smem_int_ptr), + "r"(phase_bit)); + } + + inline __device__ void smem_bar_arrive(uint32_t smem_ptr) { + asm volatile("{\n\t.reg .b64 state;" + " \n\tmbarrier.arrive.shared::cta.b64 state, [%0];" + " \n\t}" :: "r"(smem_ptr)); + } + + // Barrier arrive on local smem + inline __device__ + void arrive_barrier(uint32_t smem_addr) { + asm volatile( + "{\n\t" + "mbarrier.arrive.shared::cta.b64 _, [%0];\n\t" + "}" + : + : "r"(smem_addr)); + } + +#endif + + extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *ptr); + + inline __device__ uint32_t get_smem_pointer(const void *ptr) { + return __nvvm_get_smem_pointer(const_cast<void *>(ptr)); + } + + extern "C" __device__ inline void *__nv_cvta_shared_to_generic_impl(size_t __ptr) { + return (void *)(void __attribute__((address_space(3))) *)__ptr; + } + inline __device__ void *set_smem_pointer(uint32_t ptr) { + return __nv_cvta_shared_to_generic_impl(ptr); + } + + inline __device__ uint32_t + cast_smem_ptr_to_uint(void const* const ptr) { + return static_cast<uint32_t>(__cvta_generic_to_shared(ptr)); + } + + inline __device__ void stsm_x4(r32 dst, r32 src[4]) { + asm volatile("stmatrix.sync.aligned.m8n8.x4.shared.b16 [%0], {%1, %2, %3, %4};\n" ::"r"(dst), "r"(src[0]), "r"(src[1]), "r"(src[2]), "r"(src[3])); + } + + inline __device__ void fence_view_async_shared(void){ + asm volatile ("fence.proxy.async.shared::cta;\n"); + } + + inline __device__ void sts_32(r32 dst, r32 src[1]) { + asm volatile("st.shared.b32 [%0], %1;\n" :: "r"(dst), "r"(src[0])); + } + + inline __device__ void lds_32(r32 dst[1], r32 src) { + asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst[0]) : "r"(src)); + } + + inline __device__ void stg_32(void *ptr, r32 val[1]) { + uint32_t *p = reinterpret_cast<uint32_t *>(ptr); + p[0] = val[0]; + } + + // Forward ReLU activations + + inline __device__ uint32_t fp32_exp2(uint32_t in) { + uint32_t out; + asm volatile("ex2.approx.ftz.f32 %0, %1;\n" : "=r"(out) : "r"(in)); + return out; + } + + inline __device__ void fp32x2_to_bf16x2(r32 dst[1], const r32 src[2]) { + asm volatile("cvt.rn.bf16x2.f32 %0, %1, %2;\n" : "=r"(dst[0]) : "r"(src[1]), "r"(src[0])); + } + + inline __device__ void bf16x2_to_fp32x2(r32 dst[2], const r32 src[1]) { + asm volatile( \ + "{\n" \ + " .reg .b16 lo, hi;\n" \ + " mov.b32 {lo, hi}, %2;\n" \ + " mov.b32 %0, {0, lo};\n" \ + " mov.b32 %1, {0, hi};\n" \ + "}\n" : "=r"(dst[0]), "=r"(dst[1]) : "r"(src[0])); + } + + //mma_pipeline_op 1 includes + typedef struct AttentionDescriptor { + // Input parameters + // b - batch + // q_h - num heads of q/dq/o/do + // k_h - num heads of k/dk + // v_h - num heads of v/dv + // s_q - max sequence length of q + // s_kv - max sequence length of kv + // d - hidden dim (head dim) + uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v; + uint16_t q_heads_per_k, q_heads_per_v, min_q_heads_per_kv; + } AttentionDescriptor_t; + + // CUtensorMap, when issued using bulk copy async functions, are cached in constant cache. + // But the producer kernel may have directly written to global memory, without invalidating this constant cache. + // This acquire fence, invalidates the memory address in constant cache, using UTMACCTL.IV. + inline __device__ void tma_descriptor_fence_acquire( + CUtensorMap const* p_desc + ) { +#if (__CUDA_ARCH__ >= 900) && (CUDACC_VERSION >= 123) + uint64_t gmem_int_desc = reinterpret_cast<uint64_t>(p_desc); + asm volatile ( + "fence.proxy.tensormap::generic.acquire.gpu [%0], 128;\n" + : + : "l"(gmem_int_desc) + : "memory"); + asm volatile ( + "cvta.global.u64 %0, %0;\n" + : + : "l"(gmem_int_desc), "l"(gmem_int_desc) + : "memory"); +#endif + } + + inline __device__ void utmaldg_4d_tiled ( + const void *p_desc, + uint32_t urb0, // smem offset + uint32_t urb1, // smem barrier offset + int32_t urb2, // m + int32_t urb3, // n + int32_t urb4, // b + int32_t urb5, // extra coord + const uint32_t elect_one, + const uint64_t mem_desc = MEM_DESC_DEFAULT + ) { + if (elect_one) { +#if __CUDA_ARCH__ >= 1200 && __CUDA_ARCH__ < 1300 + asm volatile( + "cp.async.bulk.tensor.4d.shared::cta.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" :: + "r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb2), + "r"(urb3), + "r"(urb4), + "r"(urb5), + "r"(urb1), + "l"(mem_desc) : "memory" + ); +#else + asm volatile( + "cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;\n" :: + "r"(urb0), + "l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb2), + "r"(urb3), + "r"(urb4), + "r"(urb5), + "r"(urb1), + "l"(mem_desc) : "memory" + ); +#endif + } + } + + inline __device__ void utmastg_4d_tiled( + const void *p_desc, + uint32_t smem_offset, + int32_t urb0, // m + int32_t urb1, // n + int32_t urb2, // h + int32_t urb3, // b + uint64_t mem_desc = MEM_DESC_DEFAULT + ) { + asm volatile( + "cp.async.bulk.tensor.4d.global.shared::cta.bulk_group [%0, {%1, %2, %3, %4}], [%5];\n" :: + "l"(reinterpret_cast<uint64_t>(p_desc)), + "r"(urb0), + "r"(urb1), + "r"(urb2), + "r"(urb3), + "r"(smem_offset) : "memory" + ); + } + + inline __device__ void ldgdepbar() { + asm volatile("cp.async.commit_group;\n" ::); + } + + template<int STAGES> + inline __device__ void depbar() { + asm volatile("cp.async.wait_group %0;\n" :: "n"(STAGES)); + } + + //mma_loop_op 2 includes + + //global_load_shared_store_op 4 includes + + // shared_load_op 5 includes + + // shared_load_op 6 includes + + //global_load_shared_store_op 7 includes + + //mma_op 8 includes +)KERNEL" + R"KERNEL( +// === Section: GMMA Operations === + inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) { + __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b); + warpgroup_commit(); + } + + // === Section: GMMA Operations === + inline __device__ void bf16gmma_fp32_64x128x16_TN_asmem_bsmem(const uint64_t &desc_a, const uint64_t &desc_b, r32 acc[64]) { + __wgmma_mma_async_bf16(64, 128, 16, false, false, false, false, true, acc, desc_a, desc_b); + } + +#define BMM_S_GMMA bf16gmma_fp32_64x128x16_TN_asmem_bsmem +#define BMM_S_GMMA_ISB bf16gmma_fp32_64x128x16_TN_asmem_bsmem_isb +#define BMM_S_GMMA_C0 bf16gmma_fp32_64x128x16_TN_asmem_bsmem_ignoreC + + //pointwise_calc_op 9 includes + + //global_load_op 10 includes + + //softmax_op 12 includes + + // global_store_op 13 includes + + // global_store_op 14 includes + + // shared_load_op 15 includes + + //global_load_shared_store_op 16 includes + + //mma_op 17 includes + inline __device__ void bf16gmma_fp32_64x64x16_TT_arf_bsmem_isb(const r32 a[4], const uint64_t &desc_b, r32 acc[32]) { + __wgmma_mma_async_bf16(64, 64, 16, false, false, true, false, true, acc, a, desc_b); + warpgroup_commit(); + } + + inline __device__ void bf16gmma_fp32_64x64x16_TT_arf_bsmem(const r32 a[4], const uint64_t &desc_b, r32 acc[32]) { + __wgmma_mma_async_bf16(64, 64, 16, false, false, true, false, true, acc, a, desc_b); + } + +#define BMM_O_GMMA bf16gmma_fp32_64x64x16_TT_arf_bsmem +#define BMM_O_GMMA_ISB bf16gmma_fp32_64x64x16_TT_arf_bsmem_isb +#define BMM_O_GMMA_C0 bf16gmma_fp32_64x64x16_TT_arf_bsmem_ignoreC + + // global_store_op 20 includes + + //output_loop_op 3 includes + + // shared_store_op 18 includes + + // shared_load_op 19 includes +} // namespace fort + +//receive_op 0 types +using namespace fort; + +static constexpr int THREADS_PER_WARP_0 = 32; +static constexpr int WARPS_PER_GROUP_0 = FORT_MIN(4, 384 / THREADS_PER_WARP_0); +static constexpr int THREADS_PER_WARP_GROUP_0 = THREADS_PER_WARP_0 * WARPS_PER_GROUP_0; +static constexpr int BITS_PER_REGISTER_0 = 32; // NOTE: sizeof(uint) +static constexpr int BYTES_PER_REGISTER_0 = BITS_PER_REGISTER_0 / 8; +static constexpr int THREADS_PER_GROUP_0 = WARPS_PER_GROUP_0 * THREADS_PER_WARP_0; + +// mma_pipeline_op 1 types +static constexpr int BYTES_PER_BANK_1 = 16; +static constexpr int BITS_PER_ELEMENT_1 = 16; +static constexpr int ELEMS_PER_BANK_1 = BYTES_PER_BANK_1 * 8 / BITS_PER_ELEMENT_1; +static constexpr int BYTES_PER_ELEMENT_1 = BITS_PER_ELEMENT_1 / 8; +static constexpr int BYTES_PER_FP16_1 = 2; +static constexpr int ELEMS_PER_VECTOR_1 = BYTES_PER_REGISTER_0 / BYTES_PER_ELEMENT_1; +static constexpr int BITS_PER_ACC_1 = 32; +static constexpr int BYTES_PER_ACC_1 = BITS_PER_ACC_1 / 8; +static constexpr int TILE_M_1 = 64; +static constexpr int TILE_N_1 = 128; +static constexpr int TILE_K_1 = 64; +static constexpr int TILE_O_1 = 64; +static constexpr int TILE_V_1 = TILE_K_1; +static constexpr int TILE_DV_1 = 64; +static constexpr int WARP_TILE_M_1 = 16; +static constexpr int WARP_TILE_N_1 = 16; +static constexpr int WARP_TILE_K_1 = 32 / BYTES_PER_ELEMENT_1; +static constexpr int WARPS_M_1 = 64 / 16; +static constexpr int WARPS_N_1 = 16 / 16; +static constexpr int WARPS_K_1 = 16 / 16; +static constexpr int STAGES_1 = 1; +static constexpr int GROUPS_M_1 = 1; +static constexpr int GMMA_TILE_M_1 = WARPS_M_1 * WARP_TILE_M_1; +static constexpr int GMMA_TILE_K_1 = WARPS_K_1 * WARP_TILE_K_1; +static constexpr int WARP_TILES_M_1 = TILE_M_1 / WARP_TILE_M_1; +static constexpr int WARP_TILES_N_1 = TILE_N_1 / WARP_TILE_N_1; +static constexpr int WARP_TILES_K_1 = TILE_K_1 / WARP_TILE_K_1; +static constexpr int WARP_REGS_1 = 8; +static constexpr int REGS_M_1 = WARP_TILES_M_1 / WARPS_M_1; +static constexpr int REGS_N_1 = WARP_TILES_N_1 / WARPS_N_1; +static constexpr int REGS_K_1 = WARP_TILES_K_1 / WARPS_K_1; +static constexpr int REGS_K_FOR_DP_1 = TILE_V_1 / 16; +static constexpr int REGS_dQ_1 = TILE_O_1 / 16; + +static constexpr int REGS_O_1 = 4; + +static constexpr int CGA_M_1 = 1; +static constexpr int CGA_N_1 = 1; +static constexpr int CTA_MMA_1 = 1; +static constexpr int M_TILES_PER_OUTPUT_TILE_1 = 4; +static constexpr int N_TILES_PER_OUTPUT_TILE_1 = 1; + +static constexpr int CTA_TILE_M_1 = TILE_M_1 * GROUPS_M_1; +static constexpr int CTA_TILE_N_1 = 64; +static constexpr int CTA_TILE_K_1 = 128; +static constexpr int BUFFERS_Q_1 = 2; +static constexpr int BUFFERS_K_1 = 2; +static constexpr int BUFFERS_V_1 = 2; +static constexpr int BUFFERS_O_1 = 1; +static constexpr int BUFFERS_D_1 = 1; +static constexpr int SMEM_Q_1 = TILE_M_1 * TILE_K_1 * BYTES_PER_ELEMENT_1 * 2; +static constexpr int SMEM_K_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1; +static constexpr int SMEM_V_1 = TILE_N_1 * TILE_K_1 * BYTES_PER_ELEMENT_1; +static constexpr int SMEM_PAGE_TABLE_1 = FORT_ROUND_UP(TILE_N_1 * 2 * 2 * sizeof(int), 1024); +static constexpr int SMEM_OFFSET_Q_1 = 1024 + (false ? 0 : SMEM_PAGE_TABLE_1); +static constexpr int SMEM_OFFSET_K_1 = SMEM_OFFSET_Q_1 + SMEM_Q_1 * BUFFERS_Q_1; +static constexpr int SMEM_OFFSET_V_1 = SMEM_OFFSET_K_1 + SMEM_K_1 * BUFFERS_K_1; +static constexpr int SMEM_OFFSET_O_1 = SMEM_OFFSET_V_1 + SMEM_V_1 * BUFFERS_V_1; +static constexpr int SMEM_OFFSET_D_1 = SMEM_OFFSET_O_1; +static constexpr int SMEM_OFFSET_BAND_BIAS_1 = SMEM_OFFSET_O_1; + +static constexpr int THREADS_ON_TILE_BARRIER_1 = 256+32+0; +static constexpr int TILE_ID_SYNC_2_BARRIER_1 = 2; +static constexpr int TILE_ID_SYNC_3_BARRIER_1 = 3; +static constexpr int SOFTMAX_1_BARRIER_1 = 4; +static constexpr int SOFTMAX_2_BARRIER_1 = 5; +static constexpr int MATH_WORKGROUP_1 = 6; +static constexpr int TMA_SYNC_BARRIER_1 = 7; + +static constexpr uint32_t BYTES_PER_GMMA_K_1 = GMMA_TILE_K_1 * BYTES_PER_ELEMENT_1; +static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_1 = BYTES_PER_GMMA_K_1 >> 4; +static constexpr uint32_t BYTES_PER_GMMA_K_TRANS_1 = GMMA_TILE_K_1 * 128; +static constexpr uint32_t BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 = BYTES_PER_GMMA_K_TRANS_1 >> 4; + +static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1 = 2; +static constexpr uint32_t GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1 = 62; // bits 63-62 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_Q_1 & +((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1)) +<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1; +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_K_1 & +((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1)) +<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1; +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 = 1; // SWIZZLE_NONE=0, SWIZZLE_128B=1, SWIZZLE_64B=2, SWIZZLE_32B=3 +static constexpr uint64_t GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1 = (GMMA_DESCRIPTOR_SWIZZLE_MODE_VALUE_V_1 & +((1u << GMMA_DESCRIPTOR_SWIZZLE_MODE_BITS_1) - 1)) +<< GMMA_DESCRIPTOR_SWIZZLE_MODE_SHIFT_1; + +static constexpr uint32_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1 = 32; // bits 45-32 +static constexpr uint64_t BYTES_PER_LEADING_DIM_1 = 128; +static constexpr uint64_t STRIDE_BYTE_OFFSET_Q_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2 +static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = STRIDE_BYTE_OFFSET_Q_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1; +static constexpr uint64_t STRIDE_BYTE_OFFSET_K_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2 +static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = STRIDE_BYTE_OFFSET_K_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1; +static constexpr uint64_t STRIDE_BYTE_OFFSET_V_1 = (BYTES_PER_LEADING_DIM_1 * 8) / 16; // SWIZZLE_NONE=0, SWIZZLE_128B=8, SWIZZLE_64B=4, SWIZZLE_32B=2 +static constexpr uint64_t GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = STRIDE_BYTE_OFFSET_V_1 << GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_SHIFT_1; + +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1 = 16; // bits 29-16 +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1 = 128 * 64 / 16; // Not used??? +static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_Q_1 +<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1; +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1 = 128 * 32 / 16; // Not used??? +static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_K_1 +<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1; +static constexpr uint32_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1 = 128 * TILE_N_1 / 16; +static constexpr uint64_t GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1 = GMMA_DESCRIPTOR_LD_BYTE_OFFSET_VALUE_V_1 +<< GMMA_DESCRIPTOR_LD_BYTE_OFFSET_SHIFT_1; + +inline __device__ constexpr uint64_t create_gmma_desc_q_1() { + return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_Q_1) + | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_Q_1 + | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_Q_1; +} + +inline __device__ constexpr uint64_t create_gmma_desc_k_1() { + return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_K_1) + | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_K_1 + | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_K_1; +} + +// === Section: GMMA Descriptors & Mask Helpers === +)KERNEL" + R"KERNEL( +// === Section: GMMA Descriptors & Mask Helpers === +inline __device__ constexpr uint64_t create_gmma_desc_v_1() { + return ((uint64_t)0 | GMMA_DESCRIPTOR_SWIZZLE_MODE_IN_BIT_LOCATION_V_1) + | GMMA_DESCRIPTOR_STRIDE_BYTE_OFFSET_IN_BIT_LOCATION_V_1 + | GMMA_DESCRIPTOR_LD_BYTE_OFFSET_IN_BIT_LOCATION_V_1; +} + +class Gmma_descriptor { + public: + inline __device__ Gmma_descriptor(uint64_t desc_) { + desc = desc_; + } + template<int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void set_smem(uint32_t smem) { + desc |= (static_cast<uint64_t>(smem & 0xFFFFFF) >> 4); + + max_desc = desc + (BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1); + } + template<int BYTES_PER_BUFFER, int BUFFER_COUNT> + inline __device__ void increment_smem_buffer() { + int2 &tmp = reinterpret_cast<int2 &>(desc); + tmp.x += (desc >= max_desc) ? -(BYTES_PER_BUFFER >> 4) * (BUFFER_COUNT - 1) + : (BYTES_PER_BUFFER >> 4); + } + + uint64_t desc; + uint64_t max_desc; +}; + +//global_load_shared_store_op 4 types +static constexpr int BITS_PER_ELEMENT_4 = 16; +static constexpr int BYTES_PER_ELEMENT_4 = BITS_PER_ELEMENT_4 / 8; +static constexpr int BYTES_PER_ACCESS_4 = 16; +static constexpr int TILE_M_4 = 64; +static constexpr int TILE_N_4 = 64; +static constexpr int BYTES_PER_SMEM_4 = TILE_M_4 * TILE_N_4 * BYTES_PER_ELEMENT_4; + +// shared_load_op 5 types +static constexpr int BITS_PER_ELEMENT_5 = 16; +static constexpr int BYTES_PER_ELEMENT_5 = 2; +static constexpr int BYTES_PER_QUAD_5 = 16; +static constexpr int WARP_TILE_M_5 = 16; +static constexpr int WARP_TILE_N_5 = 16; +static constexpr int TILE_M_5 = 64; +static constexpr int TILE_N_5 = 64; +static constexpr int BYTES_PER_SMEM_5 = TILE_M_5 * TILE_N_5 * BYTES_PER_ELEMENT_5; +static constexpr int WARPS_M_5 = 4; +static constexpr int WARPS_N_5 = 1; +static constexpr int WARP_TILES_M_5 = TILE_M_5 / WARP_TILE_M_5; +static constexpr int WARP_TILES_N_5 = TILE_N_5 / WARP_TILE_N_5; +static constexpr int THREADS_PER_WARP_TILE_M_5 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_5 = 4; +static constexpr int REGS_M_5 = WARP_TILES_M_5 / WARPS_M_5; +static constexpr int REGS_N_5 = WARP_TILES_N_5 / WARPS_N_5; +static constexpr int BYTES_PER_LD_5 = 128; +static constexpr int SWIZZLE_SCALE_5 = FORT_MIN(BYTES_PER_LD_5 / 16, WARPS_PER_GROUP_0 * 4); + +// shared_load_op 6 types +static constexpr int BITS_PER_ELEMENT_6 = 16; +static constexpr int BYTES_PER_ELEMENT_6 = 2; +static constexpr int BYTES_PER_QUAD_6 = 16; +static constexpr int WARP_TILE_M_6 = 16; +static constexpr int WARP_TILE_N_6 = 16; +static constexpr int TILE_M_6 = 128; +static constexpr int TILE_N_6 = 64; + +static constexpr int BYTES_PER_SMEM_6 = TILE_M_6 * TILE_N_6 * BYTES_PER_ELEMENT_6; +static constexpr int WARPS_M_6 = 1; +static constexpr int WARPS_N_6 = 1; +static constexpr int WARP_TILES_M_6 = TILE_M_6 / WARP_TILE_M_6; +static constexpr int WARP_TILES_N_6 = TILE_N_6 / WARP_TILE_N_6; +static constexpr int THREADS_PER_WARP_TILE_M_6 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_6 = 4; +static constexpr int REGS_M_6 = WARP_TILES_M_6 / WARPS_M_6; +static constexpr int REGS_N_6 = WARP_TILES_N_6 / WARPS_N_6; +static constexpr int BYTES_PER_LD_6 = 128; +static constexpr int SWIZZLE_SCALE_6 = FORT_MIN(BYTES_PER_LD_6 / 16, WARPS_PER_GROUP_0 * 4); + +//global_load_shared_store_op 7 types +static constexpr int BITS_PER_ELEMENT_7 = 16; +static constexpr int BYTES_PER_ELEMENT_7 = BITS_PER_ELEMENT_7 / 8; +static constexpr int BYTES_PER_ACCESS_7 = 16; +static constexpr int TILE_M_7 = 128; +static constexpr int TILE_N_7 = 64; +static constexpr int BYTES_PER_SMEM_7 = TILE_M_7 * TILE_N_7 * BYTES_PER_ELEMENT_7; + +//mma_op 8 types +static constexpr int BYTES_PER_ELEMENT_8 = 2; +static constexpr int BYTES_PER_ACC_8 = 4; +static constexpr int WARP_TILE_M_8 = 16; +static constexpr int WARP_TILE_N_8 = 16; +static constexpr int WARP_TILE_K_8 = 16; +static constexpr int TILE_M_8 = 64; +static constexpr int TILE_N_8 = 128; +static constexpr int TILE_K_8 = 64; +static constexpr int WARPS_M_8 = 4; +static constexpr int WARPS_N_8 = 1; +static constexpr int WARP_TILES_M_8 = TILE_M_8 / WARP_TILE_M_8; +static constexpr int WARP_TILES_N_8 = TILE_N_8 / WARP_TILE_N_8; +static constexpr int MMA_STEPS_K_8 = TILE_K_8 / WARP_TILE_K_8; +static constexpr int WARP_REGS_8 = 8; +static constexpr int REGS_M_8 = WARP_TILES_M_8 / WARPS_M_8; +static constexpr int REGS_N_8 = WARP_TILES_N_8 / WARPS_N_8; + +//pointwise_calc_op 9 types +static constexpr int WARP_TILE_M_9 = 16; +static constexpr int WARP_TILE_N_9 = 16; +static constexpr int TILE_M_9 = 64; +static constexpr int TILE_N_9 = 128; +static constexpr int WARPS_M_9 = 4; +static constexpr int WARPS_N_9 = 1; +static constexpr int WARP_TILES_M_9 = TILE_M_9 / WARP_TILE_M_9; +static constexpr int WARP_TILES_N_9 = TILE_N_9 / WARP_TILE_N_9; +static constexpr int WARP_REGS_9 = 8; +static constexpr int REGS_M_9 = WARP_TILES_M_9 / WARPS_M_9; +static constexpr int REGS_N_9 = WARP_TILES_N_9 / WARPS_N_9; + +//global_load_op 10 types +static constexpr int BITS_PER_ELEMENT_10 = 32; +static constexpr int BYTES_PER_ELEMENT_10 = 4; +static constexpr int REGISTERS_PER_VECTOR_10 = 1; +static constexpr int REGISTERS_PER_ACCESS_10 = 1; + +//mha_mask_op 11 types +static constexpr int WARP_TILE_M_11 = 16; +static constexpr int WARP_TILE_N_11 = 16; +static constexpr int TILE_M_11 = 64; +static constexpr int TILE_N_11 = 128; +static constexpr int WARPS_M_11 = 4; +static constexpr int WARPS_N_11 = 1; +static constexpr int WARP_TILES_M_11 = TILE_M_11 / WARP_TILE_M_11; +static constexpr int WARP_TILES_N_11 = TILE_N_11 / WARP_TILE_N_11; +static constexpr int WARP_REGS_11 = 8; +static constexpr int REGS_M_11 = WARP_TILES_M_11 / WARPS_M_11; +static constexpr int REGS_N_11 = WARP_TILES_N_11 / WARPS_N_11; +inline __device__ bool compute_diagonal_band_mask_11(const int row, const int col, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound) { + constexpr bool is_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_right_bound = true; + constexpr bool is_left_bound = false; + constexpr bool need_oob_check = false; + + const int diag = is_bottom_right_alignment ? row + (actual_seqlen_kv - actual_seqlen_q) : row; + const int shifted_right_bound = is_shift_right_bound ? diag + shift_right_bound : diag; + const bool right_bound_mask = is_right_bound ? col <= shifted_right_bound : true; + const bool left_bound_mask = is_left_bound ? col + left_bound > diag : true; + const bool oob_check = need_oob_check ? (row < actual_seqlen_q && col < actual_seqlen_kv) : true; + return right_bound_mask && left_bound_mask && oob_check; +} + +//softmax_op 12 types +static constexpr int BYTES_PER_ELEMENT_12 = 2; +static constexpr int WARP_TILE_M_12 = 16; +static constexpr int WARP_TILE_N_12 = 16; +static constexpr int TILE_M_12 = 64; +static constexpr int TILE_N_12 = 128; +static constexpr int WARPS_M_12 = 4; +static constexpr int WARPS_N_12 = 1; +static constexpr int WARP_TILES_M_12 = TILE_M_12 / WARP_TILE_M_12; +static constexpr int WARP_TILES_N_12 = TILE_N_12 / WARP_TILE_N_12; +static constexpr int THREADS_PER_WARP_TILE_M_12 = 8; + +static constexpr int THREADS_PER_WARP_TILE_N_12 = 4; +static constexpr int WARP_REGS_12 = 8; +static constexpr int REGS_M_12 = WARP_TILES_M_12 / WARPS_M_12; +static constexpr int REGS_N_12 = WARP_TILES_N_12 / WARPS_N_12; +static constexpr int ROWS_PER_THREAD_12 = TILE_M_12 / WARPS_M_12 / THREADS_PER_WARP_TILE_M_12; + +// global_store_op 13 types +static constexpr int BYTES_PER_ELEMENT_13 = 4; +static constexpr int WARP_TILE_M_13 = 16; +static constexpr int WARP_TILE_N_13 = 16; +static constexpr int TILE_M_13 = 64; +static constexpr int TILE_N_13 = 128; +static constexpr int WARPS_M_13 = 4; +static constexpr int WARPS_N_13 = 1; +static constexpr int WARP_TILES_M_13 = TILE_M_13 / WARP_TILE_M_13; +static constexpr int WARP_TILES_N_13 = TILE_N_13 / WARP_TILE_N_13; +static constexpr int THREADS_PER_WARP_TILE_M_13 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_13 = 4; +static constexpr int ROWS_PER_THREAD_13 = TILE_M_13 / WARPS_M_13 / THREADS_PER_WARP_TILE_M_13; + +// global_store_op 14 types +static constexpr int BYTES_PER_ELEMENT_14 = 4; +static constexpr int WARP_TILE_M_14 = 16; +static constexpr int WARP_TILE_N_14 = 16; +static constexpr int TILE_M_14 = 64; +static constexpr int TILE_N_14 = 128; +static constexpr int WARPS_M_14 = 4; +static constexpr int WARPS_N_14 = 1; +static constexpr int WARP_TILES_M_14 = TILE_M_14 / WARP_TILE_M_14; +static constexpr int WARP_TILES_N_14 = TILE_N_14 / WARP_TILE_N_14; +static constexpr int THREADS_PER_WARP_TILE_M_14 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_14 = 4; +static constexpr int ROWS_PER_THREAD_14 = TILE_M_14 / WARPS_M_14 / THREADS_PER_WARP_TILE_M_14; + +// shared_load_op 15 types +static constexpr int BITS_PER_ELEMENT_15 = 16; +static constexpr int BYTES_PER_ELEMENT_15 = 2; +static constexpr int BYTES_PER_QUAD_15 = 16; +static constexpr int WARP_TILE_M_15 = 16; +static constexpr int WARP_TILE_N_15 = 16; +static constexpr int TILE_M_15 = 128; +static constexpr int TILE_N_15 = 64; +static constexpr int BYTES_PER_SMEM_15 = TILE_M_15 * TILE_N_15 * BYTES_PER_ELEMENT_15; +static constexpr int WARPS_M_15 = 1; +static constexpr int WARPS_N_15 = 1; +static constexpr int WARP_TILES_M_15 = TILE_M_15 / WARP_TILE_M_15; +static constexpr int WARP_TILES_N_15 = TILE_N_15 / WARP_TILE_N_15; +static constexpr int THREADS_PER_WARP_TILE_M_15 = 8; +static constexpr int THREADS_PER_WARP_TILE_N_15 = 4; +static constexpr int REGS_M_15 = WARP_TILES_M_15 / WARPS_M_15; +static constexpr int REGS_N_15 = WARP_TILES_N_15 / WARPS_N_15; +static constexpr int BYTES_PER_LD_15 = 128; +static constexpr int SWIZZLE_SCALE_15 = FORT_MIN(BYTES_PER_LD_15 / 16, WARPS_PER_GROUP_0 * 4); + +//global_load_shared_store_op 16 types +static constexpr int BITS_PER_ELEMENT_16 = 16; +static constexpr int BYTES_PER_ELEMENT_16 = BITS_PER_ELEMENT_16 / 8; +static constexpr int BYTES_PER_ACCESS_16 = 16; +static constexpr int TILE_M_16 = 128; +static constexpr int TILE_N_16 = 64; +static constexpr int BYTES_PER_SMEM_16 = TILE_M_16 * TILE_N_16 * BYTES_PER_ELEMENT_16; + +//mma_op 17 types +static constexpr int BYTES_PER_ELEMENT_17 = 2; +static constexpr int BYTES_PER_ACC_17 = 4; +static constexpr int WARP_TILE_M_17 = 16; +static constexpr int WARP_TILE_N_17 = 16; +static constexpr int WARP_TILE_K_17 = 16; +static constexpr int TILE_M_17 = 64; +static constexpr int TILE_N_17 = 64; +static constexpr int TILE_K_17 = 128; +static constexpr int WARPS_M_17 = 4; +static constexpr int WARPS_N_17 = 1; +static constexpr int WARP_TILES_M_17 = TILE_M_17 / WARP_TILE_M_17; +static constexpr int WARP_TILES_N_17 = TILE_N_17 / WARP_TILE_N_17; +static constexpr int MMA_STEPS_K_17 = TILE_K_17 / WARP_TILE_K_17; +static constexpr int WARP_REGS_17 = 8; +static constexpr int REGS_M_17 = WARP_TILES_M_17 / WARPS_M_17; +static constexpr int REGS_N_17 = WARP_TILES_N_17 / WARPS_N_17; + +// global_store_op 20 types + +// mma_loop_op 2 types +inline __device__ int2 compute_kv_loop_bounds(const int row_coord, const int ROW_TILE_SIZE, const int COL_TILE_SIZE, const int actual_seqlen_kv, const int actual_seqlen_q, const int shift_right_bound, const int left_bound) +{ + constexpr bool is_right_bound = true; + constexpr bool is_right_bound_bottom_right_alignment = false; + constexpr bool is_shift_right_bound = false; + constexpr bool is_left_bound = false; + constexpr bool is_left_bound_bottom_right_alignment = false; + + const int right_bound_diagonal = is_right_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord; + const int shifted_right_bound_diagonal = is_shift_right_bound ? right_bound_diagonal + shift_right_bound : right_bound_diagonal; + const int left_bound_diagonal = is_left_bound_bottom_right_alignment ? row_coord + (actual_seqlen_kv - actual_seqlen_q) : row_coord; + + const int kv_loop_left_bound = is_left_bound ? FORT_MAX(0, (left_bound_diagonal - left_bound) / COL_TILE_SIZE) : 0; + const int kv_loop_right_bound = is_right_bound ? FORT_MIN(FORT_DIV_UP(shifted_right_bound_diagonal + ROW_TILE_SIZE, COL_TILE_SIZE), FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE)) : FORT_DIV_UP(actual_seqlen_kv, COL_TILE_SIZE); + return make_int2(kv_loop_left_bound, kv_loop_right_bound); +} + +// output_loop_op 3 types +static constexpr int BYTES_PER_BANK_3 = 16; +static constexpr int LDS_TILE_M_3 = 16; +static constexpr int LDS_TILE_N_3 = 32; +static constexpr int ACC_CORE_MATRIX_ROWS_3 = 8; // NOTE: fixed due to GMMA design +static constexpr int ACC_CORE_MATRIX_COLS_3 = 8; // NOTE: fixed due to GMMA design +static constexpr int ELEMENTS_PER_VECTOR_3 = 8; +static constexpr int LDS_PER_TILE_3 = ELEMENTS_PER_VECTOR_3 / 2; +static constexpr int LDS_TILES_N_3 = FORT_MAX(CTA_TILE_N_1 / LDS_TILE_N_3, 1); +static constexpr int LDS_TILES_M_3 = FORT_MAX(1, (CTA_TILE_M_1 / GROUPS_M_1) / (LDS_TILE_M_3 * WARPS_PER_GROUP_0)); +static constexpr int VECTORS_PER_LDS_TILES_3 = LDS_TILE_M_3 / ACC_CORE_MATRIX_ROWS_3; +static constexpr int STS_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3; +static constexpr int STSM_X4_PER_OUTPUT_TILE_N_3 = CTA_TILE_N_1 / ACC_CORE_MATRIX_COLS_3 / 2; +static constexpr int BANKS_PER_PAD_LINE_3 = BYTES_PER_ACC_1 == 4 ? 1 : 2; + +static constexpr int PADDING_BYTES_3 = BANKS_PER_PAD_LINE_3 * BYTES_PER_BANK_3 * LDS_PER_TILE_3; +)KERNEL" + R"KERNEL( +static constexpr int BYTES_PER_STS_PER_WARP_3= 16 * THREADS_PER_WARP_0; // 16 bytes due to STS_128 +static constexpr int BYTES_PER_LDS_TILE_3 = LDS_TILE_N_3 * LDS_TILE_M_3 * BYTES_PER_ACC_1 + PADDING_BYTES_3; +static constexpr int BYTES_PER_WARP_3 = LDS_TILES_N_3 * BYTES_PER_LDS_TILE_3; + +static constexpr int ELEMS_PER_STS_BLOCK_3 = 16; + +static constexpr int STG_THREADS_PER_TILE_N_3 = LDS_TILE_N_3 / ELEMENTS_PER_VECTOR_3; +static constexpr int EPILOGUE_SMEM_SIZE_PER_XMMA_M_3 = BYTES_PER_WARP_3 * WARPS_PER_GROUP_0; + +// shared_store_op 18 types + +// shared_load_op 19 types +static constexpr int BITS_PER_ELEMENT_19 = 32 * 1; +static constexpr int BYTES_PER_ELEMENT_19 = BITS_PER_ELEMENT_19 / 8; +static constexpr int BITS_PER_VECTOR_19 = BITS_PER_ELEMENT_19 * ELEMENTS_PER_VECTOR_3; +static constexpr int BYTES_PER_VECTOR_19 = BITS_PER_VECTOR_19 / 8; +static constexpr int REGISTERS_PER_VECTOR_19 = BITS_PER_VECTOR_19 / BITS_PER_REGISTER_0; + +//receive_op 0 code + +// === Section: Kernel Function === +)KERNEL" + R"KERNEL( +// === Section: Kernel Function === +extern "C" __global__ __launch_bounds__(384, 1) +void cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x64_4x1x1_cga1x1x1_kernel0_0(const AttentionDescriptor_t attnDesc +, int num_tiles_1 +, const FastDivisor_t tiles_hr_div_1 +, const FastDivisor_t tiles_r_div_1 +, int32_t* tile_id_counter +, __grid_constant__ const CUtensorMap tma_Q +, __grid_constant__ const CUtensorMap tma_K +, float attn_scale +, float neg_infinity +, void* d_max +, fort::tensor_descriptor desc_max +, void* d_sum_exp +, fort::tensor_descriptor desc_sum_exp +, __grid_constant__ const CUtensorMap tma_V +, __grid_constant__ const CUtensorMap tma_O +) { + extern __shared__ char smem_[]; + uint32_t smem_0 = get_smem_pointer(smem_); + + //receive_op 0 decls + + // mma_pipeline_op 1 decls + const uint32_t tid = threadIdx.x % THREADS_PER_GROUP_0; + const uint32_t gid = threadIdx.x / THREADS_PER_GROUP_0; + const uint32_t wid = threadIdx.x / 32; + const uint32_t tiw = threadIdx.x % 32; + + const uint32_t elect_one = fort::elect_one_sync(); + + uint32_t smem_1 = smem_0; + uint32_t smem_bar_qkv_1 = smem_1; + uint32_t smem_page = smem_1 + 1024; + uint32_t smem_Q = smem_1 + SMEM_OFFSET_Q_1; + uint32_t smem_K = smem_1 + SMEM_OFFSET_K_1; + uint32_t smem_V = smem_1 + SMEM_OFFSET_V_1; + uint32_t smem_O = smem_1 + SMEM_OFFSET_O_1; + uint32_t smem_d_1 = smem_1 + SMEM_OFFSET_D_1; + uint32_t smem_band_bias_1 = smem_1 + SMEM_OFFSET_BAND_BIAS_1; + + uint32_t smem_bar_qkv_tma_1 = smem_bar_qkv_1; + uint32_t smem_bar_qkv_mma_1 = smem_bar_qkv_1 + 1 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); + uint32_t smem_tile_id_1 = smem_bar_qkv_1 + 2 * 8 * (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); + uint32_t smem_bar_tile_id_tma_1 = smem_tile_id_1 + 16; + uint32_t smem_bar_bias_tma_1 = smem_bar_tile_id_tma_1 + 8; + + uint32_t smem_bar_bias_mma_1 = smem_bar_bias_tma_1 + 8 * 2; + + if (elect_one) { + for (int i = wid; i < (BUFFERS_Q_1 + BUFFERS_K_1 + BUFFERS_V_1 + BUFFERS_D_1 + 0); i+=12) { + smem_bar_init(smem_bar_qkv_tma_1 + i * 8, 1); + smem_bar_init(smem_bar_qkv_mma_1 + i * 8, 2); + } + } + __syncthreads(); + + // mma_pipeline_op 1 code + const int actual_num_tiles_1 = num_tiles_1; + if (gid == 0) { + reg_dealloc<40>(); + const uint32_t local_wid = wid % 4; + + uint32_t tile_id; + uint32_t batch_coord_1 = 0, head_coord_1 = 0, q_row_coord = 0, rows_temp; + uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1; + int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q; + + if (local_wid == 0) { + uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1; + uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1; + + uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1; + uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1; + + uint32_t buffer_id_q = 0; + uint32_t buffer_id_kv = 0; + uint32_t cnt_q = 0; + uint32_t cnt_kv = 0; + + uint32_t sts_page_buffer_id = 0; + uint32_t lds_page_buffer_id = 0; + + int cumulative_tiles = 0; + if (tiw == 0) { + tile_id = atomicAdd(tile_id_counter, 1); + } + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + + named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + sts_32(smem_tile_id_1, &tile_id); + } + named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + + // Persistent loop over output tiles +#pragma unroll 1 + while (tile_id < actual_num_tiles_1) { + fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp); + fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord); + q_row_coord *= TILE_M_1 * 2; + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + + const int left_bound = 0; + const int shift_right_bound = 0; + + int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + int kv_loop_left_bound = kv_loop_bounds.x; + int kv_loop_right_bound = kv_loop_bounds.y; + + //global_load_shared_store_op 4 decls + + //global_load_shared_store_op 7 decls + + //global_load_shared_store_op 16 decls + + uint32_t local_smem_q = smem_Q + buffer_id_q * SMEM_Q_1; + uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8; + uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8; + + if (kv_loop_left_bound < kv_loop_right_bound) { + uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 1 : 0; + + cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0; + buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0; + + if (!smem_bar_peek(local_smem_bar_mma_q, smem_bar_phase_q)) { + smem_bar_wait(local_smem_bar_mma_q, smem_bar_phase_q); + } + + smem_bar_set_transaction_count(local_smem_bar_tma_q, SMEM_Q_1, elect_one); + { + const uint32_t row_coord = q_row_coord; + + //global_load_shared_store_op 4 code +#pragma unroll + for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_Q, + local_smem_q + i * TILE_M_1 * 2, + local_smem_bar_tma_q, + i / BYTES_PER_ELEMENT_1, + row_coord, + head_coord_1 + 0, + batch_coord_1, + elect_one); + } + } + } + +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) { + const int p_col_coord = kv_loop * TILE_N_1; + + uint32_t local_smem_k = smem_K + buffer_id_kv * SMEM_K_1; + uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8; + + uint32_t local_smem_v = smem_V + buffer_id_kv * SMEM_V_1; + uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8; + + uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8; + + uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 1 : 0; + + cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0; + buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0; + + uint32_t kv_col_base = (kv_loop + 1) * TILE_N_1; + + if (!smem_bar_peek(local_smem_bar_mma_k, smem_bar_phase_kv)) { + smem_bar_wait(local_smem_bar_mma_k, smem_bar_phase_kv); + } + smem_bar_set_transaction_count(local_smem_bar_tma_k, SMEM_K_1, elect_one); + + //global_load_shared_store_op 7 code +#pragma unroll + for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128) { + utmaldg_4d_tiled(&tma_K, + local_smem_k + i * TILE_N_1, + local_smem_bar_tma_k, + i / BYTES_PER_ELEMENT_1, + p_col_coord, + head_coord_k_1, + batch_coord_1, + elect_one); + } + if (!smem_bar_peek(local_smem_bar_mma_v, smem_bar_phase_kv)) { + smem_bar_wait(local_smem_bar_mma_v, smem_bar_phase_kv); + } + smem_bar_set_transaction_count(local_smem_bar_tma_v, SMEM_V_1, elect_one); + + //global_load_shared_store_op 16 code +#pragma unroll + for (int i = 0; i < TILE_K_1 * BYTES_PER_ELEMENT_1; i += 128 * CTA_MMA_1) { + utmaldg_4d_tiled(&tma_V, + local_smem_v + i * TILE_N_1, + local_smem_bar_tma_v, + 0 + i / BYTES_PER_ELEMENT_1, + p_col_coord, + head_coord_v_1, + batch_coord_1, + elect_one); + } + lds_page_buffer_id ^= 1; + } + if (kv_loop_left_bound < kv_loop_right_bound) { + lds_page_buffer_id ^= 1; + } + + if (tiw == 0) { + tile_id = atomicAdd(tile_id_counter, 1); + } + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + + named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + sts_32(smem_tile_id_1, &tile_id); + } + named_barrier_arrive(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + } + named_barrier_wait(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + } + reg_dealloc<40>(); + } else { + reg_alloc<232>(); + named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + + const uint32_t local_wid = wid % 4; + const uint32_t local_gid = gid % 2; + + uint32_t tile_id; + uint32_t batch_coord_1, head_coord_1, q_row_coord, rows_temp; + uint32_t head_coord_from_grid_1, head_coord_k_1, head_coord_v_1, head_coord_q_offset_1; + int actual_seqlen_kv_1 = attnDesc.s_kv, actual_seqlen_q_1 = attnDesc.s_q, oob_for_stats_1 = attnDesc.s_q; + + uint32_t smem_bar_q_tma = smem_bar_qkv_tma_1; + uint32_t smem_bar_k_tma = smem_bar_q_tma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_tma = smem_bar_k_tma + 8 * BUFFERS_K_1; + + uint32_t smem_bar_q_mma = smem_bar_qkv_mma_1; + uint32_t smem_bar_k_mma = smem_bar_q_mma + 8 * BUFFERS_Q_1; + uint32_t smem_bar_v_mma = smem_bar_k_mma + 8 * BUFFERS_K_1; + + uint32_t buffer_id_q = 0; + uint32_t buffer_id_kv = 0; + uint32_t cnt_q = 0; + uint32_t cnt_kv = 0; + + static constexpr float inv_ln2 = 1.4426950408889634074f; + static constexpr float ln2 = 0.6931471805599453094f; + + Gmma_descriptor gmma_desc_q(create_gmma_desc_q_1()); + Gmma_descriptor gmma_desc_k(create_gmma_desc_k_1()); + Gmma_descriptor gmma_desc_v(create_gmma_desc_v_1()); + + gmma_desc_q.set_smem<SMEM_Q_1, BUFFERS_Q_1>(smem_Q + local_gid * TILE_M_1 * 128); + gmma_desc_k.set_smem<SMEM_K_1, BUFFERS_K_1>(smem_K); + gmma_desc_v.set_smem<SMEM_V_1, BUFFERS_V_1>(smem_V); + + named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + lds_32(&tile_id, smem_tile_id_1); + } + named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + + // Persistent loop over output tiles +#pragma unroll 1 + while (tile_id < actual_num_tiles_1) { + fastDivMod(tiles_hr_div_1, tile_id, batch_coord_1, rows_temp); + fastDivMod(tiles_r_div_1, rows_temp, head_coord_from_grid_1, q_row_coord); + q_row_coord = q_row_coord * TILE_M_1 * 2; + head_coord_1 = head_coord_from_grid_1; + head_coord_k_1 = head_coord_1 / attnDesc.q_heads_per_k; + head_coord_v_1 = head_coord_1 / attnDesc.q_heads_per_v; + const int left_bound = 0; + const int shift_right_bound = 0; + + int2 kv_loop_bounds = compute_kv_loop_bounds(q_row_coord, TILE_M_1 * 2, TILE_N_1, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + int kv_loop_left_bound = kv_loop_bounds.x; + int kv_loop_right_bound = kv_loop_bounds.y; + q_row_coord += local_gid * TILE_M_1; + + const int causal_mask_col = (tiw % 4) * 2; + const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4); + + // mma_loop_op 2 decls + + //global_load_shared_store_op 4 decls + + // shared_load_op 5 decls + + // shared_load_op 6 decls + + //global_load_shared_store_op 7 decls + + //mma_op 8 decls + r32 reg_8_0[REGS_M_8][REGS_N_8][WARP_REGS_8]; + + //pointwise_calc_op 9 decls + + //global_load_op 10 decls + r32 reg_10_0[1]; + reg_10_0[0] = reinterpret_cast<const r32 &>(attn_scale); + const int oob_M_10 = 1; + const int oob_N_10 = 1; + + //mha_mask_op 11 decls + + //softmax_op 12 decls + r32 reg_12_0[REGS_M_12][REGS_N_12][4]; // output for second gemm + r32 reg_12_1[ROWS_PER_THREAD_12]; // acc_max + r32 reg_12_2[ROWS_PER_THREAD_12]; // p_max + r32 reg_12_3[ROWS_PER_THREAD_12]; // acc_sum + r32 reg_12_4[ROWS_PER_THREAD_12]; // p_sum + r32 reg_12_5[ROWS_PER_THREAD_12]; // softmax stats + float beta_12[ROWS_PER_THREAD_12]; + +#pragma unroll + for (int i = 0; i < ROWS_PER_THREAD_12; ++i) { + reinterpret_cast<float &>(reg_12_1[i]) = NEG_INFINITY; + reinterpret_cast<float &>(reg_12_3[i]) = 0.0f; + } + + //global_store_op 13 decls + int oob_M_13 = desc_max.dims[2]; + int row_13 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4); + char *ptr_13 = reinterpret_cast<char *>(d_max) + + batch_coord_1 * desc_max.strides[0] * BYTES_PER_ELEMENT_13 + + head_coord_1 * desc_max.strides[1] * BYTES_PER_ELEMENT_13 + + row_13 * desc_max.strides[2] * BYTES_PER_ELEMENT_13; + + //global_store_op 14 decls + int oob_M_14 = desc_sum_exp.dims[2]; + int row_14 = q_row_coord + local_wid * WARP_TILE_M_1 + (tiw / 4); + char *ptr_14 = reinterpret_cast<char *>(d_sum_exp) + + batch_coord_1 * desc_sum_exp.strides[0] * BYTES_PER_ELEMENT_14 +)KERNEL" + R"KERNEL( + + head_coord_1 * desc_sum_exp.strides[1] * BYTES_PER_ELEMENT_14 + + row_14 * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14; + + // shared_load_op 15 decls + + //global_load_shared_store_op 16 decls + + //mma_op 17 decls + + r32 reg_17_0[REGS_M_17][REGS_N_17][WARP_REGS_17]; + + //global_store_op 20 decls + static constexpr int cols_per_step_20 = (TILE_K_1 <= 128) ? TILE_K_1 : 64; + uint32_t smem_20 = smem_O + (local_gid * 4 + local_wid) * 16 * cols_per_step_20 * BYTES_PER_ELEMENT_1; + + const int swizzled_row_20 = (tiw % 16); + const int swizzled_col_20 = (tiw / 16); + constexpr int stsm_per_tile_20 = 128 / (BYTES_PER_BANK_1 * 2); + uint32_t stsm_base_20[stsm_per_tile_20]; + +#pragma unroll + for (int n = 0; n < stsm_per_tile_20; ++n) { + stsm_base_20[n] = smem_20 + ((swizzled_row_20 % 8) ^ (n * 2 + swizzled_col_20)) * BYTES_PER_BANK_1 + swizzled_row_20 * 128; + } + + const int row_20 = q_row_coord + (local_wid % 4) * 16; + + uint32_t local_smem_bar_tma_q = smem_bar_q_tma + buffer_id_q * 8; + uint32_t local_smem_bar_mma_q = smem_bar_q_mma + buffer_id_q * 8; + + if (local_gid == 1) { + named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256); + } + + if (kv_loop_left_bound < kv_loop_right_bound) { + uint32_t smem_bar_phase_q = cnt_q < BUFFERS_Q_1 ? 0 : 1; + + cnt_q = cnt_q < (2 * BUFFERS_Q_1 - 1) ? (cnt_q + 1) : 0; + buffer_id_q = buffer_id_q < ( BUFFERS_Q_1 - 1) ? (buffer_id_q + 1) : 0; + + if (!smem_bar_peek(local_smem_bar_tma_q, smem_bar_phase_q)) { + smem_bar_wait(local_smem_bar_tma_q, smem_bar_phase_q); + } + } + + r32 reg_1_0[REGS_M_1][REGS_O_1][WARP_REGS_1]; + memset(®_1_0[0][0][0], 0, sizeof(reg_1_0)); + + named_barrier_wait(MATH_WORKGROUP_1, 256); +#pragma unroll 1 + for (int kv_loop = kv_loop_left_bound; kv_loop < kv_loop_right_bound; kv_loop++) { + static constexpr int kMulPipeCount = REGS_M_1 * REGS_N_1 * WARP_REGS_1; + + static constexpr int kSubtractPipeCount = 6; + static constexpr int kConvertPipeCount = 4; + static constexpr int oBlockSize = 2; + + const int p_col_coord = kv_loop * TILE_N_1; + const int causal_mask_col = p_col_coord + (tiw % 4) * 2; + const int causal_mask_row = q_row_coord + local_wid * 16 + (tiw / 4); + + uint32_t local_smem_bar_tma_k = smem_bar_k_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_k = smem_bar_k_mma + buffer_id_kv * 8; + + uint32_t local_smem_bar_tma_v = smem_bar_v_tma + buffer_id_kv * 8; + uint32_t local_smem_bar_mma_v = smem_bar_v_mma + buffer_id_kv * 8; + + uint32_t smem_bar_phase_kv = cnt_kv < BUFFERS_K_1 ? 0 : 1; + + cnt_kv = cnt_kv < (2 * BUFFERS_K_1 - 1) ? (cnt_kv + 1) : 0; + buffer_id_kv = buffer_id_kv < ( BUFFERS_K_1 - 1) ? (buffer_id_kv + 1) : 0; + + memset(®_8_0[0][0][0], 0, sizeof(reg_8_0)); + + if (!smem_bar_peek(local_smem_bar_tma_k, smem_bar_phase_kv)) { + smem_bar_wait(local_smem_bar_tma_k, smem_bar_phase_kv); + } + + warpgroup_arrive(); +#pragma unroll + for (int k = 0; k < REGS_K_1; ++k) { + if (k == REGS_K_1 - 1) { + BMM_S_GMMA_ISB(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0])); + } else { + BMM_S_GMMA(gmma_desc_q.desc, gmma_desc_k.desc, reinterpret_cast<uint32_t *>(reg_8_0[0])); + } + int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc); + tmp_desc_q.x += BYTES_PER_GMMA_K_NO_4LSB_1; + if ((k % 4) == 3) { + tmp_desc_q.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4; + tmp_desc_q.x += ((128*TILE_M_1*2) >> 4); + } + int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc); + tmp_desc_k.x += BYTES_PER_GMMA_K_NO_4LSB_1; + if ((k % 4) == 3) { + tmp_desc_k.x -= BYTES_PER_GMMA_K_NO_4LSB_1 * 4; + tmp_desc_k.x += ((128*TILE_N_1) >> 4); + } + } + { + int2 &tmp_desc_q = reinterpret_cast<int2 &>(gmma_desc_q.desc); + tmp_desc_q.x -= ((128 * TILE_M_1 * 2) >> 4) * (REGS_K_1 / 4); + int2 &tmp_desc_k = reinterpret_cast<int2 &>(gmma_desc_k.desc); + tmp_desc_k.x -= ((128 * TILE_N_1) >> 4) * (REGS_K_1 / 4); + } + gmma_desc_k.increment_smem_buffer<SMEM_K_1, BUFFERS_K_1>(); + warpgroup_wait<0>(); + + if (local_wid == 0 && elect_one) { + smem_bar_arrive(local_smem_bar_mma_k); + } + + uint32_t wait_v_done = smem_bar_peek(local_smem_bar_tma_v, smem_bar_phase_kv); + + //mha_mask_op 11 code + if (kv_loop >= kv_loop_right_bound - 1) + { +#pragma unroll + for (int m = 0; m < REGS_M_11; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_11; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_11; ++i) { + int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8; + int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8; + bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + if (!mask) { + reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity; + } + } + } + } + } + + //global_load_op 10 code + + //mha_mask_op 11 code + if (kv_loop >= kv_loop_right_bound - 1) + { +#pragma unroll + for (int m = 0; m < REGS_M_11; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_11; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_11; ++i) { + int row = causal_mask_row + m * WARPS_PER_GROUP_0 * WARP_TILE_M_11 + ((i / 2) % 2) * 8; + int col = causal_mask_col + n * WARP_TILE_N_11 + i % 2 + (i / 4) * 8; + bool mask = compute_diagonal_band_mask_11(row, col, actual_seqlen_kv_1, actual_seqlen_q_1, shift_right_bound, left_bound); + if (!mask) { + reinterpret_cast<float &>(reg_8_0[m][n][i]) = neg_infinity; + } + } + } + } + } + + //softmax_op 12 code + static constexpr float inv_ln2_12 = 1.4426950408889634074f; + + float scaled_inv_ln2_12 = inv_ln2_12 * reinterpret_cast<const float &>(reg_10_0[0]); + + r32 *flattened_s = reinterpret_cast<r32 *>(reg_8_0); + r32 *flattened_s_fp16 = reinterpret_cast<r32 *>(reg_12_0); + r32 *flattened_o = reinterpret_cast<r32 *>(reg_1_0); + + float tmp_max_level_0[REGS_N_12][4]; + float tmp_max_level_1[REGS_N_12][2]; + float tmp_max_level_2[REGS_N_12 / 2][2]; +#pragma unroll + for (int m = 0; m < REGS_M_12; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_12; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_12; i+=2) { + tmp_max_level_0[n][i/2] = fmaxf(reinterpret_cast<const float &>(reg_8_0[m][n][i+0]), + reinterpret_cast<const float &>(reg_8_0[m][n][i+1])); + } + } + } + // FMUL +#pragma unroll + for (int i = 0; i < kMulPipeCount; i++) { + reinterpret_cast<float &>(flattened_s[i]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i])); + } + { +#pragma unroll + for (int n = 0; n < REGS_N_12; ++n) { +#pragma unroll + for (int i = 0; i < 2; i++) { + tmp_max_level_1[n][i] = fmaxf(tmp_max_level_0[n][i + 0], + tmp_max_level_0[n][i + 2]); + } + } + } + { +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=2) { + tmp_max_level_2[n/2][0] = fmaxf(tmp_max_level_1[n][0], tmp_max_level_1[n+1][0]); + tmp_max_level_2[n/2][1] = fmaxf(tmp_max_level_1[n][1], tmp_max_level_1[n+1][1]); + } + } + if (TILE_N_1 == 256) { + float tmp_max_level_3[REGS_N_12 / 4][2]; + float tmp_max_level_4[FORT_MAX(1,REGS_N_12 / 8)][2]; +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=4) { + tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]); + tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]); + } +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=8) { + tmp_max_level_4[n/8][0] = fmaxf(tmp_max_level_3[n/4][0], tmp_max_level_3[n/4+1][0]); + tmp_max_level_4[n/8][1] = fmaxf(tmp_max_level_3[n/4][1], tmp_max_level_3[n/4+1][1]); + } + reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_4[0][0], tmp_max_level_4[1][0]); + reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_4[0][1], tmp_max_level_4[1][1]); + } else if (TILE_N_1 == 128) { + float tmp_max_level_3[REGS_N_12 / 4][2]; +#pragma unroll + for (int n = 0; n < REGS_N_12; n+=4) { + tmp_max_level_3[n/4][0] = fmaxf(tmp_max_level_2[n/2][0], tmp_max_level_2[n/2+1][0]); + tmp_max_level_3[n/4][1] = fmaxf(tmp_max_level_2[n/2][1], tmp_max_level_2[n/2+1][1]); + } + reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_3[0][0], tmp_max_level_3[1][0]); + reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_3[0][1], tmp_max_level_3[1][1]); + } else { + reinterpret_cast<float &>(reg_12_2[0]) = fmaxf(tmp_max_level_2[0][0], tmp_max_level_2[1][0]); + reinterpret_cast<float &>(reg_12_2[1]) = fmaxf(tmp_max_level_2[0][1], tmp_max_level_2[1][1]); + } + + // Apply the functor for each row inside each group of 4 threads. +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 1); + + reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]), + reinterpret_cast<const float &>(tmp_0)); + + tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_2[m], 2); + + reinterpret_cast<float &>(reg_12_2[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]), + reinterpret_cast<const float &>(tmp_0)) * scaled_inv_ln2_12; + } + + // Update acc_max scale of flash attention +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + r32 curr_max = reg_12_1[m]; + reinterpret_cast<float &>(reg_12_1[m]) = fmaxf(reinterpret_cast<const float &>(reg_12_2[m]), + reinterpret_cast<const float &>(curr_max)); + reg_12_2[m] = curr_max; + } + + float alpha_12[ROWS_PER_THREAD_12]; +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + float p_max = reinterpret_cast<const float &>(reg_12_2[m]); + float acc_max = reinterpret_cast<const float &>(reg_12_1[m]); + + // disable FMA for scale * P - max + float tmp = (acc_max == NEG_INFINITY) ? p_max : __fsub_rn(p_max, acc_max); + reinterpret_cast<r32 &>(alpha_12[m]) = fp32_exp2(reinterpret_cast<r32 &>(tmp)); + } + +#pragma unroll + for (int i = 0; i < ROWS_PER_THREAD_12; ++i) { + reinterpret_cast<float &>(reg_12_4[i]) = 0.0f; + } + + // Broadcast scaled_max and alpha + float flattened_scaled_max[REGS_M_12 * REGS_N_12 * WARP_REGS_12]; + float flattened_alpha[REGS_M_12 * REGS_O_1 * WARP_REGS_12]; +#pragma unroll + for (int m = 0; m < REGS_M_12; ++m) { +#pragma unroll + for (int n = 0; n < REGS_N_12; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_12; ++i) { + int row_indx = m * 2 + (i / 2) % 2; + float max = reinterpret_cast<const float &>(reg_12_1[row_indx]); + flattened_scaled_max[m * REGS_N_12 * WARP_REGS_12 + n * WARP_REGS_12 + i] = (max == NEG_INFINITY ? 0.0f : max); + } + } + } + +#pragma unroll + for (int m = 0; m < REGS_M_12; ++m) { +#pragma unroll + for (int n = 0; n < REGS_O_1; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_12; ++i) { + int row_indx = m * 2 + (i / 2) % 2; + flattened_alpha[m * REGS_O_1 * WARP_REGS_12 + n * WARP_REGS_12 + i] = alpha_12[row_indx]; + } + } + } + + cfence(); + if (local_gid == 1) { + named_barrier_wait(SOFTMAX_1_BARRIER_1, 256); + } else { + named_barrier_wait(SOFTMAX_2_BARRIER_1, 256); + } + cfence(); + + // FSUB +#pragma unroll + for (int i = 0; i < kSubtractPipeCount; i++) { +)KERNEL" + R"KERNEL( + reinterpret_cast<float &>(flattened_s[i]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i]), flattened_scaled_max[i]); + } + +#pragma unroll + + for (int i = 0; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) { + int m_0 = (i-kConvertPipeCount+0) / (REGS_N_12 * WARP_REGS_12); + int ii_0 = (i-kConvertPipeCount+0) % WARP_REGS_12; + int m_1 = (i-kConvertPipeCount+1) / (REGS_N_12 * WARP_REGS_12); + int ii_1 = (i-kConvertPipeCount+1) % WARP_REGS_12; + int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2; + int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2; + // cast and FADD + if (i >= kConvertPipeCount) { + fp32x2_to_bf16x2(&flattened_s_fp16[(i - kConvertPipeCount)/2], &flattened_s[i - kConvertPipeCount]); + reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+0]); + reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i-kConvertPipeCount+1]); + } + cfence(); + + // exp + flattened_s[i+0] = fp32_exp2(flattened_s[i+0]); + + // O update +#pragma unroll + for (int j = 0; j < oBlockSize; j++) { + if (oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) { + reinterpret_cast<float &>(flattened_o[oBlockSize*i+j]) *= flattened_alpha[oBlockSize*i+j]; + } + } + + // fmul + if (i + kMulPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) { + reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+0])); + reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1]) = __fmul_rn(scaled_inv_ln2_12, reinterpret_cast<float &>(flattened_s[i+kMulPipeCount+1])); + } + // fsub + + if (i + kSubtractPipeCount < REGS_M_12 * REGS_N_12 * WARP_REGS_12) { + reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+0]), flattened_scaled_max[i+kSubtractPipeCount+0]); + reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]) = __fsub_rn(reinterpret_cast<float &>(flattened_s[i+kSubtractPipeCount+1]), flattened_scaled_max[i+kSubtractPipeCount+1]); + } + + // exp + flattened_s[i+1] = fp32_exp2(flattened_s[i+1]); + + // O update +#pragma unroll + for (int j = 0; j < oBlockSize; j++) { + if (oBlockSize+oBlockSize*i+j < REGS_O_1 * REGS_M_1 * WARP_REGS_1) { + reinterpret_cast<float &>(flattened_o[oBlockSize+oBlockSize*i+j]) *= flattened_alpha[oBlockSize+oBlockSize*i+j]; + } + } + } + if (local_gid == 0) { + named_barrier_arrive(SOFTMAX_1_BARRIER_1, 256); + } else { + named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256); + } + cfence(); + +#pragma unroll + for (int i = REGS_M_12 * REGS_N_12 * WARP_REGS_12 - kConvertPipeCount; i < REGS_M_12 * REGS_N_12 * WARP_REGS_12; i+=2) { + int m_0 = (i + 0) / (REGS_N_12 * WARP_REGS_12); + int ii_0 = (i + 0) % WARP_REGS_12; + int m_1 = (i + 1) / (REGS_N_12 * WARP_REGS_12); + int ii_1 = (i + 1) % WARP_REGS_12; + int row_indx_0 = m_0 * 2 + (ii_0 / 2) % 2; + int row_indx_1 = m_1 * 2 + (ii_1 / 2) % 2; + fp32x2_to_bf16x2(&flattened_s_fp16[i/2], &flattened_s[i]); + reinterpret_cast<float &>(reg_12_4[row_indx_0]) += reinterpret_cast<float &>(flattened_s[i+0]); + reinterpret_cast<float &>(reg_12_4[row_indx_1]) += reinterpret_cast<float &>(flattened_s[i+1]); + } + + if (!wait_v_done) { + smem_bar_wait(local_smem_bar_tma_v, smem_bar_phase_kv); + } + + warpgroup_arrive(); +#pragma unroll + for (int k = 0; k < TILE_N_1 / GMMA_TILE_K_1; ++k) { + if (k == (TILE_N_1 / GMMA_TILE_K_1) - 1) { + BMM_O_GMMA_ISB(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0])); + } else { + BMM_O_GMMA(reg_12_0[0][k], gmma_desc_v.desc, reinterpret_cast<uint32_t *>(reg_1_0[0])); + } + int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc); + tmp_desc_v.x += BYTES_PER_GMMA_K_NO_4LSB_TRANS_1; + } + { + int2 &tmp_desc_v = reinterpret_cast<int2 &>(gmma_desc_v.desc); + tmp_desc_v.x -= BYTES_PER_GMMA_K_NO_4LSB_TRANS_1 * (TILE_N_1 / GMMA_TILE_K_1); + } + gmma_desc_v.increment_smem_buffer<SMEM_V_1, BUFFERS_V_1>(); + + warpgroup_wait<0>(); + if (local_wid == 0 && elect_one) { + smem_bar_arrive(local_smem_bar_mma_v); + } + + // Update acc_sum of flash attention +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + float p_sum = reinterpret_cast<const float &>(reg_12_4[m]); + float acc_sum = reinterpret_cast<const float &>(reg_12_3[m]); + + reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<float &>(alpha_12[m]) * acc_sum + p_sum; + } + } + if (kv_loop_left_bound < kv_loop_right_bound) { + gmma_desc_q.increment_smem_buffer<SMEM_Q_1, BUFFERS_Q_1>(); + + if (local_wid == 0 && elect_one) { + smem_bar_arrive(local_smem_bar_mma_q); + } + } + if (local_gid == 0) { + named_barrier_arrive(SOFTMAX_2_BARRIER_1, 256); + } +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_12; ++m) { + r32 tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 1); + + reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) + + reinterpret_cast<const float &>(tmp_0); + + tmp_0 = __shfl_xor_sync(uint32_t(-1), reg_12_3[m], 2); + + reinterpret_cast<float &>(reg_12_3[m]) = reinterpret_cast<const float &>(reg_12_3[m]) + + reinterpret_cast<const float &>(tmp_0); + + float sum = reinterpret_cast<float &>(reg_12_3[m]); + reinterpret_cast<float &>(reg_12_1[m]) *= ln2; + + reinterpret_cast<float &>(reg_12_5[m]) = (sum == 0.f) ? NEG_INFINITY : reinterpret_cast<const float &>(reg_12_1[m]) + __logf(sum); + + beta_12[m] = (sum == 0.f) ? 0.f : 1.f / sum; + } + +#pragma unroll + for (int m = 0; m < REGS_M_1; ++m) { +#pragma unroll + for (int n = 0; n < REGS_O_1; ++n) { +#pragma unroll + for (int i = 0; i < WARP_REGS_1; ++i) { + int row_indx = m * 2 + (i / 2) % 2; + + reinterpret_cast<float &>(reg_1_0[m][n][i]) *= beta_12[row_indx]; + } + } + } + + //global_store_op 13 code +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_13; ++m) { + const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_13 + (m / 2) * WARPS_M_13 * WARP_TILE_M_13; + + if (row_13 + row_offset < oob_M_13 && (tiw % 4) == 0) { + stg_32(ptr_13 + row_offset * desc_max.strides[2] * BYTES_PER_ELEMENT_13, ®_12_1[m]); + } + } + + //global_store_op 14 code +#pragma unroll + for (int m = 0; m < ROWS_PER_THREAD_14; ++m) { + const int row_offset = (m % 2) * THREADS_PER_WARP_TILE_M_14 + (m / 2) * WARPS_M_14 * WARP_TILE_M_14; + + if (row_14 + row_offset < oob_M_14 && (tiw % 4) == 0) { + stg_32(ptr_14 + row_offset * desc_sum_exp.strides[2] * BYTES_PER_ELEMENT_14, ®_12_3[m]); + } + } + + tmastg_wait(); + + //global_store_op 20 code +#pragma unroll + for (int s = 0; s < TILE_O_1 / 64; ++s) { +#pragma unroll + for (int n = 0; n < stsm_per_tile_20; ++n) { + uint32_t tmp[4]; + fp32x2_to_bf16x2(&tmp[0], ®_1_0[0][s * stsm_per_tile_20 + n][0]); + fp32x2_to_bf16x2(&tmp[1], ®_1_0[0][s * stsm_per_tile_20 + n][2]); + fp32x2_to_bf16x2(&tmp[2], ®_1_0[0][s * stsm_per_tile_20 + n][4]); + fp32x2_to_bf16x2(&tmp[3], ®_1_0[0][s * stsm_per_tile_20 + n][6]); + stsm_x4(stsm_base_20[n] + s * 64 * 16 * BYTES_PER_ELEMENT_1, tmp); + } + } + fence_view_async_shared(); + + int head_coord_loc = 0; + int row = row_20; + int head = head_coord_1; +#pragma unroll + for (int s = 0; s < TILE_K_1 / 64; ++s) { + utmastg_4d_tiled(&tma_O, + smem_20 + s * 64 * 16 * BYTES_PER_ELEMENT_1, + s * 64, + row, + head + head_coord_loc, + batch_coord_1); + } + tmastg_arrive(); + + named_barrier_wait(TILE_ID_SYNC_3_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + if (tiw == 0) { + lds_32(&tile_id, smem_tile_id_1); + } + named_barrier_arrive(TILE_ID_SYNC_2_BARRIER_1, THREADS_ON_TILE_BARRIER_1); + tile_id = __shfl_sync(0xffffffff, tile_id, 0); + } + tmastg_wait(); + reg_alloc<232>(); + } +} +)KERNEL"; +inline constexpr size_t d64_fprop_source_len = sizeof(d64_fprop_source) - 1; + +inline constexpr const char d64_fprop_flags[] = R"FLAGS(--gpu-architecture=sm_90a +--std=c++17 +--define-macro=__x86_64__ +-w +--define-macro=__CUDACC_RTC__ +-default-device +--use_fast_math +)FLAGS"; +inline constexpr size_t d64_fprop_flags_len = sizeof(d64_fprop_flags) - 1; + +} // namespace generated +} // namespace experimental +} // namespace cudnn_frontend + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif |
