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 2765ab70c..258c4c5f3 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") @@ -1226,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/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_ 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