aboutsummaryrefslogtreecommitdiff
path: root/deps/cudnn-frontend/include/cudnn_frontend/experimental
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-07-02 19:44:08 +0200
committerOnur Gündüz <ogunduz@gmail.com>2026-07-02 19:44:08 +0200
commit6a10d3577232f1fd646a20f22a4a1ab4ec29f28a (patch)
treee4a077b064876ddb39144935fa256a4ab0692488 /deps/cudnn-frontend/include/cudnn_frontend/experimental
parent98a713e86c23bc6098bf7a5558507a9f27a7a1c1 (diff)
downloadffwd-6a10d3577232f1fd646a20f22a4a1ab4ec29f28a.tar.gz
ffwd-6a10d3577232f1fd646a20f22a4a1ab4ec29f28a.zip
cuda: add cuDNN fused attention path with runtime fallback
Diffstat (limited to 'deps/cudnn-frontend/include/cudnn_frontend/experimental')
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h385
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h252
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h261
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h697
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h215
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h544
-rw-r--r--deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h450
7 files changed, 2804 insertions, 0 deletions
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h
new file mode 100644
index 0000000..b44a55e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/attention_utils.h
@@ -0,0 +1,385 @@
+#pragma once
+
+#include <cstdint>
+#include <sstream>
+#include <string>
+#include <vector>
+
+// cudaLibrary_t, cudaKernel_t, cudaJitOption, cudaLibraryOption etc.
+// were introduced in CUDA 12.8. On older toolkits (or when using dynamic
+// loading where cuda_runtime.h may lack these types), provide typedefs
+// from the driver API equivalents (available via cuda.h) so that
+// engine headers can declare members without #ifdef clutter.
+// The actual runtime API functions are guarded by CUDART_VERSION checks below.
+#if !defined(CUDART_VERSION) || CUDART_VERSION < 12080
+using cudaLibrary_t = CUlibrary;
+using cudaKernel_t = CUkernel;
+using cudaJitOption = CUjit_option;
+using cudaLibraryOption = CUlibraryOption;
+#endif
+
+namespace cudnn_frontend::experimental {
+
+// ============================================================
+// Internal types matching generated kernel parameter layouts
+// ============================================================
+
+struct AttentionShape_t {
+ uint32_t b, q_h, k_h, v_h, s_q, s_kv, d_qk, d_v;
+};
+
+struct AttentionDescriptor_t {
+ 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;
+};
+
+struct FastDivisor_t {
+ uint32_t val, shr, mul;
+};
+
+struct tensor_descriptor {
+ static const int MAX_DIMS = 12;
+ int64_t num_dims;
+ int64_t dims[MAX_DIMS];
+ int64_t strides[MAX_DIMS];
+};
+
+// ============================================================
+// Utility functions
+// ============================================================
+
+inline int
+div_up(int a, int b) {
+ return (a + b - 1) / b;
+}
+
+// floor(log2(x)) for x > 0.
+inline int
+find_log_2_floor(uint32_t x) {
+ if (x <= 1) return 0;
+ int a = 0;
+ while ((1u << (a + 1)) <= x) a++;
+ return a;
+}
+
+// Compute FastDivisor_t for the kernel's fastDivMod which uses:
+// div = __umulhi(2 * val, mul) >> shr
+// This matches cuDNN backend's find_divisor_v2 fast-math helper.
+inline FastDivisor_t
+make_fast_divisor(uint32_t divisor) {
+ FastDivisor_t d;
+ d.val = divisor;
+
+ if (divisor <= 1) {
+ // Division by 1: umulhi(2*val, 0x80000000) >> 0 = val, mod = 0
+ d.shr = 0;
+ d.mul = 0x80000000u;
+ return d;
+ }
+
+ // find_log_2(2 * divisor, round_up=true)
+ uint32_t x2 = 2u * divisor;
+ int a = 0;
+ {
+ uint32_t tmp = x2;
+ while (tmp > 1) {
+ tmp >>= 1;
+ a++;
+ }
+ }
+ // round up if not a power of 2
+ if (x2 & (x2 - 1)) a++;
+
+ uint32_t p = 31 + static_cast<uint32_t>(a);
+ d.mul = static_cast<uint32_t>(((1ULL << p) + static_cast<uint64_t>(x2) - 1) / static_cast<uint64_t>(x2));
+ d.shr = p - 32;
+ return d;
+}
+
+inline std::vector<std::string>
+parse_flags_string(const char* data, size_t len) {
+ std::vector<std::string> flags;
+ std::string content(data, len);
+ std::istringstream stream(content);
+ std::string line;
+ while (std::getline(stream, line)) {
+ size_t start = line.find_first_not_of(" \t\r\n");
+ if (start == std::string::npos) continue;
+ size_t end = line.find_last_not_of(" \t\r\n");
+ line = line.substr(start, end - start + 1);
+ if (!line.empty()) {
+ flags.push_back(line);
+ }
+ }
+ return flags;
+}
+
+// ============================================================
+// Kernel specification (compile-time metadata per kernel variant)
+// ============================================================
+
+struct KernelSpec {
+ const char* source;
+ size_t source_len;
+ const char* flags_raw;
+ size_t flags_len;
+ const char* kernel_name;
+ int tile_m, tile_n, tile_k;
+ int smem_bytes;
+};
+
+// ============================================================
+// CUDA runtime API wrappers (using NV_FE_CALL_TO_CUDA)
+// ============================================================
+
+namespace detail {
+
+// NV_FE_CALL_TO_CUDA macros reference symbols in cudnn_frontend::detail
+// via unqualified lookup. Import them into this namespace.
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+using cudnn_frontend::detail::CudaLibrary;
+using cudnn_frontend::detail::get_cuda_symbol;
+#endif
+
+// Re-export CUDA runtime wrappers from the main shim so the engine
+// never calls cudaMalloc/cudaFree/etc. directly (required for dynamic loading).
+using cudnn_frontend::detail::cuda_get_device;
+using cudnn_frontend::detail::cuda_get_device_properties;
+using cudnn_frontend::detail::cuda_get_error_string;
+using cudnn_frontend::detail::cuda_mem_cpy_async;
+using cudnn_frontend::detail::cuda_mem_set_async;
+
+// Write a 32-bit pattern to device memory (async, on stream).
+// Uses thread_local storage so the source buffer persists through the async copy.
+// Only used with N=1 in practice (writing float 1.0f for FP8 default scale).
+// Cannot use NV_FE_CALL_TO_CUDA because cudaMemcpyAsync has more args than this wrapper.
+inline cudaError_t
+cuda_mem_set_d32_async(void* dstDevice, unsigned int ui, size_t N, cudaStream_t stream) {
+ static thread_local unsigned int val;
+ val = ui;
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ using fn_t = cudaError_t (*)(void*, const void*, size_t, cudaMemcpyKind, cudaStream_t);
+ auto _fn = reinterpret_cast<fn_t>(cudnn_frontend::detail::get_cuda_symbol(CudaLibrary::CUDART, "cudaMemcpyAsync"));
+ return _fn(dstDevice, &val, N * sizeof(unsigned int), cudaMemcpyHostToDevice, stream);
+#else
+ return cudaMemcpyAsync(dstDevice, &val, N * sizeof(unsigned int), cudaMemcpyHostToDevice, stream);
+#endif
+}
+
+// Convert cudaError_t to a descriptive string (e.g., "invalid argument")
+inline std::string
+cuda_error_to_string(cudaError_t err) {
+ const char* str = cuda_get_error_string(err);
+ return str ? std::string(str) : ("cudaError=" + std::to_string(static_cast<int>(err)));
+}
+
+// cudaGetLastError takes zero arguments — can't use NV_FE_CALL_TO_CUDA
+// (variadic macro requires at least one arg). Handle both paths manually.
+inline cudaError_t
+cuda_get_last_error() {
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ using fn_t = cudaError_t (*)();
+ auto _fn = reinterpret_cast<fn_t>(cudnn_frontend::detail::get_cuda_symbol(CudaLibrary::CUDART, "cudaGetLastError"));
+ return _fn();
+#else
+ return cudaGetLastError();
+#endif
+}
+
+// ============================================================
+// CUDA 12.8+ runtime API wrappers for library/kernel management.
+// These APIs (cudaLibraryLoadData, cudaLibraryGetKernel, cudaLibraryUnload,
+// cudaKernelSetAttributeForDevice, cudaGetDriverEntryPointByVersion) require
+// CUDART_VERSION >= 12080. On older toolkits, the OSS engine check_support()
+// will reject the configuration before these are called.
+// ============================================================
+
+#if !defined(NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING) && defined(CUDART_VERSION) && CUDART_VERSION < 12080
+
+// Stubs that return errors — OSS engines require CUDA 12.8+.
+inline cudaError_t
+cuda_library_load_data(void*, const void*, void*, void**, unsigned int, void*, void**, unsigned int) {
+ return cudaErrorNotSupported;
+}
+inline cudaError_t
+cuda_library_get_kernel(void*, void*, const char*) {
+ return cudaErrorNotSupported;
+}
+inline cudaError_t
+cuda_library_unload(void*) {
+ return cudaErrorNotSupported;
+}
+inline cudaError_t
+cuda_kernel_set_attribute_for_device(void*, int, int, int) {
+ return cudaErrorNotSupported;
+}
+
+#else // CUDART_VERSION >= 12080 or dynamic loading
+
+inline cudaError_t
+cuda_library_load_data(cudaLibrary_t* library,
+ const void* code,
+ cudaJitOption* jitOptions,
+ void** jitOptionsValues,
+ unsigned int numJitOptions,
+ cudaLibraryOption* libraryOptions,
+ void** libraryOptionsValues,
+ unsigned int numLibraryOptions) {
+ NV_FE_CALL_TO_CUDA(cuda_library_load_data,
+ cudaLibraryLoadData,
+ library,
+ code,
+ jitOptions,
+ jitOptionsValues,
+ numJitOptions,
+ libraryOptions,
+ libraryOptionsValues,
+ numLibraryOptions);
+}
+
+inline cudaError_t
+cuda_library_get_kernel(cudaKernel_t* pKernel, cudaLibrary_t library, const char* name) {
+ NV_FE_CALL_TO_CUDA(cuda_library_get_kernel, cudaLibraryGetKernel, pKernel, library, name);
+}
+
+inline cudaError_t
+cuda_library_unload(cudaLibrary_t library) {
+ NV_FE_CALL_TO_CUDA(cuda_library_unload, cudaLibraryUnload, library);
+}
+
+inline cudaError_t
+cuda_kernel_set_attribute_for_device(cudaKernel_t kernel, cudaFuncAttribute attrib, int val, int dev) {
+ NV_FE_CALL_TO_CUDA(cuda_kernel_set_attribute_for_device, cudaKernelSetAttributeForDevice, kernel, attrib, val, dev);
+}
+
+#endif // CUDART_VERSION check
+
+inline cudaError_t
+cuda_launch_kernel(const void* func, dim3 gridDim, dim3 blockDim, void** args, size_t sharedMem, cudaStream_t stream) {
+ NV_FE_CALL_TO_CUDA(cuda_launch_kernel, cudaLaunchKernel, func, gridDim, blockDim, args, sharedMem, stream);
+}
+
+// cuTensorMapEncodeTiled has no runtime API equivalent.
+// Resolve the driver function pointer via cudaGetDriverEntryPointByVersion
+// so we never link against libcuda.so directly. Requires CUDA 12.8+.
+inline CUresult
+cu_tensor_map_encode_tiled(CUtensorMap* tensorMap,
+ CUtensorMapDataType tensorDataType,
+ cuuint32_t tensorRank,
+ void* globalAddress,
+ const cuuint64_t* globalDim,
+ const cuuint64_t* globalStrides,
+ const cuuint32_t* boxDim,
+ const cuuint32_t* elementStrides,
+ CUtensorMapInterleave interleave,
+ CUtensorMapSwizzle swizzle,
+ CUtensorMapL2promotion l2Promotion,
+ CUtensorMapFloatOOBfill oobFill) {
+#if !defined(NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING) && defined(CUDART_VERSION) && CUDART_VERSION < 12080
+ (void)tensorMap;
+ (void)tensorDataType;
+ (void)tensorRank;
+ (void)globalAddress;
+ (void)globalDim;
+ (void)globalStrides;
+ (void)boxDim;
+ (void)elementStrides;
+ (void)interleave;
+ (void)swizzle;
+ (void)l2Promotion;
+ (void)oobFill;
+ return CUDA_ERROR_NOT_SUPPORTED;
+#else
+ using PFN = CUresult(CUDAAPI*)(CUtensorMap*,
+ CUtensorMapDataType,
+ cuuint32_t,
+ void*,
+ const cuuint64_t*,
+ const cuuint64_t*,
+ const cuuint32_t*,
+ const cuuint32_t*,
+ CUtensorMapInterleave,
+ CUtensorMapSwizzle,
+ CUtensorMapL2promotion,
+ CUtensorMapFloatOOBfill);
+ // Thread-safe static initialization (C++11 guarantees)
+ static const PFN pfn = []() -> PFN {
+ void* raw_pfn = nullptr;
+ cudaDriverEntryPointQueryResult status;
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ // In dynamic loading mode, resolve cudaGetDriverEntryPointByVersion via dlsym
+ using GetEntryPointFn =
+ cudaError_t (*)(const char*, void**, unsigned int, int, cudaDriverEntryPointQueryResult*);
+ auto get_entry_point = reinterpret_cast<GetEntryPointFn>(
+ cudnn_frontend::detail::get_cuda_symbol(CudaLibrary::CUDART, "cudaGetDriverEntryPointByVersion"));
+ cudaError_t err = get_entry_point("cuTensorMapEncodeTiled", &raw_pfn, 12000, cudaEnableDefault, &status);
+#else
+ cudaError_t err =
+ cudaGetDriverEntryPointByVersion("cuTensorMapEncodeTiled", &raw_pfn, 12000, cudaEnableDefault, &status);
+#endif
+ if (err != cudaSuccess || status != cudaDriverEntryPointSuccess || !raw_pfn) {
+ return nullptr;
+ }
+ return reinterpret_cast<PFN>(raw_pfn);
+ }();
+ if (!pfn) {
+ return CUDA_ERROR_NOT_FOUND;
+ }
+ return pfn(tensorMap,
+ tensorDataType,
+ tensorRank,
+ globalAddress,
+ globalDim,
+ globalStrides,
+ boxDim,
+ elementStrides,
+ interleave,
+ swizzle,
+ l2Promotion,
+ oobFill);
+#endif // CUDART_VERSION check
+}
+
+} // namespace detail
+
+// ============================================================
+// TMA descriptor creation (4D)
+// ============================================================
+inline error_t
+create_tma_desc_4d(CUtensorMap* desc,
+ void* globalAddress,
+ CUtensorMapDataType dataType,
+ uint32_t dim0,
+ uint32_t dim1,
+ uint32_t dim2,
+ uint32_t dim3,
+ uint64_t stride1_bytes,
+ uint64_t stride2_bytes,
+ uint64_t stride3_bytes,
+ uint32_t boxDim0,
+ uint32_t boxDim1,
+ CUtensorMapSwizzle swizzle) {
+ uint64_t globalDims[4] = {dim0, dim1, dim2, dim3};
+ uint64_t globalStrides[3] = {stride1_bytes, stride2_bytes, stride3_bytes};
+ uint32_t boxDims[4] = {boxDim0, boxDim1, 1, 1};
+ uint32_t elemStrides[4] = {1, 1, 1, 1};
+
+ CUresult err_status = detail::cu_tensor_map_encode_tiled(desc,
+ dataType,
+ 4,
+ globalAddress,
+ globalDims,
+ globalStrides,
+ boxDims,
+ elemStrides,
+ CU_TENSOR_MAP_INTERLEAVE_NONE,
+ swizzle,
+ CU_TENSOR_MAP_L2_PROMOTION_NONE,
+ CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA);
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ err_status != CUDA_SUCCESS, error_code_t::CUDA_API_FAILED, "cuTensorMapEncodeTiled failed");
+ return {error_code_t::OK, ""};
+}
+
+} // namespace cudnn_frontend::experimental \ No newline at end of file
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h
new file mode 100644
index 0000000..eaad3de
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/nvrtc_shim.h
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include <nvrtc.h>
+#include <cuda_runtime.h> // for cudaError_t (needed by cudnn_frontend_shim.h wrappers)
+
+// Pull in HMODULE, dlopen, dlsym, dlclose macros and platform definitions
+// from the existing cudnn_frontend shim infrastructure.
+#include "../../cudnn_frontend_shim.h"
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+#include <mutex>
+#endif
+
+namespace cudnn_frontend {
+namespace experimental {
+namespace detail {
+
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+
+/// @brief Attempt to dynamically load the NVRTC shared library.
+///
+/// Tries a sequence of candidate library names in order, returning
+/// the handle for the first one that loads successfully.
+///
+/// @return A valid library handle on success, or nullptr on failure.
+/// This function does NOT throw.
+inline HMODULE
+load_nvrtc_so() {
+#ifdef _WIN32
+ constexpr const char *candidates[] = {
+ "nvrtc64_131_0.dll",
+ "nvrtc64_130_0.dll",
+ "nvrtc64_120_0.dll",
+ };
+#else
+ constexpr const char *candidates[] = {
+ "libnvrtc.so",
+ "libnvrtc.so.13",
+ "libnvrtc.so.12",
+ };
+#endif
+ constexpr size_t num_candidates = sizeof(candidates) / sizeof(candidates[0]);
+
+ for (size_t i = 0; i < num_candidates; ++i) {
+ // Clear any prior error state
+ dlerror();
+
+ HMODULE handle = dlopen(candidates[i], RTLD_NOW);
+ if (handle) {
+ return handle;
+ }
+ }
+
+ // All candidates failed -- return nullptr (no throw)
+ return nullptr;
+}
+
+/// @brief Look up a symbol in the dynamically-loaded NVRTC library.
+///
+/// The library handle is loaded once (lazily, thread-safe) and cached
+/// in a function-local static. If the library could not be loaded,
+/// every call returns nullptr.
+///
+/// @param function_name The mangled / C symbol name to resolve.
+/// @return A generic pointer to the symbol, or nullptr if the library
+/// is not loaded or the symbol is not found.
+inline void *
+get_nvrtc_symbol(const char *function_name) {
+ static std::mutex nvrtc_lib_mutex;
+ static HMODULE nvrtc_handle = nullptr;
+ static bool load_attempted = false;
+
+ std::lock_guard<std::mutex> lock(nvrtc_lib_mutex);
+
+ if (!load_attempted) {
+ load_attempted = true;
+ nvrtc_handle = load_nvrtc_so();
+ }
+
+ if (!nvrtc_handle) {
+ return nullptr;
+ }
+
+ // Clear any existing error before calling dlsym
+ dlerror();
+
+ void *symbol = dlsym(nvrtc_handle, function_name);
+ // If dlsym fails we simply return nullptr -- callers decide how to
+ // report the error (the macro returns NVRTC_ERROR_INTERNAL_ERROR).
+ return symbol;
+}
+
+/// @brief Check whether the NVRTC library was successfully loaded.
+///
+/// Internally triggers a lazy load attempt if one has not been made yet.
+///
+/// @return true if the library handle is valid, false otherwise.
+inline bool
+nvrtc_is_loaded() {
+ // Trigger the lazy load by requesting any symbol (the name is
+ // irrelevant -- we only care about whether the handle is valid).
+ // get_nvrtc_symbol will initialise the handle on the first call.
+ get_nvrtc_symbol("nvrtcVersion");
+
+ // We cannot directly inspect the static inside get_nvrtc_symbol,
+ // so we probe for a symbol that must exist in every NVRTC build.
+ return get_nvrtc_symbol("nvrtcVersion") != nullptr;
+}
+
+/// @brief Macro for calling an NVRTC function via dynamic loading.
+///
+/// Looks up @p nvrtc_symbol by name, and if the symbol is nullptr
+/// returns @c NVRTC_ERROR_INTERNAL_ERROR. Otherwise casts the
+/// pointer to the wrapper function's own signature and tail-calls it.
+#define NV_FE_CALL_TO_NVRTC(function_name, nvrtc_symbol, ...) \
+ void *fptr = get_nvrtc_symbol(#nvrtc_symbol); \
+ if (fptr == nullptr) { \
+ return NVRTC_ERROR_INTERNAL_ERROR; \
+ } \
+ return reinterpret_cast<decltype(function_name) *>(fptr)(__VA_ARGS__);
+
+#else // static linking
+
+/// @brief When statically linked NVRTC is always considered loaded.
+inline bool
+nvrtc_is_loaded() {
+ return true;
+}
+
+/// @brief Macro for calling an NVRTC function via static linking.
+///
+/// Simply forwards the call directly to the NVRTC symbol.
+#define NV_FE_CALL_TO_NVRTC(function_name, nvrtc_symbol, ...) return nvrtc_symbol(__VA_ARGS__);
+
+#endif // NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+
+// ---------------------------------------------------------------------------
+// Wrapper functions for the NVRTC API
+//
+// Each wrapper has the exact same signature as the underlying NVRTC
+// function it delegates to. Under dynamic loading the macro resolves
+// the symbol at first call; under static linking the call is direct.
+// ---------------------------------------------------------------------------
+
+/// @brief Create an NVRTC program from source.
+/// @see nvrtcCreateProgram
+inline nvrtcResult
+nvrtc_create_program(nvrtcProgram *prog,
+ const char *src,
+ const char *name,
+ int numHeaders,
+ const char *const *headers,
+ const char *const *includeNames) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_create_program, nvrtcCreateProgram, prog, src, name, numHeaders, headers, includeNames);
+}
+
+/// @brief Destroy an NVRTC program.
+/// @see nvrtcDestroyProgram
+inline nvrtcResult
+nvrtc_destroy_program(nvrtcProgram *prog) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_destroy_program, nvrtcDestroyProgram, prog);
+}
+
+/// @brief Compile an NVRTC program with the given options.
+/// @see nvrtcCompileProgram
+inline nvrtcResult
+nvrtc_compile_program(nvrtcProgram prog, int numOptions, const char *const *options) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_compile_program, nvrtcCompileProgram, prog, numOptions, options);
+}
+
+/// @brief Query the size of the compilation log (including the NUL terminator).
+/// @see nvrtcGetProgramLogSize
+inline nvrtcResult
+nvrtc_get_program_log_size(nvrtcProgram prog, size_t *logSizeRet) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_program_log_size, nvrtcGetProgramLogSize, prog, logSizeRet);
+}
+
+/// @brief Retrieve the compilation log.
+/// @see nvrtcGetProgramLog
+inline nvrtcResult
+nvrtc_get_program_log(nvrtcProgram prog, char *log) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_program_log, nvrtcGetProgramLog, prog, log);
+}
+
+/// @brief Query the size of the compiled CUBIN image.
+/// @see nvrtcGetCUBINSize
+inline nvrtcResult
+nvrtc_get_cubin_size(nvrtcProgram prog, size_t *cubinSizeRet) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_cubin_size, nvrtcGetCUBINSize, prog, cubinSizeRet);
+}
+
+/// @brief Retrieve the compiled CUBIN image.
+/// @see nvrtcGetCUBIN
+inline nvrtcResult
+nvrtc_get_cubin(nvrtcProgram prog, char *cubin) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_cubin, nvrtcGetCUBIN, prog, cubin);
+}
+
+/// @brief Query the size of the generated PTX.
+/// @see nvrtcGetPTXSize
+inline nvrtcResult
+nvrtc_get_ptx_size(nvrtcProgram prog, size_t *ptxSizeRet) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_ptx_size, nvrtcGetPTXSize, prog, ptxSizeRet);
+}
+
+/// @brief Retrieve the generated PTX.
+/// @see nvrtcGetPTX
+inline nvrtcResult
+nvrtc_get_ptx(nvrtcProgram prog, char *ptx) {
+ NV_FE_CALL_TO_NVRTC(nvrtc_get_ptx, nvrtcGetPTX, prog, ptx);
+}
+
+/// @brief Map an nvrtcResult code to a human-readable string.
+/// @see nvrtcGetErrorString
+inline const char *
+nvrtc_get_error_string(nvrtcResult result) {
+#if defined NV_CUDNN_FRONTEND_USE_DYNAMIC_LOADING
+ void *fptr = get_nvrtc_symbol("nvrtcGetErrorString");
+ if (fptr == nullptr) {
+ return "NVRTC error (library not loaded)";
+ }
+ return reinterpret_cast<decltype(nvrtc_get_error_string) *>(fptr)(result);
+#else
+ return nvrtcGetErrorString(result);
+#endif
+}
+
+} // namespace detail
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h
new file mode 100644
index 0000000..7c0a38e
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/oss_engine_interface.h
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "nvrtc_shim.h"
+#include "attention_utils.h"
+#include "../graph_helpers.h"
+#include "../../cudnn_frontend_shim.h"
+
+#include <cuda_runtime.h>
+
+#include <cstdint>
+#include <fstream>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// IOssSdpaEngine — virtual interface for OSS SDPA engines
+// Implemented by Sm90SdpaPrefillEngine and Sm100SdpaPrefillEngine.
+// ============================================================
+
+class IOssSdpaEngine {
+ public:
+ virtual ~IOssSdpaEngine() = default;
+
+ virtual error_t
+ check_support(AttentionShape_t shape, int sm_version) = 0;
+ virtual error_t
+ build() = 0;
+
+ virtual error_t
+ execute(int batch,
+ int heads_q,
+ int heads_kv,
+ int seq_q,
+ int seq_kv,
+ int d,
+ void* d_Q,
+ std::vector<int64_t> const& q_strides,
+ void* d_K,
+ std::vector<int64_t> const& k_strides,
+ void* d_V,
+ std::vector<int64_t> const& v_strides,
+ void* d_O,
+ std::vector<int64_t> const& o_strides,
+ void* d_max,
+ std::vector<int64_t> const& max_strides,
+ void* d_sum_exp,
+ std::vector<int64_t> const& se_strides,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::optional<float> user_attn_scale = std::nullopt) = 0;
+
+ static int64_t
+ get_workspace_size() {
+ return 16;
+ }
+};
+
+// ============================================================
+// IOssNormEngine — virtual interface for OSS norm+activation engines.
+// Implemented by Sm100RmsNormSiluEngine (SM100/Blackwell).
+// Future implementations: Sm90, Sm110, LayerNorm variants, etc.
+// ============================================================
+
+// RmsNormSiluDtype is defined in sm100_rms_norm_silu_knobs.h (self-contained,
+// also used by standalone tests without the framework). All arch-specific
+// engine implementations share this enum.
+//
+// Forward-declared here; concrete implementations #include the knobs header.
+enum class RmsNormSiluDtype : uint8_t;
+
+// Problem shape for RmsNorm+SiLU (extensible for future fields).
+struct NormSiluShape_t {
+ int C = 0; // hidden dimension (columns)
+ int num_tokens = 0; // number of rows
+ RmsNormSiluDtype output_dtype{}; // output data type (bf16, fp8, nvfp4)
+};
+
+// Optional parameters for FP8 / NVFP4 output modes.
+struct RmsNormSiluExtraParams {
+ // FP8 output: quantization scale (float*). If nullptr, uses 1.0 from workspace.
+ void* fp8_scale = nullptr;
+ void* fp8_scale_inv = nullptr; // optional: written by kernel if hasScaleInv
+ void* fp8_amax = nullptr; // optional: written by kernel if hasAmax
+
+ // NVFP4 (1D1X1X) output: row-wise block-scale factors (float*, written by kernel)
+ // Shape: [num_tokens, ceil(C / 16)]
+ void* nvfp4_scale_row = nullptr;
+};
+
+class IOssNormEngine {
+ public:
+ virtual ~IOssNormEngine() = default;
+
+ // Phase 1: Validate that (shape, sm_version) is supported.
+ virtual error_t
+ check_support(NormSiluShape_t shape, int sm_version) = 0;
+
+ // Phase 2: NVRTC compile the kernel for the selected config.
+ virtual error_t
+ build() = 0;
+
+ // Phase 3: Launch the kernel.
+ // input — [num_tokens, C] bf16 input tensor
+ // output — [num_tokens, C] output tensor (bf16, fp8, or nvfp4)
+ // weight — [C] bf16 gamma weights
+ // bias — [C] bf16 beta bias (can be nullptr)
+ // rows — num_tokens
+ // cols — C (hidden dimension)
+ // epsilon — RMSNorm epsilon (for L2Norm equiv: eps_l2 / C)
+ // extra — optional FP8/NVFP4 params (can be empty)
+ virtual error_t
+ execute(void* input,
+ void* output,
+ void* weight,
+ void* bias,
+ int rows,
+ int cols,
+ float epsilon,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ RmsNormSiluExtraParams const& extra = {}) = 0;
+
+ // Workspace size in bytes. The kernel needs an `rs` (inverse RMS) buffer,
+ // plus a float for FP8 default scale if no external scale is provided.
+ virtual int64_t
+ get_workspace_size() const = 0;
+};
+
+// ============================================================
+// Shared NVRTC compilation + module loading
+// Used by both Sm90 and Sm100 engines to avoid code duplication.
+// ============================================================
+
+inline error_t
+compile_and_load_kernel(const KernelSpec* spec,
+ cudaLibrary_t& module,
+ cudaKernel_t& kernelPtr,
+ std::unique_ptr<char[]>& cubin,
+ size_t& cubinSize,
+ std::string& kernelName) {
+ // Ensure NVRTC library is available
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !detail::nvrtc_is_loaded(), error_code_t::CUDA_API_FAILED, "NVRTC library could not be loaded");
+
+ // Parse flags from embedded string
+ std::vector<std::string> flags = parse_flags_string(spec->flags_raw, spec->flags_len);
+ std::vector<const char*> flag_ptrs;
+ flag_ptrs.reserve(flags.size());
+ for (auto& f : flags) {
+ flag_ptrs.push_back(f.c_str());
+ }
+
+ // Create NVRTC program from embedded source
+ nvrtcProgram prog;
+ nvrtcResult nvrtc_err;
+
+ nvrtc_err = detail::nvrtc_create_program(&prog, spec->source, "kernel.cu", 0, nullptr, nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcCreateProgram failed");
+
+ // Compile
+ nvrtcResult compResult = detail::nvrtc_compile_program(prog, (int)flag_ptrs.size(), flag_ptrs.data());
+
+ if (cudnn_frontend::isLoggingEnabled()) {
+ // Write the source to a file for debugging
+ std::ofstream ofs("kernel.cu");
+ ofs << spec->source;
+
+ // Try to dump PTX (cicc may have succeeded even if ptxas failed)
+ size_t ptxSize = 0;
+ if (detail::nvrtc_get_ptx_size(prog, &ptxSize) == NVRTC_SUCCESS && ptxSize > 1) {
+ std::vector<char> ptx(ptxSize);
+ if (detail::nvrtc_get_ptx(prog, ptx.data()) == NVRTC_SUCCESS) {
+ std::ofstream ptx_ofs("kernel.ptx");
+ ptx_ofs.write(ptx.data(), static_cast<std::streamsize>(ptxSize - 1));
+ }
+ }
+ }
+
+ if (compResult != NVRTC_SUCCESS) {
+ // Try to retrieve the compilation log for diagnostics
+ size_t logSize = 0;
+ detail::nvrtc_get_program_log_size(prog, &logSize);
+ std::string log_msg = "NVRTC compilation failed";
+ if (logSize > 1) {
+ std::vector<char> log(logSize);
+ detail::nvrtc_get_program_log(prog, log.data());
+ log_msg += ": ";
+ log_msg += log.data();
+ }
+
+ CUDNN_FE_LOG_LABEL_ENDL("ERROR: NVRTC compilation failed: " << log_msg);
+ detail::nvrtc_destroy_program(&prog);
+ return {error_code_t::CUDA_API_FAILED, log_msg};
+ }
+
+ // Extract CUBIN
+ nvrtc_err = detail::nvrtc_get_cubin_size(prog, &cubinSize);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBINSize failed");
+
+ cubin = std::make_unique<char[]>(cubinSize);
+
+ nvrtc_err = detail::nvrtc_get_cubin(prog, cubin.get());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBIN failed");
+
+ nvrtc_err = detail::nvrtc_destroy_program(&prog);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcDestroyProgram failed");
+
+ // Load module + extract kernel function
+ cudaError_t cuda_err;
+
+ cuda_err = detail::cuda_library_load_data(&module, cubin.get(), nullptr, nullptr, 0, nullptr, nullptr, 0);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryLoadData failed (cubin_size=" + std::to_string(cubinSize) +
+ ", error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ kernelName = spec->kernel_name;
+ cuda_err = detail::cuda_library_get_kernel(&kernelPtr, module, kernelName.c_str());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryGetKernel failed: " + detail::cuda_error_to_string(cuda_err) + " (kernel: " + kernelName + ")");
+
+ CUDNN_FE_LOG_LABEL_ENDL("INFO: NVRTC compilation successful, kernel: " << kernelName);
+ return {error_code_t::OK, ""};
+}
+
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h
new file mode 100644
index 0000000..bb7048c
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_engine.h
@@ -0,0 +1,697 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "oss_engine_interface.h"
+#include "sm100_rms_norm_silu_knobs.h"
+// LN headers and kernel source for NVRTC compilation.
+#include "../generated/rms_norm_silu/sm100/ln_headers.h"
+#include "../generated/rms_norm_silu/sm100/ln_fwd_silu_kernel.h"
+
+#include <cuda_fp16.h>
+#include <algorithm>
+#include <cmath>
+#include <string>
+#include <memory>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// PersistentLnFwdParams — matches the kernel's expected parameter struct.
+// Matches the kernel's expected parameter struct layout (PersistentLnFwdParams).
+// ============================================================
+
+struct PersistentLnFwdParams {
+ int ctas_per_col = 0;
+ int rows = 0;
+ int cols = 0;
+ int batchSize = 1;
+ int seqLen = 1;
+
+ void* x = nullptr;
+ void* mu = nullptr;
+ void* rs = nullptr;
+ void* gamma = nullptr;
+
+ void* workspace = nullptr;
+ int* barrier = nullptr;
+
+ bool isRMSNorm = false;
+ bool noScale = false;
+ bool noBias = false;
+ bool isAdaLN = false;
+ bool isBatchFirst = true;
+
+ // Output
+ void* z = nullptr;
+ void* beta = nullptr;
+ float epsilon = 0.f;
+
+ // FP8
+ bool fp8_out = false;
+ float* scale = nullptr;
+ float* scale_inv = nullptr;
+ float* amax = nullptr;
+
+ // Block scale (NVFP4) — field order must match CuDNN's ln.h exactly
+ 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 for 1d2x2x colwise kernel
+};
+
+// ============================================================
+// reduced_divisor — matches the kernel's expected second argument.
+// Matches the kernel's expected second argument (reduced_divisor).
+// ============================================================
+
+struct reduced_divisor {
+ uint32_t mul_coeff = 0;
+ uint32_t shift_coeff = 0;
+ int32_t y = 0;
+
+ reduced_divisor() = default;
+ reduced_divisor(int32_t _y) : y(_y) {
+ if (_y <= 1) {
+ mul_coeff = 0;
+ shift_coeff = 0;
+ return;
+ }
+ // Find shift such that 2^(32+shift) / y fits in 32 bits
+ for (shift_coeff = 0; shift_coeff < 32; ++shift_coeff) {
+ uint64_t one = 1;
+ uint64_t num = (one << (32 + shift_coeff));
+ uint64_t den = static_cast<uint64_t>(_y);
+ if (num / den < (one << 32)) {
+ mul_coeff = static_cast<uint32_t>(num / den + 1);
+ break;
+ }
+ }
+ }
+};
+
+// ============================================================
+// Sm100RmsNormSiluEngine
+// ============================================================
+
+class Sm100RmsNormSiluEngine : public IOssNormEngine {
+ public:
+ Sm100RmsNormSiluEngine() = default;
+
+ ~Sm100RmsNormSiluEngine() override {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ }
+
+ // Non-copyable
+ Sm100RmsNormSiluEngine(const Sm100RmsNormSiluEngine&) = delete;
+ Sm100RmsNormSiluEngine&
+ operator=(const Sm100RmsNormSiluEngine&) = delete;
+
+ // ---- Phase 1: Support check + knob selection ----
+ error_t
+ check_support(NormSiluShape_t shape, int sm_version) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ sm_version < 80, error_code_t::GRAPH_NOT_SUPPORTED, "RmsNormSiluEngine requires SM80+");
+
+ // FP8 output requires SM89+ (Ada Lovelace / Hopper)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(shape.output_dtype == RmsNormSiluDtype::FP8 && sm_version < 89,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "FP8 output requires SM89+ (Ada/Hopper)");
+
+ // NVFP4 output requires SM100+ (Blackwell)
+ RETURN_CUDNN_FRONTEND_ERROR_IF(shape.output_dtype == RmsNormSiluDtype::NVFP4 && sm_version < 100,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "NVFP4 output requires SM100+ (Blackwell)");
+
+ sm_version_ = sm_version;
+
+ // Look up knobs: SM100 uses sweep-tuned LUT, other archs use fallback heuristic
+ knobs_ = lookup_rms_norm_silu_knobs(shape.C, shape.num_tokens, shape.output_dtype, sm_version);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ knobs_ == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unsupported problem size: C=" + std::to_string(shape.C) + " tokens=" + std::to_string(shape.num_tokens));
+
+ C_ = shape.C;
+ num_tokens_ = shape.num_tokens;
+ output_dtype_ = shape.output_dtype;
+ bytes_per_ldg_ = knobs_->bytes_per_ldg;
+
+ // Derived config
+ warps_m_ = knobs_->warps_m;
+ warps_n_ = 1; // Always 1
+ threads_per_cta_ = warps_m_ * warps_n_ * 32;
+
+ // Estimate CTAS_PER_ROW when the sweep found column splitting optimal.
+ // Matches CuDNN's estimate_ctas_per_row() from LayerNorm_common.cpp:
+ // Find largest LDGS per CTA that avoids register spilling (< 64/NUM_ELTS),
+ // then CTAS_PER_ROW = total_ldgs / ldgs_per_cta.
+ // kernel_cfg=2 (non-persistent) requires CTAS_PER_ROW=1.
+ if (knobs_->split_cols == 4 && knobs_->kernel_cfg != 2) {
+ int input_size = 2; // bf16
+ int num_elts = bytes_per_ldg_ / input_size;
+ int elts_per_ldg = num_elts * warps_n_ * 32;
+ if (elts_per_ldg > 0 && shape.C % elts_per_ldg == 0) {
+ int ldgs_per_row = shape.C / elts_per_ldg;
+ int ldgs_to_cause_register_spill = (num_elts > 0) ? (64 / num_elts) : 1;
+ ctas_per_row_ = 1;
+ for (int ldgs = std::min(ldgs_per_row, ldgs_to_cause_register_spill - 1); ldgs > 0; ldgs--) {
+ if (ldgs_per_row % ldgs == 0) {
+ ctas_per_row_ = ldgs_per_row / ldgs;
+ break;
+ }
+ }
+ } else {
+ ctas_per_row_ = 1;
+ }
+ } else {
+ ctas_per_row_ = 1;
+ }
+ is_cooperative_ = (ctas_per_row_ > 1);
+
+ // Cache SM count
+ cudaDeviceProp devProp;
+ int device_ordinal = 0;
+ cudaError_t cuda_err = detail::cuda_get_device(&device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDevice failed");
+ cuda_err = detail::cuda_get_device_properties(&devProp, device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDeviceProperties failed");
+ sm_count_ = devProp.multiProcessorCount;
+
+ support_checked_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ // Workspace layout (all offsets 128-byte aligned):
+ // [0] rs : num_tokens * sizeof(float)
+ // [aligned] fp8_scale : sizeof(float)
+ // [aligned] scale_row : num_tokens * ceil(C/16) bytes (NVFP4 only)
+ // [aligned] coop_workspace : ctas_per_col * WARPS_M * CTAS_PER_ROW * sizeof(float2) * 2
+ // [aligned] coop_barrier : 2 * ctas_per_col * sizeof(int32_t)
+ // + 128 padding
+ int64_t
+ get_workspace_size() const override {
+ int64_t ws = static_cast<int64_t>(num_tokens_) * sizeof(float); // rs
+ ws = ((ws + 127) / 128) * 128;
+ ws += sizeof(float); // FP8 default scale
+ ws = ((ws + 127) / 128) * 128;
+ if (output_dtype_ == RmsNormSiluDtype::NVFP4) {
+ ws += static_cast<int64_t>(num_tokens_) * ((C_ + 15) / 16);
+ ws = ((ws + 127) / 128) * 128;
+ }
+ if (is_cooperative_) {
+ int ctas_per_col = std::max(1, (num_tokens_ + warps_m_ - 1) / warps_m_);
+ // Inter-CTA partial stats: ctas_per_col * WARPS_M * CTAS_PER_ROW * sizeof(float2) * 2
+ ws += static_cast<int64_t>(ctas_per_col) * warps_m_ * ctas_per_row_ * sizeof(float) * 2 * 2;
+ ws = ((ws + 127) / 128) * 128;
+ // Barrier array: 2 * ctas_per_col * sizeof(int32_t)
+ ws += 2 * static_cast<int64_t>(ctas_per_col) * sizeof(int32_t);
+ ws = ((ws + 127) / 128) * 128;
+ }
+ ws += 128; // final alignment
+ return ws;
+ }
+
+ // Get offset of scale_row within workspace (for reading back in tests).
+ // Returns -1 if not NVFP4 output.
+ int64_t
+ get_scale_row_workspace_offset() const {
+ if (output_dtype_ != RmsNormSiluDtype::NVFP4) return -1;
+ int64_t off = static_cast<int64_t>(num_tokens_) * sizeof(float);
+ off = ((off + 127) / 128) * 128;
+ off += sizeof(float);
+ off = ((off + 127) / 128) * 128;
+ return off;
+ }
+
+ int64_t
+ get_scale_row_size_bytes() const {
+ if (output_dtype_ != RmsNormSiluDtype::NVFP4) return 0;
+ return static_cast<int64_t>(num_tokens_) * ((C_ + 15) / 16);
+ }
+
+ // ---- Phase 2: NVRTC compilation ----
+ error_t
+ build() override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!support_checked_ || knobs_ == nullptr,
+ error_code_t::INVALID_VALUE,
+ "build() called before check_support()");
+
+ // Assemble the full kernel source:
+ // 1. Generate constexpr defines from knobs
+ // 2. Prepend to headers + kernel body
+
+ // Order: preamble → headers (defines cuda types) → constexpr defines
+ // (uses those types) → kernel body (uses everything).
+ std::string defines = generate_constexpr_defines();
+
+ // Undefine EWP/RDC to avoid removed cudaCGScopeMultiGrid in cooperative_groups
+ std::string preamble = "#undef __CUDACC_EWP__\n#undef __CUDACC_RDC__\n";
+
+ std::string full_source = preamble + std::string(generated::ln_headers_source) + defines +
+ std::string(generated::ln_fwd_silu_kernel_source);
+
+ // Parse compile flags and override --gpu-architecture for the target SM version
+ std::vector<std::string> flags =
+ parse_flags_string(generated::ln_fwd_silu_kernel_flags, generated::ln_fwd_silu_kernel_flags_len);
+
+ // Replace the embedded --gpu-architecture with the correct arch for this GPU.
+ // The 'a' suffix = architecture-specific (enables SM-specific features like redux.sync).
+ // The 'f' suffix = forward-compatible across an SM family (e.g., sm_100f works on SM100-SM103).
+ // The kernel source has #if __CUDA_ARCH__ guards for SM-specific instructions.
+ {
+ std::string target_arch;
+ if (sm_version_ == 100)
+ target_arch = "sm_100a"; // B200: arch-specific for best codegen
+ else if (sm_version_ > 100 && sm_version_ < 110)
+ target_arch = "sm_100f"; // GB300 etc: forward-compat
+ else if (sm_version_ == 90)
+ target_arch = "sm_90a";
+ else if (sm_version_ > 90 && sm_version_ < 100)
+ target_arch = "sm_90"; // SM92 etc
+ else if (sm_version_ >= 89)
+ target_arch = "sm_89";
+ else if (sm_version_ >= 86)
+ target_arch = "sm_86";
+ else
+ target_arch = "sm_80";
+
+ for (auto& f : flags) {
+ if (f.find("--gpu-architecture=") == 0) {
+ f = "--gpu-architecture=" + target_arch;
+ break;
+ }
+ }
+ }
+
+ // Add CUDA Toolkit include paths for NVRTC to resolve #include <cuda_bf16.h> etc.
+ std::string cuda_include = "/usr/local/cuda/include";
+ if (auto env0 = get_environment("CUDA_HOME")) {
+ cuda_include = std::string(env0) + "/include";
+ } else if (auto env1 = get_environment("CUDA_PATH")) {
+ cuda_include = std::string(env1) + "/include";
+ }
+ flags.push_back("--include-path=" + cuda_include);
+
+ // CCCL headers needed for cuda::ptx:: used by block-scale (NVFP4) code paths.
+ // CUDA 13+ ships CCCL under targets/<arch>-linux/include/cccl.
+ // Add both x86_64 and aarch64 paths — NVRTC silently ignores non-existent paths.
+ std::string cuda_base = cuda_include.substr(0, cuda_include.rfind("/include"));
+ for (const char* arch : {"x86_64", "aarch64"}) {
+ std::string target_dir = cuda_base + "/targets/" + arch + "-linux/include";
+ flags.push_back("--include-path=" + target_dir);
+ flags.push_back("--include-path=" + target_dir + "/cccl");
+ }
+
+ std::vector<const char*> flag_ptrs;
+ for (auto& f : flags) flag_ptrs.push_back(f.c_str());
+
+ // NVRTC compile
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ !detail::nvrtc_is_loaded(), error_code_t::CUDA_API_FAILED, "NVRTC library could not be loaded");
+
+ nvrtcProgram prog;
+ nvrtcResult nvrtc_err;
+
+ nvrtc_err = detail::nvrtc_create_program(&prog, full_source.c_str(), "ln_fwd_silu.cu", 0, nullptr, nullptr);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcCreateProgram failed");
+
+ nvrtcResult compResult = detail::nvrtc_compile_program(prog, (int)flag_ptrs.size(), flag_ptrs.data());
+ if (compResult != NVRTC_SUCCESS) {
+ size_t logSize = 0;
+ detail::nvrtc_get_program_log_size(prog, &logSize);
+ std::string log_msg = "NVRTC compilation failed";
+ if (logSize > 1) {
+ std::vector<char> log(logSize);
+ detail::nvrtc_get_program_log(prog, log.data());
+ log_msg += ": ";
+ log_msg += log.data();
+ }
+ detail::nvrtc_destroy_program(&prog);
+ return {error_code_t::CUDA_API_FAILED, log_msg};
+ }
+
+ // Extract CUBIN
+ nvrtc_err = detail::nvrtc_get_cubin_size(prog, &cubinSize_);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBINSize failed");
+
+ cubin_ = std::make_unique<char[]>(cubinSize_);
+ nvrtc_err = detail::nvrtc_get_cubin(prog, cubin_.get());
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ nvrtc_err != NVRTC_SUCCESS, error_code_t::CUDA_API_FAILED, "nvrtcGetCUBIN failed");
+
+ detail::nvrtc_destroy_program(&prog);
+
+ // Load module + kernel
+ cudaError_t cuda_err;
+ cuda_err = detail::cuda_library_load_data(&module_, cubin_.get(), nullptr, nullptr, 0, nullptr, nullptr, 0);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryLoadData failed: " + detail::cuda_error_to_string(cuda_err));
+
+ cuda_err = detail::cuda_library_get_kernel(&kernelPtr_, module_, "ln_fwd_kernel");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLibraryGetKernel failed: " + detail::cuda_error_to_string(cuda_err));
+
+ built_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ // ---- Phase 3: Execute ----
+ error_t
+ execute(void* input,
+ void* output,
+ void* weight, // gamma
+ void* bias, // beta (can be nullptr)
+ int rows,
+ int cols,
+ float epsilon,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ RmsNormSiluExtraParams const& extra = {}) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!built_, error_code_t::INVALID_VALUE, "execute() called before build()");
+
+ // Compute grid dimensions
+ int ctas_per_col_max = (rows + warps_m_ - 1) / warps_m_;
+ int ctas_per_col;
+ if (knobs_->kernel_cfg == 2) {
+ // Non-persistent mode: launch one CTA group per row (max CTAs).
+ // CuDNN overrides ctas_per_col to max when use_non_persistent_mode=true.
+ ctas_per_col = ctas_per_col_max;
+ } else {
+ ctas_per_col = std::min(sm_count_ * static_cast<int>(knobs_->occupancy) / ctas_per_row_, ctas_per_col_max);
+ }
+ ctas_per_col = std::max(ctas_per_col, 1);
+
+ dim3 grid(ctas_per_row_ * ctas_per_col);
+ dim3 block(threads_per_cta_);
+
+ // Pack params
+ PersistentLnFwdParams params{};
+ params.rows = rows;
+ params.cols = cols;
+ params.ctas_per_col = ctas_per_col;
+ params.isRMSNorm = true;
+ params.noScale = (weight == nullptr);
+ params.noBias = (bias == nullptr);
+ params.isBatchFirst = true;
+ params.batchSize = 1;
+ params.seqLen = rows;
+ params.epsilon = epsilon;
+ params.x = input;
+ params.z = output;
+ params.gamma = weight;
+ params.beta = bias;
+
+ // Workspace layout (128-byte aligned):
+ // [0] rs : rows * sizeof(float)
+ // [aligned] fp8_scale : sizeof(float)
+ // [aligned] scale_row : rows * ceil(cols/16) bytes (NVFP4 only)
+ char* ws_ptr = static_cast<char*>(workspace);
+ params.rs = ws_ptr;
+ {
+ int64_t off = static_cast<int64_t>(rows) * sizeof(float);
+ off = ((off + 127) / 128) * 128;
+ ws_ptr = static_cast<char*>(workspace) + off;
+ }
+
+ // FP8 output: set scale pointer
+ if (output_dtype_ == RmsNormSiluDtype::FP8) {
+ params.fp8_out = true;
+ if (extra.fp8_scale) {
+ params.scale = static_cast<float*>(extra.fp8_scale);
+ } else {
+ // Use default scale = 1.0 from workspace (device memory)
+ // Write 1.0f (IEEE 754: 0x3F800000) asynchronously on stream
+ float* default_scale = reinterpret_cast<float*>(ws_ptr);
+ cudaError_t memset_err = detail::cuda_mem_set_d32_async(default_scale, 0x3F800000u, 1, stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(memset_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaMemcpyAsync for default scale failed");
+ params.scale = default_scale;
+ }
+ params.scale_inv = static_cast<float*>(extra.fp8_scale_inv); // may be nullptr
+ params.amax = static_cast<float*>(extra.fp8_amax); // may be nullptr
+ }
+
+ // NVFP4 output: set scale_row pointer
+ if (output_dtype_ == RmsNormSiluDtype::NVFP4) {
+ if (extra.nvfp4_scale_row) {
+ params.scale_row = extra.nvfp4_scale_row;
+ } else {
+ // Auto-allocate from workspace after fp8_scale slot
+ int64_t scale_row_off = get_scale_row_workspace_offset();
+ params.scale_row = static_cast<char*>(workspace) + scale_row_off;
+ }
+ }
+
+ // Multi-CTA cooperative reduction: allocate workspace + barrier from workspace
+ if (is_cooperative_) {
+ // Compute workspace offset after rs + fp8_scale + scale_row
+ int64_t coop_off = static_cast<int64_t>(rows) * sizeof(float);
+ coop_off = ((coop_off + 127) / 128) * 128;
+ coop_off += sizeof(float);
+ coop_off = ((coop_off + 127) / 128) * 128;
+ if (output_dtype_ == RmsNormSiluDtype::NVFP4) {
+ coop_off += static_cast<int64_t>(rows) * ((cols + 15) / 16);
+ coop_off = ((coop_off + 127) / 128) * 128;
+ }
+
+ // Inter-CTA partial stats workspace
+ int64_t coop_ws_size =
+ static_cast<int64_t>(ctas_per_col) * warps_m_ * ctas_per_row_ * sizeof(float) * 2 * 2;
+ params.workspace = static_cast<char*>(workspace) + coop_off;
+ coop_off += coop_ws_size;
+ coop_off = ((coop_off + 127) / 128) * 128;
+
+ // Barrier array — must be zeroed before each launch
+ int64_t barrier_count = 2 * ctas_per_col;
+ params.barrier = reinterpret_cast<int*>(static_cast<char*>(workspace) + coop_off);
+ cudaError_t memset_err =
+ detail::cuda_mem_set_async(params.barrier, 0, barrier_count * sizeof(int32_t), stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ memset_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaMemsetAsync failed for cooperative barrier (count=" + std::to_string(barrier_count) +
+ " offset=" + std::to_string(coop_off) + ")");
+ }
+
+ // reduced_divisor for batch/seqLen (batchFirst=true, so divide by seqLen=rows)
+ reduced_divisor divisor(rows);
+
+ // Kernel args
+ void* kernelParams[] = {
+ reinterpret_cast<void*>(&params),
+ reinterpret_cast<void*>(&divisor),
+ };
+
+ // Static shared memory: USE_STATIC_SMEM_VALUE is defined in the NVRTC source,
+ // so the kernel allocates smem at compile time. Pass 0 for dynamic smem.
+ // The kernel uses compile-time static shared memory (no dynamic smem needed).
+ int smem_bytes = 0;
+
+ // Set shared memory attribute
+ cudaError_t cuda_err;
+ cuda_err = detail::cuda_kernel_set_attribute_for_device(
+ kernelPtr_, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_bytes, device);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaKernelSetAttributeForDevice failed: " + detail::cuda_error_to_string(cuda_err));
+
+ // Launch
+ cuda_err = detail::cuda_launch_kernel((const void*)kernelPtr_, grid, block, kernelParams, smem_bytes, stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLaunchKernel failed: " + detail::cuda_error_to_string(cuda_err) +
+ " (grid=" + std::to_string(grid.x) + " block=" + std::to_string(block.x) +
+ " smem=" + std::to_string(smem_bytes) + ")");
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ std::string
+ generate_constexpr_defines() const {
+ std::string s;
+
+ // Type aliases (bf16 input always for VAE)
+ s += "\nusing ITYPE = nv_bfloat16;";
+ switch (output_dtype_) {
+ case RmsNormSiluDtype::BF16:
+ s += "\nusing OTYPE = nv_bfloat16;";
+ break;
+ case RmsNormSiluDtype::FP8:
+ s += "\nusing OTYPE = nv_fp8_e4m3;";
+ break;
+ case RmsNormSiluDtype::NVFP4:
+ s += "\nusing OTYPE = nv_fp4_e2m1;";
+ break;
+ }
+ s += "\nusing WTYPE = nv_bfloat16;";
+ s += "\nusing CTYPE = float;";
+ // NORM_OTYPE must match the norm output type, not compute type.
+ // Must match the norm output type, not compute type.
+ // For bf16 output: nv_bfloat16. For FP8/NVFP4: float (block-scale intermediate).
+ switch (output_dtype_) {
+ case RmsNormSiluDtype::BF16:
+ s += "\nusing NORM_OTYPE = nv_bfloat16;";
+ break;
+ case RmsNormSiluDtype::FP8:
+ case RmsNormSiluDtype::NVFP4:
+ s += "\nusing NORM_OTYPE = float;";
+ break;
+ }
+
+ // Kernel config
+ s += "\nconstexpr int HIDDEN_SIZE = " + std::to_string(C_) + ";";
+ s += "\nconstexpr int BATCH_SIZE = 1;";
+ s += "\nconstexpr int CTAS_PER_ROW = " + std::to_string(ctas_per_row_) + ";";
+ s += "\nconstexpr int WARPS_M = " + std::to_string(warps_m_) + ";";
+ s += "\nconstexpr int WARPS_N = " + std::to_string(warps_n_) + ";";
+ s += "\nconstexpr int BYTES_PER_LDG = " + std::to_string(bytes_per_ldg_) + ";";
+ s += "\nconstexpr bool isRMSNorm = 1;";
+ s += "\nconstexpr bool isAdaLN = 0;";
+ s += "\nconstexpr bool isBatchFirst = 1;";
+ s += "\nconstexpr bool hasGamma = 1;";
+ s += "\nconstexpr bool hasBeta = 0;";
+ s += "\nconstexpr bool isZeroCenteredGamma = 0;";
+ s += "\nconstexpr bool isZeroCenteredGammaCastBeforeAdd = 0;";
+
+ bool use_smem_gamma = (knobs_->kernel_cfg == 1);
+ bool use_non_persistent = (knobs_->kernel_cfg == 2);
+ s += "\nconstexpr bool useSmemGamma = " + std::to_string(use_smem_gamma ? 1 : 0) + ";";
+ s += "\nconstexpr bool GAMMA_ON_DEMAND = " + std::to_string((!use_smem_gamma && use_non_persistent) ? 1 : 0) +
+ ";";
+
+ bool is_fp8 = (output_dtype_ == RmsNormSiluDtype::FP8);
+ bool is_nvfp4 = (output_dtype_ == RmsNormSiluDtype::NVFP4);
+ s += "\nconstexpr bool isFP8Out = " + std::to_string(is_fp8 ? 1 : 0) + ";";
+ s += "\nconstexpr bool hasScaleInv = 0;";
+ s += "\nconstexpr bool hasAmax = 0;";
+ s += "\n#define LN_USE_CLUSTER 0";
+ s += "\nconstexpr bool USE_CLUSTER = 0;";
+ s += "\nconstexpr bool isBlockScaleOut = " + std::to_string(is_nvfp4 ? 1 : 0) + ";";
+ s += "\nconstexpr bool isFP4Out = " + std::to_string(is_nvfp4 ? 1 : 0) + ";";
+ s += "\nconstexpr bool isBlockScale_1D1X1X = " + std::to_string(is_nvfp4 ? 1 : 0) + ";";
+ s += "\nconstexpr bool isBlockScale_1D2X2X = 0;";
+ s += "\nconstexpr bool isBlockScale_1D2X2X_Transpose = 0;";
+ s += "\nconstexpr bool useBlockScaleColwiseKernel = 0;";
+ s += "\nconstexpr int DESIRED_OCCUPANCY = " + std::to_string(knobs_->occupancy) + ";";
+
+ // Ktraits instantiation
+ s += "\nusing Ktraits = Kernel_traits<WTYPE, ITYPE, OTYPE, CTYPE, NORM_OTYPE, uint32_t,";
+ s += "\n HIDDEN_SIZE, BATCH_SIZE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG,";
+ s += "\n isRMSNorm, isAdaLN, isBatchFirst, hasGamma, hasBeta, useSmemGamma,";
+ s += "\n USE_CLUSTER, false>;"; // WHOLE_CTA = false
+
+ // Static shared memory: let the kernel template compute the exact struct size.
+ // The kernel template computes the exact struct size at compile time.
+ // The kernel uses __shared__ char smem[USE_STATIC_SMEM_VALUE] instead of extern __shared__.
+ s += "\n#define USE_STATIC_SMEM_VALUE ((int)sizeof(LnFwdShared<Ktraits>))";
+
+ return s;
+ }
+
+ // Compute shared memory size matching the kernel's LnFwdShared struct.
+ // Every field has at least 1 element and __align__(16).
+ //
+ // LnFwdShared<Ktraits>:
+ // __align__(16) char smem_stats[SMEM_STATS_ELEMENTS] — 1 or Stats::SMEM_BYTES
+ // __align__(16) uint64_t smem_bar[SMEM_BAR_ELEMENTS] — 1 (no cluster)
+ // __align__(16) weight_t smem_gamma[GAMMA_ELEMENTS] — 1 or LDGS*THREADS_PER_ROW*NUM_ELTS
+ // __align__(16) weight_t smem_beta[BETA_ELEMENTS] — 1 (no beta)
+ // __align__(16) float smem_mxfp8[SMEM_MXFP8_ELEMENTS] — 1 (no 1D2X2X)
+ int
+ compute_smem_bytes() const {
+ int elts_per_ldg = bytes_per_ldg_ / 2;
+ int vec_cols = C_ / elts_per_ldg;
+ int threads_per_row = warps_n_ * 32;
+ int vec_cols_per_ldg = ctas_per_row_ * threads_per_row;
+ int ldgs = (vec_cols_per_ldg > 0) ? (vec_cols / vec_cols_per_ldg) : 1;
+ int num_elts = elts_per_ldg;
+
+ auto align16 = [](int bytes) { return ((bytes + 15) / 16) * 16; };
+
+ // smem_stats: min 1 byte → 16 when aligned.
+ // When CTAS_PER_ROW=1 && WARPS_N=1, Stats::SMEM_BYTES=0, so element count = max(0,1) = 1.
+ int stats_bytes = 1;
+ if (ctas_per_row_ > 1 || warps_n_ > 1) {
+ stats_bytes = warps_m_ * warps_n_ * sizeof(float) * 2 * 2;
+ }
+ int smem_stats = align16(stats_bytes);
+
+ // smem_bar: 1 uint64_t (no cluster)
+ int smem_bar = align16(static_cast<int>(sizeof(uint64_t)));
+
+ // smem_gamma: kernel_cfg=1 loads gamma to smem
+ int gamma_elements = 1;
+ if (knobs_->kernel_cfg == 1) {
+ gamma_elements = 1 * ldgs * threads_per_row * num_elts; // BATCH_SIZE=1
+ }
+ int smem_gamma = align16(gamma_elements * 2); // weight_t = bf16 = 2 bytes
+
+ // smem_beta: 1 element (hasBeta=false)
+ int smem_beta = align16(2); // 1 * sizeof(bf16)
+
+ // smem_mxfp8: 1 element (not 1D2X2X)
+ int smem_mxfp8 = align16(static_cast<int>(sizeof(float)));
+
+ int smem_bytes = smem_stats + smem_bar + smem_gamma + smem_beta + smem_mxfp8;
+ smem_bytes = ((smem_bytes + 127) / 128) * 128;
+ return smem_bytes;
+ }
+
+ // State from check_support()
+ const RmsNormSiluKnobs* knobs_ = nullptr;
+ int C_ = 0;
+ int num_tokens_ = 0;
+ RmsNormSiluDtype output_dtype_ = RmsNormSiluDtype::BF16;
+ int bytes_per_ldg_ = 0;
+ int warps_m_ = 0;
+ int warps_n_ = 0;
+ int threads_per_cta_ = 0;
+ int ctas_per_row_ = 0;
+ int sm_count_ = 0;
+ int sm_version_ = 0;
+ bool is_cooperative_ = false;
+ bool support_checked_ = false;
+
+ // State from build()
+ cudaLibrary_t module_ = nullptr;
+ cudaKernel_t kernelPtr_ = nullptr;
+ std::unique_ptr<char[]> cubin_;
+ size_t cubinSize_ = 0;
+ bool built_ = false;
+};
+
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h
new file mode 100644
index 0000000..8080ab2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_rms_norm_silu_knobs.h
@@ -0,0 +1,215 @@
+#pragma once
+
+// Auto-generated knob selection logic for Sm100RmsNormSiluEngine.
+// Generated from optimal knob sweep results on B200 (SM100).
+// Knob mapping: knobTileRows {0:1,1:4,2:8,3:32}, knobLoadSize {0:2,1:4,2:8,3:16}
+
+#include <cstdint>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+enum class RmsNormSiluDtype : uint8_t {
+ BF16 = 0,
+ FP8 = 1,
+ NVFP4 = 2,
+};
+
+// Compact knob configuration per (C, tokens, dtype) entry.
+// WARPS_N is always 1. All values are the ACTUAL kernel parameters
+// (not knob indices).
+struct RmsNormSiluKnobs {
+ uint8_t warps_m; // WARPS_M value: 1, 4, 8, or 32
+ uint8_t split_cols; // knobSplitCols: 0 = no split, 4 = estimated CTAS_PER_ROW
+ uint8_t kernel_cfg; // knobKernelCfg: 0, 1, or 2
+ uint8_t occupancy; // DESIRED_OCCUPANCY: 0-16
+ uint8_t bytes_per_ldg; // BYTES_PER_LDG: 2, 4, 8, or 16
+};
+
+static constexpr int kSupportedC[] = {64, 128, 160, 256, 320, 512, 640, 1024};
+static constexpr int kSupportedTokens[] = {1560, 6240, 24960, 99840, 399360};
+static constexpr int kNumC = 8;
+static constexpr int kNumTokens = 5;
+static constexpr int kNumDtypes = 3;
+
+// Knob LUT indexed as: knob_lut[c_idx][tokens_idx][dtype_idx]
+// c_idx: 0=64, 1=128, 2=160, 3=256, 4=320, 5=512, 6=640, 7=1024
+// tokens_idx: 0=1560, 1=6240, 2=24960, 3=99840, 4=399360
+// dtype_idx: 0=bf16, 1=fp8, 2=nvfp4
+static constexpr RmsNormSiluKnobs knob_lut[kNumC][kNumTokens][kNumDtypes] = {
+ {
+ // C=64
+ {{8, 0, 0, 2, 4}, {8, 4, 0, 6, 4}, {8, 0, 2, 1, 4}}, // tokens=1560
+ {{32, 4, 0, 2, 4}, {8, 0, 0, 3, 2}, {8, 4, 0, 4, 4}}, // tokens=6240
+ {{32, 4, 0, 2, 4}, {8, 0, 0, 7, 4}, {8, 0, 1, 6, 4}}, // tokens=24960
+ {{8, 0, 1, 8, 4}, {8, 0, 1, 6, 2}, {32, 4, 1, 2, 4}}, // tokens=99840
+ {{4, 0, 1, 16, 4}, {32, 0, 1, 2, 2}, {32, 4, 1, 2, 4}}, // tokens=399360
+ },
+ {
+ // C=128
+ {{8, 4, 0, 3, 4}, {8, 0, 0, 3, 4}, {8, 4, 0, 3, 8}}, // tokens=1560
+ {{8, 0, 0, 3, 4}, {8, 0, 0, 4, 8}, {8, 0, 0, 5, 8}}, // tokens=6240
+ {{8, 0, 0, 6, 4}, {8, 0, 0, 8, 8}, {8, 0, 1, 8, 8}}, // tokens=24960
+ {{32, 4, 0, 2, 4}, {32, 0, 0, 2, 8}, {32, 0, 1, 2, 8}}, // tokens=99840
+ {{8, 0, 0, 8, 4}, {32, 0, 0, 2, 8}, {32, 0, 1, 2, 8}}, // tokens=399360
+ },
+ {
+ // C=160
+ {{8, 0, 0, 4, 2}, {8, 0, 0, 2, 2}, {4, 4, 0, 4, 2}}, // tokens=1560
+ {{8, 0, 0, 4, 2}, {8, 0, 0, 4, 2}, {8, 0, 1, 4, 2}}, // tokens=6240
+ {{8, 4, 1, 6, 2}, {8, 4, 0, 6, 2}, {8, 4, 1, 8, 2}}, // tokens=24960
+ {{32, 4, 1, 2, 2}, {32, 4, 1, 2, 2}, {32, 4, 0, 1, 2}}, // tokens=99840
+ {{32, 4, 1, 2, 2}, {32, 4, 1, 2, 2}, {32, 0, 1, 2, 2}}, // tokens=399360
+ },
+ {
+ // C=256
+ {{8, 0, 0, 6, 16}, {8, 4, 0, 2, 4}, {8, 0, 2, 1, 16}}, // tokens=1560
+ {{8, 0, 0, 4, 4}, {8, 0, 0, 4, 4}, {8, 0, 2, 1, 16}}, // tokens=6240
+ {{8, 0, 0, 8, 16}, {8, 4, 0, 8, 16}, {8, 4, 1, 6, 16}}, // tokens=24960
+ {{4, 4, 0, 16, 16}, {4, 0, 0, 16, 16}, {32, 0, 1, 1, 16}}, // tokens=99840
+ {{4, 0, 0, 16, 16}, {32, 0, 0, 2, 16}, {32, 0, 1, 2, 16}}, // tokens=399360
+ },
+ {
+ // C=320
+ {{8, 4, 1, 4, 4}, {8, 0, 0, 2, 4}, {4, 4, 0, 9, 4}}, // tokens=1560
+ {{8, 4, 0, 5, 4}, {8, 0, 0, 5, 4}, {4, 0, 0, 9, 4}}, // tokens=6240
+ {{8, 0, 0, 5, 4}, {8, 0, 0, 5, 4}, {8, 0, 1, 8, 4}}, // tokens=24960
+ {{4, 0, 1, 16, 4}, {32, 0, 1, 2, 4}, {32, 4, 1, 2, 4}}, // tokens=99840
+ {{32, 4, 0, 2, 4}, {32, 0, 1, 2, 4}, {32, 4, 1, 2, 4}}, // tokens=399360
+ },
+ {
+ // C=512
+ {{8, 0, 0, 2, 16}, {8, 0, 0, 2, 8}, {4, 4, 0, 3, 16}}, // tokens=1560
+ {{8, 0, 0, 5, 16}, {8, 0, 0, 4, 8}, {4, 0, 0, 9, 16}}, // tokens=6240
+ {{4, 0, 0, 8, 16}, {4, 0, 0, 9, 8}, {4, 0, 2, 1, 16}}, // tokens=24960
+ {{4, 0, 2, 1, 8}, {32, 4, 1, 2, 8}, {32, 4, 0, 1, 16}}, // tokens=99840
+ {{4, 0, 2, 1, 4}, {32, 4, 1, 2, 8}, {32, 0, 0, 1, 16}}, // tokens=399360
+ },
+ {
+ // C=640
+ {{4, 0, 0, 4, 4}, {4, 0, 0, 3, 8}, {4, 4, 0, 5, 8}}, // tokens=1560
+ {{4, 0, 0, 5, 4}, {8, 0, 0, 4, 8}, {4, 0, 1, 9, 8}}, // tokens=6240
+ {{4, 0, 0, 5, 4}, {8, 0, 0, 4, 8}, {4, 0, 2, 1, 8}}, // tokens=24960
+ {{4, 0, 2, 1, 8}, {4, 4, 0, 9, 8}, {32, 0, 1, 1, 8}}, // tokens=99840
+ {{4, 0, 2, 1, 8}, {32, 4, 1, 2, 8}, {32, 4, 1, 1, 8}}, // tokens=399360
+ },
+ {
+ // C=1024
+ {{4, 4, 0, 3, 16}, {4, 0, 0, 3, 4}, {4, 4, 0, 7, 16}}, // tokens=1560
+ {{4, 0, 0, 5, 16}, {4, 0, 0, 5, 8}, {4, 0, 2, 1, 16}}, // tokens=6240
+ {{4, 4, 1, 10, 16}, {1, 4, 0, 16, 8}, {4, 0, 2, 1, 16}}, // tokens=24960
+ {{8, 0, 2, 1, 16}, {4, 0, 1, 9, 8}, {32, 0, 1, 1, 16}}, // tokens=99840
+ {{8, 0, 2, 1, 16}, {32, 4, 1, 1, 8}, {32, 4, 1, 1, 16}}, // tokens=399360
+ },
+};
+
+// Compute conservative default knobs for arbitrary problem sizes not in the LUT.
+// Uses safe defaults (WARPS_M=1, BPL=4, occupancy=1) and validates vectorization
+// divisibility constraints before accepting a configuration.
+// Returns true if a valid configuration was found, false otherwise.
+inline bool
+compute_default_knobs(int C, int num_tokens, RmsNormSiluDtype dtype, RmsNormSiluKnobs& out) {
+ // Conservative defaults:
+ // CTAS_PER_ROW = 1, WARPS_M = 1, WARPS_N = 1, BPL = 4, occupancy = 1, kernel_cfg = 0
+ // For block-scale output (NVFP4): WARPS_M = 32
+
+ int input_size = 2; // bf16 input always
+
+ // Start with conservative defaults
+ int warps_m = (dtype == RmsNormSiluDtype::NVFP4) ? 32 : 1;
+ int warps_n = 1; // always 1 for our engine
+ int bpl = 4; // default bytes per load
+ int cpr = 1; // no column splitting for fallback
+ int occ = 1;
+ int kcfg = 0;
+
+ // Validation: C must be evenly divisible into vectorized loads.
+ // NUM_ELTS = BYTES_PER_LDG / sizeof(input_t)
+ // VEC_COLS = C / NUM_ELTS
+ // VEC_COLS_PER_LDG = CTAS_PER_ROW * WARPS_N * 32
+ // Require: C % NUM_ELTS == 0 AND VEC_COLS % VEC_COLS_PER_LDG == 0
+ // Also: LDGS = VEC_COLS / VEC_COLS_PER_LDG <= 1024 (avoid register spill)
+
+ auto validate = [&](int test_bpl, int test_wm) -> bool {
+ int num_elts = test_bpl / input_size;
+ if (num_elts <= 0 || C % num_elts != 0) return false;
+ int vec_cols = C / num_elts;
+ int vec_cols_per_ldg = cpr * warps_n * 32;
+ if (vec_cols_per_ldg <= 0 || vec_cols % vec_cols_per_ldg != 0) return false;
+ int ldgs = vec_cols / vec_cols_per_ldg;
+ if (ldgs > 1024) return false; // reject extreme LDGS to avoid register spilling
+ // Check WARPS_M constraint: if WARPS_M > 1, rows per CTA must divide evenly
+ if (test_wm > 1 && num_tokens % test_wm != 0) return false;
+ return true;
+ };
+
+ // Try default BPL=4, then cascade through {4, 8, 16, 2}
+ static constexpr int bpl_candidates[] = {4, 8, 16, 2};
+ bool found = false;
+ for (int candidate : bpl_candidates) {
+ if (validate(candidate, warps_m)) {
+ bpl = candidate;
+ found = true;
+ break;
+ }
+ }
+
+ // If WARPS_M=1 failed, try bumping to WARPS_M=4 for better row coverage
+ if (!found && warps_m == 1 && num_tokens % 4 == 0) {
+ warps_m = 4;
+ for (int candidate : bpl_candidates) {
+ if (validate(candidate, warps_m)) {
+ bpl = candidate;
+ found = true;
+ break;
+ }
+ }
+ }
+
+ if (!found) return false;
+
+ out.warps_m = static_cast<uint8_t>(warps_m);
+ out.split_cols = 0; // no column splitting
+ out.kernel_cfg = static_cast<uint8_t>(kcfg);
+ out.occupancy = static_cast<uint8_t>(occ);
+ out.bytes_per_ldg = static_cast<uint8_t>(bpl);
+ return true;
+}
+
+// Look up knob configuration for a given (C, num_tokens, output_dtype, sm_version).
+// Tier 1: exact LUT match for SM100 VAE problem sizes (optimal, sweep-tuned on B200).
+// Tier 2: fallback heuristic for other archs or arbitrary sizes (functional, conservative).
+// Returns nullptr only if the problem is fundamentally unsupported.
+inline const RmsNormSiluKnobs*
+lookup_rms_norm_silu_knobs(int C, int num_tokens, RmsNormSiluDtype dtype, int sm_version = 100) {
+ // Tier 1: exact LUT match — only valid for SM100 (swept on B200)
+ if (sm_version >= 100) {
+ int c_idx = -1, t_idx = -1;
+ for (int i = 0; i < kNumC; ++i) {
+ if (kSupportedC[i] == C) {
+ c_idx = i;
+ break;
+ }
+ }
+ for (int i = 0; i < kNumTokens; ++i) {
+ if (kSupportedTokens[i] == num_tokens) {
+ t_idx = i;
+ break;
+ }
+ }
+ if (c_idx >= 0 && t_idx >= 0) {
+ return &knob_lut[c_idx][t_idx][static_cast<int>(dtype)];
+ }
+ }
+
+ // Tier 2: fallback heuristic for non-SM100 archs or non-LUT problem sizes
+ static thread_local RmsNormSiluKnobs fallback;
+ if (compute_default_knobs(C, num_tokens, dtype, fallback)) {
+ return &fallback;
+ }
+
+ return nullptr; // fundamentally unsupported (C not divisible by any valid config)
+}
+
+} // namespace experimental
+} // namespace cudnn_frontend
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h
new file mode 100644
index 0000000..73da07d
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm100_sdpa_prefill_engine.h
@@ -0,0 +1,544 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "oss_engine_interface.h"
+#include "../generated/sdpa/sm100/prefill/full_seqlens/d128_fprop_kernel.h"
+#include "../generated/sdpa/sm100/prefill/full_seqlens/d64_fprop_kernel.h"
+
+#include <cuda_fp16.h>
+
+// Suppress MSVC C4127 "conditional expression is constant" triggered by
+// RETURN_CUDNN_FRONTEND_ERROR_IF macro (which has `if (retval == error_code_t::OK)`)
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4127)
+#endif
+
+#include <algorithm>
+#include <cmath>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// Kernel spec lookup for SM100 SDPA prefill kernels
+// ============================================================
+
+/// @brief Look up the SM100 kernel specification for a given head dimension.
+/// @param d Head dimension (d_qk). Currently supports 64 and 128.
+/// @param sm_version SM version from cudaDeviceProp (e.g. 100, 101).
+/// @return Pointer to static KernelSpec, or nullptr if unsupported.
+inline const KernelSpec*
+lookup_sm100_kernel_spec(int d, int sm_version) {
+ // SM100 family: sm_version 100..109
+ if (sm_version / 10 != 10) return nullptr;
+
+ static const KernelSpec spec_d128 = {
+ generated::sm100_d128_fprop_source,
+ generated::sm100_d128_fprop_source_len,
+ generated::sm100_d128_fprop_flags,
+ generated::sm100_d128_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x128_4x1x1_cga1x1x1_kernel0_0",
+ 128,
+ 128,
+ 128,
+ 232448 // smem_bytes for d=128
+ };
+
+ static const KernelSpec spec_d64 = {
+ generated::sm100_d64_fprop_source,
+ generated::sm100_d64_fprop_source_len,
+ generated::sm100_d64_fprop_flags,
+ generated::sm100_d64_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm100_flash_fprop_f16_knob_7_128x128x64_4x1x1_cga1x1x1_kernel0_0",
+ 128,
+ 128,
+ 64,
+ 232448 // smem_bytes for d=64
+ };
+
+ switch (d) {
+ case 128:
+ return &spec_d128;
+ case 64:
+ return &spec_d64;
+ default:
+ return nullptr;
+ }
+}
+
+// ============================================================
+// Sm100SdpaPrefillEngine
+// ============================================================
+
+/// @brief SM100-specific SDPA prefill engine using NVRTC-compiled kernels.
+///
+/// This engine targets the SM100 (Blackwell) architecture and uses L2-aware
+/// tile scheduling instead of the SM90 persistent-tile-counter approach.
+/// The kernel is compiled at runtime via NVRTC from embedded source and
+/// launched with TMA descriptors for Q, K, V, and O tensors.
+///
+/// Usage:
+/// 1. check_support() -- validates shape + SM version, caches device info.
+/// 2. build() -- NVRTC-compiles the kernel and loads the CU module.
+/// 3. execute() -- sets up TMA descriptors, packs params, launches.
+///
+/// Thread safety: instances are NOT thread-safe. Each thread should own its
+/// own engine, or external synchronization must be provided.
+class Sm100SdpaPrefillEngine : public IOssSdpaEngine {
+ public:
+ Sm100SdpaPrefillEngine() = default;
+
+ ~Sm100SdpaPrefillEngine() override {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ }
+
+ // Non-copyable
+ Sm100SdpaPrefillEngine(const Sm100SdpaPrefillEngine&) = delete;
+ Sm100SdpaPrefillEngine&
+ operator=(const Sm100SdpaPrefillEngine&) = delete;
+
+ // Movable
+ Sm100SdpaPrefillEngine(Sm100SdpaPrefillEngine&& other) noexcept
+ : spec_(other.spec_),
+ d_(other.d_),
+ sm_version_(other.sm_version_),
+ sm_count_(other.sm_count_),
+ support_checked_(other.support_checked_),
+ module_(other.module_),
+ kernelPtr_(other.kernelPtr_),
+ cubin_(std::move(other.cubin_)),
+ cubinSize_(other.cubinSize_),
+ tile_m_(other.tile_m_),
+ tile_n_(other.tile_n_),
+ tile_k_(other.tile_k_),
+ smemBytes_(other.smemBytes_),
+ kernelName_(std::move(other.kernelName_)),
+ built_(other.built_) {
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+
+ Sm100SdpaPrefillEngine&
+ operator=(Sm100SdpaPrefillEngine&& other) noexcept {
+ if (this != &other) {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ spec_ = other.spec_;
+ d_ = other.d_;
+ sm_version_ = other.sm_version_;
+ sm_count_ = other.sm_count_;
+ support_checked_ = other.support_checked_;
+ module_ = other.module_;
+ kernelPtr_ = other.kernelPtr_;
+ cubin_ = std::move(other.cubin_);
+ cubinSize_ = other.cubinSize_;
+ tile_m_ = other.tile_m_;
+ tile_n_ = other.tile_n_;
+ tile_k_ = other.tile_k_;
+ smemBytes_ = other.smemBytes_;
+ kernelName_ = std::move(other.kernelName_);
+ built_ = other.built_;
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+ return *this;
+ }
+
+ // ---- Phase 1: Support check (spec lookup, cache SM count) ----
+
+ /// @brief Validate that the given attention shape and SM version are supported.
+ /// @param shape Attention shape (batch, heads, seqlens, head dim).
+ /// @param sm_version SM version (e.g. 100 for SM100).
+ /// @return error_t with OK on success, GRAPH_NOT_SUPPORTED if unsupported.
+ error_t
+ check_support(AttentionShape_t shape, int sm_version) override {
+ spec_ = lookup_sm100_kernel_spec(shape.d_qk, sm_version);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ spec_ == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unsupported config: d=" + std::to_string(shape.d_qk) + " sm_version=" + std::to_string(sm_version));
+
+ d_ = shape.d_qk;
+ sm_version_ = sm_version;
+ tile_m_ = spec_->tile_m;
+ tile_n_ = spec_->tile_n;
+ tile_k_ = spec_->tile_k;
+ smemBytes_ = spec_->smem_bytes;
+ kernelName_ = spec_->kernel_name;
+
+ // Cache SM count for later use in execute()
+ cudaDeviceProp devProp;
+ int device_ordinal = 0;
+ cudaError_t cuda_err = detail::cuda_get_device(&device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDevice failed");
+ cuda_err = detail::cuda_get_device_properties(&devProp, device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDeviceProperties failed");
+ sm_count_ = devProp.multiProcessorCount;
+
+ support_checked_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ /// @brief Returns the workspace size in bytes needed by execute().
+ /// SM100 does not use a workspace tile counter, but we keep the interface
+ /// consistent with SM90 for uniform allocation by the caller.
+ static int64_t
+ get_workspace_size() {
+ return 16;
+ }
+
+ // ---- Phase 2: NVRTC compilation + module loading ----
+
+ /// @brief Compile the kernel via NVRTC and load the resulting CU module.
+ /// @pre check_support() must have been called successfully.
+ /// @return error_t with OK on success.
+ error_t
+ build() override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!support_checked_ || spec_ == nullptr,
+ error_code_t::INVALID_VALUE,
+ "build() called before check_support()");
+
+ auto status = compile_and_load_kernel(spec_, module_, kernelPtr_, cubin_, cubinSize_, kernelName_);
+ if (status.is_good()) {
+ built_ = true;
+ }
+ return status;
+ }
+
+ // ---- Phase 3: Set up TMA descriptors, pack params, launch ----
+
+ /// @brief Execute the SM100 SDPA prefill kernel.
+ ///
+ /// Sets up TMA descriptors for Q/K/V/O, computes L2-aware tile scheduling
+ /// parameters, and launches the kernel on the given stream.
+ ///
+ /// Strides are in ELEMENTS (not bytes), matching PyTorch's .stride() convention.
+ /// All stride vectors have 4 elements in (b, h, s, d) order.
+ /// For max/sum_exp the 4th element (d-stride) is typically 1 and is unused internally.
+ ///
+ /// @param batch Batch size (B).
+ /// @param heads_q Number of query heads (H_q).
+ /// @param heads_kv Number of key/value heads (H_kv).
+ /// @param seq_q Query sequence length (S_q).
+ /// @param seq_kv Key/value sequence length (S_kv).
+ /// @param d Head dimension (d_qk = d_v).
+ /// @param d_Q Device pointer to Q tensor (fp16).
+ /// @param q_strides Q strides in elements: [b, h, s, d].
+ /// @param d_K Device pointer to K tensor (fp16).
+ /// @param k_strides K strides in elements: [b, h, s, d].
+ /// @param d_V Device pointer to V tensor (fp16).
+ /// @param v_strides V strides in elements: [b, h, s, d].
+ /// @param d_O Device pointer to O tensor (fp16, output).
+ /// @param o_strides O strides in elements: [b, h, s, d].
+ /// @param d_max Device pointer to per-row max values (fp32, [B, H_q, S_q]).
+ /// @param max_strides Max strides in elements: [b, h, s].
+ /// @param d_sum_exp Device pointer to per-row sum-of-exp values (fp32, [B, H_q, S_q]).
+ /// @param se_strides Sum-exp strides in elements: [b, h, s].
+ /// @param workspace Device workspace pointer (at least 16 bytes, unused by SM100 but kept for API consistency).
+ /// @param device Device ordinal for kernel attribute setting.
+ /// @param stream CUDA stream for asynchronous execution.
+ /// @param user_attn_scale Optional attention scale; defaults to 1/sqrt(D).
+ /// @return error_t with OK on success.
+ error_t
+ execute(int batch,
+ int heads_q,
+ int heads_kv,
+ int seq_q,
+ int seq_kv,
+ int d,
+ void* d_Q,
+ std::vector<int64_t> const& q_strides,
+ void* d_K,
+ std::vector<int64_t> const& k_strides,
+ void* d_V,
+ std::vector<int64_t> const& v_strides,
+ void* d_O,
+ std::vector<int64_t> const& o_strides,
+ void* d_max,
+ std::vector<int64_t> const& max_strides,
+ void* d_sum_exp,
+ std::vector<int64_t> const& se_strides,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::optional<float> user_attn_scale = std::nullopt) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!built_, error_code_t::INVALID_VALUE, "execute() called before build()");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ d > 128, error_code_t::GRAPH_NOT_SUPPORTED, "SM100 OSS engine requires d <= 128");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ q_strides.size() < 4 || k_strides.size() < 4 || v_strides.size() < 4 || o_strides.size() < 4,
+ error_code_t::INVALID_VALUE,
+ "Q/K/V/O strides must have at least 4 elements");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(max_strides.size() < 3 || se_strides.size() < 3,
+ error_code_t::INVALID_VALUE,
+ "max/sum_exp strides must have at least 3 elements");
+
+ // Suppress unused-parameter warning for workspace (SM100 does not use a tile counter)
+ (void)workspace;
+
+ int B = batch;
+ int H_q = heads_q;
+ int H_kv = heads_kv;
+ int S_q = seq_q;
+ int S_kv = seq_kv;
+ int D = d;
+ int TILE_M = tile_m_;
+ int TILE_N = tile_n_;
+
+ // ---- Set up AttentionDescriptor ----
+ AttentionDescriptor_t attnDesc = {};
+ attnDesc.b = B;
+ attnDesc.q_h = H_q;
+ attnDesc.k_h = H_kv;
+ attnDesc.v_h = H_kv;
+ attnDesc.s_q = S_q;
+ attnDesc.s_kv = S_kv;
+ attnDesc.d_qk = D;
+ attnDesc.d_v = D;
+ attnDesc.q_heads_per_k = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.q_heads_per_v = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.min_q_heads_per_kv = attnDesc.q_heads_per_k;
+
+ // ---- L2-aware tile scheduling ----
+ // SM100 uses an L2-aware swizzle pattern for better cache utilization
+ // instead of SM90's persistent tile counter approach.
+ constexpr int Tiles_Q = 2;
+ constexpr uint32_t size_l2 = 50u * 1024u * 1024u;
+
+ int ctas_in_q_dim = div_up(S_q, TILE_M * Tiles_Q);
+ int num_hb = B * H_q;
+
+ // Compute the swizzle factor based on how many KV heads fit in L2
+ uint32_t one_kv_head_size = static_cast<uint32_t>(S_kv) * (D + D) * sizeof(half);
+ int swizzle = (one_kv_head_size > 0) ? (1 << find_log_2_floor(size_l2 / one_kv_head_size)) : 1;
+ swizzle = std::max(1, std::min(swizzle, num_hb));
+
+ int num_hb_quotient = num_hb / swizzle;
+ int num_hb_remainder = num_hb % swizzle;
+ int num_block = ctas_in_q_dim;
+ int total_blocks = num_block * num_hb;
+
+ // Fast divisors for tile index decomposition in the kernel
+ FastDivisor_t num_head_divmod = make_fast_divisor(static_cast<uint32_t>(H_q));
+ FastDivisor_t l2_minor_divmod = make_fast_divisor(static_cast<uint32_t>(swizzle));
+ FastDivisor_t l2_major_divmod = make_fast_divisor(static_cast<uint32_t>(swizzle * num_block));
+ FastDivisor_t l2_minor_residual_divmod =
+ make_fast_divisor(static_cast<uint32_t>(std::max(1, num_hb_remainder)));
+
+ // ---- TMA descriptors (4D) ----
+ // Caller strides are in elements; TMA needs bytes.
+ uint32_t elem_bytes = sizeof(half);
+ uint32_t elems_per_ld = std::min(64, D);
+
+ // Q TMA: dims = (D, S_q, H_q, B), box = (elems_per_ld, TILE_M)
+ // SM100 uses TILE_M (128) directly, unlike SM90 which uses TILE_M * 2.
+ CUtensorMap tma_q = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_q,
+ d_Q,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)q_strides[2] * elem_bytes,
+ (uint64_t)q_strides[1] * elem_bytes,
+ (uint64_t)q_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_M,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // K TMA: dims = (D, S_kv, H_kv, B), box = (elems_per_ld, TILE_N)
+ CUtensorMap tma_k = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_k,
+ d_K,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)k_strides[2] * elem_bytes,
+ (uint64_t)k_strides[1] * elem_bytes,
+ (uint64_t)k_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // V TMA: dims = (D, S_kv, H_kv, B), box = (elems_per_ld, TILE_N)
+ CUtensorMap tma_v = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_v,
+ d_V,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)v_strides[2] * elem_bytes,
+ (uint64_t)v_strides[1] * elem_bytes,
+ (uint64_t)v_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // O TMA: dims = (D, S_q, H_q, B), box = (elems_per_ld, TILE_M)
+ // SM100 uses TILE_M (128) for the O box dim, unlike SM90 which uses 16.
+ CUtensorMap tma_o = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_o,
+ d_O,
+ CU_TENSOR_MAP_DATA_TYPE_BFLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)o_strides[2] * elem_bytes,
+ (uint64_t)o_strides[1] * elem_bytes,
+ (uint64_t)o_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_M,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // ---- Scaling ----
+ float attn_scale = user_attn_scale.value_or(1.0f / std::sqrt((float)D));
+ float tensor_13 = -INFINITY;
+
+ // ---- Tensor descriptors for max and sum_exp (f32, [B, H_q, S_q]) ----
+ // Strides provided by caller in elements.
+ tensor_descriptor desc_max = {};
+ desc_max.num_dims = 3;
+ desc_max.dims[0] = B;
+ desc_max.dims[1] = H_q;
+ desc_max.dims[2] = S_q;
+ desc_max.strides[0] = max_strides[0];
+ desc_max.strides[1] = max_strides[1];
+ desc_max.strides[2] = max_strides[2];
+
+ tensor_descriptor desc_sum_exp = {};
+ desc_sum_exp.num_dims = 3;
+ desc_sum_exp.dims[0] = B;
+ desc_sum_exp.dims[1] = H_q;
+ desc_sum_exp.dims[2] = S_q;
+ desc_sum_exp.strides[0] = se_strides[0];
+ desc_sum_exp.strides[1] = se_strides[1];
+ desc_sum_exp.strides[2] = se_strides[2];
+
+ // ---- Grid/Block ----
+ // SM100 launches total_blocks CTAs with 512 threads each.
+ // No persistent scheduling -- the L2 swizzle parameters handle work distribution.
+ dim3 grid(total_blocks, 1, 1);
+ dim3 block(512, 1, 1);
+
+ // ---- Build kernel params array (18 parameters) ----
+ // The parameter order must match the SM100 kernel's expected layout exactly.
+ void* kernelParams[] = {
+ (void*)&attnDesc,
+ (void*)&num_head_divmod,
+ (void*)&l2_minor_divmod,
+ (void*)&l2_major_divmod,
+ (void*)&l2_minor_residual_divmod,
+ (void*)&num_hb_quotient,
+ (void*)&num_block,
+ (void*)&total_blocks,
+ (void*)&tma_q,
+ (void*)&tma_k,
+ (void*)&attn_scale,
+ (void*)&tensor_13,
+ (void*)&d_max,
+ (void*)&desc_max,
+ (void*)&d_sum_exp,
+ (void*)&desc_sum_exp,
+ (void*)&tma_v,
+ (void*)&tma_o,
+ };
+
+ // ---- Debug logging ----
+ if (cudnn_frontend::isLoggingEnabled()) {
+ CUDNN_FE_LOG_LABEL_ENDL("SM100 OSS Engine Launch:");
+ CUDNN_FE_LOG_LABEL_ENDL(" Grid = (" << grid.x << "," << grid.y << "," << grid.z << ")");
+ CUDNN_FE_LOG_LABEL_ENDL(" Block = (" << block.x << "," << block.y << "," << block.z << ")");
+ CUDNN_FE_LOG_LABEL_ENDL(" Smem = " << smemBytes_);
+ CUDNN_FE_LOG_LABEL_ENDL(" Kernel: " << kernelName_);
+ CUDNN_FE_LOG_LABEL_ENDL(" B=" << B << " H_q=" << H_q << " H_kv=" << H_kv << " S_q=" << S_q
+ << " S_kv=" << S_kv << " D=" << D);
+ CUDNN_FE_LOG_LABEL_ENDL(" L2: swizzle=" << swizzle << " num_hb_quotient=" << num_hb_quotient
+ << " num_block=" << num_block << " total_blocks=" << total_blocks);
+ CUDNN_FE_LOG_LABEL_ENDL(" attn_scale=" << attn_scale);
+ }
+
+ // ---- Set shared memory attribute and launch ----
+ cudaError_t cuda_err;
+
+ cuda_err = detail::cuda_kernel_set_attribute_for_device(
+ kernelPtr_, cudaFuncAttributeMaxDynamicSharedMemorySize, smemBytes_, device);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaKernelSetAttributeForDevice failed (smem=" + std::to_string(smemBytes_) +
+ " bytes, error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ cuda_err = detail::cuda_launch_kernel((const void*)kernelPtr_, grid, block, kernelParams, smemBytes_, stream);
+ cudaError_t last_err = detail::cuda_get_last_error();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLaunchKernel failed (grid=" + std::to_string(grid.x) +
+ ", block=512, smem=" + std::to_string(smemBytes_) +
+ ", error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ last_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaGetLastError after kernel launch: " + detail::cuda_error_to_string(last_err));
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ // State from check_support()
+ const KernelSpec* spec_ = nullptr;
+ int d_ = 0;
+ int sm_version_ = 0;
+ int sm_count_ = 0;
+ bool support_checked_ = false;
+
+ // State from build()
+ cudaLibrary_t module_ = nullptr;
+ cudaKernel_t kernelPtr_ = nullptr;
+ std::unique_ptr<char[]> cubin_;
+ size_t cubinSize_ = 0;
+ int tile_m_ = 0, tile_n_ = 0, tile_k_ = 0;
+ int smemBytes_ = 0;
+ std::string kernelName_;
+ bool built_ = false;
+};
+
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
diff --git a/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h
new file mode 100644
index 0000000..d1fb8a2
--- /dev/null
+++ b/deps/cudnn-frontend/include/cudnn_frontend/experimental/sm90_sdpa_prefill_engine.h
@@ -0,0 +1,450 @@
+/*
+ * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#pragma once
+
+#include "oss_engine_interface.h"
+#include "../generated/sdpa/sm90/prefill/full_seqlens/d128_fprop_kernel.h"
+#include "../generated/sdpa/sm90/prefill/full_seqlens/d64_fprop_kernel.h"
+
+#include <cuda_fp16.h>
+
+// Suppress MSVC C4127 "conditional expression is constant" triggered by
+// RETURN_CUDNN_FRONTEND_ERROR_IF macro (which has `if (retval == error_code_t::OK)`)
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4127)
+#endif
+
+#include <algorithm>
+#include <cmath>
+
+namespace cudnn_frontend {
+namespace experimental {
+
+// ============================================================
+// Kernel spec lookup (replaces KernelFactory)
+// ============================================================
+
+inline const KernelSpec*
+lookup_kernel_spec(int d, int sm_version) {
+ if (sm_version != 90) return nullptr;
+
+ static const KernelSpec spec_d128 = {
+ generated::d128_fprop_source,
+ generated::d128_fprop_source_len,
+ generated::d128_fprop_flags,
+ generated::d128_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x128_4x1x1_cga1x1x1_kernel0_0",
+ 64,
+ 128,
+ 128,
+ 232448 // smem_bytes for d=128 (227 * 1024)
+ };
+
+ static const KernelSpec spec_d64 = {
+ generated::d64_fprop_source,
+ generated::d64_fprop_source_len,
+ generated::d64_fprop_flags,
+ generated::d64_fprop_flags_len,
+ "cudnn_generated_oss_sdpa_sm90_flash_fprop_wgmma_f16_knob_7_64x128x64_4x1x1_cga1x1x1_kernel0_0",
+ 64,
+ 128,
+ 64,
+ 122880 // smem_bytes for d=64 (120 * 1024)
+ };
+
+ switch (d) {
+ case 128:
+ return &spec_d128;
+ case 64:
+ return &spec_d64;
+ default:
+ return nullptr;
+ }
+}
+// ============================================================
+// Sm90SdpaPrefillEngine
+// ============================================================
+
+class Sm90SdpaPrefillEngine : public IOssSdpaEngine {
+ public:
+ Sm90SdpaPrefillEngine() = default;
+
+ ~Sm90SdpaPrefillEngine() override {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ }
+
+ // Non-copyable
+ Sm90SdpaPrefillEngine(const Sm90SdpaPrefillEngine&) = delete;
+ Sm90SdpaPrefillEngine&
+ operator=(const Sm90SdpaPrefillEngine&) = delete;
+
+ // Movable
+ Sm90SdpaPrefillEngine(Sm90SdpaPrefillEngine&& other) noexcept
+ : spec_(other.spec_),
+ d_(other.d_),
+ sm_version_(other.sm_version_),
+ sm_count_(other.sm_count_),
+ support_checked_(other.support_checked_),
+ module_(other.module_),
+ kernelPtr_(other.kernelPtr_),
+ cubin_(std::move(other.cubin_)),
+ cubinSize_(other.cubinSize_),
+ tile_m_(other.tile_m_),
+ tile_n_(other.tile_n_),
+ tile_k_(other.tile_k_),
+ smemBytes_(other.smemBytes_),
+ kernelName_(std::move(other.kernelName_)),
+ built_(other.built_) {
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+
+ Sm90SdpaPrefillEngine&
+ operator=(Sm90SdpaPrefillEngine&& other) noexcept {
+ if (this != &other) {
+ if (module_) {
+ detail::cuda_library_unload(module_);
+ }
+ spec_ = other.spec_;
+ d_ = other.d_;
+ sm_version_ = other.sm_version_;
+ sm_count_ = other.sm_count_;
+ support_checked_ = other.support_checked_;
+ module_ = other.module_;
+ kernelPtr_ = other.kernelPtr_;
+ cubin_ = std::move(other.cubin_);
+ cubinSize_ = other.cubinSize_;
+ tile_m_ = other.tile_m_;
+ tile_n_ = other.tile_n_;
+ tile_k_ = other.tile_k_;
+ smemBytes_ = other.smemBytes_;
+ kernelName_ = std::move(other.kernelName_);
+ built_ = other.built_;
+ other.module_ = nullptr;
+ other.kernelPtr_ = nullptr;
+ other.built_ = false;
+ }
+ return *this;
+ }
+
+ // ---- Phase 1: Support check (spec lookup, cache SM count) ----
+ error_t
+ check_support(AttentionShape_t shape, int sm_version) override {
+ spec_ = lookup_kernel_spec(shape.d_qk, sm_version);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ spec_ == nullptr,
+ error_code_t::GRAPH_NOT_SUPPORTED,
+ "Unsupported config: d=" + std::to_string(shape.d_qk) + " sm_version=" + std::to_string(sm_version));
+
+ d_ = shape.d_qk;
+ sm_version_ = sm_version;
+ tile_m_ = spec_->tile_m;
+ tile_n_ = spec_->tile_n;
+ tile_k_ = spec_->tile_k;
+ smemBytes_ = spec_->smem_bytes;
+ kernelName_ = spec_->kernel_name;
+
+ // Cache SM count for later use in execute()
+ cudaDeviceProp devProp;
+ int device_ordinal = 0;
+ cudaError_t cuda_err = detail::cuda_get_device(&device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDevice failed");
+ cuda_err = detail::cuda_get_device_properties(&devProp, device_ordinal);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ cuda_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaGetDeviceProperties failed");
+ sm_count_ = devProp.multiProcessorCount;
+
+ support_checked_ = true;
+ return {error_code_t::OK, ""};
+ }
+
+ // Workspace size needed by execute() (tile_id_counter: 4 bytes, 16-byte aligned)
+ static int64_t
+ get_workspace_size() {
+ return 16;
+ }
+
+ // ---- Phase 2: NVRTC compilation + module loading ----
+ error_t
+ build() override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!support_checked_ || spec_ == nullptr,
+ error_code_t::INVALID_VALUE,
+ "build() called before check_support()");
+
+ auto status = compile_and_load_kernel(spec_, module_, kernelPtr_, cubin_, cubinSize_, kernelName_);
+ if (status.is_good()) {
+ built_ = true;
+ }
+ return status;
+ }
+
+ // ---- Phase 3: Set up TMA descriptors, pack params, launch ----
+ // Strides are in ELEMENTS (not bytes), matching PyTorch's .stride() convention.
+ // All stride vectors have 4 elements in (b, h, s, d) order.
+ // For max/sum_exp the 4th element (d-stride) is typically 1 and is unused internally.
+ error_t
+ execute(int batch,
+ int heads_q,
+ int heads_kv,
+ int seq_q,
+ int seq_kv,
+ int d,
+ void* d_Q,
+ std::vector<int64_t> const& q_strides,
+ void* d_K,
+ std::vector<int64_t> const& k_strides,
+ void* d_V,
+ std::vector<int64_t> const& v_strides,
+ void* d_O,
+ std::vector<int64_t> const& o_strides,
+ void* d_max,
+ std::vector<int64_t> const& max_strides,
+ void* d_sum_exp,
+ std::vector<int64_t> const& se_strides,
+ void* workspace,
+ int device,
+ cudaStream_t stream,
+ std::optional<float> user_attn_scale = std::nullopt) override {
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!built_, error_code_t::INVALID_VALUE, "execute() called before build()");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ q_strides.size() < 4 || k_strides.size() < 4 || v_strides.size() < 4 || o_strides.size() < 4,
+ error_code_t::INVALID_VALUE,
+ "Q/K/V/O strides must have at least 4 elements");
+ RETURN_CUDNN_FRONTEND_ERROR_IF(max_strides.size() < 3 || se_strides.size() < 3,
+ error_code_t::INVALID_VALUE,
+ "max/sum_exp strides must have at least 3 elements");
+
+ int B = batch;
+ int H_q = heads_q;
+ int H_kv = heads_kv;
+ int S_q = seq_q;
+ int S_kv = seq_kv;
+ int D = d;
+ int TILE_M = tile_m_;
+ int TILE_N = tile_n_;
+
+ // ---- Set up AttentionDescriptor ----
+ AttentionDescriptor_t attnDesc = {};
+ attnDesc.b = B;
+ attnDesc.q_h = H_q;
+ attnDesc.k_h = H_kv;
+ attnDesc.v_h = H_kv;
+ attnDesc.s_q = S_q;
+ attnDesc.s_kv = S_kv;
+ attnDesc.d_qk = D;
+ attnDesc.d_v = D;
+ attnDesc.q_heads_per_k = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.q_heads_per_v = (H_q >= H_kv && H_kv > 0) ? (uint16_t)(H_q / H_kv) : 1;
+ attnDesc.min_q_heads_per_kv = attnDesc.q_heads_per_k;
+
+ // ---- Tile scheduling ----
+ int effective_tile_m = TILE_M * 2;
+ int tiles_r = div_up(S_q, effective_tile_m);
+ int tiles_hr = H_q * tiles_r;
+ int num_tiles = B * tiles_hr;
+ FastDivisor_t tiles_hr_div = make_fast_divisor(tiles_hr);
+ FastDivisor_t tiles_r_div = make_fast_divisor(tiles_r);
+
+ // ---- TMA descriptors (4D) ----
+ // Caller strides are in elements; TMA needs bytes.
+ uint32_t elem_bytes = sizeof(half);
+ uint32_t elems_per_ld = std::min(64, D);
+
+ // Q TMA (tma_tensor_3): dims = (D, S_q, H_q, B)
+ CUtensorMap tma_q = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_q,
+ d_Q,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)q_strides[2] * elem_bytes,
+ (uint64_t)q_strides[1] * elem_bytes,
+ (uint64_t)q_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_M * 2,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // K TMA (tma_tensor_2)
+ CUtensorMap tma_k = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_k,
+ d_K,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)k_strides[2] * elem_bytes,
+ (uint64_t)k_strides[1] * elem_bytes,
+ (uint64_t)k_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // V TMA (tma_tensor_1)
+ CUtensorMap tma_v = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_v,
+ d_V,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_kv,
+ H_kv,
+ B,
+ (uint64_t)v_strides[2] * elem_bytes,
+ (uint64_t)v_strides[1] * elem_bytes,
+ (uint64_t)v_strides[0] * elem_bytes,
+ elems_per_ld,
+ TILE_N,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // O TMA (tma_tensor_5)
+ CUtensorMap tma_o = {};
+ CHECK_CUDNN_FRONTEND_ERROR(create_tma_desc_4d(&tma_o,
+ d_O,
+ CU_TENSOR_MAP_DATA_TYPE_FLOAT16,
+ D,
+ S_q,
+ H_q,
+ B,
+ (uint64_t)o_strides[2] * elem_bytes,
+ (uint64_t)o_strides[1] * elem_bytes,
+ (uint64_t)o_strides[0] * elem_bytes,
+ elems_per_ld,
+ 16,
+ CU_TENSOR_MAP_SWIZZLE_128B));
+
+ // ---- Scaling ----
+ float attn_scale = user_attn_scale.value_or(1.0f / std::sqrt((float)D));
+ float tensor_13 = -INFINITY;
+
+ // ---- Tensor descriptors for max and sum_exp (f32, [B, H_q, S_q]) ----
+ // Strides provided by caller in elements.
+ tensor_descriptor desc_max = {};
+ desc_max.num_dims = 3;
+ desc_max.dims[0] = B;
+ desc_max.dims[1] = H_q;
+ desc_max.dims[2] = S_q;
+ desc_max.strides[0] = max_strides[0];
+ desc_max.strides[1] = max_strides[1];
+ desc_max.strides[2] = max_strides[2];
+
+ tensor_descriptor desc_sum_exp = {};
+ desc_sum_exp.num_dims = 3;
+ desc_sum_exp.dims[0] = B;
+ desc_sum_exp.dims[1] = H_q;
+ desc_sum_exp.dims[2] = S_q;
+ desc_sum_exp.strides[0] = se_strides[0];
+ desc_sum_exp.strides[1] = se_strides[1];
+ desc_sum_exp.strides[2] = se_strides[2];
+
+ // ---- Grid/Block ----
+ int CTAs = std::min(sm_count_, num_tiles);
+ dim3 grid(CTAs, 1, 1);
+ dim3 block(384, 1, 1);
+
+ // ---- Memset tile_id_counter (uses caller-provided workspace) ----
+ RETURN_CUDNN_FRONTEND_ERROR_IF(!workspace,
+ error_code_t::INVALID_VALUE,
+ "workspace must not be null (need at least 16 bytes for tile_id_counter)");
+ int32_t* d_tile_id_counter = reinterpret_cast<int32_t*>(workspace);
+ {
+ cudaError_t memset_err = detail::cuda_mem_set_async(d_tile_id_counter, 0, sizeof(int32_t), stream);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ memset_err != cudaSuccess, error_code_t::CUDA_API_FAILED, "cudaMemsetAsync for tile_id_counter failed");
+ }
+
+ // ---- Build kernel params array ----
+ void* kernelParams[] = {
+ (void*)&attnDesc,
+ (void*)&num_tiles,
+ (void*)&tiles_hr_div,
+ (void*)&tiles_r_div,
+ (void*)&d_tile_id_counter,
+ (void*)&tma_q,
+ (void*)&tma_k,
+ (void*)&attn_scale,
+ (void*)&tensor_13,
+ (void*)&d_max,
+ (void*)&desc_max,
+ (void*)&d_sum_exp,
+ (void*)&desc_sum_exp,
+ (void*)&tma_v,
+ (void*)&tma_o,
+ };
+
+ // ---- Set shared memory attribute and launch ----
+ cudaError_t cuda_err;
+
+ cuda_err = detail::cuda_kernel_set_attribute_for_device(
+ kernelPtr_, cudaFuncAttributeMaxDynamicSharedMemorySize, smemBytes_, device);
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaKernelSetAttributeForDevice failed (smem=" + std::to_string(smemBytes_) +
+ " bytes, error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ cuda_err = detail::cuda_launch_kernel((const void*)kernelPtr_, grid, block, kernelParams, smemBytes_, stream);
+ cudaError_t last_err = detail::cuda_get_last_error();
+ RETURN_CUDNN_FRONTEND_ERROR_IF(cuda_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaLaunchKernel failed (grid=" + std::to_string(grid.x) +
+ ", block=384, smem=" + std::to_string(smemBytes_) +
+ ", error=" + detail::cuda_error_to_string(cuda_err) + ")");
+
+ RETURN_CUDNN_FRONTEND_ERROR_IF(
+ last_err != cudaSuccess,
+ error_code_t::CUDA_API_FAILED,
+ "cudaGetLastError after kernel launch: " + detail::cuda_error_to_string(last_err));
+
+ return {error_code_t::OK, ""};
+ }
+
+ private:
+ // State from check_support()
+ const KernelSpec* spec_ = nullptr;
+ int d_ = 0;
+ int sm_version_ = 0;
+ int sm_count_ = 0;
+ bool support_checked_ = false;
+
+ // State from build()
+ cudaLibrary_t module_ = nullptr;
+ cudaKernel_t kernelPtr_ = nullptr;
+ std::unique_ptr<char[]> cubin_;
+ size_t cubinSize_ = 0;
+ int tile_m_ = 0, tile_n_ = 0, tile_k_ = 0;
+ int smemBytes_ = 0;
+ std::string kernelName_;
+ bool built_ = false;
+};
+
+} // namespace experimental
+} // namespace cudnn_frontend
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif