diff --git a/src/native/cuda/metax/ops/common/flash_mla_launch.h b/src/native/cuda/metax/ops/common/flash_mla_launch.h new file mode 100644 index 000000000..f8388fbc3 --- /dev/null +++ b/src/native/cuda/metax/ops/common/flash_mla_launch.h @@ -0,0 +1,44 @@ +#pragma once + +#include "data_type.h" +#include "native/cuda/metax/caster.cuh" +#include "native/cuda/metax/runtime_.h" + +namespace infini::ops::native_flash_mla { + +struct MlaPrefillLaunch { + std::size_t num_heads, num_seqs, num_kv_heads, total_qtokens; + std::size_t max_num_blocks_per_seq, block_size; + float scale; + std::ptrdiff_t block_table_batch_stride, q_stride, q_head_stride; + std::ptrdiff_t k_batch_stride, k_row_stride, k_head_stride; + std::ptrdiff_t v_batch_stride, v_row_stride, v_head_stride; + std::ptrdiff_t o_stride, o_head_stride; +}; + +struct MlaDecodeLaunch { + std::size_t num_heads, num_seqs, num_kv_heads; + std::size_t max_num_blocks_per_seq, block_size; + float scale; + std::ptrdiff_t block_table_batch_stride; + std::ptrdiff_t q_batch_stride, q_head_stride; + std::ptrdiff_t k_block_stride, k_head_stride, k_slot_stride; + std::ptrdiff_t v_block_stride, v_head_stride, v_slot_stride; + std::ptrdiff_t o_batch_stride, o_head_stride; + std::ptrdiff_t seqlens_stride; +}; + +void launch_mla_prefill(void* out, const void* q, const void* k_cache, + const void* v_cache, const void* block_tables, + const void* cu_seqlens_k, const void* cu_seqlens_q, + DataType data_dtype, DataType index_dtype, + const MlaPrefillLaunch& p, + Runtime::Stream stream); + +void launch_mla_decode(void* out, const void* q, const void* k_cache, + const void* v_cache, const void* block_tables, + const void* seqlens, DataType data_dtype, + DataType index_dtype, const MlaDecodeLaunch& p, + Runtime::Stream stream); + +} // namespace infini::ops::native_flash_mla diff --git a/src/native/cuda/metax/ops/common/flash_mla_launch.maca b/src/native/cuda/metax/ops/common/flash_mla_launch.maca new file mode 100644 index 000000000..ba0c52659 --- /dev/null +++ b/src/native/cuda/metax/ops/common/flash_mla_launch.maca @@ -0,0 +1,78 @@ +#include "flash_mla_launch.h" + +#include "dispatcher.h" +#include "native/cuda/metax/runtime_.h" +#include "native/cuda/ops/flash_mla_warp.cuh" + +namespace infini::ops::native_flash_mla { + +void launch_mla_prefill(void* out, const void* q, const void* k_cache, + const void* v_cache, const void* block_tables, + const void* cu_seqlens_k, const void* cu_seqlens_q, + DataType data_dtype, DataType index_dtype, + const MlaPrefillLaunch& p, + Runtime::Stream stream) { + DispatchFunc, + List<576>>( + {static_cast(data_dtype), static_cast(index_dtype), + static_cast(576)}, + [&](auto list_tag) { + using TData = TypeMapType(list_tag)>; + using TIndex = TypeMapType(list_tag)>; + constexpr int kHeadSize = ListGet<2>(list_tag); + constexpr int kValueHeadSize = 512; + dim3 grid(static_cast(p.num_heads), + static_cast(p.total_qtokens)); + op::flash::cuda::FlashMlaPrefillWarpKernel + <<>>( + static_cast(out), static_cast(q), + static_cast(k_cache), + static_cast(v_cache), + static_cast(block_tables), + static_cast(cu_seqlens_k), + static_cast(cu_seqlens_q), p.num_heads, + p.num_seqs, p.num_kv_heads, p.total_qtokens, p.scale, + p.max_num_blocks_per_seq, p.block_size, + p.block_table_batch_stride, p.q_stride, p.q_head_stride, + p.k_batch_stride, p.k_row_stride, p.k_head_stride, + p.v_batch_stride, p.v_row_stride, p.v_head_stride, p.o_stride, + p.o_head_stride); + }, + "native_flash_mla::launch_mla_prefill"); +} + +void launch_mla_decode(void* out, const void* q, const void* k_cache, + const void* v_cache, const void* block_tables, + const void* seqlens, DataType data_dtype, + DataType index_dtype, const MlaDecodeLaunch& p, + Runtime::Stream stream) { + DispatchFunc, + List<576>>( + {static_cast(data_dtype), static_cast(index_dtype), + static_cast(576)}, + [&](auto list_tag) { + using TData = TypeMapType(list_tag)>; + using TIndex = TypeMapType(list_tag)>; + constexpr int kHeadSize = ListGet<2>(list_tag); + constexpr int kValueHeadSize = 512; + dim3 grid(static_cast(p.num_heads), + static_cast(p.num_seqs)); + op::flash::cuda::FlashMlaDecodeWarpKernel + <<>>( + static_cast(out), static_cast(q), + static_cast(k_cache), + static_cast(v_cache), + static_cast(block_tables), + static_cast(seqlens), p.num_heads, + p.num_kv_heads, p.scale, p.max_num_blocks_per_seq, p.block_size, + p.q_batch_stride, p.q_head_stride, p.k_block_stride, + p.k_head_stride, p.k_slot_stride, p.v_block_stride, + p.v_head_stride, p.v_slot_stride, p.o_batch_stride, + p.o_head_stride, p.block_table_batch_stride, p.seqlens_stride); + }, + "native_flash_mla::launch_mla_decode"); +} + +} // namespace infini::ops::native_flash_mla diff --git a/src/native/cuda/metax/ops/deepseek_moe/kernel.cuh b/src/native/cuda/metax/ops/deepseek_moe/kernel.cuh new file mode 100644 index 000000000..40e7f95ac --- /dev/null +++ b/src/native/cuda/metax/ops/deepseek_moe/kernel.cuh @@ -0,0 +1,194 @@ +#ifndef INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_CUH_ +#define INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_CUH_ + +// Shared declarations of the MetaX DeepseekMoe provider: constants, the +// workspace layout, the workspace lease, and the device-side template +// kernels. The registration lives in kernel.h; kernel.maca is the single +// compilation unit that defines the host scheduling (including the +// non-template routing kernels) and explicitly instantiates RunChunks +// for the two supported element types. + +#include +#include +#include +#include +#include +#include + +// MACA's cu-bridge provides the CUDA-style half/bfloat16 headers; +// __nv_bfloat16 aliases __maca_bfloat16 (same include pattern as +// native/cuda/metax/ops/chunk_gated_delta_rule). +#include +#include + +#include "native/cuda/metax/blas.h" +#include "native/cuda/metax/runtime_.h" + +namespace infini::ops { +namespace metax_deepseek_moe_detail { + +constexpr int kThreads = 256; +// The prefix-scan kernel runs in a single block of kThreads threads. +// 021 routes over 80 experts; nvidia's grouped path also caps at 256. +constexpr int kMaxExperts = 256; +// Tokens processed per pass so the intermediate workspace stays bounded +// for long-context prefill (021 supports 256k tokens). +constexpr size_t kChunkTokens = 4096; + +struct WorkspaceLayout { + size_t counts, offsets, positions, row_to_route, route_to_row, packed_hidden, + gate_buf, up_buf, total; +}; + +inline size_t AlignUp(size_t value, size_t alignment = 256) { + return (value + alignment - 1) / alignment * alignment; +} + +inline WorkspaceLayout Layout(size_t num_experts, size_t routes, + size_t hidden_size, size_t intermediate_size, + size_t element_size) { + WorkspaceLayout l{}; + l.counts = 0; + // Counts and offsets stay adjacent so one D2H copy fetches both. + l.offsets = l.counts + (num_experts + 1) * sizeof(int); + l.positions = AlignUp(l.offsets + (num_experts + 1) * sizeof(int)); + l.row_to_route = AlignUp(l.positions + (num_experts + 1) * sizeof(int)); + l.route_to_row = l.row_to_route + routes * sizeof(int); + l.packed_hidden = AlignUp(l.route_to_row + routes * sizeof(int)); + l.gate_buf = AlignUp(l.packed_hidden + routes * hidden_size * element_size); + l.up_buf = AlignUp(l.gate_buf + routes * intermediate_size * element_size); + l.total = AlignUp(l.up_buf + routes * intermediate_size * element_size); + return l; +} + +// Stream-ordered workspace lease for one operator invocation. Callers with a +// dispatch-provided workspace use it directly (validated); callers without one +// (python bindings) fall back to an eager MallocAsync that is released in +// stream order, so it outlives every kernel of the submission. +class WorkspaceLease { + public: + WorkspaceLease(void* external, std::size_t available, std::size_t required, + Runtime::Stream stream); + WorkspaceLease(const WorkspaceLease&) = delete; + WorkspaceLease& operator=(const WorkspaceLease&) = delete; + ~WorkspaceLease(); + void* data() const { return data_; } + + private: + void* data_{nullptr}; + Runtime::Stream stream_; + bool owned_{false}; +}; + +// Pack every routed (token, expert) pair into expert-contiguous rows and +// record both index directions of the permutation. +template +__global__ void PackHiddenKernel(const T* hidden, const int* topk_indices, + const int* offsets, int* positions, + int* row_to_route, int* route_to_row, + T* packed_hidden, int routes, int hidden_size, + int topk, int num_experts) { + const int route = blockIdx.x; + if (route >= routes) { + return; + } + const int expert = topk_indices[route]; + if (expert < 0 || expert >= num_experts) { + return; + } + const int tid = threadIdx.x; + __shared__ int row; + if (tid == 0) { + const int local = atomicAdd(positions + expert, 1); + row = offsets[expert] + local; + row_to_route[row] = route; + route_to_row[route] = row; + } + __syncthreads(); + const int token = route / topk; + for (int h = tid; h < hidden_size; h += blockDim.x) { + packed_hidden[static_cast(row) * hidden_size + h] = + hidden[static_cast(token) * hidden_size + h]; + } +} + +// In-place SiLU(gate) * up * topk_weight over the expert-packed buffer. +template +__global__ void SwigluWeightKernel(T* activated, const T* gate, const T* up, + const float* topk_weights, + const int* row_to_route, int rows, + int intermediate_size) { + const int idx = blockIdx.x * blockDim.x + threadIdx.x; + const int total = rows * intermediate_size; + if (idx >= total) { + return; + } + const int row = idx / intermediate_size; + const int route = row_to_route[row]; + const float g = static_cast(gate[idx]); + const float u = static_cast(up[idx]); + const float silu = g / (1.0f + expf(-g)); + activated[idx] = static_cast(silu * u * topk_weights[route]); +} + +// Sum the topk expert contributions back per (token, hidden) element. +template +__global__ void SumGroupedOutKernel(T* out, const T* packed_out, + const int* route_to_row, int ntokens, + int hidden_size, int topk) { + const int idx = blockIdx.x * blockDim.x + threadIdx.x; + const int total = ntokens * hidden_size; + if (idx >= total) { + return; + } + const int token = idx / hidden_size; + const int h = idx - token * hidden_size; + float acc = 0.0f; + for (int k = 0; k < topk; ++k) { + const int route = token * topk + k; + const int row = route_to_row[route]; + acc += static_cast( + packed_out[static_cast(row) * hidden_size + h]); + } + out[idx] = static_cast(acc); +} + +// Expert-grouped MoE: pack routed tokens by expert, run gate/up/down GEMMs +// per expert (batch=1 strided GEMM, the pattern moe_fused_dense already +// exercises on MetaX), apply SiLU*up*weight in place, then sum the topk +// contributions per token. Large prefills are chunked so the workspace +// stays bounded. +template +void RunChunks(std::uint8_t* base, const WorkspaceLayout& layout, + size_t ntokens, size_t hidden_size, size_t topk, + size_t intermediate_size, size_t num_experts, const T* hidden, + const int* topk_indices, const float* topk_weights, + const std::vector& gate_ptrs, + const std::vector& up_ptrs, + const std::vector& down_ptrs, T* out, + Runtime::Stream stream, + mcblasHandle_t handle); + +// mcBLAS handle is created lazily once per thread; defined in kernel.maca. +mcblasHandle_t GetHandle(); + +// The two element types the provider dispatches on; defined in kernel.maca. +extern template void RunChunks<__half>(std::uint8_t*, const WorkspaceLayout&, + size_t, size_t, size_t, size_t, size_t, + const __half*, const int*, const float*, + const std::vector&, + const std::vector&, + const std::vector&, __half*, + Runtime::Stream, + mcblasHandle_t); +extern template void RunChunks<__nv_bfloat16>( + std::uint8_t*, const WorkspaceLayout&, size_t, size_t, size_t, size_t, + size_t, const __nv_bfloat16*, const int*, const float*, + const std::vector&, const std::vector&, + const std::vector&, __nv_bfloat16*, + Runtime::Stream, mcblasHandle_t); + +} // namespace metax_deepseek_moe_detail +} // namespace infini::ops + +#endif // INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_CUH_ diff --git a/src/native/cuda/metax/ops/deepseek_moe/kernel.h b/src/native/cuda/metax/ops/deepseek_moe/kernel.h new file mode 100644 index 000000000..2c871a4c9 --- /dev/null +++ b/src/native/cuda/metax/ops/deepseek_moe/kernel.h @@ -0,0 +1,113 @@ +#ifndef INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_H_ +#define INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_H_ + +// Registration entry of the native MetaX DeepseekMoe provider. The +// shared declarations (constants, workspace layout/lease and the +// device-side template kernels) live in kernel.cuh; kernel.maca is the +// compilation unit that defines the host scheduling, the non-template +// routing kernels, and the RunChunks instantiations, so kernel launches +// and definitions share one TU per the repository convention. + +#include +#include +#include +#include + +#include "base/deepseek_moe.h" +#include "native/cuda/metax/blas.h" +#include "native/cuda/metax/ops/deepseek_moe/kernel.cuh" +#include "native/cuda/metax/runtime_.h" + +namespace infini::ops { + +// Native MetaX DeepseekMoe: expert-grouped GEMM path. The routing +// (count/scan/pack), activation and reduction kernels run on device and +// the per-expert projections go through mcBLAS, so no per-expert operator +// submits cross the dispatcher. +template <> +class Operator : public DeepseekMoe { + public: + using DeepseekMoe::DeepseekMoe; + + bool capture_safe() const override { return false; } + + size_t workspace_size_in_bytes() const override { + const auto& hidden = metadata_[1]; + const size_t esz = hidden.element_size(); + const size_t ntokens = std::min( + hidden.size(0), metax_deepseek_moe_detail::kChunkTokens); + const size_t routes = ntokens * metadata_[2].size(1); + return metax_deepseek_moe_detail::Layout(num_experts_, routes, + hidden.size(1), intermediate_, esz) + .total; + } + + void operator()(Tensor output, const Tensor hidden, const Tensor ids, + const Tensor weights, const std::vector gate, + const std::vector up, const std::vector down, + size_t intermediate, size_t num_experts) const override { + namespace detail = metax_deepseek_moe_detail; + using MetaxBlas = Blas; + using MetaxRuntime = Runtime; + + Invocation(output, hidden, ids, weights, gate, up, down, intermediate, + num_experts); + if (hidden.size(0) == 0) { + return; + } + moe_detail::Require(num_experts <= size_t(detail::kMaxExperts)); + moe_detail::Require(hidden.dtype() == DataType::kFloat16 || + hidden.dtype() == DataType::kBFloat16); + + const size_t hidden_size = hidden.size(1); + const size_t topk = ids.size(1); + const size_t ntokens = hidden.size(0); + const size_t esz = hidden.element_size(); + + const auto stream = + static_cast(stream_ ? stream_ : nullptr); + const auto layout = detail::Layout( + num_experts, std::min(ntokens, detail::kChunkTokens) * topk, + hidden_size, intermediate, esz); + // Dispatch callers pass a stable workspace; python bindings get a + // stream-ordered lease that is freed after the submission completes. + detail::WorkspaceLease lease(workspace_, workspace_size_in_bytes_, + layout.total, stream); + auto* base = static_cast(lease.data()); + + auto handle = detail::GetHandle(); + if (MetaxBlas::BlasSetStream(handle, stream) != MCBLAS_STATUS_SUCCESS) { + throw std::runtime_error("MetaX DeepseekMoe BLAS set stream failed"); + } + + std::vector gate_ptrs(num_experts); + std::vector up_ptrs(num_experts); + std::vector down_ptrs(num_experts); + for (size_t e = 0; e < num_experts; ++e) { + gate_ptrs[e] = gate[e].data(); + up_ptrs[e] = up[e].data(); + down_ptrs[e] = down[e].data(); + } + + if (hidden.dtype() == DataType::kFloat16) { + detail::RunChunks<__half>( + base, layout, ntokens, hidden_size, topk, intermediate, num_experts, + reinterpret_cast(hidden.data()), + reinterpret_cast(ids.data()), + reinterpret_cast(weights.data()), gate_ptrs, up_ptrs, + down_ptrs, reinterpret_cast<__half*>(output.data()), stream, handle); + } else { + detail::RunChunks<__nv_bfloat16>( + base, layout, ntokens, hidden_size, topk, intermediate, num_experts, + reinterpret_cast(hidden.data()), + reinterpret_cast(ids.data()), + reinterpret_cast(weights.data()), gate_ptrs, up_ptrs, + down_ptrs, reinterpret_cast<__nv_bfloat16*>(output.data()), stream, + handle); + } + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_H_ diff --git a/src/native/cuda/metax/ops/deepseek_moe/kernel.maca b/src/native/cuda/metax/ops/deepseek_moe/kernel.maca new file mode 100644 index 000000000..09115fdc3 --- /dev/null +++ b/src/native/cuda/metax/ops/deepseek_moe/kernel.maca @@ -0,0 +1,241 @@ +#ifndef INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_MACA_ +#define INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_MACA_ + +// Single compilation unit of the MetaX DeepseekMoe host scheduling: the +// two non-template routing kernels, the mcBLAS resource helpers, the +// chunked dispatch loop, and the explicit RunChunks instantiations. The +// shared declarations live in kernel.cuh and the registration in +// kernel.h, so the kernel launches here are defined in the same +// translation unit, per the repository convention for backend sources. + +#include + +#include "native/cuda/metax/ops/deepseek_moe/kernel.cuh" + +namespace infini::ops { +namespace metax_deepseek_moe_detail { + +inline void CheckMc(mcError_t status, const char* what) { + if (status != mcSuccess) { + throw std::runtime_error(std::string("MetaX DeepseekMoe ") + what + + " failed: " + std::to_string(int(status))); + } +} + +mcblasHandle_t GetHandle() { + static thread_local mcblasHandle_t handle = []() { + mcblasHandle_t h{}; + if (Blas::BlasCreate(&h) != MCBLAS_STATUS_SUCCESS) + throw std::runtime_error( + "MetaX DeepseekMoe: creating mcBLAS handle failed"); + return h; + }(); + return handle; +} + +WorkspaceLease::WorkspaceLease(void* external, std::size_t available, + std::size_t required, + Runtime::Stream stream) + : data_{external}, stream_{stream} { + if (external || available) { + if (!external || available < required) + throw std::invalid_argument( + "MetaX DeepseekMoe workspace is missing or too small"); + if (reinterpret_cast(external) % 256) + throw std::invalid_argument( + "MetaX DeepseekMoe workspace is not 256-byte aligned"); + return; + } + CheckMc(Runtime::MallocAsync(&data_, required, stream), + "workspace MallocAsync"); + owned_ = true; +} + +WorkspaceLease::~WorkspaceLease() { + if (!owned_) return; + if (Runtime::FreeAsync(data_, stream_) == mcSuccess) { + return; + } + // Failure path only: wait for any submitted work before conventional free. + if (Runtime::StreamSynchronize(stream_) == mcSuccess) { + Runtime::Free(data_); + return; + } + Runtime::Free(data_); +} + +__global__ void CountExpertsKernel(const int* topk_indices, int* counts, + int routes, int num_experts) { + const int route = blockIdx.x * blockDim.x + threadIdx.x; + if (route >= routes) { + return; + } + const int expert = topk_indices[route]; + if (expert >= 0 && expert < num_experts) { + atomicAdd(counts + expert, 1); + } +} + +__global__ void PrefixCountsKernel(const int* counts, int* offsets, + int num_experts) { + extern __shared__ int scan[]; + const int tid = threadIdx.x; + scan[tid] = tid < num_experts ? counts[tid] : 0; + __syncthreads(); + for (int stride = 1; stride < blockDim.x; stride <<= 1) { + int value = 0; + if (tid >= stride) { + value = scan[tid - stride]; + } + __syncthreads(); + scan[tid] += value; + __syncthreads(); + } + if (tid == 0) { + offsets[0] = 0; + } + if (tid < num_experts) { + offsets[tid + 1] = scan[tid]; + } +} + +template +void RunChunks(std::uint8_t* base, const WorkspaceLayout& layout, + size_t ntokens, size_t hidden_size, size_t topk, + size_t intermediate_size, size_t num_experts, const T* hidden, + const int* topk_indices, const float* topk_weights, + const std::vector& gate_ptrs, + const std::vector& up_ptrs, + const std::vector& down_ptrs, T* out, + Runtime::Stream stream, + mcblasHandle_t handle) { + using MetaxBlas = Blas; + using MetaxRuntime = Runtime; + const auto blas_dtype = std::is_same_v ? macaDataType(MACA_R_16F) + : macaDataType(MACA_R_16BF); + const int hidden_i = static_cast(hidden_size); + const int inter_i = static_cast(intermediate_size); + const int topk_i = static_cast(topk); + const int experts_i = static_cast(num_experts); + + auto* counts = reinterpret_cast(base + layout.counts); + auto* offsets = reinterpret_cast(base + layout.offsets); + auto* positions = reinterpret_cast(base + layout.positions); + auto* row_to_route = reinterpret_cast(base + layout.row_to_route); + auto* route_to_row = reinterpret_cast(base + layout.route_to_row); + auto* packed = reinterpret_cast(base + layout.packed_hidden); + auto* gate_buf = reinterpret_cast(base + layout.gate_buf); + auto* up_buf = reinterpret_cast(base + layout.up_buf); + + std::vector host_counts(num_experts + 1); + std::vector host_offsets(num_experts + 1); + + // Weights are row-major [out_features, in_features]; OP_T turns them + // into column-major (in_features, out_features), matching the nvidia + // run_gemm convention (m=out, n=tokens, k=in). + auto gemm = [&](const void* a, const void* b, void* c, int m, int n, int k, + int lda, int ldb, int ldc) { + const float alpha = 1.0f; + const float beta = 0.0f; + const auto status = MetaxBlas::BlasGemmStridedBatchedEx( + handle, MetaxBlas::BLAS_OP_T, MetaxBlas::BLAS_OP_N, m, n, k, &alpha, a, + blas_dtype, lda, 0, b, blas_dtype, ldb, 0, &beta, c, blas_dtype, ldc, 0, + 1, MetaxBlas::BLAS_COMPUTE_32F, MetaxBlas::BLAS_GEMM_DEFAULT); + if (status != MCBLAS_STATUS_SUCCESS) { + throw std::runtime_error("MetaX DeepseekMoe GEMM failed: " + + std::to_string(int(status))); + } + }; + + for (size_t begin = 0; begin < ntokens; begin += kChunkTokens) { + const int tokens = + static_cast(std::min(kChunkTokens, ntokens - begin)); + const int routes = tokens * topk_i; + const T* hidden_chunk = hidden + begin * hidden_size; + const int* ids_chunk = topk_indices + begin * topk_i; + const float* weights_chunk = topk_weights + begin * topk_i; + T* out_chunk = out + begin * hidden_size; + + CheckMc(MetaxRuntime::MemsetAsync(counts, 0, + (num_experts + 1) * sizeof(int), stream), + "memset"); + CheckMc(MetaxRuntime::MemsetAsync(positions, 0, + (num_experts + 1) * sizeof(int), stream), + "memset"); + CountExpertsKernel<<<(routes + kThreads - 1) / kThreads, kThreads, 0, + stream>>>(ids_chunk, counts, routes, experts_i); + PrefixCountsKernel<<<1, kThreads, kThreads * sizeof(int), stream>>>( + counts, offsets, experts_i); + PackHiddenKernel<<>>( + hidden_chunk, ids_chunk, offsets, positions, row_to_route, route_to_row, + packed, routes, hidden_i, topk_i, experts_i); + CheckMc(MetaxRuntime::MemcpyAsync( + host_counts.data(), counts, (num_experts + 1) * sizeof(int), + MetaxRuntime::kMemcpyDeviceToHost, stream), + "counts copy"); + CheckMc(MetaxRuntime::MemcpyAsync( + host_offsets.data(), offsets, (num_experts + 1) * sizeof(int), + MetaxRuntime::kMemcpyDeviceToHost, stream), + "offsets copy"); + CheckMc(MetaxRuntime::StreamSynchronize(stream), "route sync"); + + for (int e = 0; e < experts_i; ++e) { + const int count = host_counts[e]; + if (count <= 0) { + continue; + } + const size_t off = static_cast(host_offsets[e]); + gemm(gate_ptrs[e], packed + off * hidden_size, + gate_buf + off * intermediate_size, inter_i, count, hidden_i, + hidden_i, hidden_i, inter_i); + gemm(up_ptrs[e], packed + off * hidden_size, + up_buf + off * intermediate_size, inter_i, count, hidden_i, hidden_i, + hidden_i, inter_i); + } + SwigluWeightKernel + <<<(static_cast(routes) * intermediate_size + kThreads - 1) / + kThreads, + kThreads, 0, stream>>>(gate_buf, gate_buf, up_buf, weights_chunk, + row_to_route, routes, inter_i); + for (int e = 0; e < experts_i; ++e) { + const int count = host_counts[e]; + if (count <= 0) { + continue; + } + const size_t off = static_cast(host_offsets[e]); + gemm(down_ptrs[e], gate_buf + off * intermediate_size, + packed + off * hidden_size, hidden_i, count, inter_i, inter_i, + inter_i, hidden_i); + } + SumGroupedOutKernel + <<<(static_cast(tokens) * hidden_size + kThreads - 1) / + kThreads, + kThreads, 0, stream>>>(out_chunk, packed, route_to_row, tokens, + hidden_i, topk_i); + } + // Keep workspace reuse safe across chunks / subsequent layers. + CheckMc(MetaxRuntime::StreamSynchronize(stream), "final sync"); +} + +// The explicit instantiations pair with the extern templates in +// kernel.cuh: registration TU sees declarations only, this TU owns the +// definitions (kernels and host code compiled together). +template void RunChunks<__half>(std::uint8_t*, const WorkspaceLayout&, size_t, + size_t, size_t, size_t, size_t, const __half*, + const int*, const float*, + const std::vector&, + const std::vector&, + const std::vector&, __half*, + Runtime::Stream, + mcblasHandle_t); +template void RunChunks<__nv_bfloat16>( + std::uint8_t*, const WorkspaceLayout&, size_t, size_t, size_t, size_t, + size_t, const __nv_bfloat16*, const int*, const float*, + const std::vector&, const std::vector&, + const std::vector&, __nv_bfloat16*, + Runtime::Stream, mcblasHandle_t); + +} // namespace metax_deepseek_moe_detail +} // namespace infini::ops + +#endif // INFINI_OPS_METAX_DEEPSEEK_MOE_KERNEL_MACA_ diff --git a/src/native/cuda/metax/ops/flash_attn_varlen_func/mla_kernel.cc b/src/native/cuda/metax/ops/flash_attn_varlen_func/mla_kernel.cc new file mode 100644 index 000000000..07889cb80 --- /dev/null +++ b/src/native/cuda/metax/ops/flash_attn_varlen_func/mla_kernel.cc @@ -0,0 +1,106 @@ +#include "mla_kernel.h" + +#include + +#include "native/cuda/metax/ops/common/flash_mla_launch.h" +#include "native/cuda/metax/runtime_.h" + +// The provider header undefines its macro; the definitions below re-spell +// the same public overloads locally, matching the pinned provider pattern. +#define MLA_VARLEN_ARGS \ + const Tensor q, const Tensor k, const Tensor v, const Tensor cu_seqlens_q, \ + const Tensor cu_seqlens_k, const std::optional alibi_slopes, \ + const std::optional block_table, const int64_t max_seqlen_q, \ + const int64_t max_seqlen_k, const double dropout_p, \ + const std::optional softmax_scale, const bool causal, \ + const std::vector window_size, const double softcap, \ + const bool deterministic, const bool return_attn_probs, Tensor out, \ + std::optional softmax_lse, std::optional s_dmask + +namespace infini::ops { + +struct Operator::Impl { + native_flash_mla::MlaPrefillLaunch params{}; + std::optional scale; + bool requested_causal; + std::array requested_window; +}; + +void Operator::prepare( + MLA_VARLEN_ARGS) { + (void)alibi_slopes; + (void)cu_seqlens_k; + (void)max_seqlen_q; + (void)max_seqlen_k; + (void)dropout_p; + (void)softcap; + (void)deterministic; + (void)return_attn_probs; + (void)softmax_lse; + (void)s_dmask; + auto state = std::make_shared(); + state->scale = softmax_scale; + state->requested_causal = causal; + state->requested_window = {window_size[0], window_size[1]}; + auto& p = state->params; + p.num_heads = q.size(1); + p.num_seqs = cu_seqlens_q.size(0) - 1; + p.num_kv_heads = k.size(-2); + p.total_qtokens = q.size(0); + p.max_num_blocks_per_seq = block_table->size(1); + p.block_size = k.size(1); + p.scale = static_cast( + softmax_scale.value_or(1.0 / std::sqrt(static_cast(q.size(2))))); + if (!std::isfinite(p.scale)) + throw std::invalid_argument("nonfinite native MLA varlen Attention scale"); + p.block_table_batch_stride = block_table->stride(0); + p.q_stride = q.stride(0); + p.q_head_stride = q.stride(1); + p.k_batch_stride = k.stride(0); + p.k_row_stride = k.stride(1); + p.k_head_stride = k.stride(2); + p.v_batch_stride = v.stride(0); + p.v_row_stride = v.stride(1); + p.v_head_stride = v.stride(2); + p.o_stride = out.stride(0); + p.o_head_stride = out.stride(1); + impl_ = std::move(state); +} + +void Operator::operator()( + MLA_VARLEN_ARGS) const { + // Same guard scope as the NVIDIA varlen provider: a prepared instance + // launched directly must carry the exact metadata baked into Impl. + if (q.shape() != q_shape_ || q.strides() != q_strides_ || + k.shape() != k_shape_ || k.strides() != k_strides_ || + v.shape() != v_shape_ || v.strides() != v_strides_ || + out.shape() != out_shape_ || out.strides() != out_strides_ || + cu_seqlens_q.shape() != cu_seqlens_q_shape_ || + cu_seqlens_q.strides() != cu_seqlens_q_strides_ || + cu_seqlens_k.shape() != cu_seqlens_k_shape_ || + cu_seqlens_k.strides() != cu_seqlens_k_strides_ || + (block_table ? Tensor::Shape{block_table->shape()} : Tensor::Shape{}) != + block_table_shape_ || + (block_table ? Tensor::Strides{block_table->strides()} + : Tensor::Strides{}) != block_table_strides_ || + q.device().index() != device_index_ || q.dtype() != q_dtype_ || + softmax_scale != impl_->scale || causal != impl_->requested_causal || + window_size[0] != impl_->requested_window[0] || + window_size[1] != impl_->requested_window[1]) + throw std::invalid_argument( + "native MLA varlen Attention prepared metadata changed"); + auto stream = static_cast::Stream>( + stream_ ? stream_ : nullptr); + native_flash_mla::launch_mla_prefill( + out.data(), q.data(), k.data(), v.data(), block_table->data(), + cu_seqlens_k.data(), cu_seqlens_q.data(), q_dtype_, block_table_dtype_, + impl_->params, stream); +} + +Operator::~Operator() { + impl_.reset(); +} + +} // namespace infini::ops + +#undef MLA_VARLEN_ARGS diff --git a/src/native/cuda/metax/ops/flash_attn_varlen_func/mla_kernel.h b/src/native/cuda/metax/ops/flash_attn_varlen_func/mla_kernel.h new file mode 100644 index 000000000..f4c4bbc24 --- /dev/null +++ b/src/native/cuda/metax/ops/flash_attn_varlen_func/mla_kernel.h @@ -0,0 +1,122 @@ +#ifndef INFINI_OPS_METAX_FLASH_ATTN_VARLEN_FUNC_MLA_KERNEL_H_ +#define INFINI_OPS_METAX_FLASH_ATTN_VARLEN_FUNC_MLA_KERNEL_H_ + +#include +#include +#include +#include +#include +#include + +#include "base/flash_attn_varlen_func.h" +#include "native/cuda/metax/caster.cuh" +#include "native/cuda/metax/runtime_.h" +#include "native/cuda/runtime_utils.h" + +#define INFINI_METAX_VARLEN_MLA_ARGS \ + const Tensor q, const Tensor k, const Tensor v, const Tensor cu_seqlens_q, \ + const Tensor cu_seqlens_k, const std::optional alibi_slopes, \ + const std::optional block_table, const int64_t max_seqlen_q, \ + const int64_t max_seqlen_k, const double dropout_p, \ + const std::optional softmax_scale, const bool causal, \ + const std::vector window_size, const double softcap, \ + const bool deterministic, const bool return_attn_probs, Tensor out, \ + std::optional softmax_lse, std::optional s_dmask +#define INFINI_METAX_VARLEN_MLA_VALUES \ + q, k, v, cu_seqlens_q, cu_seqlens_k, alibi_slopes, block_table, \ + max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale, causal, \ + window_size, softcap, deterministic, return_attn_probs, out, \ + softmax_lse, s_dmask + +namespace infini::ops { + +// MLA-packed paged prefill over the fused latent KV cache: q/k +// head dim 576 (kv_lora_rank 512 + rope 64) with a separate 512 +// value latent. MetaX port of the NVIDIA MLA provider (nvidia +// mla_kernel.h); the shared warp kernel in flash_mla_warp.cuh only +// needs warp shuffles and exp2f, both available under MACA. Non-MLA +// shapes stay with the linked torch provider. +// +// Slot index: this specialization omits the explicit index, so it +// takes the default slot 0 -- the first native implementation of the +// operator on this device. The other provider is the linked-torch +// one at slot 16 (docs/linked-operators.md: linked providers declare +// 16 or greater); automatic dispatch tries slots in ascending order, +// so MLA layouts hit this kernel first and regular MHA falls through +// to slot 16. The NVIDIA backend keeps a separate numbering (its +// slot 0 is the pinned FA2 kernel, its MLA provider is slot 1); +// indexes are local to an operator and device (docs/api/operators.md). +template <> +class Operator + : public FlashAttnVarlenFunc { + public: + static bool is_mla_layout(const Tensor& k, const Tensor& v) { + return k.shape() != v.shape(); + } + + static bool supports(INFINI_METAX_VARLEN_MLA_ARGS) { + const bool mla = is_mla_layout(k, v); + if (!FlashAttnVarlenFunc::supports(INFINI_METAX_VARLEN_MLA_VALUES)) + return false; + if (!mla) return false; // Non-MLA belongs to the linked provider. + const bool paged = block_table.has_value(); + if (dropout_p != 0.0 || softcap != 0.0 || deterministic || + return_attn_probs || alibi_slopes) + return false; + // Full causal only: the MLA warp kernels have no sliding-window path. + if (!(window_size[0] == -1 && window_size[1] == -1)) return false; + if (!causal) return false; + if (!paged) return false; // MLA prefill always reads the paged cache. + if (q.size(2) != 576 || v.size(-1) != 512) return false; + // grid.y carries the packed query tokens; MACA caps it at 65535. + if (q.size(0) > 65535) return false; + if (k.size(1) != v.size(1) || k.size(2) != v.size(2)) return false; + // The fused MLA cache packs k|v in one 1088-wide row; K and V are + // narrow views of it, so token strides are shared and only the head + // dims differ. The kernel reads each cache through its own strides. + if (k.stride(3) != 1 || v.stride(3) != 1 || k.stride(1) != v.stride(1) || + k.stride(2) != v.stride(2) || k.stride(0) != v.stride(0)) + return false; + if (q.stride(2) != 1 || out.stride(2) != 1) return false; + if (q.stride(0) != q.size(1) * q.size(2) || + out.stride(0) != out.size(1) * out.size(2)) + return false; + if (q.stride(1) != q.size(2) || out.stride(1) != out.size(2)) return false; + if (cu_seqlens_q.size(0) != cu_seqlens_k.size(0)) return false; + return true; + } + + Operator(INFINI_METAX_VARLEN_MLA_ARGS) + : FlashAttnVarlenFunc( + checked_q(INFINI_METAX_VARLEN_MLA_VALUES), k, v, cu_seqlens_q, + cu_seqlens_k, alibi_slopes, block_table, max_seqlen_q, max_seqlen_k, + dropout_p, softmax_scale, causal, window_size, softcap, + deterministic, return_attn_probs, out, softmax_lse, s_dmask) { + prepare(INFINI_METAX_VARLEN_MLA_VALUES); + } + ~Operator() override; + using FlashAttnVarlenFunc::operator(); + + void operator()(INFINI_METAX_VARLEN_MLA_ARGS) const override; + + bool capture_safe() const override { return true; } + std::size_t workspace_size_in_bytes() const override { return 0; } + + private: + static Tensor checked_q(INFINI_METAX_VARLEN_MLA_ARGS) { + if (!supports(INFINI_METAX_VARLEN_MLA_VALUES)) + throw std::invalid_argument( + "unsupported native MLA varlen Attention configuration"); + return q; + } + struct Impl; + std::shared_ptr impl_; + void prepare(INFINI_METAX_VARLEN_MLA_ARGS); +}; + +} // namespace infini::ops + +#undef INFINI_METAX_VARLEN_MLA_ARGS +#undef INFINI_METAX_VARLEN_MLA_VALUES + +#endif // INFINI_OPS_METAX_FLASH_ATTN_VARLEN_FUNC_MLA_KERNEL_H_ diff --git a/src/native/cuda/metax/ops/flash_attn_with_kvcache/mla_kernel.cc b/src/native/cuda/metax/ops/flash_attn_with_kvcache/mla_kernel.cc new file mode 100644 index 000000000..dd9ef32ca --- /dev/null +++ b/src/native/cuda/metax/ops/flash_attn_with_kvcache/mla_kernel.cc @@ -0,0 +1,83 @@ +#include "mla_kernel.h" + +#include + +#include "native/cuda/metax/ops/common/flash_mla_launch.h" +#include "native/cuda/metax/runtime_.h" + +namespace infini::ops { + +struct Operator::Impl { + native_flash_mla::MlaDecodeLaunch params{}; + std::optional scale; + std::array requested_window; + bool lengths_present; +}; + +void Operator::prepare( + const Tensor& q, Tensor k_cache, Tensor v_cache, + const std::optional& lengths, const std::optional& blocks, + const std::optional& scale, + const std::vector& window_size) { + auto state = std::make_shared(); + state->scale = scale; + state->requested_window = {window_size[0], window_size[1]}; + state->lengths_present = lengths.has_value(); + auto& p = state->params; + p.num_heads = q.size(2); + p.num_seqs = q.size(0); + p.num_kv_heads = k_cache.size(2); + p.max_num_blocks_per_seq = blocks->size(1); + p.block_size = k_cache.size(1); + p.scale = static_cast( + scale.value_or(1.0 / std::sqrt(static_cast(q.size(3))))); + if (!std::isfinite(p.scale)) + throw std::invalid_argument("nonfinite native MLA KV Attention scale"); + p.block_table_batch_stride = blocks->stride(0); + p.q_batch_stride = q.stride(0); + p.q_head_stride = q.stride(2); + p.k_block_stride = k_cache.stride(0); + p.k_head_stride = k_cache.stride(2); + p.k_slot_stride = k_cache.stride(1); + p.v_block_stride = v_cache.stride(0); + p.v_head_stride = v_cache.stride(2); + p.v_slot_stride = v_cache.stride(1); + p.o_batch_stride = out_strides_[0]; + p.o_head_stride = out_strides_[2]; + p.seqlens_stride = lengths ? lengths->stride(0) : 0; + impl_ = std::move(state); +} + +Operator::~Operator() { + impl_.reset(); +} + +void Operator::execute( + const Tensor& q, Tensor k_cache, Tensor v_cache, + const std::optional& lengths, const std::optional& blocks, + const std::optional& scale, const std::vector& window_size, + Tensor out) const { + if (q.shape() != q_shape_ || q.strides() != q_strides_ || + k_cache.shape() != k_cache_shape_ || + k_cache.strides() != k_cache_strides_ || + v_cache.shape() != v_cache_shape_ || + v_cache.strides() != v_cache_strides_ || out.shape() != out_shape_ || + out.strides() != out_strides_ || + (blocks ? Tensor::Shape{blocks->shape()} : Tensor::Shape{}) != + block_table_shape_ || + (blocks ? Tensor::Strides{blocks->strides()} : Tensor::Strides{}) != + block_table_strides_ || + scale != impl_->scale || window_size.size() != 2 || + window_size[0] != impl_->requested_window[0] || + window_size[1] != impl_->requested_window[1] || + lengths.has_value() != impl_->lengths_present) + throw std::invalid_argument( + "native MLA KV Attention prepared metadata changed"); + auto stream = static_cast::Stream>( + stream_ ? stream_ : nullptr); + native_flash_mla::launch_mla_decode( + out.data(), q.data(), k_cache.data(), v_cache.data(), blocks->data(), + lengths->data(), q_dtype_, block_table_dtype_, impl_->params, stream); +} + +} // namespace infini::ops diff --git a/src/native/cuda/metax/ops/flash_attn_with_kvcache/mla_kernel.h b/src/native/cuda/metax/ops/flash_attn_with_kvcache/mla_kernel.h new file mode 100644 index 000000000..975ee86be --- /dev/null +++ b/src/native/cuda/metax/ops/flash_attn_with_kvcache/mla_kernel.h @@ -0,0 +1,177 @@ +#ifndef INFINI_OPS_METAX_FLASH_ATTN_WITH_KVCACHE_MLA_KERNEL_H_ +#define INFINI_OPS_METAX_FLASH_ATTN_WITH_KVCACHE_MLA_KERNEL_H_ + +#include +#include +#include +#include +#include + +#include "base/flash_attn_with_kvcache.h" +#include "native/cuda/metax/caster.cuh" +#include "native/cuda/metax/runtime_.h" +#include "native/cuda/runtime_utils.h" + +#define INFINI_METAX_KVCACHE_MLA_PARAMS(Lengths) \ + const Tensor q, Tensor k_cache, Tensor v_cache, \ + const std::optional k, const std::optional v, \ + const std::optional rotary_cos, \ + const std::optional rotary_sin, const Lengths cache_seqlens, \ + const std::optional cache_batch_idx, \ + const std::optional cache_leftpad, \ + const std::optional block_table, \ + const std::optional alibi_slopes, \ + const std::optional softmax_scale, const bool causal, \ + const std::vector window_size, const double softcap, \ + const bool rotary_interleaved, const int64_t num_splits, \ + const bool return_softmax_lse, Tensor out, \ + std::optional softmax_lse +#define INFINI_METAX_KVCACHE_MLA_VALUES \ + q, k_cache, v_cache, k, v, rotary_cos, rotary_sin, cache_seqlens, \ + cache_batch_idx, cache_leftpad, block_table, alibi_slopes, \ + softmax_scale, causal, window_size, softcap, rotary_interleaved, \ + num_splits, return_softmax_lse, out, softmax_lse + +namespace infini::ops { + +// MLA-packed decode over the fused latent KV cache: q/k head +// dim 576 (kv_lora_rank 512 + rope 64) with a separate 512 +// value latent. MetaX port of the NVIDIA MLA provider (nvidia +// mla_kernel.h); the shared warp kernel only needs warp shuffles +// and exp2f, both available under MACA. Non-MLA shapes stay with +// the linked torch provider. +// +// Slot index: this specialization omits the explicit index, so it +// takes the default slot 0 -- the first native implementation of the +// operator on this device. The other provider is the linked-torch +// one at slot 16 (docs/linked-operators.md: linked providers declare +// 16 or greater); automatic dispatch tries slots in ascending order, +// so MLA layouts hit this kernel first and regular MHA falls through +// to slot 16. The NVIDIA backend keeps a separate numbering (its +// slot 0 is the pinned FA2 kernel, its MLA provider is slot 1); +// indexes are local to an operator and device (docs/api/operators.md). +template <> +class Operator + : public FlashAttnWithKvcache { + public: + static bool is_mla_layout(Tensor k_cache, Tensor v_cache) { + return k_cache.shape() != v_cache.shape(); + } + + template + static bool supports(INFINI_METAX_KVCACHE_MLA_PARAMS(Lengths)) { + if constexpr (!std::is_same_v>) { + return false; // Scalar metadata needs a separate prepared device buffer. + } else { + if (!FlashAttnWithKvcache::supports(INFINI_METAX_KVCACHE_MLA_VALUES)) + return false; + if (!is_mla_layout(k_cache, v_cache)) return false; + // The kernel reads per-sequence lengths unconditionally. + if (!cache_seqlens) return false; + if (k || v || rotary_cos || rotary_sin || cache_batch_idx || + cache_leftpad || alibi_slopes) + return false; + if (softcap != 0.0 || num_splits != 0 || return_softmax_lse) return false; + // Full causal only: the MLA warp kernels have no sliding-window path. + if (!(window_size[0] == -1 && window_size[1] == -1)) return false; + if (!causal) return false; + if (!block_table || q.size(1) != 1) return false; + if (q.size(3) != 576 || v_cache.size(3) != 512) return false; + if (k_cache.size(1) != v_cache.size(1) || + k_cache.size(2) != v_cache.size(2)) + return false; + // The fused MLA cache packs k|v in one 1088-wide row; K and V are + // narrow views of it, so token strides are shared and only the head + // dims differ. The kernel reads each cache through its own strides. + if (k_cache.stride(3) != 1 || v_cache.stride(3) != 1 || + k_cache.stride(2) != v_cache.stride(2) || + k_cache.stride(1) != v_cache.stride(1) || + k_cache.stride(0) != v_cache.stride(0)) + return false; + if (q.stride(3) != 1 || out.stride(3) != 1) return false; + if (q.stride(0) != q.size(1) * q.size(2) * q.size(3) || + out.stride(0) != out.size(1) * out.size(2) * out.size(3)) + return false; + // Dim 1 is the singleton token axis (enforced above), and unsqueezed + // views carry a meaningless zero stride there, so it is not checked. + if (q.stride(2) != q.size(3) || out.stride(2) != out.size(3)) + return false; + return true; + } + } + + template + Operator(INFINI_METAX_KVCACHE_MLA_PARAMS(Lengths)) + : FlashAttnWithKvcache{checked_q(INFINI_METAX_KVCACHE_MLA_VALUES), + k_cache, + v_cache, + k, + v, + rotary_cos, + rotary_sin, + cache_seqlens, + cache_batch_idx, + cache_leftpad, + block_table, + alibi_slopes, + softmax_scale, + causal, + window_size, + softcap, + rotary_interleaved, + num_splits, + return_softmax_lse, + out, + softmax_lse} { + if constexpr (std::is_same_v>) { + prepare(q, k_cache, v_cache, cache_seqlens, block_table, softmax_scale, + window_size); + } + } + ~Operator() override; + using FlashAttnWithKvcache::operator(); + + void operator()(INFINI_METAX_KVCACHE_MLA_PARAMS(int64_t)) const override { + throw std::invalid_argument( + "native MLA KV Attention requires device length metadata"); + } + void operator()( + INFINI_METAX_KVCACHE_MLA_PARAMS(std::optional)) const override { + checked_q(INFINI_METAX_KVCACHE_MLA_VALUES); + execute(q, k_cache, v_cache, cache_seqlens, block_table, softmax_scale, + window_size, out); + } + + // Graph callers must supply stable external workspace for the graph lifetime. + bool capture_safe() const override { return true; } + std::size_t workspace_size_in_bytes() const override { return 0; } + + private: + template + static Tensor checked_q(INFINI_METAX_KVCACHE_MLA_PARAMS(Lengths)) { + if (!supports(INFINI_METAX_KVCACHE_MLA_VALUES)) { + throw std::invalid_argument( + "unsupported native MLA KV Attention configuration"); + } + return q; + } + struct Impl; + std::shared_ptr impl_; + void prepare(const Tensor& q, Tensor k_cache, Tensor v_cache, + const std::optional& lengths, + const std::optional& blocks, + const std::optional& scale, + const std::vector& window_size); + void execute(const Tensor& q, Tensor k_cache, Tensor v_cache, + const std::optional& lengths, + const std::optional& blocks, + const std::optional& scale, + const std::vector& window_size, Tensor out) const; +}; + +} // namespace infini::ops + +#undef INFINI_METAX_KVCACHE_MLA_PARAMS +#undef INFINI_METAX_KVCACHE_MLA_VALUES + +#endif // INFINI_OPS_METAX_FLASH_ATTN_WITH_KVCACHE_MLA_KERNEL_H_ diff --git a/src/native/cuda/metax/ops/mul/kernel.h b/src/native/cuda/metax/ops/mul/kernel.h index b80e96843..9fbe984eb 100644 --- a/src/native/cuda/metax/ops/mul/kernel.h +++ b/src/native/cuda/metax/ops/mul/kernel.h @@ -1,19 +1,24 @@ #ifndef INFINI_OPS_METAX_MUL_KERNEL_H_ #define INFINI_OPS_METAX_MUL_KERNEL_H_ -#include - -#include "native/cuda/metax/caster.cuh" +#include "native/cuda/metax/ops/mul/scalar.h" #include "native/cuda/metax/runtime_.h" -#include "native/cuda/ops/mul/kernel.h" +#include "native/cuda/ops/mul/scalar_provider.h" namespace infini::ops { +// The DeepSeek-V2 MoE router scale (routed_scaling_factor) needs the +// scalar `Mul(tensor, double, tensor)` overload; the wrapper wires +// MetaX's header-only scalar kernel into the shared CUDA provider +// skeleton (see scalar_provider.h). The tensor x tensor overload +// comes from `CudaMul` unchanged. template <> class Operator - : public CudaMul> { + : public CudaScalarMulProvider, + MetaxScalarMul> { public: - using CudaMul>::CudaMul; + using CudaScalarMulProvider, + MetaxScalarMul>::CudaScalarMulProvider; }; } // namespace infini::ops diff --git a/src/native/cuda/metax/ops/mul/scalar.h b/src/native/cuda/metax/ops/mul/scalar.h new file mode 100644 index 000000000..d86a44007 --- /dev/null +++ b/src/native/cuda/metax/ops/mul/scalar.h @@ -0,0 +1,146 @@ +#ifndef INFINI_OPS_METAX_MUL_SCALAR_H_ +#define INFINI_OPS_METAX_MUL_SCALAR_H_ + +#include +#include +#include + +#include "native/cuda/caster.cuh" +#include "native/cuda/metax/caster.cuh" +#include "native/cuda/metax/runtime_.h" +#include "native/cuda/ops/mul/kernel.cuh" + +namespace infini::ops::metax_mul_scalar_detail { + +// Shape/strides ride in a fixed-size struct passed by value at launch, +// matching the NVIDIA scalar Mul and the MetaX Matmul-style layouts +// (per_tensor_i8 uses the same pattern): no device metadata buffer, no +// packing/unpacking around the launch. +struct Layout { + std::int64_t ndim = 0; + std::int64_t shape[16]{}; + std::int64_t input_strides[16]{}; + std::int64_t out_strides[16]{}; + bool contiguous = false; +}; + +template +__global__ void MulScalarContiguousKernel(T* __restrict__ out, + const T* __restrict__ input, T alpha, + std::size_t count) { + const auto start = + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const auto step = static_cast(gridDim.x) * blockDim.x; + for (std::size_t linear = start; linear < count; linear += step) { + out[linear] = MulOp{}(input[linear], alpha); + } +} + +template +__global__ void MulScalarStridedKernel(T* __restrict__ out, + const T* __restrict__ input, T alpha, + std::size_t count, Layout layout) { + const auto start = + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const auto step = static_cast(gridDim.x) * blockDim.x; + for (std::size_t linear = start; linear < count; linear += step) { + std::size_t remaining = linear; + std::int64_t input_offset = 0, out_offset = 0; + for (std::int64_t d = layout.ndim; d-- > 0;) { + const auto coord = static_cast( + remaining % static_cast(layout.shape[d])); + remaining /= static_cast(layout.shape[d]); + input_offset += coord * layout.input_strides[d]; + out_offset += coord * layout.out_strides[d]; + } + out[out_offset] = MulOp{}(input[input_offset], alpha); + } +} + +} // namespace infini::ops::metax_mul_scalar_detail + +namespace infini::ops { + +// Scalar-multiplier provider for MetaX: `Mul(tensor, double, tensor)`. +// The shared `CudaMul` only implements the tensor x tensor ctor; the +// scalar ctor there is protected and its `operator()` rejects scalar +// mode, so dispatch of the scalar overload finds no MetaX provider. +// The DeepSeek-V2 MoE router scale (routed_scaling_factor) needs it. +class MetaxScalarMul { + public: + static bool supports(const Tensor input, const double, Tensor out) { + if (input.device().type() != Device::Type::kMetax || + input.device() != out.device() || input.dtype() != out.dtype()) + return false; + switch (input.dtype()) { + case DataType::kFloat16: + case DataType::kBFloat16: + case DataType::kFloat32: + case DataType::kFloat64: + break; + default: + return false; + } + const auto ndim = input.ndim(); + // The by-value Layout carries up to 16 dims (same bound as NVIDIA). + if (ndim > 16 || out.shape() != input.shape() || + out.strides().size() != ndim || input.strides().size() != ndim) + return false; + // The strided kernel indexes linearly over the output; require a + // contiguous output so the linear index maps directly. + return out.IsContiguous(); + } + + MetaxScalarMul(const Tensor input, const double alpha, Tensor out) + : input_meta_(input), out_meta_(out), alpha_(alpha) { + count_ = out.numel(); + layout_.ndim = static_cast(input.ndim()); + layout_.contiguous = input.IsContiguous() && out.IsContiguous(); + for (std::size_t d = 0; d < input.ndim(); ++d) { + layout_.shape[d] = static_cast(input.shape()[d]); + layout_.input_strides[d] = static_cast(input.strides()[d]); + layout_.out_strides[d] = static_cast(out.strides()[d]); + } + } + + void Run(const Tensor input, const double alpha, Tensor out, + typename Runtime::Stream stream) const { + if (!std::equal_to{}(input, input_meta_) || + !std::equal_to{}(out, out_meta_) || alpha != alpha_) + throw std::invalid_argument( + "MetaX scalar Mul metadata or alpha changed after Make"); + if (!count_) return; + DispatchFunc( + {static_cast(input.dtype())}, + [&](auto list_tag) { + using T = TypeMapType(list_tag)>; + const auto scalar = Caster::Cast(alpha_); + auto* d_out = reinterpret_cast(out.data()); + const T* d_input = reinterpret_cast(input.data()); + constexpr unsigned kThreads = 256; + const auto blocks = static_cast( + std::min((count_ - 1) / kThreads + 1, 65535)); + if (layout_.contiguous) { + metax_mul_scalar_detail::MulScalarContiguousKernel + <<>>(d_out, d_input, scalar, + count_); + } else { + metax_mul_scalar_detail::MulScalarStridedKernel + <<>>(d_out, d_input, scalar, + count_, layout_); + } + }, + "MetaxScalarMul::Run"); + } + + private: + Tensor input_meta_; + Tensor out_meta_; + double alpha_; + std::size_t count_{0}; + metax_mul_scalar_detail::Layout layout_{}; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/nvidia/ops/mul/kernel.h b/src/native/cuda/nvidia/ops/mul/kernel.h index c62f55b44..923cbf1da 100644 --- a/src/native/cuda/nvidia/ops/mul/kernel.h +++ b/src/native/cuda/nvidia/ops/mul/kernel.h @@ -1,39 +1,22 @@ #ifndef INFINI_OPS_NVIDIA_MUL_KERNEL_H_ #define INFINI_OPS_NVIDIA_MUL_KERNEL_H_ -#include - -#include "native/cuda/nvidia/caster.cuh" #include "native/cuda/nvidia/ops/mul/scalar.h" -#include "native/cuda/nvidia/runtime_.h" -#include "native/cuda/ops/mul/kernel.h" +#include "native/cuda/ops/mul/scalar_provider.h" namespace infini::ops { +// The scalar `Mul(tensor, double, tensor)` overload is served by the +// shared CUDA provider skeleton (see scalar_provider.h) with +// NVIDIA's launch-side scalar kernel; the tensor x tensor overload +// comes from `CudaMul` unchanged. template <> class Operator - : public CudaMul> { + : public CudaScalarMulProvider, + NvidiaScalarMul> { public: - using CudaMul>::CudaMul; - using CudaMul>::operator(); - Operator(const Tensor input, const double alpha, Tensor out) - : CudaMul>{input, alpha, out}, - scalar_(std::in_place, input, alpha, out) {} - static bool supports(const Tensor input, const double alpha, Tensor out) { - return NvidiaScalarMul::supports(input, alpha, out); - } - void operator()(const Tensor input, const double alpha, - Tensor out) const override { - if (!scalar_) - throw std::invalid_argument("Mul prepared for tensor operands"); - scalar_->Run(input, alpha, out, - static_cast(stream_ ? stream_ : 0)); - } - // All dispatched types use kernels and constructor-owned metadata on replay. - bool capture_safe() const override { return true; } - - private: - std::optional scalar_; + using CudaScalarMulProvider, + NvidiaScalarMul>::CudaScalarMulProvider; }; } // namespace infini::ops diff --git a/src/native/cuda/ops/mul/scalar_provider.h b/src/native/cuda/ops/mul/scalar_provider.h new file mode 100644 index 000000000..3955ef973 --- /dev/null +++ b/src/native/cuda/ops/mul/scalar_provider.h @@ -0,0 +1,53 @@ +#ifndef INFINI_OPS_CUDA_MUL_SCALAR_PROVIDER_H_ +#define INFINI_OPS_CUDA_MUL_SCALAR_PROVIDER_H_ + +#include +#include + +#include "native/cuda/ops/mul/kernel.h" + +namespace infini::ops { + +// Shared operator wrapper for the CUDA-family scalar-multiplier +// `Mul(tensor, double, tensor)` providers. The per-platform +// `ScalarMul` class supplies the actual kernel capture and launch; +// this wrapper only wires the scalar overload into the operator: +// the shared `CudaMul` scalar constructor is protected and its +// tensor `operator()` rejects scalar mode, so without it dispatch +// of the scalar overload finds no provider. +template +class CudaScalarMulProvider : public CudaMul { + public: + using CudaMul::CudaMul; + using CudaMul::operator(); + + CudaScalarMulProvider(const Tensor input, const double alpha, Tensor out) + : CudaMul{input, alpha, out}, + scalar_(std::in_place, input, alpha, out) {} + + static bool supports(const Tensor input, const double alpha, Tensor out) { + return ScalarMul::supports(input, alpha, out); + } + + void operator()(const Tensor input, const double alpha, + Tensor out) const override { + if (!scalar_) + throw std::invalid_argument("Mul prepared for tensor operands"); + // `this->` is required: the base `CudaMul` is dependent, so + // unqualified lookup of the `OperatorBase::stream_` member fails at + // the template definition phase. + scalar_->Run(input, alpha, out, + static_cast( + this->stream_ ? this->stream_ : nullptr)); + } + + // All dispatched types use kernels and constructor-owned metadata on replay. + bool capture_safe() const override { return true; } + + private: + std::optional scalar_; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_MUL_SCALAR_PROVIDER_H_ diff --git a/tests/test_deepseek_moe.py b/tests/test_deepseek_moe.py new file mode 100644 index 000000000..23caf6fd1 --- /dev/null +++ b/tests/test_deepseek_moe.py @@ -0,0 +1,86 @@ +import infini.ops +import pytest +import torch + +from tests.utils import get_stream + +if not hasattr(infini.ops, "DeepseekMoe"): + pytest.skip( + "`DeepseekMoe` is not available on this platform", allow_module_level=True + ) + +# Small config so the reference stays trivially checkable while still +# exercising multiple experts, uneven per-expert loads and float32 weights. +# The 5000-token case crosses the 4096-token chunk boundary of the metax +# provider, so both single- and multi-chunk execution are covered. +_CASES = ( + ((5, 32, 3, 48, 6), torch.float16, 2e-3, 2e-3), + ((5, 32, 3, 48, 6), torch.bfloat16, 4e-3, 4e-3), + ((5000, 32, 3, 48, 6), torch.float16, 2e-3, 2e-3), +) + + +def _reference(hidden, topk_ids, topk_weights, gate, up, down): + """MoE output = sum_k w[t,k] * ((silu(x @ g_e^T) * (x @ u_e^T)) @ d_e^T). + + Matches the provider contract: `topk_ids` selects the expert per route, + `topk_weights` scales each route's contribution before the top-k sum. + """ + out = torch.zeros_like(hidden) + for token in range(hidden.size(0)): + for k in range(topk_ids.size(1)): + expert = int(topk_ids[token, k]) + weight = float(topk_weights[token, k]) + x = hidden[token : token + 1].float() + gate_out = x @ gate[expert].t().float() + up_out = x @ up[expert].t().float() + activated = torch.nn.functional.silu(gate_out) * up_out * weight + out[token] += (activated @ down[expert].t().float())[0] + return out.to(hidden.dtype) + + +@pytest.mark.parametrize("shape_config, dtype, rtol, atol", _CASES) +def test_deepseek_moe(shape_config, dtype, device, rtol, atol): + if device != "cuda": + pytest.skip("deepseek_moe requires an accelerator device") + + ntokens, hidden_dim, topk, intermediate, num_experts = shape_config + torch.manual_seed(42) + # Native device construction avoids the MACA H2D stride bug; the expert + # projections are scaled down so the output stays O(0.1) and rounding + # noise stays far below the tolerance. + hidden = torch.randn((ntokens, hidden_dim), dtype=dtype, device=device) + logits = torch.randn((ntokens, num_experts), dtype=torch.float32, device=device) + topk = torch.topk(logits, topk, dim=1) + topk_ids = topk.indices.to(torch.int32) + topk_weights = torch.softmax(topk.values, dim=1) + gate = [ + torch.randn((intermediate, hidden_dim), dtype=dtype, device=device) * 0.1 + for _ in range(num_experts) + ] + up = [ + torch.randn((intermediate, hidden_dim), dtype=dtype, device=device) * 0.1 + for _ in range(num_experts) + ] + down = [ + torch.randn((hidden_dim, intermediate), dtype=dtype, device=device) * 0.1 + for _ in range(num_experts) + ] + out = torch.full((ntokens, hidden_dim), torch.nan, dtype=dtype, device=device) + + result = infini.ops.deepseek_moe( + out, + hidden, + topk_ids, + topk_weights, + gate, + up, + down, + intermediate, + num_experts, + stream=get_stream(hidden.device), + ) + + assert result is None + expected = _reference(hidden, topk_ids, topk_weights, gate, up, down) + torch.testing.assert_close(out, expected, rtol=rtol, atol=atol) diff --git a/tests/test_mul.py b/tests/test_mul.py index c9cb674a8..7f9c1919c 100644 --- a/tests/test_mul.py +++ b/tests/test_mul.py @@ -150,3 +150,74 @@ def _torch_mul(input, other, out): out.copy_(res.to(out.dtype)) return out + + +# --------------------------------------------------------------------------- +# Scalar multiplier overload: `mul(input, alpha, out)`. The generated bindings +# register the `double` overload on every platform, but providers opt in +# individually (cpu, nvidia and metax ship scalar kernels; others reject the +# dispatch), so probe per case and skip where unsupported. +# --------------------------------------------------------------------------- + + +def _scalar_mul_supported(device) -> bool: + try: + input = torch.zeros((2,), dtype=torch.float32, device=device) + out = torch.empty_like(input) + infini.ops.mul(input, 1.0, out, stream=get_stream(input.device)) + if input.is_cuda: + torch.cuda.synchronize() + return bool((out == 0.0).all()) + except (RuntimeError, ValueError): + return False + + +@pytest.mark.parametrize("alpha", (2.5, -0.5)) +@pytest.mark.parametrize( + "shape, input_strides", + (((13, 4), None), ((13, 4), (10, 1)), ((16, 5632), None)), +) +@pytest.mark.parametrize( + ("dtype", "rtol", "atol"), + ( + (torch.float32, 1e-7, 1e-7), + (torch.float64, 1e-12, 1e-12), + (torch.float16, 1e-3, 1e-3), + (torch.bfloat16, 1e-2, 5e-3), + ), +) +@pytest.mark.auto_act_and_assert +def test_mul_scalar(alpha, shape, input_strides, dtype, device, rtol, atol): + if not _scalar_mul_supported(device): + pytest.skip("scalar `mul` has no provider on this platform") + + if input_strides is not None and device == "cpu": + pytest.skip("cpu scalar `mul` requires contiguous input") + + if input_strides is None: + input = torch.randn(shape, dtype=dtype, device=device) + else: + input = randn_strided(shape, input_strides, dtype=dtype, device=device) + out = torch.empty(shape, dtype=dtype, device=device) + + return Payload( + _mul_scalar, + _torch_mul_scalar, + (input, out), + {"alpha": alpha}, + rtol=rtol, + atol=atol, + ) + + +def _mul_scalar(input, out, *, alpha): + infini.ops.mul(input, alpha, out, stream=get_stream(input.device)) + + return out + + +def _torch_mul_scalar(input, out, *, alpha): + res = torch.mul(input, alpha) + out.copy_(res.to(out.dtype)) + + return out