From 889fa86898f986225757027dd04620463ca166aa Mon Sep 17 00:00:00 2001 From: wooway777 Date: Wed, 25 Nov 2026 09:40:23 +0800 Subject: [PATCH 1/2] feat(mars): add llama flash attention operators --- src/CMakeLists.txt | 20 +++- src/native/cuda/mars/ops/argmax/kernel.cu | 92 +++++++++++++++++++ src/native/cuda/mars/ops/argmax/kernel.h | 70 ++++++++++++++ src/native/cuda/mars/ops/flash_attn_common.h | 86 +++++++++++++++++ .../mars/ops/flash_attn_varlen_func/kernel.cu | 61 ++++++++++++ .../mars/ops/flash_attn_varlen_func/kernel.h | 48 ++++++++++ .../ops/flash_attn_with_kvcache/kernel.cu | 80 ++++++++++++++++ .../mars/ops/flash_attn_with_kvcache/kernel.h | 79 ++++++++++++++++ 8 files changed, 535 insertions(+), 1 deletion(-) create mode 100644 src/native/cuda/mars/ops/argmax/kernel.cu create mode 100644 src/native/cuda/mars/ops/argmax/kernel.h create mode 100644 src/native/cuda/mars/ops/flash_attn_common.h create mode 100644 src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu create mode 100644 src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.h create mode 100644 src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu create mode 100644 src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2765ab70c..2aebb475d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -51,6 +51,20 @@ endfunction() include(GNUInstallDirs) +if(NOT DEFINED INFINI_OPS_JSON_SOURCE_DIR) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../../../json/CMakeLists.txt") + set(INFINI_OPS_JSON_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../json" + CACHE PATH "Offline nlohmann_json source" FORCE) + else() + set(INFINI_OPS_JSON_SOURCE_DIR "" + CACHE PATH "Offline nlohmann_json source" FORCE) + endif() +endif() +if(INFINI_OPS_JSON_SOURCE_DIR) + set(FETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON "${INFINI_OPS_JSON_SOURCE_DIR}" + CACHE PATH "Offline nlohmann_json source" FORCE) +endif() + find_package(nlohmann_json 3.12.0 CONFIG QUIET) if(NOT TARGET nlohmann_json::nlohmann_json) if(POLICY CMP0135) @@ -377,9 +391,10 @@ if(WITH_MARS) "native/cuda/mars/*.cu" ) - file(GLOB_RECURSE MARS_SOURCES CONFIGURE_DEPENDS ${MARS_PATTERNS}) + file(GLOB_RECURSE MARS_SOURCES ${MARS_PATTERNS}) list(FILTER MARS_SOURCES EXCLUDE REGEX ".*/native/cuda/(hygon|iluvatar|metax|moore|nvidia|thead)/.*") + list(FILTER MARS_SOURCES EXCLUDE REGEX "\\.(cc|cpp|cxx)\\.cu$") set_source_files_properties(${MARS_SOURCES} PROPERTIES LANGUAGE CXX) @@ -389,11 +404,14 @@ if(WITH_MARS) target_include_directories(infiniops PUBLIC "${HPCC_PATH}/include" "${HPCC_PATH}/tools/cu-bridge/include") + find_library(HPCC_FLASH_ATTN_LIB NAMES hcFlashAttn + HINTS "${HPCC_PATH}/lib" REQUIRED) target_link_libraries(infiniops PUBLIC ${HPCC_RUNTIME_LIB} ${HPCC_DNN_LIB} ${HPCC_BLAS_LIB} ${HPCC_OMP_LIB} + ${HPCC_FLASH_ATTN_LIB} ) set_property(TARGET infiniops APPEND PROPERTY INSTALL_RPATH "${HPCC_PATH}/htgpu_llvm/lib") diff --git a/src/native/cuda/mars/ops/argmax/kernel.cu b/src/native/cuda/mars/ops/argmax/kernel.cu new file mode 100644 index 000000000..792a1a035 --- /dev/null +++ b/src/native/cuda/mars/ops/argmax/kernel.cu @@ -0,0 +1,92 @@ +#include + +#include +#include +#include + +#include "native/cuda/mars/caster.cuh" +#include "native/cuda/mars/ops/argmax/kernel.h" + +namespace infini::ops::mars_argmax_detail { +namespace { + +__host__ __device__ inline float ToFloat(float value) { return value; } +__host__ __device__ inline float ToFloat(__half value) { + return __half2float(value); +} +__host__ __device__ inline float ToFloat(__hpcc_bfloat16 value) { + return __bfloat162float(value); +} + +template +__global__ void Argmax1DKernel(const TData* input, std::size_t count, + TIndex* out) { + constexpr int kThreads = 256; + __shared__ float values[kThreads]; + __shared__ std::size_t indices[kThreads]; + + const int tid = static_cast(threadIdx.x); + float best = -FLT_MAX; + std::size_t best_index = 0; + for (std::size_t i = tid; i < count; i += kThreads) { + const float value = ToFloat(input[i]); + if (value > best || (value == best && i < best_index)) { + best = value; + best_index = i; + } + } + values[tid] = best; + indices[tid] = best_index; + __syncthreads(); + + for (int stride = kThreads / 2; stride > 0; stride /= 2) { + if (tid < stride) { + const float other = values[tid + stride]; + const std::size_t other_index = indices[tid + stride]; + if (other > values[tid] || + (other == values[tid] && other_index < indices[tid])) { + values[tid] = other; + indices[tid] = other_index; + } + } + __syncthreads(); + } + + if (tid == 0) *out = static_cast(indices[0]); +} + +template +void Submit(const void* input, std::size_t count, void* out, DataType out_dtype, + cudaStream_t stream) { + if (out_dtype == DataType::kInt64) + Argmax1DKernel + <<<1, 256, 0, stream>>>(static_cast(input), count, + static_cast(out)); + else + Argmax1DKernel + <<<1, 256, 0, stream>>>(static_cast(input), count, + static_cast(out)); +} + +} // namespace + +void Launch(const void* input, DataType dtype, std::size_t count, void* out, + DataType out_dtype, cudaStream_t stream) { + if (!count) + throw std::invalid_argument("Mars Argmax requires a nonempty input"); + switch (dtype) { + case DataType::kFloat16: + Submit<__half>(input, count, out, out_dtype, stream); + break; + case DataType::kBFloat16: + Submit<__hpcc_bfloat16>(input, count, out, out_dtype, stream); + break; + case DataType::kFloat32: + Submit(input, count, out, out_dtype, stream); + break; + default: + throw std::invalid_argument("Mars Argmax unsupported dtype"); + } +} + +} // namespace infini::ops::mars_argmax_detail diff --git a/src/native/cuda/mars/ops/argmax/kernel.h b/src/native/cuda/mars/ops/argmax/kernel.h new file mode 100644 index 000000000..c873d74a6 --- /dev/null +++ b/src/native/cuda/mars/ops/argmax/kernel.h @@ -0,0 +1,70 @@ +#ifndef INFINI_OPS_MARS_ARGMAX_KERNEL_H_ +#define INFINI_OPS_MARS_ARGMAX_KERNEL_H_ + +#include + +#include +#include +#include + +#include "base/argmax.h" +#include "native/cuda/mars/runtime_.h" + +namespace infini::ops::mars_argmax_detail { +void Launch(const void* input, DataType dtype, std::size_t count, void* out, + DataType out_dtype, cudaStream_t stream); +} // namespace infini::ops::mars_argmax_detail + +namespace infini::ops { + +template <> +class Operator : public Argmax { + public: + static bool supports(const Tensor input, const std::optional dim, + const bool keepdim, Tensor out) { + return input.device().type() == Device::Type::kMars && + input.device() == out.device() && input.ndim() == 1 && + input.IsContiguous() && out.numel() == 1 && !keepdim && + (!dim.has_value() || *dim == 0) && + (input.dtype() == DataType::kFloat16 || + input.dtype() == DataType::kBFloat16 || + input.dtype() == DataType::kFloat32) && + (out.dtype() == DataType::kInt32 || out.dtype() == DataType::kInt64); + } + + Operator(const Tensor input, const std::optional dim, + const bool keepdim, Tensor out) + : Argmax(Checked(input, dim, keepdim, out), dim, keepdim, out), + input_meta_(input), + out_meta_(out) {} + + bool capture_safe() const override { return true; } + + void operator()(const Tensor input, const std::optional dim, + const bool keepdim, Tensor out) const override { + if (!std::equal_to{}(input, input_meta_) || + !std::equal_to{}(out, out_meta_) || dim != dim_ || + keepdim != keepdim_) + throw std::invalid_argument( + "Mars Argmax metadata or alias changed after Make"); + mars_argmax_detail::Launch( + input.data(), input.dtype(), input.numel(), out.data(), out.dtype(), + static_cast(stream_ ? stream_ : 0)); + } + + private: + static Tensor Checked(const Tensor input, const std::optional& dim, + bool keepdim, Tensor out) { + if (!supports(input, dim, keepdim, out)) + throw std::invalid_argument( + "unsupported Mars Argmax metadata, device or dtype"); + return input; + } + + Tensor input_meta_; + Tensor out_meta_; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_MARS_ARGMAX_KERNEL_H_ diff --git a/src/native/cuda/mars/ops/flash_attn_common.h b/src/native/cuda/mars/ops/flash_attn_common.h new file mode 100644 index 000000000..57a8997ac --- /dev/null +++ b/src/native/cuda/mars/ops/flash_attn_common.h @@ -0,0 +1,86 @@ +#ifndef INFINI_OPS_MARS_FLASH_ATTN_COMMON_H_ +#define INFINI_OPS_MARS_FLASH_ATTN_COMMON_H_ + +#include + +#include +#include +#include +#include +#include + +#include "data_type.h" +#include "tensor.h" + +namespace infini::ops::mars_flash_attn { + +inline hcflashattnDataType_t ToHcDataType(DataType dtype) { + switch (dtype) { + case DataType::kFloat16: + return HCFLASHATTN_DATATYPE_FP16; + case DataType::kBFloat16: + return HCFLASHATTN_DATATYPE_BF16; + case DataType::kInt32: + return HCFLASHATTN_DATATYPE_INT32; + case DataType::kInt64: + return HCFLASHATTN_DATATYPE_INT64; + case DataType::kFloat32: + return HCFLASHATTN_DATATYPE_FP32; + case DataType::kFloat64: + return HCFLASHATTN_DATATYPE_FP64; + default: + throw std::invalid_argument("unsupported HPCC FlashAttention dtype"); + } +} + +inline Tensor_t MakeHcTensor(const Tensor& tensor) { + void* data = const_cast(tensor.data()); + const auto dtype = ToHcDataType(tensor.dtype()); + const auto size = [&tensor](std::size_t index) { + return static_cast(tensor.size(index)); + }; + const auto stride = [&tensor](std::size_t index) { + return static_cast(tensor.stride(index)); + }; + switch (tensor.ndim()) { + case 1: + return make_tensor1d(data, dtype, size(0), stride(0)); + case 2: + return make_tensor2d(data, dtype, size(0), size(1), stride(0), stride(1)); + case 3: + return make_tensor3d(data, dtype, size(0), size(1), size(2), stride(0), + stride(1), stride(2)); + case 4: + return make_tensor4d(data, dtype, size(0), size(1), size(2), size(3), + stride(0), stride(1), stride(2), stride(3)); + default: + throw std::invalid_argument("HPCC FlashAttention requires 1D-4D tensors"); + } +} + +inline void ReleaseHcTensor(Tensor_t& tensor) { + if (tensor) { + release_tensor(tensor); + tensor = nullptr; + } +} + +inline hcStream_t ToHcStream(void* stream) { + return reinterpret_cast(stream); +} + +inline void CheckHcStatus(hcflashattnStatus_t status, const char* call) { + if (status != HCFLASHATTN_STATUS_SUCCESS) + throw std::runtime_error(std::string{"HPCC FlashAttention failed: "} + + call); +} + +inline float SoftmaxScaleOrDefault(const std::optional& scale, + std::size_t head_size) { + return static_cast( + scale.value_or(1.0 / std::sqrt(static_cast(head_size)))); +} + +} // namespace infini::ops::mars_flash_attn + +#endif // INFINI_OPS_MARS_FLASH_ATTN_COMMON_H_ diff --git a/src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu b/src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu new file mode 100644 index 000000000..d04c8be2e --- /dev/null +++ b/src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu @@ -0,0 +1,61 @@ +#include "native/cuda/mars/ops/flash_attn_varlen_func/kernel.h" + +namespace infini::ops { + +void Operator::operator()( + 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) const { + if (!block_table.has_value()) + throw std::invalid_argument( + "Mars FlashAttnVarlenFunc requires a paged block table"); + if (alibi_slopes || softmax_lse || s_dmask || return_attn_probs || + deterministic || dropout_p != 0.0 || softcap != 0.0) + throw std::invalid_argument( + "Mars FlashAttnVarlenFunc supports inference only"); + if (q.dtype() != DataType::kFloat16 && q.dtype() != DataType::kBFloat16) + throw std::invalid_argument( + "Mars FlashAttnVarlenFunc requires float16 or bfloat16"); + + Tensor_t hc_q = mars_flash_attn::MakeHcTensor(q); + Tensor_t hc_k = mars_flash_attn::MakeHcTensor(k); + Tensor_t hc_v = mars_flash_attn::MakeHcTensor(v); + Tensor_t hc_out = mars_flash_attn::MakeHcTensor(out); + Tensor_t hc_cu_q = mars_flash_attn::MakeHcTensor(cu_seqlens_q); + Tensor_t hc_cu_k = mars_flash_attn::MakeHcTensor(cu_seqlens_k); + Tensor_t hc_block_table = mars_flash_attn::MakeHcTensor(*block_table); + hcflashattnExtendParameter_t extend = make_extend_param(); + set_extend_parameter_block_table(extend, + const_cast(block_table->data()), + static_cast(block_table->size(0)), + static_cast(block_table->size(1))); + + const int64_t batch_size = cu_seqlens_q.numel() - 1; + const int64_t total_k = k.size(0) * k.size(1); + const float scale = mars_flash_attn::SoftmaxScaleOrDefault( + softmax_scale, static_cast(q.size(2))); + const auto status = mha_varlen_fwd( + batch_size, q.size(0), q.size(1), total_k, k.size(2), q.size(2), hc_q, + hc_k, hc_v, hc_out, hc_cu_q, hc_cu_k, nullptr, nullptr, nullptr, nullptr, + nullptr, static_cast(max_seqlen_q), static_cast(max_seqlen_k), + 0.0f, scale, causal, static_cast(window_size.at(0)), + static_cast(window_size.at(1)), + mars_flash_attn::ToHcStream(stream_ ? stream_ : nullptr), extend); + + release_extend_param(extend); + mars_flash_attn::ReleaseHcTensor(hc_block_table); + mars_flash_attn::ReleaseHcTensor(hc_cu_k); + mars_flash_attn::ReleaseHcTensor(hc_cu_q); + mars_flash_attn::ReleaseHcTensor(hc_out); + mars_flash_attn::ReleaseHcTensor(hc_v); + mars_flash_attn::ReleaseHcTensor(hc_k); + mars_flash_attn::ReleaseHcTensor(hc_q); + mars_flash_attn::CheckHcStatus(status, "mha_varlen_fwd"); +} + +} // namespace infini::ops diff --git a/src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.h b/src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.h new file mode 100644 index 000000000..46b4493fd --- /dev/null +++ b/src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.h @@ -0,0 +1,48 @@ +#ifndef INFINI_OPS_MARS_FLASH_ATTN_VARLEN_FUNC_KERNEL_H_ +#define INFINI_OPS_MARS_FLASH_ATTN_VARLEN_FUNC_KERNEL_H_ + +#include +#include + +#include "base/flash_attn_varlen_func.h" +#include "native/cuda/mars/ops/flash_attn_common.h" + +namespace infini::ops { + +template <> +class Operator + : public FlashAttnVarlenFunc { + public: + Operator(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) + : FlashAttnVarlenFunc(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) {} + + bool capture_safe() const override { return true; } + + void operator()(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) const override; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_MARS_FLASH_ATTN_VARLEN_FUNC_KERNEL_H_ diff --git a/src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu b/src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu new file mode 100644 index 000000000..02488f007 --- /dev/null +++ b/src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu @@ -0,0 +1,80 @@ +#include "native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h" + +namespace infini::ops { + +void Operator::operator()( + const Tensor, Tensor, Tensor, const std::optional, + const std::optional, const std::optional, + const std::optional, const int64_t, const std::optional, + const std::optional, const std::optional, + const std::optional, const std::optional, const bool, + const std::vector, const double, const bool, const int64_t, + const bool, Tensor, std::optional) const { + throw std::invalid_argument( + "Mars FlashAttnWithKvcache requires tensor cache_seqlens"); +} + +void Operator::operator()( + 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 std::optional 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) const { + if (!cache_seqlens.has_value() || !block_table.has_value()) + throw std::invalid_argument( + "Mars FlashAttnWithKvcache requires paged cache metadata"); + if (k || v || rotary_cos || rotary_sin || cache_batch_idx || cache_leftpad || + alibi_slopes || softmax_lse || return_softmax_lse || softcap != 0.0 || + num_splits < 0) + throw std::invalid_argument( + "Mars FlashAttnWithKvcache supports inference-only paged attention"); + if (q.dtype() != DataType::kFloat16 && q.dtype() != DataType::kBFloat16) + throw std::invalid_argument( + "Mars FlashAttnWithKvcache requires float16 or bfloat16"); + + Tensor_t hc_q = mars_flash_attn::MakeHcTensor(q); + Tensor_t hc_k_cache = mars_flash_attn::MakeHcTensor(k_cache); + Tensor_t hc_v_cache = mars_flash_attn::MakeHcTensor(v_cache); + Tensor_t hc_out = mars_flash_attn::MakeHcTensor(out); + Tensor_t hc_seqlens = mars_flash_attn::MakeHcTensor(*cache_seqlens); + Tensor_t hc_block_table = mars_flash_attn::MakeHcTensor(*block_table); + if (!workspace_) + throw std::invalid_argument( + "Mars FlashAttnWithKvcache requires a softmax_lse workspace"); + const int batch = static_cast(q.size(0)); + const int heads = static_cast(q.size(2)); + const int query_length = static_cast(q.size(1)); + Tensor_t hc_softmax_lse = + make_tensor3d(workspace_, HCFLASHATTN_DATATYPE_FP32, batch, heads, + query_length, heads * query_length, query_length, 1); + const float scale = mars_flash_attn::SoftmaxScaleOrDefault( + softmax_scale, static_cast(q.size(3))); + + const auto status = mha_fwd_kvcache( + hc_q, hc_k_cache, hc_v_cache, nullptr, nullptr, hc_seqlens, nullptr, + nullptr, nullptr, hc_block_table, nullptr, hc_softmax_lse, hc_out, scale, + causal, static_cast(window_size.at(0)), + static_cast(window_size.at(1)), rotary_interleaved, + mars_flash_attn::ToHcStream(stream_ ? stream_ : nullptr), 1, nullptr, + nullptr, nullptr); + + mars_flash_attn::ReleaseHcTensor(hc_softmax_lse); + mars_flash_attn::ReleaseHcTensor(hc_block_table); + mars_flash_attn::ReleaseHcTensor(hc_seqlens); + mars_flash_attn::ReleaseHcTensor(hc_out); + mars_flash_attn::ReleaseHcTensor(hc_v_cache); + mars_flash_attn::ReleaseHcTensor(hc_k_cache); + mars_flash_attn::ReleaseHcTensor(hc_q); + mars_flash_attn::CheckHcStatus(status, "mha_fwd_kvcache"); +} + +} // namespace infini::ops diff --git a/src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h b/src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h new file mode 100644 index 000000000..45a84e402 --- /dev/null +++ b/src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h @@ -0,0 +1,79 @@ +#ifndef INFINI_OPS_MARS_FLASH_ATTN_WITH_KVCACHE_KERNEL_H_ +#define INFINI_OPS_MARS_FLASH_ATTN_WITH_KVCACHE_KERNEL_H_ + +#include +#include + +#include "base/flash_attn_with_kvcache.h" +#include "native/cuda/mars/ops/flash_attn_common.h" + +namespace infini::ops { + +template <> +class Operator + : public FlashAttnWithKvcache { + public: + Operator(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 std::optional 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) + : FlashAttnWithKvcache(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) { + } + + bool capture_safe() const override { return true; } + + std::size_t workspace_size_in_bytes() const override { + if (q_shape_.size() < 3) return 0; + return static_cast(q_shape_[0]) * + static_cast(q_shape_[1]) * + static_cast(q_shape_[2]) * sizeof(float); + } + + void operator()(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 int64_t 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) const override; + + void operator()(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 std::optional 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) const override; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_MARS_FLASH_ATTN_WITH_KVCACHE_KERNEL_H_ From 30227c63450a3ff35b985be9d0de28cdd7befc97 Mon Sep 17 00:00:00 2001 From: wooway777 Date: Wed, 25 Nov 2026 13:01:41 +0800 Subject: [PATCH 2/2] fix(mars): use ATen argmax for llama inference --- scripts/configs/infiniops_ops_mars_llama.json | 175 ++++++++++++++++++ src/CMakeLists.txt | 1 + src/native/cuda/mars/ops/argmax/kernel.cu | 92 --------- src/native/cuda/mars/ops/argmax/kernel.h | 70 ------- src/torch/instantiate.h | 2 +- 5 files changed, 177 insertions(+), 163 deletions(-) create mode 100644 scripts/configs/infiniops_ops_mars_llama.json delete mode 100644 src/native/cuda/mars/ops/argmax/kernel.cu delete mode 100644 src/native/cuda/mars/ops/argmax/kernel.h diff --git a/scripts/configs/infiniops_ops_mars_llama.json b/scripts/configs/infiniops_ops_mars_llama.json new file mode 100644 index 000000000..acfcf1046 --- /dev/null +++ b/scripts/configs/infiniops_ops_mars_llama.json @@ -0,0 +1,175 @@ +{ + "add": { + "implementations": "all" + }, + "argmax": { + "implementations": [ + 8 + ] + }, + "cast": { + "public_api_only": true + }, + "cat": { + "public_api_only": true + }, + "causal_conv1d": { + "public_api_only": true + }, + "chunk_gated_delta_rule": { + "public_api_only": true + }, + "convolution": { + "public_api_only": true + }, + "copy": { + "implementations": "all" + }, + "deepseek_moe": { + "public_api_only": true + }, + "embedding": { + "implementations": "all" + }, + "fill": { + "implementations": "all" + }, + "flash_attn_varlen_func": { + "implementations": "all" + }, + "flash_attn_with_kvcache": { + "implementations": "all" + }, + "fused_add_rms_norm": { + "implementations": "all" + }, + "fused_gated_delta_net_gating": { + "public_api_only": true + }, + "fused_qk_norm": { + "public_api_only": true + }, + "fused_qk_rms_norm": { + "public_api_only": true + }, + "gelu": { + "public_api_only": true + }, + "gemm": { + "implementations": "all" + }, + "i8_gemm": { + "public_api_only": true + }, + "layer_norm": { + "public_api_only": true + }, + "mamba_selective_scan": { + "public_api_only": true + }, + "moe_align_block_size": { + "public_api_only": true + }, + "moe_fused_dense": { + "public_api_only": true + }, + "moe_fused_gate": { + "public_api_only": true + }, + "mrope": { + "public_api_only": true + }, + "mul": { + "implementations": "all" + }, + "pad": { + "public_api_only": true + }, + "paged_attention_infinilm": { + "implementations": "all" + }, + "paged_attention_prefill_infinilm": { + "implementations": "all" + }, + "per_channel_quant_i8": { + "public_api_only": true + }, + "per_tensor_dequant_i8": { + "public_api_only": true + }, + "per_tensor_quant_i8": { + "public_api_only": true + }, + "quick_gelu": { + "public_api_only": true + }, + "recurrent_gated_delta_rule": { + "public_api_only": true + }, + "relu": { + "public_api_only": true + }, + "reshape_and_cache_flash": { + "implementations": "all" + }, + "rms_norm": { + "implementations": "all" + }, + "rotary_embedding": { + "implementations": "all" + }, + "row_l2_normalize": { + "public_api_only": true + }, + "separate_table_rope": { + "public_api_only": true + }, + "sigmoid": { + "public_api_only": true + }, + "silu": { + "public_api_only": true + }, + "silu_and_mul": { + "implementations": "all" + }, + "softmax": { + "public_api_only": true + }, + "sum": { + "public_api_only": true + }, + "take": { + "public_api_only": true + }, + "top_k_top_p_sampling_from_logits": { + "public_api_only": true + }, + "topk_sigmoid": { + "public_api_only": true + }, + "topk_softmax": { + "public_api_only": true + }, + "tril": { + "public_api_only": true + }, + "triu": { + "public_api_only": true + }, + "upsample_bicubic2d": { + "public_api_only": true + }, + "upsample_bilinear2d": { + "public_api_only": true + }, + "w4_marlin_gemm": { + "public_api_only": true + }, + "w4_marlin_parameters": { + "public_api_only": true + }, + "w4_marlin_repack": { + "public_api_only": true + } +} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2aebb475d..258c4c5f3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1244,6 +1244,7 @@ if(TORCH_SOURCES) # Vendor-specific defines required by forked `torch` headers. set(_torch_extra_flags "") + list(APPEND _torch_extra_flags "-DWITH_TORCH=1") if(WITH_METAX) list(APPEND _torch_extra_flags "-DUSE_MACA=1" "-DWITH_METAX=1") endif() diff --git a/src/native/cuda/mars/ops/argmax/kernel.cu b/src/native/cuda/mars/ops/argmax/kernel.cu deleted file mode 100644 index 792a1a035..000000000 --- a/src/native/cuda/mars/ops/argmax/kernel.cu +++ /dev/null @@ -1,92 +0,0 @@ -#include - -#include -#include -#include - -#include "native/cuda/mars/caster.cuh" -#include "native/cuda/mars/ops/argmax/kernel.h" - -namespace infini::ops::mars_argmax_detail { -namespace { - -__host__ __device__ inline float ToFloat(float value) { return value; } -__host__ __device__ inline float ToFloat(__half value) { - return __half2float(value); -} -__host__ __device__ inline float ToFloat(__hpcc_bfloat16 value) { - return __bfloat162float(value); -} - -template -__global__ void Argmax1DKernel(const TData* input, std::size_t count, - TIndex* out) { - constexpr int kThreads = 256; - __shared__ float values[kThreads]; - __shared__ std::size_t indices[kThreads]; - - const int tid = static_cast(threadIdx.x); - float best = -FLT_MAX; - std::size_t best_index = 0; - for (std::size_t i = tid; i < count; i += kThreads) { - const float value = ToFloat(input[i]); - if (value > best || (value == best && i < best_index)) { - best = value; - best_index = i; - } - } - values[tid] = best; - indices[tid] = best_index; - __syncthreads(); - - for (int stride = kThreads / 2; stride > 0; stride /= 2) { - if (tid < stride) { - const float other = values[tid + stride]; - const std::size_t other_index = indices[tid + stride]; - if (other > values[tid] || - (other == values[tid] && other_index < indices[tid])) { - values[tid] = other; - indices[tid] = other_index; - } - } - __syncthreads(); - } - - if (tid == 0) *out = static_cast(indices[0]); -} - -template -void Submit(const void* input, std::size_t count, void* out, DataType out_dtype, - cudaStream_t stream) { - if (out_dtype == DataType::kInt64) - Argmax1DKernel - <<<1, 256, 0, stream>>>(static_cast(input), count, - static_cast(out)); - else - Argmax1DKernel - <<<1, 256, 0, stream>>>(static_cast(input), count, - static_cast(out)); -} - -} // namespace - -void Launch(const void* input, DataType dtype, std::size_t count, void* out, - DataType out_dtype, cudaStream_t stream) { - if (!count) - throw std::invalid_argument("Mars Argmax requires a nonempty input"); - switch (dtype) { - case DataType::kFloat16: - Submit<__half>(input, count, out, out_dtype, stream); - break; - case DataType::kBFloat16: - Submit<__hpcc_bfloat16>(input, count, out, out_dtype, stream); - break; - case DataType::kFloat32: - Submit(input, count, out, out_dtype, stream); - break; - default: - throw std::invalid_argument("Mars Argmax unsupported dtype"); - } -} - -} // namespace infini::ops::mars_argmax_detail diff --git a/src/native/cuda/mars/ops/argmax/kernel.h b/src/native/cuda/mars/ops/argmax/kernel.h deleted file mode 100644 index c873d74a6..000000000 --- a/src/native/cuda/mars/ops/argmax/kernel.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef INFINI_OPS_MARS_ARGMAX_KERNEL_H_ -#define INFINI_OPS_MARS_ARGMAX_KERNEL_H_ - -#include - -#include -#include -#include - -#include "base/argmax.h" -#include "native/cuda/mars/runtime_.h" - -namespace infini::ops::mars_argmax_detail { -void Launch(const void* input, DataType dtype, std::size_t count, void* out, - DataType out_dtype, cudaStream_t stream); -} // namespace infini::ops::mars_argmax_detail - -namespace infini::ops { - -template <> -class Operator : public Argmax { - public: - static bool supports(const Tensor input, const std::optional dim, - const bool keepdim, Tensor out) { - return input.device().type() == Device::Type::kMars && - input.device() == out.device() && input.ndim() == 1 && - input.IsContiguous() && out.numel() == 1 && !keepdim && - (!dim.has_value() || *dim == 0) && - (input.dtype() == DataType::kFloat16 || - input.dtype() == DataType::kBFloat16 || - input.dtype() == DataType::kFloat32) && - (out.dtype() == DataType::kInt32 || out.dtype() == DataType::kInt64); - } - - Operator(const Tensor input, const std::optional dim, - const bool keepdim, Tensor out) - : Argmax(Checked(input, dim, keepdim, out), dim, keepdim, out), - input_meta_(input), - out_meta_(out) {} - - bool capture_safe() const override { return true; } - - void operator()(const Tensor input, const std::optional dim, - const bool keepdim, Tensor out) const override { - if (!std::equal_to{}(input, input_meta_) || - !std::equal_to{}(out, out_meta_) || dim != dim_ || - keepdim != keepdim_) - throw std::invalid_argument( - "Mars Argmax metadata or alias changed after Make"); - mars_argmax_detail::Launch( - input.data(), input.dtype(), input.numel(), out.data(), out.dtype(), - static_cast(stream_ ? stream_ : 0)); - } - - private: - static Tensor Checked(const Tensor input, const std::optional& dim, - bool keepdim, Tensor out) { - if (!supports(input, dim, keepdim, out)) - throw std::invalid_argument( - "unsupported Mars Argmax metadata, device or dtype"); - return input; - } - - Tensor input_meta_; - Tensor out_meta_; -}; - -} // namespace infini::ops - -#endif // INFINI_OPS_MARS_ARGMAX_KERNEL_H_ diff --git a/src/torch/instantiate.h b/src/torch/instantiate.h index 6aab85518..e8950a91d 100644 --- a/src/torch/instantiate.h +++ b/src/torch/instantiate.h @@ -3,7 +3,7 @@ // Emit definitions only for the backends enabled in this translation unit. -#ifdef WITH_CPU +#if defined(WITH_CPU) || defined(WITH_TORCH) #define INFINI_OPS_TORCH_INSTANTIATE_CPU(Op, Index) \ template class Operator; #else