diff --git a/CMakeLists.txt b/CMakeLists.txt index bf0cb2f4e..864e7bb1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -430,10 +430,10 @@ if(WITH_NINETOOTHED) endif() if(WITH_TRITON) - if(NOT WITH_NVIDIA) + if(NOT WITH_NVIDIA AND NOT WITH_HYGON) message( FATAL_ERROR - "`WITH_TRITON` requires `WITH_NVIDIA=ON` because NVIDIA is the only implemented Triton JIT backend." + "`WITH_TRITON` requires `WITH_NVIDIA=ON` or `WITH_HYGON=ON`." ) endif() if(NOT GENERATE_PYTHON_BINDINGS) diff --git a/THIRD_PARTY.txt b/THIRD_PARTY.txt index e588b1443..3cc8a0337 100644 --- a/THIRD_PARTY.txt +++ b/THIRD_PARTY.txt @@ -113,3 +113,11 @@ from actual package metadata. That conservative package inventory can include materials for components outside these two DSOs; it is intentionally not filtered by fixed hashes or used to restrict build capability. A complete wheel or SDK redistribution must retain its own applicable notices, including secondary ones. + +Clover preview kernels +src/triton/ops/clover_block_conv1d/jit.py and +src/triton/ops/clover_local_memory/jit.py are adapted from SGLang PR #46927, +WilliamZR/sglang commit 058939af24d5cdc44bb4b8852d0ddfab555ed71e, +python/sglang/kernels/ops/{mamba/clover_conv_triton.py,attention/clover_gdn_triton.py}. +They retain Apache-2.0 licensing. Changes provide InfiniOps JIT entry points, +Hygon launch geometry, and bounds checks for the state pool. diff --git a/docs/build-hygon-inference.md b/docs/build-hygon-inference.md new file mode 100644 index 000000000..45d7cd61e --- /dev/null +++ b/docs/build-hygon-inference.md @@ -0,0 +1,76 @@ +# Hygon inference SDK build + +This recipe builds the InfiniRT/InfiniOps/InfiniCCL stack for Hygon DCUs. It +was validated on DTK 26.04 with `gfx936` (BW) devices; other Hygon +architectures need their own validation and their own `HYGON_ARCH`. It is a +build recipe, not a toolkit qualification report. Use the source revisions +pinned by the consuming InfiniCore checkout. + +## Prerequisites + +```sh +source /opt/dtk/env.sh +export CUDA_HOME=/opt/dtk/cuda/cuda +export LD_LIBRARY_PATH="$CUDA_HOME/lib64:$LD_LIBRARY_PATH" +``` + +Consumers that bind Torch must match its C++ ABI (`_GLIBCXX_USE_CXX11_ABI`). +DTK's Triton compiles the HIP target of the device (for example `gfx936`, +wave size 64) on first use; CUDA compute-capability arithmetic does not apply. + +## InfiniRT + +```sh +cmake -S submodules/InfiniRT -B build/rt \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" \ + -DWITH_CPU=ON -DWITH_HYGON=ON +cmake --build build/rt -j 12 +cmake --install build/rt +``` + +## InfiniOps + +`INFINI_OPS_OPS` selects what the build generates. The profile +`scripts/configs/infiniops_ops_hygon_infinilm.json` lists every operator the +InfiniLM model registry references: with the providers of this platform, or +as `public_api_only` where Hygon has none. The latter keep the complete +InfiniLM source compiling while those model families report unsupported at +runtime; they install no substitute kernels. Update the profile when InfiniLM +references another operator or Hygon gains a provider. + +```sh +cmake -S submodules/InfiniOps -B build/ops \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" \ + -DINFINI_RT_ROOT="$INFINI_ROOT" -DWITH_CPU=ON -DWITH_HYGON=ON \ + -DWITH_TRITON=ON -DHYGON_ARCH=gfx936 \ + -DGENERATE_PYTHON_BINDINGS=ON -DGENERATE_OPERATOR_CALL_INSTANTIATIONS=ON \ + -DAUTO_DETECT_DEVICES=OFF -DAUTO_DETECT_BACKENDS=OFF \ + -DINFINI_OPS_OPS="$PWD/scripts/configs/infiniops_ops_hygon_infinilm.json" +cmake --build build/ops -j 12 +cmake --install build/ops +``` + +The Python `infini` package must remain importable: its JIT compiler and +kernel sources stay in use after installation. A CMake install puts the +package contents at the prefix; a wheel installs the namespace normally. + +## InfiniCCL + +```sh +cmake -S submodules/InfiniCCL -B build/ccl \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$INFINI_ROOT" \ + -DWITH_HYGON=ON -DWITH_NCCL=ON \ + -DAUTO_DETECT_DEVICES=OFF -DBUILD_EXAMPLES=OFF +cmake --build build/ccl -j 12 +cmake --install build/ccl +``` + +## Coverage + +With this profile the operators of the dense transformer serving chain, the +standard MoE routing and the fused MoE — native `gfx936` kernels where the +architecture provides them, Triton JIT kernels otherwise — and the Clover +block-diffusion operators have Hygon providers. The model families whose +operators are `public_api_only` in the profile compile but report +unsupported; see the profile for the list. Model-level integration and +serving are documented in the InfiniLM repository. diff --git a/docs/operator-api-alignment.md b/docs/operator-api-alignment.md index 1118420ab..5000349af 100644 --- a/docs/operator-api-alignment.md +++ b/docs/operator-api-alignment.md @@ -238,3 +238,11 @@ unless callers need it. When applying these rules, record the selected upstream interface and any intentional C++ adaptations in the pull request. Follow `CONTRIBUTING.md` for compatibility, testing, and validation requirements. + +## Clover diffusion state operators + +The `Clover*` operators use the released Clover model equations, with packed +request/state-pool arguments for inference; the causal GDN recurrence is the +packed form of `RecurrentGatedDeltaRule`. Each contract is documented in the +operator's base header, and the source provenance of the preview kernels in +`THIRD_PARTY.txt`. diff --git a/scripts/configs/infiniops_ops_hygon_infinilm.json b/scripts/configs/infiniops_ops_hygon_infinilm.json new file mode 100644 index 000000000..632c3b615 --- /dev/null +++ b/scripts/configs/infiniops_ops_hygon_infinilm.json @@ -0,0 +1,194 @@ +{ + "add": { + "implementations": "all" + }, + "argmax": { + "implementations": "all" + }, + "cast": { + "implementations": "all" + }, + "cat": { + "implementations": "all" + }, + "causal_conv1d": { + "implementations": "all" + }, + "chunk_gated_delta_rule": { + "public_api_only": true + }, + "clover_block_conv1d": { + "implementations": "all" + }, + "clover_coreset": { + "implementations": "all" + }, + "clover_live_mask": { + "implementations": "all" + }, + "clover_local_memory": { + "implementations": "all" + }, + "clover_mask_routes": { + "implementations": "all" + }, + "clover_merge_moe": { + "implementations": "all" + }, + "convolution": { + "implementations": "all" + }, + "copy": { + "implementations": "all" + }, + "deepseek_moe": { + "public_api_only": true + }, + "embedding": { + "implementations": "all" + }, + "fill": { + "implementations": "all" + }, + "flash_attn_varlen_func": { + "public_api_only": true + }, + "flash_attn_with_kvcache": { + "public_api_only": true + }, + "fused_add_rms_norm": { + "implementations": "all" + }, + "fused_gated_delta_net_gating": { + "implementations": "all" + }, + "fused_qk_norm": { + "public_api_only": true + }, + "fused_qk_rms_norm": { + "public_api_only": true + }, + "gelu": { + "implementations": "all" + }, + "gemm": { + "implementations": "all" + }, + "i8_gemm": { + "public_api_only": true + }, + "internal_softmax": { + "public_api_only": true + }, + "layer_norm": { + "public_api_only": true + }, + "mamba_selective_scan": { + "public_api_only": true + }, + "matmul_weight_nz": { + "public_api_only": true + }, + "moe_align_block_size": { + "implementations": "all" + }, + "moe_fused_dense": { + "implementations": "all" + }, + "moe_fused_gate": { + "public_api_only": true + }, + "mrope": { + "implementations": "all" + }, + "mul": { + "implementations": "all" + }, + "pad": { + "public_api_only": true + }, + "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": { + "implementations": "all" + }, + "relu": { + "implementations": "all" + }, + "reshape_and_cache_flash": { + "implementations": "all" + }, + "rms_norm": { + "implementations": "all" + }, + "rotary_embedding": { + "implementations": "all" + }, + "row_l2_normalize": { + "implementations": "all" + }, + "separate_table_rope": { + "implementations": "all" + }, + "sigmoid": { + "implementations": "all" + }, + "silu": { + "implementations": "all" + }, + "silu_and_mul": { + "implementations": "all" + }, + "softmax": { + "implementations": "all" + }, + "sum": { + "public_api_only": true + }, + "take": { + "public_api_only": true + }, + "top_k_top_p_sampling_from_logits": { + "implementations": "all" + }, + "topk_sigmoid": { + "public_api_only": true + }, + "topk_softmax": { + "implementations": "all" + }, + "trans_matmul_weight_nz": { + "public_api_only": true + }, + "tril": { + "implementations": "all" + }, + "triu": { + "implementations": "all" + }, + "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/scripts/configs/infiniops_ops_nvidia_infinilm.json b/scripts/configs/infiniops_ops_nvidia_infinilm.json new file mode 100644 index 000000000..e6c61a79b --- /dev/null +++ b/scripts/configs/infiniops_ops_nvidia_infinilm.json @@ -0,0 +1,194 @@ +{ + "add": { + "implementations": "all" + }, + "argmax": { + "implementations": "all" + }, + "cast": { + "implementations": "all" + }, + "cat": { + "implementations": "all" + }, + "causal_conv1d": { + "implementations": "all" + }, + "chunk_gated_delta_rule": { + "implementations": "all" + }, + "clover_block_conv1d": { + "implementations": "all" + }, + "clover_coreset": { + "implementations": "all" + }, + "clover_live_mask": { + "implementations": "all" + }, + "clover_local_memory": { + "implementations": "all" + }, + "clover_mask_routes": { + "implementations": "all" + }, + "clover_merge_moe": { + "implementations": "all" + }, + "convolution": { + "implementations": "all" + }, + "copy": { + "implementations": "all" + }, + "deepseek_moe": { + "implementations": "all" + }, + "embedding": { + "implementations": "all" + }, + "fill": { + "implementations": "all" + }, + "flash_attn_varlen_func": { + "public_api_only": true + }, + "flash_attn_with_kvcache": { + "public_api_only": true + }, + "fused_add_rms_norm": { + "implementations": "all" + }, + "fused_gated_delta_net_gating": { + "implementations": "all" + }, + "fused_qk_norm": { + "implementations": "all" + }, + "fused_qk_rms_norm": { + "implementations": "all" + }, + "gelu": { + "implementations": "all" + }, + "gemm": { + "implementations": "all" + }, + "i8_gemm": { + "implementations": "all" + }, + "internal_softmax": { + "public_api_only": true + }, + "layer_norm": { + "implementations": "all" + }, + "mamba_selective_scan": { + "implementations": "all" + }, + "matmul_weight_nz": { + "public_api_only": true + }, + "moe_align_block_size": { + "implementations": "all" + }, + "moe_fused_dense": { + "implementations": "all" + }, + "moe_fused_gate": { + "implementations": "all" + }, + "mrope": { + "implementations": "all" + }, + "mul": { + "implementations": "all" + }, + "pad": { + "implementations": "all" + }, + "per_channel_quant_i8": { + "implementations": "all" + }, + "per_tensor_dequant_i8": { + "implementations": "all" + }, + "per_tensor_quant_i8": { + "implementations": "all" + }, + "quick_gelu": { + "implementations": "all" + }, + "recurrent_gated_delta_rule": { + "implementations": "all" + }, + "relu": { + "implementations": "all" + }, + "reshape_and_cache_flash": { + "implementations": "all" + }, + "rms_norm": { + "implementations": "all" + }, + "rotary_embedding": { + "implementations": "all" + }, + "row_l2_normalize": { + "implementations": "all" + }, + "separate_table_rope": { + "implementations": "all" + }, + "sigmoid": { + "implementations": "all" + }, + "silu": { + "implementations": "all" + }, + "silu_and_mul": { + "implementations": "all" + }, + "softmax": { + "implementations": "all" + }, + "sum": { + "implementations": "all" + }, + "take": { + "implementations": "all" + }, + "top_k_top_p_sampling_from_logits": { + "implementations": "all" + }, + "topk_sigmoid": { + "implementations": "all" + }, + "topk_softmax": { + "implementations": "all" + }, + "trans_matmul_weight_nz": { + "public_api_only": true + }, + "tril": { + "implementations": "all" + }, + "triu": { + "implementations": "all" + }, + "upsample_bicubic2d": { + "public_api_only": true + }, + "upsample_bilinear2d": { + "implementations": "all" + }, + "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..aa9828f8f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -158,6 +158,11 @@ if(WITH_NVIDIA) ) file(GLOB_RECURSE NVIDIA_SOURCES CONFIGURE_DEPENDS ${NVIDIA_PATTERNS}) + # The recursive top-level `native/cuda/*.cu` pattern also matches sibling + # vendor subtrees (hygon/iluvatar/metax/moore); drop them so their symbols + # are not defined twice when those backends are also enabled. + list(FILTER NVIDIA_SOURCES EXCLUDE REGEX + ".*/native/cuda/(hygon|iluvatar|metax|moore|thead|cambricon|ascend)/.*") # Optional pinned kernels have their own include closure and CUDA TUs. list(FILTER NVIDIA_SOURCES EXCLUDE REGEX "/ops/flash_attn_with_kvcache/") list(FILTER NVIDIA_SOURCES EXCLUDE REGEX "/ops/flash_attn_varlen_func/") @@ -249,7 +254,13 @@ if(WITH_TRITON OR GENERATE_PYTHON_BINDINGS) find_package(pybind11 CONFIG REQUIRED) endif() +if(WITH_TRITON AND WITH_HYGON) + target_link_directories(infiniops PRIVATE "${HYGON_CUDA_ROOT}/lib64") + target_link_libraries(infiniops PRIVATE cuda) +endif() + if(WITH_TRITON) + target_compile_definitions(infiniops PUBLIC WITH_TRITON=1) target_link_libraries(infiniops PRIVATE Python::Python pybind11::headers) @@ -300,6 +311,10 @@ if(WITH_HYGON) enable_language(CUDA) target_compile_definitions(infiniops PUBLIC WITH_HYGON=1) + if(HYGON_ARCH STREQUAL "gfx936") + # The native fused-MoE expert kernels use the matrix instructions of gfx936. + target_compile_definitions(infiniops PRIVATE INFINI_OPS_HYGON_MMAC=1) + endif() target_sources(infiniops PRIVATE ${HYGON_SOURCES}) find_package(CUDAToolkit REQUIRED) diff --git a/src/base/clover_block_conv1d.h b/src/base/clover_block_conv1d.h new file mode 100644 index 000000000..88636eab0 --- /dev/null +++ b/src/base/clover_block_conv1d.h @@ -0,0 +1,56 @@ +#pragma once + +#include "operator.h" + +namespace infini::ops { + +// Block convolution of a Clover preview: a depthwise causal 4-tap +// convolution whose first taps read the clean history of the slot, plus a +// symmetric 3-tap convolution with the following tokens of the block. `input` +// holds `[requests * block_size, channels]` rows in BF16 or FP16, `state` the +// last three inputs of every slot, `indices[r]` the slot of request r and +// `valid` the rows that take part. A row that is invalid, or that belongs to a +// request with an out-of-range slot, outputs zero. `out` is passed through +// SiLU. The state is only read. +class CloverBlockConv1d : public Operator { + public: + CloverBlockConv1d(const Tensor input, const Tensor state, + const Tensor indices, const Tensor weight, + const Tensor right_weight, const Tensor valid, + size_t block_size, Tensor out) { + assert((input.ndim() == 2 && out.shape() == input.shape() && + state.ndim() == 3 && weight.ndim() == 3 && + weight.shape() == Tensor::Shape{input.size(1), 1, 4} && + right_weight.shape() == Tensor::Shape{input.size(1), 1, 3} && + state.size(1) == input.size(1) && state.size(2) == 3 && + indices.ndim() == 1 && block_size > 0 && block_size <= 32 && + input.size(0) == indices.numel() * block_size && + valid.shape() == Tensor::Shape{input.size(0)}) && + "CloverBlockConv1d: invalid block or state shape."); + assert((input.dtype() == DataType::kBFloat16 || + input.dtype() == DataType::kFloat16) && + "CloverBlockConv1d: expected BF16 or FP16 input."); + for (const auto& tensor : {state, weight, right_weight, out}) { + assert(tensor.dtype() == input.dtype() && + "CloverBlockConv1d: input and weight dtypes must match."); + } + assert((indices.dtype() == DataType::kInt32 || + indices.dtype() == DataType::kInt64) && + indices.IsContiguous() && valid.dtype() == DataType::kInt8 && + valid.IsContiguous() && + "CloverBlockConv1d: expected contiguous indices and int8 validity."); + for (const auto& tensor : + {state, indices, weight, right_weight, valid, out}) { + assert(tensor.device() == input.device() && + "CloverBlockConv1d: device mismatch."); + } + assert(!out.HasBroadcastDim() && "CloverBlockConv1d: overlapping output."); + } + + virtual void operator()(const Tensor input, const Tensor state, + const Tensor indices, const Tensor weight, + const Tensor right_weight, const Tensor valid, + size_t block_size, Tensor out) const = 0; +}; + +} // namespace infini::ops diff --git a/src/base/clover_coreset.h b/src/base/clover_coreset.h new file mode 100644 index 000000000..c2b2ad2c3 --- /dev/null +++ b/src/base/clover_coreset.h @@ -0,0 +1,29 @@ +#pragma once + +#include "operator.h" + +namespace infini::ops { + +// Block coreset of the Clover router. For every block of `block_size` rows it +// aggregates the softmax probabilities of the top-8 experts of each row and +// keeps, most massive first, the experts that carry `top_p` of that mass; the +// logits of the other experts become -inf. `logits` and `out` are contiguous +// `[tokens, 256]`. A provider allocates its workspace when the caller provides +// none. +class CloverCoreset : public Operator { + public: + CloverCoreset(const Tensor logits, size_t block_size, double top_p, + Tensor out) { + assert(logits.ndim() == 2 && logits.size(1) == 256 && block_size > 0 && + block_size <= 32 && logits.size(0) % block_size == 0 && + out.shape() == logits.shape() && out.dtype() == logits.dtype() && + logits.IsContiguous() && out.IsContiguous() && + logits.device() == out.device() && top_p > 0 && top_p <= 1 && + "CloverCoreset: invalid logits, block size or routing mass."); + } + + virtual void operator()(const Tensor logits, size_t block_size, double top_p, + Tensor out) const = 0; +}; + +} // namespace infini::ops diff --git a/src/base/clover_live_mask.h b/src/base/clover_live_mask.h new file mode 100644 index 000000000..ac0ce89c9 --- /dev/null +++ b/src/base/clover_live_mask.h @@ -0,0 +1,28 @@ +#pragma once +#include "operator.h" + +namespace infini::ops { + +// Clover-specific interface of the expert-budget decoder, used through the +// C++ API. `ids` holds the token IDs of the current preview and `previous` +// the snapshot of the preceding one; a row is live when either ID is +// `mask_id` or when `refresh` is set. `live` receives 1 or 0 per row and +// `previous` is overwritten with `ids` for the next call. `previous` must be a +// buffer of its own; nothing else is written. +class CloverLiveMask : public Operator { + public: + CloverLiveMask(const Tensor ids, Tensor previous, int64_t mask_id, + bool refresh, Tensor live) { + assert(ids.IsContiguous() && previous.IsContiguous() && + live.IsContiguous() && ids.numel() == previous.numel() && + ids.numel() == live.numel() && ids.dtype() == DataType::kInt64 && + previous.dtype() == ids.dtype() && live.dtype() == DataType::kInt8 && + ids.device() == previous.device() && ids.device() == live.device() && + "CloverLiveMask: invalid token state."); + } + + virtual void operator()(const Tensor ids, Tensor previous, int64_t mask_id, + bool refresh, Tensor live) const = 0; +}; + +} // namespace infini::ops diff --git a/src/base/clover_local_memory.h b/src/base/clover_local_memory.h new file mode 100644 index 000000000..5d1571d72 --- /dev/null +++ b/src/base/clover_local_memory.h @@ -0,0 +1,70 @@ +#pragma once + +#include "operator.h" + +namespace infini::ops { + +// Block attention of a Clover preview: every token of a block attends to the +// valid tokens of the same block and to one bucket that reads the clean state +// of its slot. `q`, `k` and `v` are `[1, tokens, heads, 128]` in BF16 or FP16, +// with the value heads grouped onto the query and key heads; `state` is the +// FP32 `[slots, value_heads, 128, 128]` pool, `g` the FP32 log decay per token +// and value head, `indices[r]` the slot of request r and `valid` the live +// rows. Query and key rows are L2-normalized. The history logit of a token is +// `history_bias + history_c * log(valid_tokens / block_size)` per value head, +// and its value is `exp(g) / sqrt(128)` times the state read. A row that is +// invalid, or that belongs to a request with an out-of-range slot, outputs +// zero. The state is only read. +class CloverLocalMemory : public Operator { + public: + CloverLocalMemory(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + size_t block_size, Tensor out) { + assert((q.ndim() == 4 && q.size(0) == 1 && k.shape() == q.shape() && + v.ndim() == 4 && v.size(0) == 1 && v.size(1) == q.size(1) && + q.size(2) > 0 && v.size(2) > 0 && v.size(2) % q.size(2) == 0 && + q.size(3) == 128 && v.size(3) == 128 && out.shape() == v.shape() && + state.ndim() == 4 && state.size(1) == v.size(2) && + state.size(2) == 128 && state.size(3) == 128 && + indices.ndim() == 1 && block_size > 0 && block_size <= 32 && + q.size(1) == indices.numel() * block_size && + g.shape() == Tensor::Shape{1, q.size(1), v.size(2)} && + valid.shape() == Tensor::Shape{q.size(1)}) && + "CloverLocalMemory: invalid sequence, head or state shape."); + assert( + (q.dtype() == DataType::kBFloat16 || q.dtype() == DataType::kFloat16) && + k.dtype() == q.dtype() && v.dtype() == q.dtype() && + out.dtype() == q.dtype() && state.dtype() == DataType::kFloat32 && + g.dtype() == DataType::kFloat32 && + "CloverLocalMemory: expected reduced data and FP32 state/gates."); + assert((indices.dtype() == DataType::kInt32 || + indices.dtype() == DataType::kInt64) && + indices.IsContiguous() && valid.dtype() == DataType::kInt8 && + valid.IsContiguous() && + "CloverLocalMemory: invalid index/validity dtype."); + for (const auto& scalar : {logit_scale, history_bias, history_c}) { + assert(scalar.ndim() == 1 && scalar.numel() == v.size(2) && + scalar.IsContiguous() && + (scalar.dtype() == q.dtype() || + scalar.dtype() == DataType::kFloat32) && + "CloverLocalMemory: invalid per-head scalars."); + } + for (const auto& tensor : {k, v, g, state, indices, valid, logit_scale, + history_bias, history_c, out}) { + assert(tensor.device() == q.device() && + "CloverLocalMemory: device mismatch."); + } + assert(!out.HasBroadcastDim() && "CloverLocalMemory: overlapping output."); + } + + virtual void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, + const Tensor indices, const Tensor valid, + const Tensor logit_scale, const Tensor history_bias, + const Tensor history_c, size_t block_size, + Tensor out) const = 0; +}; + +} // namespace infini::ops diff --git a/src/base/clover_mask_routes.h b/src/base/clover_mask_routes.h new file mode 100644 index 000000000..9ceec397b --- /dev/null +++ b/src/base/clover_mask_routes.h @@ -0,0 +1,27 @@ +#pragma once +#include "operator.h" + +namespace infini::ops { + +// Clover-specific interface of the expert-budget decoder, used through the +// C++ API. Every expert ID of `ids` (`[rows, topk]`) on a row that is not live +// is replaced by the out-of-range sentinel `num_experts`, which must be the +// expert count of the routed MoE so that its alignment drops the route. `out` +// may be `ids`. +class CloverMaskRoutes : public Operator { + public: + CloverMaskRoutes(const Tensor ids, const Tensor live, int64_t num_experts, + Tensor out) { + assert(ids.ndim() == 2 && ids.IsContiguous() && live.IsContiguous() && + out.IsContiguous() && live.numel() == ids.size(0) && + out.shape() == ids.shape() && ids.dtype() == DataType::kInt32 && + out.dtype() == ids.dtype() && live.dtype() == DataType::kInt8 && + ids.device() == live.device() && ids.device() == out.device() && + "CloverMaskRoutes: invalid routes."); + } + + virtual void operator()(const Tensor ids, const Tensor live, + int64_t num_experts, Tensor out) const = 0; +}; + +} // namespace infini::ops diff --git a/src/base/clover_merge_moe.h b/src/base/clover_merge_moe.h new file mode 100644 index 000000000..afc68f0e5 --- /dev/null +++ b/src/base/clover_merge_moe.h @@ -0,0 +1,29 @@ +#pragma once +#include "operator.h" + +namespace infini::ops { + +// Clover-specific interface of the expert-budget decoder, used through the +// C++ API. A live row takes its fresh routed output, any other row the output +// cached by the preceding call. `out` receives the selection and `cache` is +// updated with it. `out` may alias `fresh` or `cache`; `fresh` and `cache` +// must not alias each other. +class CloverMergeMoe : public Operator { + public: + CloverMergeMoe(const Tensor fresh, const Tensor live, Tensor cache, + Tensor out) { + assert(fresh.ndim() == 2 && live.numel() == fresh.size(0) && + cache.shape() == fresh.shape() && out.shape() == fresh.shape() && + cache.dtype() == fresh.dtype() && out.dtype() == fresh.dtype() && + live.dtype() == DataType::kInt8 && fresh.IsContiguous() && + cache.IsContiguous() && out.IsContiguous() && live.IsContiguous() && + fresh.device() == live.device() && + fresh.device() == cache.device() && fresh.device() == out.device() && + "CloverMergeMoe: invalid cached rows."); + } + + virtual void operator()(const Tensor fresh, const Tensor live, Tensor cache, + Tensor out) const = 0; +}; + +} // namespace infini::ops diff --git a/src/base/recurrent_gated_delta_rule.h b/src/base/recurrent_gated_delta_rule.h index 0df174b80..d1dc0a7be 100644 --- a/src/base/recurrent_gated_delta_rule.h +++ b/src/base/recurrent_gated_delta_rule.h @@ -9,6 +9,34 @@ #include "operator.h" namespace infini::ops { +// Gated delta rule recurrence over a state pool, in two forms. +// +// Batched single-token decode: `q`, `k`, `v` and `out` are `[B, 1, H, D]`. +// Batch item b reads `initial_state[initial_state_indices[b]]`, or +// `initial_state[b]` without indices, and ends in +// `initial_state[final_state_indices[b]]` or in `final_state[b]`. +// +// Packed sequences with an FP32 state: `q`, `k`, `v` and `out` are +// `[1, T, H, 128]` — the head dim of the Clover model, and of both +// providers. Request r owns the tokens `[cu_seqlens[r], cu_seqlens[r+1])` +// and runs the recurrence token by token. State and gates are F32 whatever +// the data dtype is. +// +// State-slot contract of both forms: +// - The initial slot is only read. The final state is written to the final +// slot; when the two differ, the initial slot is left unchanged, so a +// request forks a state instead of moving it. Equal slots update in place. +// - Requests run concurrently. Within one call, final slots must be pairwise +// distinct and must not be the initial slot of any request; several requests +// may read the same initial slot. A separate `final_state` tensor leaves the +// pool read-only. +// - A request with an out-of-range initial or final slot writes nothing to the +// pool and zeroes its output. A packed request with a malformed token range +// leaves its output untouched. +// +// Each step applies `state *= exp(g)`, `state += (v - state @ k) * beta * k` +// and `out = state @ q`. `use_qk_l2norm` L2-normalizes q and k with eps 1e-6; +// q is always scaled by 1/sqrt(D). class RecurrentGatedDeltaRule : public Operator { public: RecurrentGatedDeltaRule(const Tensor q, const Tensor k, const Tensor v, @@ -40,6 +68,29 @@ class RecurrentGatedDeltaRule : public Operator { D_ = q.shape()[3]; pool_ = initial_state.shape()[0]; } + // Packed form; `metadata_` holds [q, k, v, g, beta, state, cu_seqlens, + // initial indices, final indices, out]. + RecurrentGatedDeltaRule(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, + Tensor initial_state, const Tensor cu_seqlens, + const Tensor initial_slots, const Tensor final_slots, + Tensor out, bool use_qk_l2norm) + : norm_(use_qk_l2norm), metadata_{q, k, + v, g, + beta, initial_state, + cu_seqlens, initial_slots, + final_slots, out} { + ValidatePacked(metadata_); + device_ = q.device(); + data_type_ = q.dtype(); + gate_type_ = g.dtype(); + tokens_ = q.shape()[1]; + Hk_ = q.shape()[2]; + Hv_ = v.shape()[2]; + D_ = q.shape()[3]; + pool_ = initial_state.shape()[0]; + requests_ = cu_seqlens.numel() - 1; + } virtual void operator()(const Tensor q, const Tensor k, const Tensor v, const Tensor g, const Tensor beta, Tensor initial_state, @@ -47,13 +98,24 @@ class RecurrentGatedDeltaRule : public Operator { const std::optional final_state_indices, Tensor out, std::optional final_state, bool use_qk_l2norm) const = 0; + // Packed form. Providers that do not implement it keep the default. + virtual void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, + Tensor initial_state, const Tensor cu_seqlens, + const Tensor initial_slots, const Tensor final_slots, + Tensor out, bool use_qk_l2norm) const { + throw std::invalid_argument( + "this RecurrentGatedDeltaRule provider does not support packed " + "sequences"); + } protected: using Views = std::array, 10>; Device device_; DataType data_type_, gate_type_; bool norm_; - size_t B_, Hk_, Hv_, D_, pool_; + size_t B_{0}, Hk_{0}, Hv_{0}, D_{0}, pool_{0}; + size_t tokens_{0}, requests_{0}; const Views metadata_; static bool floating(DataType dtype) { return dtype == DataType::kFloat16 || dtype == DataType::kBFloat16 || @@ -104,6 +166,61 @@ class RecurrentGatedDeltaRule : public Operator { throw std::overflow_error( "recurrent delta pool exceeds int64 index extent"); } + static void ValidatePacked(const Views& a) { + const auto &q = *a[0], &k = *a[1], &v = *a[2], &g = *a[3], &beta = *a[4], + &state = *a[5], &out = *a[9]; + assert(a[6] && a[7] && a[8] && + "packed recurrent delta requires offsets and slot indices"); + assert(q.ndim() == 4 && k.shape() == q.shape() && v.ndim() == 4 && + out.shape() == v.shape() && state.ndim() == 4 && g.ndim() == 3 && + beta.shape() == g.shape() && + "packed recurrent delta rank/shape mismatch"); + const auto T = q.shape()[1], Hk = q.shape()[2], Hv = v.shape()[2], + D = q.shape()[3]; + if (D != 128) + throw std::invalid_argument( + "packed recurrent delta requires a head dim of 128"); + assert((q.shape()[0] == 1 && v.shape()[0] == 1 && v.shape()[1] == T && T && + Hk && Hv && Hv % Hk == 0 && D && v.shape()[3] == D && + g.shape() == Tensor::Shape{1, T, Hv} && state.shape()[1] == Hv && + state.shape()[2] == D && state.shape()[3] == D) && + "packed recurrent delta requires [1,T,H,D] data, Dk == Dv and a " + "[pool,Hv,D,D] state"); + assert(floating(q.dtype()) && state.dtype() == DataType::kFloat32 && + g.dtype() == DataType::kFloat32 && beta.dtype() == g.dtype() && + "packed recurrent delta keeps state and gates in F32"); + assert( + a[6]->numel() >= 2 && a[7]->numel() + 1 == a[6]->numel() && + a[8]->shape() == a[7]->shape() && + "packed recurrent delta requires [N+1] offsets and [N] slot indices"); + for (size_t i = 0; i < a.size(); ++i) { + const auto& t = *a[i]; + assert(t.device() == q.device() && + "packed recurrent delta device mismatch"); + for (auto stride : t.strides()) + assert(stride >= 0 && + "packed recurrent delta negative stride unsupported"); + if (i == 6 || i == 7 || i == 8) { + assert((t.ndim() == 1 && t.IsContiguous() && + (t.dtype() == DataType::kInt32 || + t.dtype() == DataType::kInt64)) && + "packed recurrent delta sequence indices require contiguous " + "I32/I64 vectors"); + } else if (i != 3 && i != 4) { + assert(t.dtype() == q.dtype() && + "packed recurrent delta data dtype mismatch"); + } + assert((!(i <= 2 || i == 9) || t.strides()[3] == 1) && + "packed recurrent delta innermost data dimension must be " + "contiguous"); + assert((!(i == 5 || i == 9) || !t.HasBroadcastDim()) && + "packed recurrent delta broadcast destination unsupported"); + } + if (state.shape()[0] > + static_cast(std::numeric_limits::max())) + throw std::overflow_error( + "recurrent delta pool exceeds int64 index extent"); + } void CheckInvocation(const Views& views, bool norm) const { if (norm != norm_) throw std::invalid_argument( diff --git a/src/common/generic_utils.h b/src/common/generic_utils.h index b34ce8b05..45fad3fbf 100644 --- a/src/common/generic_utils.h +++ b/src/common/generic_utils.h @@ -21,6 +21,15 @@ constexpr auto CeilDiv(const X& x, const Y& y) { return (x + y - 1) / y; } +// log2 of x when x is a power of two, else -1. +template +constexpr int Log2IfPowerOfTwo(const X& x) { + if (x <= 0 || (x & (x - 1)) != 0) return -1; + int shift = 0; + for (X bit = 1; bit != x; bit <<= 1) ++shift; + return shift; +} + } // namespace infini::ops::utils #endif diff --git a/src/native/cuda/hygon/caster.cuh b/src/native/cuda/hygon/caster.cuh index 4b381d03b..901fc1fd5 100644 --- a/src/native/cuda/hygon/caster.cuh +++ b/src/native/cuda/hygon/caster.cuh @@ -7,6 +7,9 @@ namespace infini::ops { +using infini::rt::cuda_bfloat16; +using infini::rt::cuda_bfloat162; + namespace detail { template <> diff --git a/src/native/cuda/hygon/ops/cast/kernel.h b/src/native/cuda/hygon/ops/cast/kernel.h new file mode 100644 index 000000000..25b6e7164 --- /dev/null +++ b/src/native/cuda/hygon/ops/cast/kernel.h @@ -0,0 +1,20 @@ +#ifndef INFINI_OPS_HYGON_CAST_KERNEL_H_ +#define INFINI_OPS_HYGON_CAST_KERNEL_H_ + +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/cast/kernel.h" + +namespace infini::ops { + +// Clover reads gated-delta-net projections through strided views. +template <> +class Operator + : public CudaCast, /*kStridedLayouts=*/true> { + public: + using CudaCast, true>::CudaCast; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_CAST_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/causal_conv1d/kernel.h b/src/native/cuda/hygon/ops/causal_conv1d/kernel.h new file mode 100644 index 000000000..e1aac4dca --- /dev/null +++ b/src/native/cuda/hygon/ops/causal_conv1d/kernel.h @@ -0,0 +1,19 @@ +#ifndef INFINI_OPS_HYGON_CAUSAL_CONV1D_KERNEL_H_ +#define INFINI_OPS_HYGON_CAUSAL_CONV1D_KERNEL_H_ + +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/causal_conv1d/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCausalConv1d> { + public: + using CudaCausalConv1d>::CudaCausalConv1d; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_CAUSAL_CONV1D_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/clover_block_conv1d/kernel.h b/src/native/cuda/hygon/ops/clover_block_conv1d/kernel.h new file mode 100644 index 000000000..6d37f15e7 --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_block_conv1d/kernel.h @@ -0,0 +1,19 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_BLOCK_CONV1D_KERNEL_H_ +#define INFINI_OPS_HYGON_CLOVER_BLOCK_CONV1D_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/clover_block_conv1d/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverBlockConv1d> { + public: + using CudaCloverBlockConv1d< + Runtime>::CudaCloverBlockConv1d; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/hygon/ops/clover_coreset/kernel.h b/src/native/cuda/hygon/ops/clover_coreset/kernel.h new file mode 100644 index 000000000..b9f63c268 --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_coreset/kernel.h @@ -0,0 +1,18 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_CORESET_KERNEL_H_ +#define INFINI_OPS_HYGON_CLOVER_CORESET_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/clover_coreset/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverCoreset> { + public: + using CudaCloverCoreset>::CudaCloverCoreset; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/hygon/ops/clover_live_mask/kernel.h b/src/native/cuda/hygon/ops/clover_live_mask/kernel.h new file mode 100644 index 000000000..6ef6d2fc2 --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_live_mask/kernel.h @@ -0,0 +1,18 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_live_mask_KERNEL_H_ +#define INFINI_OPS_HYGON_CLOVER_live_mask_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/clover_live_mask/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverLiveMask> { + public: + using CudaCloverLiveMask>::CudaCloverLiveMask; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/hygon/ops/clover_local_memory/kernel.h b/src/native/cuda/hygon/ops/clover_local_memory/kernel.h new file mode 100644 index 000000000..8428e8cb6 --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_local_memory/kernel.h @@ -0,0 +1,171 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_LOCAL_MEMORY_KERNEL_H_ +#define INFINI_OPS_HYGON_CLOVER_LOCAL_MEMORY_KERNEL_H_ + +#include +#include + +#include +#include +#include +#include + +#include "base/clover_local_memory.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/ops/clover_local_memory/mma.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/clover_local_memory/kernel.h" + +namespace infini::ops { + +namespace hygon_clover_local_memory_detail { + +// Whether the tensor-core kernel can take the call. It reads the q, k and +// value rows and the state columns as 16-byte vectors, takes the per-head +// scalars in the element type, and maps shared q/k heads with a shift. +inline bool Eligible(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + std::size_t block_size, const Tensor out) { + const auto dtype = q.dtype(); + if (dtype != DataType::kFloat16 && dtype != DataType::kBFloat16) return false; + const auto num_v_heads = static_cast(v.size(2)); + const auto num_q_heads = static_cast(q.size(2)); + const auto num_k_heads = static_cast(k.size(2)); + if (q.size(3) != 128 || k.size(3) != 128 || v.size(3) != 128 || + state.size(2) != 128 || state.size(3) != 128 || + state.size(1) != v.size(2) || block_size == 0 || block_size > 32 || + q.size(1) != k.size(1) || q.size(1) != v.size(1)) + return false; + if (indices.numel() > q.size(1) / block_size) return false; + // The scalars are read in the element type; fp32 scalars stay on the + // shared kernel, which converts them. + if (k.dtype() != dtype || v.dtype() != dtype || out.dtype() != dtype || + logit_scale.dtype() != dtype || history_bias.dtype() != dtype || + history_c.dtype() != dtype || g.dtype() != DataType::kFloat32 || + state.dtype() != DataType::kFloat32 || valid.dtype() != DataType::kInt8 || + (indices.dtype() != DataType::kInt32 && + indices.dtype() != DataType::kInt64)) + return false; + const auto ratio = [num_v_heads](int heads) { + return heads > 0 && num_v_heads % heads == 0 && + ((num_v_heads / heads) & (num_v_heads / heads - 1)) == 0; + }; + if (!ratio(num_q_heads) || !ratio(num_k_heads)) return false; + // Whole 16-byte vectors: 8 elements of the row type per unit, the base + // aligned, and every outer stride keeping the units aligned. + const auto rows = [&dtype](const Tensor t, std::size_t unit) { + if (t.ndim() == 0 || t.strides().back() != 1 || + reinterpret_cast(t.data()) % 16 != 0) + return false; + for (std::size_t axis = 0; axis + 1 < t.ndim(); ++axis) { + const auto stride = t.strides()[axis]; + if (stride < 0 || stride % static_cast(unit) != 0) + return false; + } + return true; + }; + return rows(q, 8) && rows(k, 8) && rows(v, 8) && rows(state, 4) && + rows(out, 1); +} + +// One tiling per request count, from a measured matrix (1 .. 128 requests, +// 16/32/64 columns): one or two requests want the narrow tiling's extra +// blocks per head, every larger batch the wide one's lower staging repeat; +// 16 columns never won. +inline int SelectTiling(std::size_t requests) { return requests <= 2 ? 0 : 1; } + +inline int RatioShift(int num_v_heads, int num_heads) { + int ratio = num_v_heads / num_heads, shift = 0; + while (ratio > 1) { + ratio >>= 1; + ++shift; + } + return shift; +} + +template +bool Launch(const Tensor q, const Tensor k, const Tensor v, const Tensor g, + const Tensor state, const Tensor indices, const Tensor valid, + const Tensor logit_scale, const Tensor history_bias, + const Tensor history_c, std::size_t block_size, Tensor out, + cudaStream_t stream) { + dim3 grid(128 / kCols, static_cast(indices.numel()), + static_cast(v.size(2))); + CloverLocalMemoryMmaKernel + <<>>( + reinterpret_cast(q.data()), + reinterpret_cast(k.data()), + reinterpret_cast(v.data()), + reinterpret_cast(g.data()), + reinterpret_cast(state.data()), + reinterpret_cast(indices.data()), + reinterpret_cast(valid.data()), + reinterpret_cast(logit_scale.data()), + reinterpret_cast(history_bias.data()), + reinterpret_cast(history_c.data()), + reinterpret_cast(out.data()), q.stride(1), q.stride(2), + k.stride(1), k.stride(2), v.stride(1), v.stride(2), g.stride(1), + g.stride(2), state.stride(0), state.stride(1), state.stride(2), + out.stride(1), out.stride(2), out.stride(3), 1.0f / sqrtf(128.0f), + 32.0f, static_cast(block_size), static_cast(state.size(0)), + RatioShift(static_cast(v.size(2)), static_cast(q.size(2))), + RatioShift(static_cast(v.size(2)), static_cast(k.size(2)))); + return cudaGetLastError() == cudaSuccess; +} + +} // namespace hygon_clover_local_memory_detail + +// Hygon takes the MMAC tensor-core kernel where the call's layout allows +// it; every other layout keeps the shared SIMT kernel. +template <> +class Operator + : public CudaCloverLocalMemory> { + public: + using Base = CudaCloverLocalMemory>; + using Base::Base; + + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + size_t block_size, Tensor out) const override { + namespace detail = hygon_clover_local_memory_detail; + const auto requests = indices.numel(); + if (requests != 0 && q.size(1) != 0 && + detail::Eligible(q, k, v, g, state, indices, valid, logit_scale, + history_bias, history_c, block_size, out)) { + const auto stream = static_cast(stream_ ? stream_ : 0); + bool launched = false; + const int tiling = detail::SelectTiling(requests); + DispatchFunc, + List>( + {static_cast(q.dtype()), + static_cast(indices.dtype())}, + [&](auto list_tag) { + using Data = + TypeMapType(list_tag)>; + using Index = + TypeMapType(list_tag)>; + if (tiling == 0) + launched = detail::Launch( + q, k, v, g, state, indices, valid, logit_scale, history_bias, + history_c, block_size, out, stream); + else + launched = detail::Launch( + q, k, v, g, state, indices, valid, logit_scale, history_bias, + history_c, block_size, out, stream); + }, + "HygonCloverLocalMemoryMma::operator()"); + if (launched) return; + } + Base::operator()(q, k, v, g, state, indices, valid, logit_scale, + history_bias, history_c, block_size, out); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_CLOVER_LOCAL_MEMORY_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/clover_local_memory/mma.cuh b/src/native/cuda/hygon/ops/clover_local_memory/mma.cuh new file mode 100644 index 000000000..79703e427 --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_local_memory/mma.cuh @@ -0,0 +1,375 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ +#define INFINI_OPS_HYGON_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ + +#include +#include +#include + +#include +#include +#include + +namespace infini::ops::hygon_clover_local_memory_detail { + +// gfx936 tensor-core kernel for CloverLocalMemory (read-only BD-GDN +// preview), built on the MMAC matrix instructions of the architecture. It +// mirrors the Triton reference at the points that decide the result: the +// normalized q/k rows, the state tile and the softmax weights are rounded +// to the element type before the products, all products accumulate in +// fp32, exp() is the exp2f expansion, and the history term enters the +// value product as its initial accumulator. +// +// One workgroup serves kCols value columns of one (request, value head). +// A wave (64 lanes) owns one 16 x 16 output tile: wave w takes row half +// w & 1 and column tile w >> 1. The two waves of column tile 0 also +// compute their row half's scores and softmax while the state tile is +// being staged; the remaining waves wait that out at the barrier. +// +// The MMAC fragment layouts (verified by a standalone probe): +// A: lane holds A[lane % 16][(lane / 16) * 4 .. +4), +// B: from a [col][k] staging the same four consecutive elements of the +// lane's column, +// C: lane holds C[lane % 16][4 * r + lane / 16] for r = 0 .. 3. +// Fragments are 8-byte reads of the padded k-contiguous rows; every +// product streams its k steps one 16-wide MMAC at a time. +// +// Grid: x = value_dim / kCols, y = requests, z = value heads. The layout +// requirements (contiguous 16-byte aligned q/k/v rows and state columns, +// element-typed per-head scalars, a power-of-two head sharing) are checked +// by the host; anything else takes the shared SIMT kernel. + +constexpr unsigned kWave = 0xffffffffffffffffu; // one wave: 64 lanes +constexpr int kDim = 128; // KEY_DIM == VALUE_DIM == 128 (validated) +constexpr int kRows = 32; // block_size <= 32 (validated) +constexpr int kLd = kDim + 8; // k-contiguous rows, padded +constexpr int kLdW = kRows + 8; // key-contiguous rows, padded + +using V2I = int __attribute__((ext_vector_type(2))); +using V4F = float __attribute__((ext_vector_type(4))); + +template +__device__ __forceinline__ V4F Mma(V2I a, V2I b, V4F c) { + if constexpr (std::is_same_v) { + return __builtin_amdgcn_mmac_f32_16x16x16bf16(a, b, c); + } else { + return __builtin_amdgcn_mmac_f32_16x16x16f16(a, b, c); + } +} + +// An A or B fragment: the four elements at `base + (lane / 16) * 4`. +template +__device__ __forceinline__ V2I Frag(const Data* __restrict__ base, int lane) { + const uint16_t* p = reinterpret_cast(base) + 4 * (lane / 16); + V2I f; + f.x = static_cast((static_cast(p[1]) << 16) | p[0]); + f.y = static_cast((static_cast(p[3]) << 16) | p[2]); + return f; +} + +template +__device__ __forceinline__ uint16_t FromFloat(float f) { + if constexpr (std::is_same_v) { + return __bfloat16_as_ushort(__float2bfloat16_rn(f)); + } else { + return __half_as_ushort(__float2half_rn(f)); + } +} +template +__device__ __forceinline__ float ToFloat(uint16_t bits) { + if constexpr (std::is_same_v) { + return __bfloat162float(__ushort_as_bfloat16(bits)); + } else { + return __half2float(__ushort_as_half(bits)); + } +} +// The per-head scalars, stored in the element type. +template +__device__ __forceinline__ float ReadScalar(const Data* __restrict__ p, + int head) { + return ToFloat(reinterpret_cast(p)[head]); +} + +// ext_vector_type elements cannot be addressed; a switch keeps the access +// compile-time for the unrolled callers. +__device__ __forceinline__ float Get(V4F v, int i) { + return i == 0 ? v.x : i == 1 ? v.y : i == 2 ? v.z : v.w; +} +__device__ __forceinline__ float Get(const float4& v, int i) { + return i == 0 ? v.x : i == 1 ? v.y : i == 2 ? v.z : v.w; +} + +// The reference lowers exp() to the ex2.approx expansion; exp2f is that. +__device__ __forceinline__ float FastExp(float x) { + return exp2f(x * 1.4426950408889634f); +} + +// Stage eight rounded elements of one padded row. +template +__device__ __forceinline__ void Store8(Data* __restrict__ dst, + const float (&x)[8]) { + uint16_t* w = reinterpret_cast(dst); +#pragma unroll + for (int e = 0; e < 8; ++e) w[e] = FromFloat(x[e]); +} + +template +__global__ void __launch_bounds__(kThreads) CloverLocalMemoryMmaKernel( + const Data* __restrict__ q, const Data* __restrict__ k, + const Data* __restrict__ v, const float* __restrict__ g, + const float* __restrict__ state, const Index* __restrict__ indices, + const int8_t* __restrict__ valid, const Data* __restrict__ logit_scale, + const Data* __restrict__ history_bias, const Data* __restrict__ history_c, + Data* __restrict__ out, int64_t q_stride_t, int64_t q_stride_h, + int64_t k_stride_t, int64_t k_stride_h, int64_t v_stride_t, + int64_t v_stride_h, int64_t g_stride_t, int64_t g_stride_h, + int64_t state_slot_stride, int64_t state_h_stride, int64_t state_v_stride, + int64_t out_t_stride, int64_t out_h_stride, int64_t out_v_stride, + float scale, float reference_block_size, int block_size, int num_slots, + int q_head_shift, int k_head_shift) { + constexpr int kTpr = kThreads / kRows; // staging threads per row + constexpr int kChunks = kDim / 8 / kTpr; // 8-element chunks of q/k each + constexpr int kColTiles = kCols / 16; + constexpr int kStateElems = kCols * kDim / kThreads; // state keys staged + static_assert(kThreads == 2 * kColTiles * 64, + "one wave per (row half, column tile)"); + static_assert(kStateElems % 8 == 0, "whole 8-key state chunks"); + + __shared__ __align__(16) Data q_s[kRows * kLd]; // normalized q rows + __shared__ __align__(16) Data k_s[kRows * kLd]; // normalized k rows + __shared__ __align__(16) Data s_s[kCols * kLd]; // state tile, rounded + __shared__ __align__(16) Data v_s[kCols * kLdW]; // values, [col][key] + __shared__ __align__(16) Data w_s[kRows * kLdW]; // softmax weights + __shared__ float history_scale_s[kRows]; + __shared__ int8_t valid_s[kRows]; + + const int c0 = static_cast(blockIdx.x) * kCols; + const int request = static_cast(blockIdx.y); + const int value_head = static_cast(blockIdx.z); + const int tid = static_cast(threadIdx.x); + const int64_t row_base = static_cast(request) * block_size; + const int wave = tid >> 6; + const int lane = tid & 63; + const int row_half = wave & 1; // the wave's output rows + const int col_tile = wave >> 1; // the wave's output columns + const int r = lane % 16; // the lane's tile row + const int half = lane / 16; // its fragment half + const int row = tid / kTpr; // the thread's staging row + const int part = tid % kTpr; + + const Index cache_index = indices[request]; + const bool request_active = num_slots > 0 && cache_index >= 0 && + cache_index < static_cast(num_slots); + Data* const head_out = + out + row_base * out_t_stride + value_head * out_h_stride; + if (!request_active) { + // The reference zeroes every row of an inactive request; rows past the + // block are not written at all. + for (int i = tid; i < kRows * kCols; i += kThreads) { + const int rr = i / kCols; + if (rr < block_size) + head_out[rr * out_t_stride + (c0 + i % kCols) * out_v_stride] = + static_cast(0.0f); + } + return; + } + const int64_t slot = cache_index; + const int q_head = value_head >> q_head_shift; + const int k_head = value_head >> k_head_shift; + const bool row_live = row < block_size; + + // ---- stage the normalized q and k rows and the transposed values ---- + { + const Data* q_src = q + row_base * q_stride_t + q_head * q_stride_h; + const Data* k_src = k + row_base * k_stride_t + k_head * k_stride_h; + float sumsq_q = 0.0f, sumsq_k = 0.0f; + float xq[kChunks][8], xk[kChunks][8]; +#pragma unroll + for (int c = 0; c < kChunks; ++c) { + const uint4 pq = + row_live ? *reinterpret_cast(q_src + row * q_stride_t + + 8 * (c * kTpr + part)) + : make_uint4(0, 0, 0, 0); + const uint4 pk = + row_live ? *reinterpret_cast(k_src + row * k_stride_t + + 8 * (c * kTpr + part)) + : make_uint4(0, 0, 0, 0); + const uint16_t* wq = reinterpret_cast(&pq); + const uint16_t* wk = reinterpret_cast(&pk); +#pragma unroll + for (int e = 0; e < 8; ++e) { + xq[c][e] = ToFloat(wq[e]); + xk[c][e] = ToFloat(wk[e]); + sumsq_q += xq[c][e] * xq[c][e]; + sumsq_k += xk[c][e] * xk[c][e]; + } + } +#pragma unroll + for (int off = 1; off < kTpr; off <<= 1) { + sumsq_q += __shfl_xor_sync(kWave, sumsq_q, off); + sumsq_k += __shfl_xor_sync(kWave, sumsq_k, off); + } + const float norm_q = rsqrtf(sumsq_q + 1.0e-6f); + const float norm_k = rsqrtf(sumsq_k + 1.0e-6f); +#pragma unroll + for (int c = 0; c < kChunks; ++c) { + float rq[8], rk[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + rq[e] = xq[c][e] * norm_q; + rk[e] = xk[c][e] * norm_k; + } + Store8(q_s + row * kLd + 8 * (c * kTpr + part), rq); + Store8(k_s + row * kLd + 8 * (c * kTpr + part), rk); + } + // The values transposed to [col][key]; one 8-element chunk per thread. + const int vpart = tid % (kCols / 8); + const int vrow = tid / (kCols / 8); + if (vrow < kRows) { + const uint4 pv = vrow < block_size + ? *reinterpret_cast( + v + (row_base + vrow) * v_stride_t + + value_head * v_stride_h + c0 + 8 * vpart) + : make_uint4(0, 0, 0, 0); + const uint16_t* wv = reinterpret_cast(&pv); +#pragma unroll + for (int e = 0; e < 8; ++e) + reinterpret_cast(v_s + (8 * vpart + e) * kLdW + vrow)[0] = + wv[e]; + } + } + if (tid < kRows) valid_s[tid] = tid < block_size ? valid[row_base + tid] : 0; + + // The state tile in fp32 registers, converted after the barrier. + const int column = tid % kCols; + const int kgroup = tid / kCols; + float4 s_raw[kStateElems / 4]; + { + const float* s_src = state + slot * state_slot_stride + + value_head * state_h_stride + + (c0 + column) * state_v_stride + kStateElems * kgroup; +#pragma unroll + for (int c = 0; c < kStateElems / 4; ++c) + s_raw[c] = *reinterpret_cast(s_src + 4 * c); + } + // The count is also the barrier the staging above needs; every thread + // computes the history logit for itself, so no lane reads what another + // lane of its wave is still writing (gfx936's __syncwarp does not order + // shared memory). + const float history_logit = + ReadScalar(history_bias, value_head) + + ReadScalar(history_c, value_head) * + logf(fmaxf(static_cast(__syncthreads_count( + tid < block_size && valid[row_base + tid] != 0)), + 1.0f) / + reference_block_size); + + // ---- the rounded state tile ---- + { + Data* dst = s_s + column * kLd + kStateElems * kgroup; +#pragma unroll + for (int c = 0; c < kStateElems / 8; ++c) { + float x[8]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + x[e] = Get(s_raw[2 * c], e); + x[4 + e] = Get(s_raw[2 * c + 1], e); + } + Store8(dst + 8 * c, x); + } + } + // ---- scores and softmax: the column tile 0 waves, once per row half ---- + if (col_tile == 0) { + const float ls = ReadScalar(logit_scale, value_head); + V4F score[2] = {}; // [key tile], lane's C[r][4 * e + half] +#pragma unroll + for (int step = 0; step < kDim / 16; ++step) { + const V2I a = + Frag(q_s + (16 * row_half + r) * kLd + 16 * step, lane); +#pragma unroll + for (int kt = 0; kt < 2; ++kt) { + const V2I b = Frag(k_s + (16 * kt + r) * kLd + 16 * step, lane); + score[kt] = Mma(a, b, score[kt]); + } + } + // A row's 32 logits sit in the four lanes holding it, eight each. + float logit[2][4]; // [key tile][register] + float row_max = -INFINITY; +#pragma unroll + for (int kt = 0; kt < 2; ++kt) { +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int key = 16 * kt + 4 * e + half; + const float value = Get(score[kt], e); + const bool live = key < block_size && valid_s[key] != 0; + logit[kt][e] = live ? value * ls : -INFINITY; + row_max = fmaxf(row_max, logit[kt][e]); + } + } + row_max = fmaxf(row_max, __shfl_xor_sync(kWave, row_max, 16)); + row_max = fmaxf(row_max, __shfl_xor_sync(kWave, row_max, 32)); + row_max = fmaxf(row_max, history_logit); + float local_sum = 0.0f; +#pragma unroll + for (int kt = 0; kt < 2; ++kt) +#pragma unroll + for (int e = 0; e < 4; ++e) { + logit[kt][e] = FastExp(logit[kt][e] - row_max); + local_sum += logit[kt][e]; + } + local_sum += __shfl_xor_sync(kWave, local_sum, 16); + local_sum += __shfl_xor_sync(kWave, local_sum, 32); + const float exp_history = FastExp(history_logit - row_max); + const float inverse = 1.0f / (local_sum + exp_history); + // The reference rounds the local weights to the element type. + Data* w_row = w_s + (16 * row_half + r) * kLdW; +#pragma unroll + for (int kt = 0; kt < 2; ++kt) +#pragma unroll + for (int e = 0; e < 4; ++e) + reinterpret_cast(w_row + 16 * kt + 4 * e + half)[0] = + FromFloat(logit[kt][e] * inverse); + const float gate = + scale * FastExp(g[(row_base + 16 * row_half + r) * g_stride_t + + value_head * g_stride_h]); + history_scale_s[16 * row_half + r] = exp_history * inverse * gate; + } + __syncthreads(); + + // ---- history = q . state, then the values on top of it ---- + V4F result = {}; + { + const Data* q_row = q_s + (16 * row_half + r) * kLd; + const Data* s_col = s_s + (16 * col_tile + r) * kLd; +#pragma unroll + for (int step = 0; step < kDim / 16; ++step) + result = Mma(Frag(q_row + 16 * step, lane), + Frag(s_col + 16 * step, lane), result); + } + const float gain = history_scale_s[16 * row_half + r]; + result *= gain; + { + const Data* w_row = w_s + (16 * row_half + r) * kLdW; + const Data* v_col = v_s + (16 * col_tile + r) * kLdW; +#pragma unroll + for (int step = 0; step < kRows / 16; ++step) + result = Mma(Frag(w_row + 16 * step, lane), + Frag(v_col + 16 * step, lane), result); + } + + // ---- write-back ---- + const int row_abs = 16 * row_half + r; + if (row_abs < block_size) { + const bool keep = valid_s[row_abs] != 0; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const float value = keep ? Get(result, e) : 0.0f; + Data* dst = head_out + row_abs * out_t_stride + + (c0 + 16 * col_tile + 4 * e + half) * out_v_stride; + reinterpret_cast(dst)[0] = FromFloat(value); + } + } +} + +} // namespace infini::ops::hygon_clover_local_memory_detail + +#endif // INFINI_OPS_HYGON_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ diff --git a/src/native/cuda/hygon/ops/clover_mask_routes/kernel.h b/src/native/cuda/hygon/ops/clover_mask_routes/kernel.h new file mode 100644 index 000000000..3a86eae5a --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_mask_routes/kernel.h @@ -0,0 +1,19 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_mask_routes_KERNEL_H_ +#define INFINI_OPS_HYGON_CLOVER_mask_routes_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/clover_mask_routes/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverMaskRoutes> { + public: + using CudaCloverMaskRoutes< + Runtime>::CudaCloverMaskRoutes; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/hygon/ops/clover_merge_moe/kernel.h b/src/native/cuda/hygon/ops/clover_merge_moe/kernel.h new file mode 100644 index 000000000..d8d8c7d88 --- /dev/null +++ b/src/native/cuda/hygon/ops/clover_merge_moe/kernel.h @@ -0,0 +1,18 @@ +#ifndef INFINI_OPS_HYGON_CLOVER_merge_moe_KERNEL_H_ +#define INFINI_OPS_HYGON_CLOVER_merge_moe_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/clover_merge_moe/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverMergeMoe> { + public: + using CudaCloverMergeMoe>::CudaCloverMergeMoe; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/hygon/ops/fill/kernel.h b/src/native/cuda/hygon/ops/fill/kernel.h new file mode 100644 index 000000000..09a9ec9c6 --- /dev/null +++ b/src/native/cuda/hygon/ops/fill/kernel.h @@ -0,0 +1,16 @@ +#pragma once + +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/fill/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaFill> { + public: + using CudaFill>::CudaFill; +}; + +} // namespace infini::ops diff --git a/src/native/cuda/hygon/ops/fused_gated_delta_net_gating/kernel.h b/src/native/cuda/hygon/ops/fused_gated_delta_net_gating/kernel.h new file mode 100644 index 000000000..8be8a0f7f --- /dev/null +++ b/src/native/cuda/hygon/ops/fused_gated_delta_net_gating/kernel.h @@ -0,0 +1,20 @@ +#ifndef INFINI_OPS_HYGON_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ +#define INFINI_OPS_HYGON_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ + +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/fused_gated_delta_net_gating/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaFusedGatedDeltaNetGating> { + public: + using CudaFusedGatedDeltaNetGating< + Runtime>::CudaFusedGatedDeltaNetGating; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/moe_align_block_size/kernel.h b/src/native/cuda/hygon/ops/moe_align_block_size/kernel.h new file mode 100644 index 000000000..4245c4d4f --- /dev/null +++ b/src/native/cuda/hygon/ops/moe_align_block_size/kernel.h @@ -0,0 +1,19 @@ +#ifndef INFINI_OPS_HYGON_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ +#define INFINI_OPS_HYGON_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/moe_align_block_size/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaMoeAlignBlockSize> { + public: + using CudaMoeAlignBlockSize< + Runtime>::CudaMoeAlignBlockSize; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/moe_fused_dense/kernel.cu b/src/native/cuda/hygon/ops/moe_fused_dense/kernel.cu new file mode 100644 index 000000000..c2440ba0e --- /dev/null +++ b/src/native/cuda/hygon/ops/moe_fused_dense/kernel.cu @@ -0,0 +1,183 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "native/cuda/hygon/ops/moe_fused_dense/kernel.h" + +#if defined(INFINI_OPS_HYGON_MMAC) +#include "native/cuda/hygon/ops/moe_fused_dense/kernel.cuh" +#endif + +namespace infini::ops { +namespace { + +class DeviceGuard { + public: + explicit DeviceGuard(int device_index) { + auto status = cudaGetDevice(&previous_device_); + assert(status == cudaSuccess && + "`MoeFusedDense` failed to query the current CUDA device"); + + if (previous_device_ != device_index) { + status = cudaSetDevice(device_index); + assert(status == cudaSuccess && + "`MoeFusedDense` failed to select the input CUDA device"); + restore_ = true; + } + } + + ~DeviceGuard() { + if (restore_) { + const auto status = cudaSetDevice(previous_device_); + assert(status == cudaSuccess && + "`MoeFusedDense` failed to restore the CUDA device"); + } + } + + private: + int previous_device_{0}; + + bool restore_{false}; +}; + +#if defined(INFINI_OPS_HYGON_MMAC) + +// Wavefronts the two streaming kernels are launched with: kWavesPerCu per CU of the device, +// cached per device. Every wavefront owns 8 KB of LDS, so the ones beyond what a CU can host +// would only wait for a slot. +int WavefrontBudget(int device_index) { + constexpr int kCachedDevices = 64; + static std::atomic cached[kCachedDevices]{}; + + int count = 0; + if (device_index >= 0 && device_index < kCachedDevices) { + count = cached[device_index].load(std::memory_order_relaxed); + if (count != 0) return count; + } + const auto status = cudaDeviceGetAttribute( + &count, cudaDevAttrMultiProcessorCount, device_index); + assert(status == cudaSuccess && + "`MoeFusedDense` failed to query the multiprocessor count"); + if (status != cudaSuccess) count = 1; + count = std::max(count, 1) * moe_fused_dense_detail::kWavesPerCu; + if (device_index >= 0 && device_index < kCachedDevices) { + cached[device_index].store(count, std::memory_order_relaxed); + } + return count; +} + +// The three kernels for one element type. A block slot is `block_size` rows of `sorted`; a +// work item covers 16 features (w13) or 32 output rows (w2) of one slot. +template +void Launch(const void* hidden, const void* w13, const void* w2, uint16_t* act, + float* pair_out, uint16_t* output, const float* weights, + const int32_t* ids, const int32_t* sorted, const int32_t* experts, + const int32_t* total, int tokens, int h, int i, int topk, + int num_experts, int slots, int waves, cudaStream_t stream) { + using namespace moe_fused_dense_detail; + const int groups13 = (i + kBlock - 1) / kBlock; + const int groups2 = (h + 2 * kBlock - 1) / (2 * kBlock); + const int items13 = slots * groups13, items2 = slots * groups2; + + W13Kernel<<>>( + static_cast(hidden), + static_cast(w13), act, sorted, experts, total, tokens, + topk, h, i, items13, groups13); + W2Kernel<<>>( + act, static_cast(w2), pair_out, weights, sorted, experts, + total, tokens, topk, h, i, items2, groups2); + CombineKernel<<(tokens)), dim3(256), 0, stream>>>( + pair_out, ids, output, tokens, topk, h, num_experts); + + const auto status = cudaGetLastError(); + assert(status == cudaSuccess && "`MoeFusedDense` CUDA kernel launch failed"); +} + +#endif // INFINI_OPS_HYGON_MMAC + +} // namespace + +namespace moe_fused_dense_detail { + +bool HasNativeKernels() { +#if defined(INFINI_OPS_HYGON_MMAC) + // INFINI_OPS_HYGON_MOE_TRITON=1 keeps the Triton JIT kernels in use instead. + static const bool triton_only = [] { + const char* value = std::getenv("INFINI_OPS_HYGON_MOE_TRITON"); + return value != nullptr && value[0] != '\0' && value[0] != '0'; + }(); + return !triton_only; +#else + return false; +#endif +} + +} // namespace moe_fused_dense_detail + +#if defined(INFINI_OPS_HYGON_MMAC) + +void Operator::Run( + Tensor output, const Tensor hidden, const Tensor w13, const Tensor w2, + const Tensor weights, const Tensor ids, const Tensor sorted, + const Tensor experts, const Tensor total, size_t block_size, + void* scratch) const { + DeviceGuard device_guard{device_index_}; + + const auto stream = static_cast(stream_); + const auto tokens = static_cast(hidden.size(0)), + h = static_cast(hidden.size(1)), i = static_cast(w2.size(2)), + topk = static_cast(ids.size(1)), + slots = static_cast(sorted.numel() / block_size); + // The workspace holds act[pairs, i] in the element type, then the fp32 expert outputs + // [pairs, h]. + moe_detail::Workspace(scratch, workspace_size_in_bytes(), + workspace_size_in_bytes(), + {output, hidden, w13, w2, weights, ids, sorted, experts, + total}); + auto* act = static_cast(scratch); + auto* pair_out = + reinterpret_cast(act + static_cast(tokens) * topk * i); + + const int waves = WavefrontBudget(device_index_); + if (hidden.dtype() == DataType::kBFloat16) { + Launch<__nv_bfloat16>(hidden.data(), w13.data(), w2.data(), act, pair_out, + static_cast(output.data()), + static_cast(weights.data()), + static_cast(ids.data()), + static_cast(sorted.data()), + static_cast(experts.data()), + static_cast(total.data()), tokens, h, i, + topk, static_cast(w13.size(0)), slots, waves, + stream); + } else { + Launch(hidden.data(), w13.data(), w2.data(), act, pair_out, + static_cast(output.data()), + static_cast(weights.data()), + static_cast(ids.data()), + static_cast(sorted.data()), + static_cast(experts.data()), + static_cast(total.data()), tokens, h, i, topk, + static_cast(w13.size(0)), slots, waves, stream); + } +} + +#else + +// Never reached: NativeSupports is false without the matrix instructions. +void Operator::Run( + Tensor, const Tensor, const Tensor, const Tensor, const Tensor, + const Tensor, const Tensor, const Tensor, const Tensor, size_t, + void*) const { + throw std::logic_error( + "`MoeFusedDense` native kernels need a Hygon architecture with matrix " + "instructions"); +} + +#endif // INFINI_OPS_HYGON_MMAC + +} // namespace infini::ops diff --git a/src/native/cuda/hygon/ops/moe_fused_dense/kernel.cuh b/src/native/cuda/hygon/ops/moe_fused_dense/kernel.cuh new file mode 100644 index 000000000..096d4d701 --- /dev/null +++ b/src/native/cuda/hygon/ops/moe_fused_dense/kernel.cuh @@ -0,0 +1,432 @@ +#ifndef INFINI_OPS_HYGON_MOE_FUSED_DENSE_KERNEL_CUH_ +#define INFINI_OPS_HYGON_MOE_FUSED_DENSE_KERNEL_CUH_ + +#include +#include +#include + +#include +#include + +namespace infini::ops::moe_fused_dense_detail { + +// Expert computation of the fused MoE with the matrix instructions of gfx936, +// on the block layout written by MoeAlignBlockSize: sorted[padded row] holds a +// pair index (or the sentinel tokens * topk for padding), experts[block] the +// expert of a block, total[0] the number of padded rows in use. +// +// W13Kernel act[pair, f] = silu(x . w13[e, f, :]) * (x . w13[e, i + f, +// :]) W2Kernel pair[pair, h] = weight[pair] * (act[pair] . w2[expert]^T) +// CombineKernel output[token] = sum over the token's active pairs +// +// One wavefront (64 lanes, one workgroup) streams two 16-row weight bands for +// one expert block: the gate and up rows of 16 features (w13), or two 16-row +// tiles of w2. A k step covers 128 k: +// - every load instruction reads 256 contiguous bytes from each of 4 rows, +// which is what the +// memory system needs to run at its peak bandwidth, +// - the 8 KB step goes through LDS and comes back in the register layout of +// v_mmac_f32_16x16x16_{bf16,f16}: +// A: row = lane % 16, k = (lane / 16) * 4 + 2 * reg + half +// B: col = lane % 16, k as above C: row = lane % 16, col = 4 * +// reg + lane / 16 +// Units of a row are stored XOR-swizzled (unit ^ row) to spread the reads +// over the banks. +// - the loads of step s + 1 are in flight while step s is consumed, and at +// the end of a work +// item they are the first step of the wavefront's next item, whose metadata +// was fetched at the start of the current one: the weight stream never +// drains between items. +// Complete tiles and k steps take a branch-free load path; partial ones at the +// end of a matrix use per-lane predicates. +// +// Requirements: block_size 16, and h and i multiples of 8 (a 16-byte unit holds +// 8 k) of at least 32. + +constexpr int kBlock = 16; // rows of an expert block (block_size) +constexpr int kLanes = 64; // lanes per wavefront; one wavefront per workgroup +constexpr int kUnit = 8; // k values per 16-byte unit +constexpr int kStep = 128; // k values per step: 16 units of a row +constexpr int kBand = 256; // 16-byte units per LDS band: 16 rows x 16 units +constexpr int kWavesPerCu = + 8; // wavefronts launched per CU; each owns 8 KB of LDS + +using V2I = int __attribute__((ext_vector_type(2))); +using V4F = float __attribute__((ext_vector_type(4))); + +// acc += a . b for one 16 x 16 tile over 16 k. +template +__device__ __forceinline__ V4F Mma(V2I a, V2I b, V4F c) { + if constexpr (std::is_same_v) { + return __builtin_amdgcn_mmac_f32_16x16x16bf16(a, b, c); + } else { + return __builtin_amdgcn_mmac_f32_16x16x16f16(a, b, c); + } +} + +// The 16-bit storage of a float, rounded to nearest even. +template +__device__ __forceinline__ uint16_t FromFloat(float f) { + if constexpr (std::is_same_v) { + return __bfloat16_as_ushort(__float2bfloat16_rn(f)); + } else { + return __half_as_ushort(__float2half_rn(f)); + } +} + +template +__device__ __forceinline__ V4F MmaTile(const uint4& w, const uint4& x, + V4F acc) { + acc = Mma((V2I){(int)w.x, (int)w.y}, (V2I){(int)x.x, (int)x.y}, acc); + return Mma((V2I){(int)w.z, (int)w.w}, (V2I){(int)x.z, (int)x.w}, acc); +} + +__device__ __forceinline__ uint4 Zero4() { return make_uint4(0u, 0u, 0u, 0u); } + +__device__ __forceinline__ uint4 Masked(uint4 v, uint32_t keep) { + return make_uint4(v.x & keep, v.y & keep, v.z & keep, v.w & keep); +} + +// LDS slot of the A fragment for accumulator column (4 * c + kg) of the lane's +// row. +__device__ __forceinline__ int Fragment(int slot, int kg, int c) { + return slot * 16 + ((4 * c + kg) ^ slot); +} + +// One work item of a wavefront: 16 features (w13) or 32 output rows (w2) of one +// expert block. Besides the stream's inputs it carries what the epilogue stores +// need: the pair of each accumulator column (4 * r + kg) and, for w2, that +// pair's routing weight. All of it is fetched one item ahead, so no dependent +// load remains once the accumulators are complete. +struct Item { + int block, group, expert, pair, q[4]; + float w[4]; + bool active; +}; + +// Publish one k step to LDS: v[band][g] is row (g * 4 + kg), unit (step * 16 + +// slot). +__device__ __forceinline__ void Publish(uint4* lds, const uint4 (&v)[2][4], + int slot, int kg) { +#pragma unroll + for (int b = 0; b < 2; ++b) { +#pragma unroll + for (int g = 0; g < 4; ++g) { + const int r = g * 4 + kg; + lds[b * kBand + r * 16 + (slot ^ r)] = v[b][g]; + } + } +} + +// Four activation fragments of k step s for the lane's token slot: zero where +// `keep` is 0 and beyond k_total. `x` already includes the lane's k offset (kg +// * kUnit) and always points at a valid row. +__device__ __forceinline__ void LoadX4(uint4 (&xq)[4], + const uint16_t* __restrict__ x, int s, + int k_total, int kg, uint32_t keep) { +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int offset = s * kStep + c * 32; + const bool in_row = offset + kg * kUnit + kUnit <= k_total; + // Beyond k_total a lane reads the last 16 bytes it can reach inside the row + // instead (k_total is at least 32, so there is one for every lane) and is + // masked below. + const uint4 t = *reinterpret_cast( + x + (in_row ? offset : k_total - kg * kUnit - kUnit)); + xq[c] = Masked(t, keep & (in_row ? 0xffffffffu : 0u)); + } +} + +// Weight loads of k step s. Rows and units beyond the matrix are zero. +// kUp: w13, whose second band holds the up rows (i + f); otherwise w2, whose +// second band holds the next 16 output rows. +template +__device__ __forceinline__ void LoadWeights(uint4 (&v)[2][4], + const uint16_t* __restrict__ w, + int expert, int group, + int rows_per_band, int k_total, + int slot, int kg, int s) { + if (expert < 0) { // a block without an expert contributes zeros +#pragma unroll + for (int b = 0; b < 2; ++b) { +#pragma unroll + for (int g = 0; g < 4; ++g) v[b][g] = Zero4(); + } + return; + } + constexpr int kTile = kUp ? kBlock : 2 * kBlock; // rows a work item covers + const int band_rows = kUp ? rows_per_band : kBlock; + const uint16_t* base = + w + + static_cast(expert) * (kUp ? 2 : 1) * rows_per_band * k_total + + static_cast(group * kTile) * k_total; + const bool full = + (group + 1) * kTile <= rows_per_band && (s + 1) * kStep <= k_total; +#pragma unroll + for (int b = 0; b < 2; ++b) { + const uint16_t* band = base + static_cast(b * band_rows) * k_total; +#pragma unroll + for (int g = 0; g < 4; ++g) { + const int row = g * 4 + kg, unit = s * 16 + slot; + const uint16_t* p = + band + static_cast(row) * k_total + unit * kUnit; + if (full) { + v[b][g] = *reinterpret_cast(p); + } else { + const bool ok = + group * kTile + (kUp ? 0 : b * kBlock) + row < rows_per_band && + (unit + 1) * kUnit <= k_total; + v[b][g] = ok ? *reinterpret_cast(p) : Zero4(); + } + } + } +} + +// act[pair, f] = silu(x . w13[e, f, :]) * (x . w13[e, i + f, :]) +template +__global__ __launch_bounds__(kLanes) void W13Kernel( + const uint16_t* __restrict__ hidden, const uint16_t* __restrict__ w13, + uint16_t* __restrict__ act, const int32_t* __restrict__ sorted, + const int32_t* __restrict__ experts, const int32_t* __restrict__ total, + int tokens, int topk, int h, int i, int items, int groups) { + __shared__ __align__(16) uint4 lds[2 * kBand]; + const int slot = threadIdx.x & 15, kg = threadIdx.x >> 4; + const int steps = (h + kStep - 1) / kStep, pairs = tokens * topk; + const int padded = total[0]; + + auto describe = [&](int item) { + Item it{item / groups, 0, -1, 0, {0, 0, 0, 0}, {0.f, 0.f, 0.f, 0.f}, false}; + it.group = item - it.block * groups; + it.active = it.block * kBlock < padded; + if (it.active) { + it.expert = experts[it.block]; + it.pair = sorted[it.block * kBlock + slot]; +#pragma unroll + for (int r = 0; r < 4; ++r) { + it.q[r] = sorted[it.block * kBlock + 4 * r + kg]; + } + } + return it; + }; + auto load = [&](uint4(&v)[2][4], const Item& it, int s) { + LoadWeights(v, w13, it.expert, it.group, i, h, slot, kg, s); + }; + + // The metadata of an item is fetched one item ahead and carried over, and the + // loads of its first k step are issued during the previous item. + int item = blockIdx.x; + Item cur = item < items ? describe(item) : Item{}; + bool pending = false; // v and xq already hold k step 0 of the current item + while (item < items) { + const int next = item + gridDim.x; + Item fut{}; + if (next < items) fut = describe(next); + if (!cur.active) { // block slots beyond the padded rows are empty + item = next; + cur = fut; + pending = false; + continue; + } + const bool x_ok = + cur.expert >= 0 && cur.pair < pairs; // padding holds the sentinel + const uint16_t* x = + hidden + + static_cast(cur.pair < pairs ? cur.pair / topk : 0) * h + + kg * kUnit; + const uint32_t keep = x_ok ? 0xffffffffu : 0u; + uint4 v[2][4], xq[4], xn[4]; + if (!pending) { + load(v, cur, 0); + LoadX4(xq, x, 0, h, kg, keep); + } + V4F acc[2]; + acc[0] = acc[1] = (V4F){0.f, 0.f, 0.f, 0.f}; + for (int s = 0; s < steps; ++s) { + __syncthreads(); // LDS reads of the previous step are complete + Publish(lds, v, slot, kg); + __syncthreads(); + const bool more = s + 1 < steps; + if (more) { + load(v, cur, s + 1); + LoadX4(xn, x, s + 1, h, kg, keep); + } else if (next < items) { + load(v, fut, 0); + LoadX4(xn, + hidden + + static_cast(fut.pair < pairs ? fut.pair / topk : 0) * + h + + kg * kUnit, + 0, h, kg, + fut.expert >= 0 && fut.pair < pairs ? 0xffffffffu : 0u); + } + uint4 wg[4], wu[4]; +#pragma unroll + for (int c = 0; c < 4; ++c) { + wg[c] = lds[Fragment(slot, kg, c)]; + wu[c] = lds[kBand + Fragment(slot, kg, c)]; + } +#pragma unroll + for (int c = 0; c < 4; ++c) { + acc[0] = MmaTile(wg[c], xq[c], acc[0]); + acc[1] = MmaTile(wu[c], xq[c], acc[1]); + } + if (more || next < items) { +#pragma unroll + for (int c = 0; c < 4; ++c) xq[c] = xn[c]; + } + } + const int row = cur.group * kBlock + slot; +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int q = cur.q[r]; + if (q < pairs) { + const float g = acc[0][r]; + const uint16_t value = FromFloat(g / (1.0f + expf(-g)) * acc[1][r]); + if (row < i) act[static_cast(q) * i + row] = value; + } + } + item = next; + cur = fut; + pending = next < items; + } +} + +// pair[pair, h] = weight[pair] * (act[pair] . w2[expert]^T) +template +__global__ __launch_bounds__(kLanes) void W2Kernel( + const uint16_t* __restrict__ act, const uint16_t* __restrict__ w2, + float* __restrict__ pair_out, const float* __restrict__ weights, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ experts, + const int32_t* __restrict__ total, int tokens, int topk, int h, int i, + int items, int groups) { + __shared__ __align__(16) uint4 lds[2 * kBand]; + const int slot = threadIdx.x & 15, kg = threadIdx.x >> 4; + const int steps = (i + kStep - 1) / kStep, pairs = tokens * topk; + const int padded = total[0]; + + auto describe = [&](int item) { + Item it{item / groups, 0, -1, 0, {0, 0, 0, 0}, {0.f, 0.f, 0.f, 0.f}, false}; + it.group = item - it.block * groups; + it.active = it.block * kBlock < padded; + if (it.active) { + it.expert = experts[it.block]; + it.pair = sorted[it.block * kBlock + slot]; +#pragma unroll + for (int r = 0; r < 4; ++r) { + it.q[r] = sorted[it.block * kBlock + 4 * r + kg]; + it.w[r] = it.q[r] < pairs ? weights[it.q[r]] : 0.f; + } + } + return it; + }; + auto load = [&](uint4(&v)[2][4], const Item& it, int s) { + LoadWeights(v, w2, it.expert, it.group, h, i, slot, kg, s); + }; + + // See W13Kernel for the pipelining across items. + int item = blockIdx.x; + Item cur = item < items ? describe(item) : Item{}; + bool pending = false; + while (item < items) { + const int next = item + gridDim.x; + Item fut{}; + if (next < items) fut = describe(next); + if (!cur.active) { + item = next; + cur = fut; + pending = false; + continue; + } + const bool x_ok = cur.expert >= 0 && cur.pair < pairs; + const uint16_t* x = + act + static_cast(cur.pair < pairs ? cur.pair : 0) * i + + kg * kUnit; + const uint32_t keep = x_ok ? 0xffffffffu : 0u; + uint4 v[2][4], xq[4], xn[4]; + if (!pending) { + load(v, cur, 0); + LoadX4(xq, x, 0, i, kg, keep); + } + V4F acc[2]; + acc[0] = acc[1] = (V4F){0.f, 0.f, 0.f, 0.f}; + for (int s = 0; s < steps; ++s) { + __syncthreads(); + Publish(lds, v, slot, kg); + __syncthreads(); + const bool more = s + 1 < steps; + if (more) { + load(v, cur, s + 1); + LoadX4(xn, x, s + 1, i, kg, keep); + } else if (next < items) { + load(v, fut, 0); + LoadX4(xn, + act + static_cast(fut.pair < pairs ? fut.pair : 0) * i + + kg * kUnit, + 0, i, kg, + fut.expert >= 0 && fut.pair < pairs ? 0xffffffffu : 0u); + } + uint4 wt[2][4]; +#pragma unroll + for (int c = 0; c < 4; ++c) { + wt[0][c] = lds[Fragment(slot, kg, c)]; + wt[1][c] = lds[kBand + Fragment(slot, kg, c)]; + } +#pragma unroll + for (int c = 0; c < 4; ++c) { + acc[0] = MmaTile(wt[0][c], xq[c], acc[0]); + acc[1] = MmaTile(wt[1][c], xq[c], acc[1]); + } + if (more || next < items) { +#pragma unroll + for (int c = 0; c < 4; ++c) xq[c] = xn[c]; + } + } + const int row = cur.group * 2 * kBlock + slot; +#pragma unroll + for (int b = 0; b < 2; ++b) { +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int q = cur.q[r]; + if (q < pairs) { + const float value = acc[b][r] * cur.w[r]; + if (row + b * kBlock < h) { + pair_out[static_cast(q) * h + row + b * kBlock] = value; + } + } + } + } + item = next; + cur = fut; + pending = next < items; + } +} + +// output[token] = sum over the token's active routes (the pair_out rows already +// carry their routing weight) +template +__global__ __launch_bounds__(256) void CombineKernel( + const float* __restrict__ pair_out, const int32_t* __restrict__ ids, + uint16_t* __restrict__ out, int tokens, int topk, int h, int num_experts) { + const int token = blockIdx.x; + for (int c = threadIdx.x * 4; c < h; c += blockDim.x * 4) { + float4 sum = make_float4(0.f, 0.f, 0.f, 0.f); + for (int s = 0; s < topk; ++s) { + const int e = ids[token * topk + s]; + if (e < 0 || e >= num_experts) continue; + const float4 v = *reinterpret_cast( + pair_out + static_cast(token * topk + s) * h + c); + sum.x += v.x; + sum.y += v.y; + sum.z += v.z; + sum.w += v.w; + } + const uint2 packed = + make_uint2(FromFloat(sum.x) | (FromFloat(sum.y) << 16), + FromFloat(sum.z) | (FromFloat(sum.w) << 16)); + *reinterpret_cast(out + static_cast(token) * h + c) = + packed; + } +} + +} // namespace infini::ops::moe_fused_dense_detail +#endif // INFINI_OPS_HYGON_MOE_FUSED_DENSE_KERNEL_CUH_ diff --git a/src/native/cuda/hygon/ops/moe_fused_dense/kernel.h b/src/native/cuda/hygon/ops/moe_fused_dense/kernel.h new file mode 100644 index 000000000..4034b8094 --- /dev/null +++ b/src/native/cuda/hygon/ops/moe_fused_dense/kernel.h @@ -0,0 +1,137 @@ +#ifndef INFINI_OPS_HYGON_MOE_FUSED_DENSE_KERNEL_H_ +#define INFINI_OPS_HYGON_MOE_FUSED_DENSE_KERNEL_H_ + +#include +#include +#include + +#include "base/moe_fused_dense.h" +#include "native/cuda/device_buffer.h" + +#if defined(WITH_TRITON) +#include "triton/ops/moe_fused_dense/jit.h" +#endif + +namespace infini::ops { + +namespace moe_fused_dense_detail { + +// Whether the library carries the native expert kernels, i.e. was built for a +// Hygon architecture with the matrix instructions they use, and they are not +// switched off. Defined in kernel.cu, so that every translation unit sees the +// same answer. +bool HasNativeKernels(); + +} // namespace moe_fused_dense_detail + +// Fused MoE expert computation on Hygon. The shapes the native gfx936 kernels +// take (see NativeSupports) run without Triton. With Triton in the build, +// everything else is left to the Triton JIT kernels, whose slot this provider +// shares. +template <> +class Operator : public MoeFusedDense { + public: + Operator(Tensor output, const Tensor hidden, const Tensor w13, + const Tensor w2, const Tensor weights, const Tensor ids, + const Tensor sorted, const Tensor experts, const Tensor total, + size_t block_size, const std::optional bias1 = std::nullopt, + const std::optional bias2 = std::nullopt) + : MoeFusedDense{output, hidden, w13, w2, weights, ids, + sorted, experts, total, block_size, bias1, bias2}, + device_index_{output.device().index()} {} + + // Block size 16 without expert biases, like the Triton kernels. + static bool supports(Tensor output, const Tensor hidden, const Tensor w13, + const Tensor w2, const Tensor weights, const Tensor ids, + const Tensor sorted, const Tensor experts, + const Tensor total, size_t block_size, + const std::optional bias1 = std::nullopt, + const std::optional bias2 = std::nullopt) { + if (block_size != 16 || bias1 || bias2 || + !::infini::ops::MoeFusedDense::supports( + output, hidden, w13, w2, weights, ids, sorted, experts, total, + block_size, bias1, bias2)) { + return false; + } + if (NativeSupports(hidden, w2, block_size, bias1, bias2)) return true; +#if defined(WITH_TRITON) + return true; // the Triton JIT kernels take every shape of the contract + // above +#else + return false; +#endif + } + + // The native kernels need the 16-byte loads of their 128-wide k steps to stay + // inside a row: h and i multiples of 8, at least 32. + static bool NativeSupports(const Tensor& hidden, const Tensor& w2, + size_t block_size, + const std::optional& bias1, + const std::optional& bias2) { + const auto h = hidden.size(1), i = w2.size(2); + return moe_fused_dense_detail::HasNativeKernels() && block_size == 16 && + !bias1 && !bias2 && h >= 32 && h % 8 == 0 && i >= 32 && i % 8 == 0; + } + + // Native: act[pairs, i] in the element type, then the fp32 expert outputs + // [pairs, h]. Triton: [pairs, 2 * i + h] in the element type. + std::size_t workspace_size_in_bytes() const override { + const auto pairs = metadata_[1].size(0) * metadata_[5].size(1); + const auto i = metadata_[3].size(2), h = metadata_[1].size(1); + std::size_t bytes = + pairs * (i * metadata_[1].element_size() + h * sizeof(float)); +#if defined(WITH_TRITON) + bytes = std::max(bytes, pairs * (2 * i + h) * metadata_[1].element_size()); +#endif + return bytes; + } + + void operator()(Tensor output, const Tensor hidden, const Tensor w13, + const Tensor w2, const Tensor weights, const Tensor ids, + const Tensor sorted, const Tensor experts, const Tensor total, + size_t block_size, const std::optional bias1, + const std::optional bias2) const override { + Invocation(output, hidden, w13, w2, weights, ids, sorted, experts, total, + block_size, bias1, bias2); + // The Python bindings call without a handle: use the caller's workspace + // when it is large enough, else a buffer owned by this operator. + void* scratch = + workspace_ && workspace_size_in_bytes_ >= workspace_size_in_bytes() + ? workspace_ + : fallback_.Allocate(workspace_size_in_bytes()); + if (NativeSupports(hidden, w2, block_size, bias1, bias2)) { + Run(output, hidden, w13, w2, weights, ids, sorted, experts, total, + block_size, scratch); + return; + } +#if defined(WITH_TRITON) + triton::jit::MoeFusedDense fallback{ + output, hidden, w13, w2, weights, ids, + sorted, experts, total, block_size, bias1, bias2}; + fallback.set_stream(stream_); + fallback.set_workspace(scratch); + fallback.set_workspace_size_in_bytes(workspace_size_in_bytes()); + fallback(output, hidden, w13, w2, weights, ids, sorted, experts, total, + block_size, bias1, bias2); +#else + throw std::invalid_argument( + "`MoeFusedDense` on Hygon needs h and i to be multiples of 8 of at " + "least 32"); +#endif + } + + protected: + void Run(Tensor output, const Tensor hidden, const Tensor w13, + const Tensor w2, const Tensor weights, const Tensor ids, + const Tensor sorted, const Tensor experts, const Tensor total, + size_t block_size, void* scratch) const; + + private: + int device_index_; + + mutable CudaDeviceBuffer> fallback_; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_MOE_FUSED_DENSE_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/mrope/kernel.h b/src/native/cuda/hygon/ops/mrope/kernel.h new file mode 100644 index 000000000..7808c0627 --- /dev/null +++ b/src/native/cuda/hygon/ops/mrope/kernel.h @@ -0,0 +1,12 @@ +#pragma once +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/mrope/kernel.h" +namespace infini::ops { +template <> +class Operator + : public CudaMrope> { + public: + using CudaMrope>::CudaMrope; +}; +} // namespace infini::ops diff --git a/src/native/cuda/hygon/ops/mul/kernel.h b/src/native/cuda/hygon/ops/mul/kernel.h new file mode 100644 index 000000000..b949617a7 --- /dev/null +++ b/src/native/cuda/hygon/ops/mul/kernel.h @@ -0,0 +1,16 @@ +#pragma once + +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/mul/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaMul> { + public: + using CudaMul>::CudaMul; +}; + +} // namespace infini::ops diff --git a/src/native/cuda/hygon/ops/recurrent_gated_delta_rule/kernel.h b/src/native/cuda/hygon/ops/recurrent_gated_delta_rule/kernel.h new file mode 100644 index 000000000..169175f5f --- /dev/null +++ b/src/native/cuda/hygon/ops/recurrent_gated_delta_rule/kernel.h @@ -0,0 +1,20 @@ +#ifndef INFINI_OPS_HYGON_RECURRENT_GATED_DELTA_RULE_KERNEL_H_ +#define INFINI_OPS_HYGON_RECURRENT_GATED_DELTA_RULE_KERNEL_H_ + +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/recurrent_gated_delta_rule/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaRecurrentGatedDeltaRule> { + public: + using CudaRecurrentGatedDeltaRule< + Runtime>::CudaRecurrentGatedDeltaRule; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_RECURRENT_GATED_DELTA_RULE_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/separate_table_rope/kernel.h b/src/native/cuda/hygon/ops/separate_table_rope/kernel.h new file mode 100644 index 000000000..d4aa1316e --- /dev/null +++ b/src/native/cuda/hygon/ops/separate_table_rope/kernel.h @@ -0,0 +1,27 @@ +#ifndef INFINI_OPS_HYGON_SEPARATE_TABLE_ROPE_KERNEL_H_ +#define INFINI_OPS_HYGON_SEPARATE_TABLE_ROPE_KERNEL_H_ +#include "native/cuda/hygon/caster.cuh" +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/separate_table_rope/kernel.h" +namespace infini::ops { +template <> +class Operator + : public CudaSeparateTableRope> { + public: + using CudaSeparateTableRope< + Runtime>::CudaSeparateTableRope; + void operator()(const Tensor x, const Tensor p, const Tensor s, + const Tensor c, bool neox, Tensor y) const override { + CudaSeparateTableRope>::operator()(x, p, s, c, + neox, y); + if (x.numel() == 0) return; + // Same native HYGON launch-error API used by the installed Argmax source. + // Peek reports immediate launch failure; it does not synchronize or claim + // that device data access / position bounds are valid. + const auto status = cudaPeekAtLastError(); + if (status != cudaSuccess) + throw std::runtime_error(cudaGetErrorString(status)); + } +}; +} // namespace infini::ops +#endif diff --git a/src/native/cuda/hygon/ops/tril/kernel.h b/src/native/cuda/hygon/ops/tril/kernel.h new file mode 100644 index 000000000..532ccd490 --- /dev/null +++ b/src/native/cuda/hygon/ops/tril/kernel.h @@ -0,0 +1,20 @@ +#ifndef INFINI_OPS_HYGON_TRIL_KERNEL_H_ +#define INFINI_OPS_HYGON_TRIL_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/triangular/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public triangular_detail::CudaTriangular, + Tril, false> { + public: + using triangular_detail::CudaTriangular, Tril, + false>::CudaTriangular; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_TRIL_KERNEL_H_ diff --git a/src/native/cuda/hygon/ops/triu/kernel.h b/src/native/cuda/hygon/ops/triu/kernel.h new file mode 100644 index 000000000..aa237ba7a --- /dev/null +++ b/src/native/cuda/hygon/ops/triu/kernel.h @@ -0,0 +1,20 @@ +#ifndef INFINI_OPS_HYGON_TRIU_KERNEL_H_ +#define INFINI_OPS_HYGON_TRIU_KERNEL_H_ + +#include "native/cuda/hygon/runtime_.h" +#include "native/cuda/ops/triangular/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public triangular_detail::CudaTriangular, + Triu, true> { + public: + using triangular_detail::CudaTriangular, Triu, + true>::CudaTriangular; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_HYGON_TRIU_KERNEL_H_ diff --git a/src/native/cuda/nvidia/ops/cast/kernel.h b/src/native/cuda/nvidia/ops/cast/kernel.h index 7bd6a4aa5..8492dc5b0 100644 --- a/src/native/cuda/nvidia/ops/cast/kernel.h +++ b/src/native/cuda/nvidia/ops/cast/kernel.h @@ -1,147 +1,19 @@ #ifndef INFINI_OPS_NVIDIA_CAST_KERNEL_H_ #define INFINI_OPS_NVIDIA_CAST_KERNEL_H_ -#include - -#include -#include -#include -#include -#include - -#include "base/cast.h" #include "native/cuda/nvidia/caster.cuh" +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/cast/kernel.h" namespace infini::ops { -namespace nvidia_cast_detail { -template -__global__ void Convert(const InT* input, OutT* out, std::size_t first, - std::size_t count) { - const auto local = - static_cast(blockIdx.x) * blockDim.x + threadIdx.x; - if (local < count) - out[first + local] = Caster::template Cast( - input[first + local]); -} -} // namespace nvidia_cast_detail template <> -class Operator : public Cast { +class Operator + : public CudaCast> { public: - static bool supports(const Tensor input, Tensor out) { - if (input.device().type() != Device::Type::kNvidia || - input.device() != out.device() || input.shape() != out.shape() || - !SupportedDtype(input.dtype()) || !SupportedDtype(out.dtype())) - return false; - std::size_t input_bytes = 0, out_bytes = 0; - if (!ContiguousBytes(input, &input_bytes) || - !ContiguousBytes(out, &out_bytes) || - !ValidAddress(input, input_bytes) || !ValidAddress(out, out_bytes)) - return false; - int current = -1; - if (cudaGetDevice(¤t) != cudaSuccess || - current != input.device().index()) - return false; - const auto ip = reinterpret_cast(input.data()); - const auto op = reinterpret_cast(out.data()); - const bool overlap = input_bytes && out_bytes && ip < op + out_bytes && - op < ip + input_bytes; - return !overlap || SameView(input, out); - } - - Operator(const Tensor input, Tensor out) - : Cast{Checked(input, out), out}, device_{input.device()} {} - - void operator()(const Tensor input, Tensor out) const override { - if (input.dtype() != input_dtype_ || out.dtype() != out_dtype_ || - input.shape() != input_shape_ || out.shape() != out_shape_ || - input.strides() != input_strides_ || out.strides() != out_strides_ || - input.device() != device_ || !supports(input, out)) - throw std::invalid_argument( - "NVIDIA Cast: call metadata or alias changed after Make"); - if (output_size_ == 0 || SameView(input, out)) return; - const auto stream = static_cast(stream_); - DispatchFunc< - List, - List>( - {static_cast(input_dtype_), static_cast(out_dtype_)}, - [&](auto list_tag) { - using InT = TypeMapType(list_tag)>; - using OutT = TypeMapType(list_tag)>; - constexpr std::size_t cap = 65535u * 256u; - for (std::size_t first = 0; first < output_size_;) { - const auto count = std::min(cap, output_size_ - first); - const auto blocks = static_cast((count + 255) / 256); - nvidia_cast_detail::Convert<<>>( - static_cast(input.data()), - static_cast(out.data()), first, count); - const auto status = cudaGetLastError(); - if (status != cudaSuccess) - throw std::runtime_error( - std::string("NVIDIA Cast: launch failed: ") + - cudaGetErrorString(status)); - first += count; - } - }, - "NVIDIA Cast"); - } - - private: - static bool SupportedDtype(DataType type) { - return type == DataType::kFloat32 || type == DataType::kFloat16 || - type == DataType::kBFloat16; - } - - static std::size_t Width(DataType type) { - return type == DataType::kFloat32 ? 4u : 2u; - } - - static bool ContiguousBytes(const Tensor t, std::size_t* bytes) { - if (t.shape().size() != t.strides().size()) return false; - bool empty = false; - for (std::size_t axis = 0; axis < t.ndim(); ++axis) { - if (t.stride(axis) < 0) return false; - empty = empty || t.size(axis) == 0; - } - if (empty) { - *bytes = 0; - return true; - } - const auto limit = - static_cast(std::numeric_limits::max()) / - Width(t.dtype()); - std::size_t count = 1; - for (std::size_t axis = t.ndim(); axis > 0; --axis) { - const auto size = t.size(axis - 1); - if (size > 1 && t.stride(axis - 1) != static_cast(count)) - return false; - if (size > limit / count) return false; - count *= size; - } - *bytes = count * Width(t.dtype()); - return true; - } - - static bool ValidAddress(const Tensor t, std::size_t bytes) { - if (bytes == 0) return true; - const auto start = reinterpret_cast(t.data()); - return start && start % Width(t.dtype()) == 0 && - start <= std::numeric_limits::max() - bytes; - } - - static bool SameView(const Tensor input, const Tensor out) { - return input.dtype() == out.dtype() && input.data() == out.data() && - input.shape() == out.shape() && input.strides() == out.strides(); - } - - static Tensor Checked(const Tensor input, const Tensor out) { - if (!supports(input, out)) - throw std::invalid_argument( - "NVIDIA Cast: unsupported dtype/device/layout or alias"); - return input; - } - - Device device_; + using CudaCast>::CudaCast; }; + } // namespace infini::ops -#endif + +#endif // INFINI_OPS_NVIDIA_CAST_KERNEL_H_ diff --git a/src/native/cuda/nvidia/ops/causal_conv1d/kernel.h b/src/native/cuda/nvidia/ops/causal_conv1d/kernel.h index 276fd41d7..108243ff2 100644 --- a/src/native/cuda/nvidia/ops/causal_conv1d/kernel.h +++ b/src/native/cuda/nvidia/ops/causal_conv1d/kernel.h @@ -1,202 +1,19 @@ -#pragma once -#include -#include -#include +#ifndef INFINI_OPS_NVIDIA_CAUSAL_CONV1D_KERNEL_H_ +#define INFINI_OPS_NVIDIA_CAUSAL_CONV1D_KERNEL_H_ -#include - -#include "base/causal_conv1d.h" #include "native/cuda/nvidia/caster.cuh" #include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/causal_conv1d/kernel.h" namespace infini::ops { -namespace causal_conv1d_detail { -struct Layout { - ptrdiff_t strides[9][3]{}; - size_t tokens, channels, pool; - bool cu_i64, initial_i64, final_i64; -}; -__device__ inline int64_t index(const void* p, bool i64, int i, int fallback) { - return p ? (i64 ? static_cast(p)[i] - : static_cast(static_cast(p)[i])) - : fallback; -} -template -__device__ inline float history(const T* state, const T* qkv, int64_t pos, - int64_t begin, int batch, int channel, - ptrdiff_t base, const Layout& p) { - if (pos < 3) return static_cast(state[base + pos * p.strides[2][2]]); - const auto off = static_cast(batch) * p.strides[0][0] + - static_cast(begin + pos - 3) * p.strides[0][1] + - static_cast(channel) * p.strides[0][2]; - return static_cast(qkv[off]); -} -// Port of baseline InfiniCore-0.2.9 causal_conv1d_k4_kernel. One thread per -// request/channel reads the entire sequence before committing its final state. -template -__global__ void kernel(const T* qkv, const T* weight, T* state, const T* bias, - const void* cu, const void* initial, - const void* final_indices, T* out, T* final_state, - Layout p) { - const int request = blockIdx.x, channel = blockIdx.y; - if (static_cast(channel) >= p.channels || threadIdx.x != 0) return; - int64_t begin = 0, end = static_cast(p.tokens); - int batch = request; - if (cu) { - begin = index(cu, p.cu_i64, request, 0); - end = index(cu, p.cu_i64, request + 1, 0); - batch = 0; - // Preserve baseline device-value behavior: malformed range leaves the - // corresponding output/state untouched. This is not host validation. - if (begin < 0 || end < begin || end > static_cast(p.tokens)) - return; - } - const int64_t length = end - begin; - const int64_t read = index(initial, p.initial_i64, request, request); - const int64_t write = index(final_indices, p.final_i64, request, request); - if (read < 0 || write < 0 || read >= static_cast(p.pool) || - (final_indices && write >= static_cast(p.pool))) - return; - const auto base = static_cast(read) * p.strides[2][0] + - static_cast(channel) * p.strides[2][1]; - const auto wb = static_cast(channel) * p.strides[1][0]; - for (int64_t t = 0; t < length; ++t) { - float acc = static_cast(weight[wb]) * - history(state, qkv, t, begin, batch, channel, base, p) + - static_cast(weight[wb + p.strides[1][2]]) * - history(state, qkv, t + 1, begin, batch, channel, base, p) + - static_cast(weight[wb + 2 * p.strides[1][2]]) * - history(state, qkv, t + 2, begin, batch, channel, base, p) + - static_cast(weight[wb + 3 * p.strides[1][2]]) * - history(state, qkv, t + 3, begin, batch, channel, base, p); - if (bias) - acc += static_cast( - bias[static_cast(channel) * p.strides[3][0]]); - const auto off = static_cast(batch) * p.strides[7][0] + - static_cast(begin + t) * p.strides[7][1] + - static_cast(channel) * p.strides[7][2]; - out[off] = static_cast(acc); - } - T* target = final_indices ? state : final_state; - const int stride_index = final_indices ? 2 : 8; - const auto target_base = - static_cast(final_indices ? write : request) * - p.strides[stride_index][0] + - static_cast(channel) * p.strides[stride_index][1]; - // Same ordered commit as baseline. Exact initial/final alias is valid for - // short sequences because copied history source positions lie ahead of - // writes. - target[target_base] = static_cast( - history(state, qkv, length, begin, batch, channel, base, p)); - target[target_base + p.strides[stride_index][2]] = static_cast( - history(state, qkv, length + 1, begin, batch, channel, base, p)); - target[target_base + 2 * p.strides[stride_index][2]] = static_cast( - history(state, qkv, length + 2, begin, batch, channel, base, p)); -} -} // namespace causal_conv1d_detail template <> -class Operator : public CausalConv1d { +class Operator + : public CudaCausalConv1d> { public: - Operator(const Tensor qkv, const Tensor weight, Tensor conv_state, - const std::optional bias, - const std::optional cu_seqlens, - const std::optional initial_state_indices, - const std::optional final_state_indices, Tensor out, - std::optional final_conv_state) - : CausalConv1d(qkv, weight, conv_state, bias, cu_seqlens, - initial_state_indices, final_state_indices, out, - final_conv_state) { - if (device_.type() != Device::Type::kNvidia) - throw std::invalid_argument("causal conv requires NVIDIA"); - if (weight.shape()[2] != 4 || conv_state.shape()[2] != 3) - throw std::invalid_argument( - "NVIDIA causal conv kernel requires K4 and state_len3"); - if (tokens_ > static_cast(std::numeric_limits::max() - 3)) - throw std::overflow_error( - "NVIDIA causal conv history index exceeds int64"); - check_device(); - // Baseline uses int request/channel variables and CUDA's grid.y dimension. - if (requests_ >= static_cast(INT_MAX) || channels_ > 65535) - throw std::invalid_argument( - "causal conv request/channel launch extent unsupported"); - p_.tokens = tokens_; - p_.channels = channels_; - p_.pool = pool_; - for (size_t i = 0; i < metadata_.size(); ++i) - if (metadata_[i]) - for (size_t j = 0; j < metadata_[i]->strides().size(); ++j) - p_.strides[i][j] = metadata_[i]->strides()[j]; - p_.cu_i64 = metadata_[4] && metadata_[4]->dtype() == DataType::kInt64; - p_.initial_i64 = metadata_[5] && metadata_[5]->dtype() == DataType::kInt64; - p_.final_i64 = metadata_[6] && metadata_[6]->dtype() == DataType::kInt64; - } - // Device capture/state-pool lifetime is not supported for this stateful path. - // Zero device allocations does not alone establish capture eligibility. - void operator()(const Tensor qkv, const Tensor weight, Tensor conv_state, - const std::optional bias, - const std::optional cu_seqlens, - const std::optional initial_state_indices, - const std::optional final_state_indices, Tensor out, - std::optional final_conv_state) const override { - const Views views{qkv, - weight, - conv_state, - bias, - cu_seqlens, - initial_state_indices, - final_state_indices, - out, - final_conv_state}; - for (size_t i = 0; i < views.size(); ++i) { - const auto& t = views[i]; - if (t.has_value() != metadata_[i].has_value() || - (t && (!std::equal_to{}(*t, *metadata_[i]) || - (t->numel() && !t->data())))) - throw std::invalid_argument( - "causal conv metadata changed or nonempty storage is null"); - } - check_device(); - if (!requests_ || !channels_) return; - switch (dtype_) { - case DataType::kFloat32: - launch(views); - break; - case DataType::kFloat16: - launch(views); - break; - case DataType::kBFloat16: - launch<__nv_bfloat16>(views); - break; - default: - throw std::invalid_argument("causal conv dtype unsupported"); - } - if (cudaPeekAtLastError() != cudaSuccess) - throw std::runtime_error("causal conv CUDA launch failed"); - } - - private: - causal_conv1d_detail::Layout p_{}; - void check_device() const { - int current = -1; - if (cudaGetDevice(¤t) != cudaSuccess) - throw std::runtime_error("causal conv device query failed"); - if (current != device_.index()) - throw std::invalid_argument("causal conv owner device mismatch"); - } - template - void launch(const Views& v) const { - auto pointer = [&](size_t i) -> void* { - return v[i] ? const_cast(v[i]->data()) : nullptr; - }; - const dim3 grid(static_cast(requests_), - static_cast(channels_), 1); - const auto stream = static_cast(stream_ ? stream_ : nullptr); - causal_conv1d_detail::kernel<<>>( - static_cast(pointer(0)), static_cast(pointer(1)), - static_cast(pointer(2)), static_cast(pointer(3)), - pointer(4), pointer(5), pointer(6), static_cast(pointer(7)), - static_cast(pointer(8)), p_); - } + using CudaCausalConv1d>::CudaCausalConv1d; }; + } // namespace infini::ops + +#endif // INFINI_OPS_NVIDIA_CAUSAL_CONV1D_KERNEL_H_ diff --git a/src/native/cuda/nvidia/ops/clover_block_conv1d/kernel.h b/src/native/cuda/nvidia/ops/clover_block_conv1d/kernel.h new file mode 100644 index 000000000..344114681 --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_block_conv1d/kernel.h @@ -0,0 +1,19 @@ +#ifndef INFINI_OPS_Nvidia_CLOVER_BLOCK_CONV1D_KERNEL_H_ +#define INFINI_OPS_Nvidia_CLOVER_BLOCK_CONV1D_KERNEL_H_ + +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/clover_block_conv1d/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverBlockConv1d> { + public: + using CudaCloverBlockConv1d< + Runtime>::CudaCloverBlockConv1d; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/nvidia/ops/clover_coreset/kernel.h b/src/native/cuda/nvidia/ops/clover_coreset/kernel.h new file mode 100644 index 000000000..cccbfb07c --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_coreset/kernel.h @@ -0,0 +1,18 @@ +#ifndef INFINI_OPS_NVIDIA_CLOVER_CORESET_KERNEL_H_ +#define INFINI_OPS_NVIDIA_CLOVER_CORESET_KERNEL_H_ + +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/clover_coreset/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverCoreset> { + public: + using CudaCloverCoreset>::CudaCloverCoreset; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/nvidia/ops/clover_live_mask/kernel.h b/src/native/cuda/nvidia/ops/clover_live_mask/kernel.h new file mode 100644 index 000000000..b4ae3dbae --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_live_mask/kernel.h @@ -0,0 +1,18 @@ +#ifndef INFINI_OPS_NVIDIA_CLOVER_live_mask_KERNEL_H_ +#define INFINI_OPS_NVIDIA_CLOVER_live_mask_KERNEL_H_ + +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/clover_live_mask/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverLiveMask> { + public: + using CudaCloverLiveMask>::CudaCloverLiveMask; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/nvidia/ops/clover_local_memory/kernel.cuh b/src/native/cuda/nvidia/ops/clover_local_memory/kernel.cuh new file mode 100644 index 000000000..37cb13631 --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_local_memory/kernel.cuh @@ -0,0 +1,692 @@ +#ifndef INFINI_OPS_NVIDIA_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ +#define INFINI_OPS_NVIDIA_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ + +#include +#include +#include + +#include +#include +#include + +namespace infini::ops::nvidia_clover_local_memory_detail { + +// NVIDIA tensor-core kernel for CloverLocalMemory (read-only BD-GDN +// preview), for sm_80 and later. It mirrors the Triton reference operation +// for operation, down to the instructions that decide the result: +// - the three products are the same bf16/f16 MMA (m16n8k16, fp32 +// accumulation, K-steps in order) that tl.dot() lowers to, +// - normalized q/k rows, the state tile and the softmax weights are +// rounded to the element type before those products, +// - exp() is the ex2.approx expansion, and +// - history * gain is the initial accumulator of the value product rather +// than an addend applied afterwards. +// Every reduction has a fixed order and there are no atomics, so the kernel +// is deterministic. +// +// The fragments are loaded with ldmatrix and fed to mma.sync directly: with +// this toolchain the wmma bf16 API lowers its fragment loads to per-element +// generic loads, and owning the layouts keeps a row's softmax in registers. +// +// One thread block serves kCols value columns of one (request, value head) +// with two warps per 16-column tile, a (row half, column tile) grid over the +// 32 rows x kCols columns. A block is bound by the latency of its dependent +// instructions and of memory, so it is laid out as a short critical path: +// 1. issue every load before anything waits on one; +// 2. stage normalized q, k and the values, then one block barrier; +// 3. the first column tile of each row half computes all 32 scores of its +// 16 rows and their softmax, while the state tile is still in flight; +// 4. stage the rounded state tile, one more block barrier; +// 5. every warp, without further barriers: q . state for its tile, then +// W . values accumulated on top of the scaled history, and the +// write-back. +// A lane holds two rows of every 16-row tile, so a row's softmax is a +// reduction over four lanes. A wide column tile keeps the work per head +// from being repeated, which is what a full GPU is bound by; a narrow one +// spreads a single request over more SMs. +// +// Grid: x = value_dim / kCols, y = requests, z = value heads; dynamic shared +// memory: Tiling::kSmemBytes. +// The layout requirements (contiguous 16-byte aligned rows, indexes and +// strides below 2^31, power-of-two head sharing, element-typed scalars) are +// checked by the host; anything else takes the shared SIMT kernel. + +constexpr unsigned kFull = 0xffffffffu; +constexpr int kDim = 128; // KEY_DIM == VALUE_DIM == 128 (validated) +constexpr int kRows = 32; // block_size <= 32 (validated) +constexpr int kMmaM = 16; // mma.m16n8k16 +constexpr int kMmaN = 8; +constexpr int kPad = 8; // 16-byte row pad; ldmatrix stays conflict free +constexpr int kLd = kDim + kPad; +constexpr int kLdW = kRows + kPad; // softmax weights: [row][key] +constexpr int kSteps = kDim / kMmaM; // K-steps of q . state / q . k +constexpr int kKeyTiles = kRows / kMmaM; // 16-key tiles of the scores +constexpr int kValueSteps = kKeyTiles; // K-steps of W . values + +template +struct Tiling { + static_assert(kCols % kMmaM == 0 && kCols <= kDim, "kCols must tile 128"); + static constexpr int kColTiles = kCols / kMmaM; + static constexpr int kWarps = kThreads / 32; + static_assert(kWarps == 2 * kColTiles, "two warps per 16-column tile"); + static constexpr int kLdV = kCols + kPad; // values: [key row][column] + // 16-byte units per row must be odd for conflict-free ldmatrix. + static_assert((kLdV / 8) % 2 == 1, "odd number of 16-byte units per row"); + static_assert(kThreads % kRows == 0, "whole row groups"); + // A row group's threads are consecutive lanes of one warp. + static constexpr int kThreadsPerRow = kThreads / kRows; + static_assert(kThreadsPerRow > 0 && kThreadsPerRow <= 32 && + (kThreadsPerRow & (kThreadsPerRow - 1)) == 0, + "a row's threads are consecutive lanes of one warp"); + static constexpr int kChunks = kDim / 8 / kThreadsPerRow; // 8 elements each + static_assert(kChunks >= 1, "at most one thread per eight elements"); + static constexpr int kOut = + kCols / kThreadsPerRow; // tile columns per thread + static_assert(kOut == 8, "each thread stages one 16-byte chunk of values"); + // State staging: a thread stages kStateF4 float4 (32 keys of one column). + static constexpr int kStateF4 = kDim * kCols / kThreads / 4; + static_assert(kStateF4 >= 2 && kStateF4 % 2 == 0 && + kStateF4 * 4 * kThreads == kDim * kCols, + "each thread stages a whole number of 8-key chunks"); + // Column pairs of the block, four per thread; an inactive request zeroes + // them through the same mapping as the write-back uses rows. + static constexpr int kZeroWrites = kRows * (kCols / 2) / kThreads; + static_assert(kZeroWrites * kThreads == kRows * (kCols / 2), + "each thread zeroes a whole number of column pairs"); + // Shared memory layout, offsets in elements; every segment starts on a + // 16-byte boundary. The last segment holds the valid flags, the history + // logit and the per-row history scale. + static constexpr int kKOffset = kRows * kLd; + static constexpr int kSOffset = kKOffset + kRows * kLd; + static constexpr int kVOffset = kSOffset + kCols * kLd; + static constexpr int kWOffset = kVOffset + kRows * kLdV; + static constexpr int kScalarsOffset = kWOffset + kRows * kLdW; + static constexpr int kSmemBytes = kScalarsOffset * 2 + 192; + static_assert(kSmemBytes % 16 == 0, "aligned shared memory size"); + // The write-back collects each warp's tile in the k tile. + static_assert(kWarps * kMmaM * kMmaM <= kRows * kLd, + "a staging slot per warp fits in the k tile"); +}; + +struct __align__(16) Words4 { + uint32_t w[4]; +}; + +// Read-only global loads: one instruction for a 16-byte group of elements. +__device__ __forceinline__ Words4 LoadWords4(const void* src) { + const uint4 v = __ldg(reinterpret_cast(src)); + return Words4{v.x, v.y, v.z, v.w}; +} +__device__ __forceinline__ float4 LoadFloat4(const float* src) { + return __ldg(reinterpret_cast(src)); +} + +// One packed pair of elements, in both directions. +template +__device__ __forceinline__ float2 ToFloat2(uint32_t pair); +template <> +__device__ __forceinline__ float2 ToFloat2<__nv_bfloat16>(uint32_t pair) { + return __bfloat1622float2(*reinterpret_cast(&pair)); +} +template <> +__device__ __forceinline__ float2 ToFloat2(uint32_t pair) { + return __half22float2(*reinterpret_cast(&pair)); +} +template +__device__ __forceinline__ uint32_t FromFloat2(float x, float y); +template <> +__device__ __forceinline__ uint32_t FromFloat2<__nv_bfloat16>(float x, + float y) { + const __nv_bfloat162 pair = __floats2bfloat162_rn(x, y); + return *reinterpret_cast(&pair); +} +template <> +__device__ __forceinline__ uint32_t FromFloat2(float x, float y) { + const __half2 pair = __floats2half2_rn(x, y); + return *reinterpret_cast(&pair); +} + +// Single elements, in both directions. +template +struct Scalar; +template <> +struct Scalar<__nv_bfloat16> { + static __device__ __forceinline__ float To(__nv_bfloat16 value) { + return __bfloat162float(value); + } + static __device__ __forceinline__ __nv_bfloat16 From(float value) { + return __float2bfloat16_rn(value); + } +}; +template <> +struct Scalar { + static __device__ __forceinline__ float To(half value) { + return __half2float(value); + } + static __device__ __forceinline__ half From(float value) { + return __float2half_rn(value); + } +}; + +// The reference lowers exp() to the ex2.approx.f32 hardware approximation; +// exp2f() is that same instruction. +__device__ __forceinline__ float FastExp(float x) { + return exp2f(x * 1.4426950408889634f); +} + +// True when every value head shares its q/k head with a power of two of +// value heads, which the tensor-core kernel needs: the mapping is then a +// shift instead of an integer division at the head of every block. +inline bool PowerOfTwoRatio(int num_v_heads, int num_heads) { + const int ratio = num_v_heads / num_heads; + return num_heads > 0 && num_v_heads % num_heads == 0 && + (ratio & (ratio - 1)) == 0; +} +inline int RatioShift(int num_v_heads, int num_heads) { + int ratio = num_v_heads / num_heads, shift = 0; + while (ratio > 1) { + ratio >>= 1; + ++shift; + } + return shift; +} + +// index * stride in elements. The host has checked that indexes and strides +// of the call fit in 32 bits (and routes wider layouts to the shared SIMT +// kernel), so the product is one wide multiply instead of a 64-bit one at +// the head of every address. +__device__ __forceinline__ int64_t Offset(int64_t index, int64_t stride) { + return static_cast( + static_cast(static_cast(index)) * + static_cast(stride)); +} + +// Normalizes one staged row and writes it to shared memory: the +// threads_per_row consecutive lanes of a warp hold chunks x 8 elements each, +// reduce the square sum in a fixed order and round the scaled elements like +// the reference. +template +__device__ __forceinline__ void NormStoreRow(const Words4 (&raw)[kChunks], + Data* __restrict__ dst, int part) { + float2 f[kChunks][4]; + float sumsq = 0.0f; +#pragma unroll + for (int c = 0; c < kChunks; ++c) { +#pragma unroll + for (int p = 0; p < 4; ++p) { + f[c][p] = ToFloat2(raw[c].w[p]); + sumsq += f[c][p].x * f[c][p].x + f[c][p].y * f[c][p].y; + } + } +#pragma unroll + for (int off = 1; off < kThreadsPerRow; off <<= 1) + sumsq += __shfl_xor_sync(kFull, sumsq, off); + const float norm = rsqrtf(sumsq + 1.0e-6f); +#pragma unroll + for (int c = 0; c < kChunks; ++c) { + Words4 out; +#pragma unroll + for (int p = 0; p < 4; ++p) + out.w[p] = FromFloat2(f[c][p].x * norm, f[c][p].y * norm); + *reinterpret_cast(dst + 8 * (c * kThreadsPerRow + part)) = out; + } +} + +// ---- warp-level mma.m16n8k16 with fp32 accumulation ---- +// Lane l (group g = l >> 2, tig = l & 3) holds: +// A (16x16, row-major): a0 = A[g][2 tig .. +1], a1 = A[g + 8][2 tig ..], +// a2, a3 = the same eight columns further +// B (16x8, column-major): b0 = B[2 tig .. +1][g], b1 = eight rows further +// D (16x8): d0, d1 = D[g][2 tig .. +1], d2, d3 = D[g + 8][..] + +__device__ __forceinline__ uint32_t SharedAddress(const void* ptr) { + return static_cast(__cvta_generic_to_shared(ptr)); +} + +// Four 8x8 matrices; lane l names a 16-byte row of matrix l / 8. +__device__ __forceinline__ void LoadMatrix4(uint32_t (&r)[4], + uint32_t address) { + asm volatile( + "ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"(address) + : "memory"); +} +// The same, each 8x8 matrix transposed on the way to the registers. +__device__ __forceinline__ void LoadMatrix4Trans(uint32_t (&r)[4], + uint32_t address) { + asm volatile( + "ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 " + "{%0, %1, %2, %3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"(address) + : "memory"); +} + +// A of one 16x16 tile from a [row][kLd] array; `tile` is its first element. +template +__device__ __forceinline__ void LoadAFrag(uint32_t (&a)[4], const Data* tile) { + const int lane = static_cast(threadIdx.x) & 31; + LoadMatrix4(a, + SharedAddress(tile + ((lane & 7) + 8 * ((lane >> 3) & 1)) * kLd + + 8 * (lane >> 4))); +} + +// Four B tiles of a 16 x 16 block, K rows 0..7 and 8..15 by N columns 0..7 +// and 8..15; b[0], b[1] serve the first 8 columns, b[2], b[3] the next 8. +// A lane ends up with the two consecutive K elements of its column. +// LoadBFrags: B[k][n] is stored as tile[n][k] (K contiguous). +// LoadBFragsTrans: B[k][n] is stored as tile[k][n] (N contiguous). +template +__device__ __forceinline__ void LoadBFrags(uint32_t (&b)[4], const Data* tile) { + const int lane = static_cast(threadIdx.x) & 31; + LoadMatrix4(b, SharedAddress(tile + ((lane & 7) + 8 * (lane >> 4)) * kLd + + 8 * ((lane >> 3) & 1))); +} +template +__device__ __forceinline__ void LoadBFragsTrans(uint32_t (&b)[4], + const Data* tile) { + const int lane = static_cast(threadIdx.x) & 31; + LoadMatrix4Trans( + b, SharedAddress(tile + ((lane & 7) + 8 * ((lane >> 3) & 1)) * kLd + + 8 * (lane >> 4))); +} + +// d = a . b + d +template +__device__ __forceinline__ void Mma16816(float (&d)[4], const uint32_t (&a)[4], + uint32_t b0, uint32_t b1) { + if constexpr (std::is_same_v) { + asm volatile( + "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 " + "{%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, {%0, %1, %2, %3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); + } else { + static_assert(std::is_same_v, "bf16 or f16"); + asm volatile( + "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 " + "{%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, {%0, %1, %2, %3};\n" + : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1)); + } +} + +template +__global__ void __launch_bounds__(kThreads, kMinBlocks) + CloverLocalMemoryMmaKernel( + const Data* __restrict__ q, const Data* __restrict__ k, + const Data* __restrict__ v, const float* __restrict__ g, + const float* __restrict__ state, const Index* __restrict__ indices, + const int8_t* __restrict__ valid, const Data* __restrict__ logit_scale, + const Data* __restrict__ history_bias, + const Data* __restrict__ history_c, Data* __restrict__ out, + int64_t q_stride_t, int64_t q_stride_h, int64_t k_stride_t, + int64_t k_stride_h, int64_t v_stride_t, int64_t v_stride_h, + int64_t g_stride_t, int64_t g_stride_h, int64_t state_slot_stride, + int64_t state_h_stride, int64_t state_v_stride, int64_t out_t_stride, + int64_t out_h_stride, int64_t out_v_stride, float scale, + float reference_block_size, int block_size, int num_slots, + int q_head_shift, int k_head_shift) { + using T = Tiling; + constexpr int kTpr = T::kThreadsPerRow; + constexpr int kPairs = kCols / 2; // adjacent column pairs per row + const int c0 = static_cast(blockIdx.x) * kCols; + const int request = static_cast(blockIdx.y); + const int value_head = static_cast(blockIdx.z); + const int tid = static_cast(threadIdx.x); + const int64_t row_base = static_cast(request) * block_size; + // This thread's warp in the (row half, column tile) grid of the products, + // and its lane's two rows of every 16-row tile. + const int warp = tid >> 5; + const int lane = tid & 31; + const int row_half = warp % 2; // rows [16 * row_half, +16) + const int col_tile = warp / 2; // columns [16 * col_tile, +16) + const int group = lane >> 2; + const int tig = lane & 3; + // The first column tile of a row half also owns the scores and the softmax + // of the row half. + const bool scorer = col_tile == 0; + const int r0 = 16 * row_half + group; // the lane's rows: r0 and r0 + 8 + // One row group per kTpr threads: the q/k/value row it stages is also the + // row whose gate, softmax and output it handles. + const int row = tid / kTpr; + const int part = tid % kTpr; + const bool row_live = row < block_size; + + // ---- issue every load before anything waits on one ---- + // Nothing below may consume a loaded value: in-order issue would stall the + // warp for the full memory latency in the middle of the address + // arithmetic. The per-head scalars need nothing but the head and stay in + // their element type until they are used; the slot index leads because the + // state tile depends on it. + const Data ls_raw = __ldg(logit_scale + value_head); + const Data history_bias_raw = __ldg(history_bias + value_head); + const Data history_c_raw = __ldg(history_c + value_head); + const Index cache_index = __ldg(indices + request); + // The gates of the lane's two rows. + const float* g_src = + g + Offset(row_base + r0, g_stride_t) + Offset(value_head, g_stride_h); + const float gate_row0 = __ldg(g_src); + const float gate_row1 = __ldg(g_src + Offset(8, g_stride_t)); + // The thread's own valid flag (thread j owns key j). + int8_t own_valid = 0; + if (tid < block_size) own_valid = __ldg(valid + row_base + tid); + + // Value heads may share q/k heads; the host passes the shift of the + // sharing ratio. + const int q_head = value_head >> q_head_shift; + const int k_head = value_head >> k_head_shift; + Words4 q_raw[T::kChunks], k_raw[T::kChunks], v_raw; + { + const Data* q_src = q + Offset(row_base + row, q_stride_t) + + Offset(q_head, q_stride_h) + 8 * part; + const Data* k_src = k + Offset(row_base + row, k_stride_t) + + Offset(k_head, k_stride_h) + 8 * part; + const Data* v_src = v + Offset(row_base + row, v_stride_t) + + Offset(value_head, v_stride_h) + c0 + 8 * part; + const Words4 zero{0u, 0u, 0u, 0u}; +#pragma unroll + for (int c = 0; c < T::kChunks; ++c) { + q_raw[c] = row_live ? LoadWords4(q_src + 8 * c * kTpr) : zero; + k_raw[c] = row_live ? LoadWords4(k_src + 8 * c * kTpr) : zero; + } + v_raw = row_live ? LoadWords4(v_src) : zero; + } + + // An inactive request reads slot 0 and writes zeros below: a return that + // waits for a load would let the compiler sink every load after it. + const bool request_active = + cache_index >= 0 && cache_index < static_cast(num_slots); + const int64_t slot = request_active ? static_cast(cache_index) : 0; + // The output base is wanted by the zero fill and the write-back only. + auto head_base = [&]() { + return out + Offset(row_base, out_t_stride) + + Offset(value_head, out_h_stride); + }; + + // Without any slot the reference output is all zeros. The test depends on + // a kernel argument alone, so it cannot delay the loads above either. + if (num_slots <= 0) { + Data* const head_out = head_base(); +#pragma unroll + for (int i = 0; i < T::kZeroWrites; ++i) { + const int item = tid + i * kThreads; + const int r = item / kPairs; + if (r < block_size) { + Data* const dst = head_out + Offset(r, out_t_stride) + + Offset(c0 + 2 * (item % kPairs), out_v_stride); + dst[0] = Scalar::From(0.0f); + dst[out_v_stride] = Scalar::From(0.0f); + } + } + return; + } + +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 800) + extern __shared__ __align__(32) unsigned char smem[]; + Data* const q_s = reinterpret_cast(smem); + Data* const k_s = reinterpret_cast(smem + T::kKOffset * sizeof(Data)); + Data* const s_s = reinterpret_cast(smem + T::kSOffset * sizeof(Data)); + Data* const v_s = reinterpret_cast(smem + T::kVOffset * sizeof(Data)); + Data* const w_s = reinterpret_cast(smem + T::kWOffset * sizeof(Data)); + unsigned char* const scalars = smem + T::kScalarsOffset * sizeof(Data); + int8_t* const valid_s = reinterpret_cast(scalars); + float* const history_logit_s = reinterpret_cast(scalars + 32); + float* const history_scale_s = reinterpret_cast(scalars + 64); + + // State: one column slice per thread, whole 8-key chunks (kStateF4 + // float4), staged as soon as the first barrier releases. + const int column = tid % kCols; + const int slice = tid / kCols; + float4 s_raw[T::kStateF4]; + { + const float* s_src = state + Offset(slot, state_slot_stride) + + Offset(value_head, state_h_stride) + + Offset(c0 + column, state_v_stride) + + 4 * T::kStateF4 * slice; +#pragma unroll + for (int c = 0; c < T::kStateF4; ++c) s_raw[c] = LoadFloat4(s_src + 4 * c); + } + if (tid < kRows) valid_s[tid] = own_valid; // zero past the block + + // ---- stage normalized q and k rows and the values ---- + NormStoreRow(q_raw, q_s + row * kLd, part); + NormStoreRow(k_raw, k_s + row * kLd, part); + *reinterpret_cast(v_s + row * T::kLdV + 8 * part) = v_raw; + // The history bucket is sized against the valid block size. The flags are + // warp 0's lanes, so that warp has the count without a barrier and the + // logarithm runs beside the other warps' staging. + if (warp == 0) { + const int valid_count = __popc(__ballot_sync(kFull, own_valid != 0)); + *history_logit_s = Scalar::To(history_bias_raw) + + Scalar::To(history_c_raw) * + logf(fmaxf(static_cast(valid_count), 1.0f) / + reference_block_size); + } + // q, k, values and the flags are staged. + __syncthreads(); + const float history_logit = *history_logit_s; + // ---- stage the state tile, rounded to the element type ---- + // It has been in flight since the slot index arrived, about as long as + // the staging above took, and releasing its registers here keeps the + // scores and the softmax lean. + { + Data* dst = s_s + column * kLd + 8 * (T::kStateF4 / 2) * slice; +#pragma unroll + for (int c = 0; c < T::kStateF4 / 2; ++c) { + Words4 out; + out.w[0] = FromFloat2(s_raw[2 * c].x, s_raw[2 * c].y); + out.w[1] = FromFloat2(s_raw[2 * c].z, s_raw[2 * c].w); + out.w[2] = FromFloat2(s_raw[2 * c + 1].x, s_raw[2 * c + 1].y); + out.w[3] = FromFloat2(s_raw[2 * c + 1].z, s_raw[2 * c + 1].w); + *reinterpret_cast(dst + 8 * c) = out; + } + } + + // ---- scores and softmax of the row half, once ---- + const Data* q_tile = q_s + 16 * row_half * kLd; + if (scorer) { + const float ls = Scalar::To(ls_raw); + // Both key tiles share the q fragments, which stream one K-step at a + // time: holding all eight would cost 32 registers. + float score[kKeyTiles][2][4] = {}; + const Data* k_tile0 = k_s; + const Data* k_tile1 = k_s + 16 * kLd; +#pragma unroll + for (int step = 0; step < kSteps; ++step) { + uint32_t a[4]; + uint32_t b0[4]; + uint32_t b1[4]; + LoadAFrag(a, q_tile + kMmaM * step); + LoadBFrags(b0, k_tile0 + kMmaM * step); + LoadBFrags(b1, k_tile1 + kMmaM * step); + Mma16816(score[0][0], a, b0[0], b0[1]); + Mma16816(score[0][1], a, b0[2], b0[3]); + Mma16816(score[1][0], a, b1[0], b1[1]); + Mma16816(score[1][1], a, b1[2], b1[3]); + } + // A row's 32 logits are spread over its four lanes: key 16 t + 8 n + + // 2 tig (+1). Dead keys and keys past the block carry -inf. The lane's + // two rows are independent chains and are interleaved. + const float gate_rows[2] = {scale * FastExp(gate_row0), + scale * FastExp(gate_row1)}; + float logit[2][kKeyTiles][2][2]; // [row][t][n][e] + float row_max[2] = {-INFINITY, -INFINITY}; +#pragma unroll + for (int t = 0; t < kKeyTiles; ++t) { +#pragma unroll + for (int n = 0; n < 2; ++n) { +#pragma unroll + for (int e = 0; e < 2; ++e) { + const int key = kMmaM * t + kMmaN * n + 2 * tig + e; + const bool live = key < block_size && valid_s[key] != 0; +#pragma unroll + for (int half = 0; half < 2; ++half) { + const float value = score[t][n][2 * half + e]; + logit[half][t][n][e] = live ? value * ls : -INFINITY; + row_max[half] = fmaxf(row_max[half], logit[half][t][n][e]); + } + } + } + } +#pragma unroll + for (int half = 0; half < 2; ++half) { + // Over the row's four lanes, in a fixed order. + row_max[half] = + fmaxf(row_max[half], __shfl_xor_sync(kFull, row_max[half], 1)); + row_max[half] = + fmaxf(row_max[half], __shfl_xor_sync(kFull, row_max[half], 2)); + row_max[half] = fmaxf(row_max[half], history_logit); + } + float local_sum[2] = {0.0f, 0.0f}; +#pragma unroll + for (int half = 0; half < 2; ++half) { +#pragma unroll + for (int t = 0; t < kKeyTiles; ++t) { +#pragma unroll + for (int n = 0; n < 2; ++n) { +#pragma unroll + for (int e = 0; e < 2; ++e) { + logit[half][t][n][e] = + FastExp(logit[half][t][n][e] - row_max[half]); + local_sum[half] += logit[half][t][n][e]; + } + } + } + local_sum[half] += __shfl_xor_sync(kFull, local_sum[half], 1); + local_sum[half] += __shfl_xor_sync(kFull, local_sum[half], 2); + } + // out = history * (scale * exp(g) * history_weight) + W . values, where + // the history term is the initial accumulator of the value product. +#pragma unroll + for (int half = 0; half < 2; ++half) { + const float exp_history = FastExp(history_logit - row_max[half]); + const float denominator = local_sum[half] + exp_history; + // The reference divides with the approximate div.full.f32 too. + const float inverse = __fdividef(1.0f, denominator); + // The reference rounds the local weights to the element type. + Data* w_row = w_s + (r0 + 8 * half) * kLdW; +#pragma unroll + for (int t = 0; t < kKeyTiles; ++t) { +#pragma unroll + for (int n = 0; n < 2; ++n) { + *reinterpret_cast(w_row + kMmaM * t + kMmaN * n + + 2 * tig) = + FromFloat2(logit[half][t][n][0] * inverse, + logit[half][t][n][1] * inverse); + } + } + history_scale_s[r0 + 8 * half] = + (exp_history * inverse) * gate_rows[half]; + } + } + + // The weights of every row are staged. + __syncthreads(); + + // ---- history = q . state: B[key][column] = state[column][key] ---- + // The q fragments stream one K-step at a time, as above. + float result[2][4] = {}; + { + const Data* s_tile = s_s + 16 * col_tile * kLd; +#pragma unroll + for (int step = 0; step < kSteps; ++step) { + uint32_t a[4]; + uint32_t b[4]; + LoadAFrag(a, q_tile + kMmaM * step); + LoadBFrags(b, s_tile + kMmaM * step); + Mma16816(result[0], a, b[0], b[1]); + Mma16816(result[1], a, b[2], b[3]); + } + } +#pragma unroll + for (int n = 0; n < 2; ++n) { + result[n][0] *= history_scale_s[r0]; + result[n][1] *= history_scale_s[r0]; + result[n][2] *= history_scale_s[r0 + 8]; + result[n][3] *= history_scale_s[r0 + 8]; + } + // The weight fragment reads below need this warp's stores only. + __syncwarp(); + + // ---- values, accumulated on top of the scaled history ---- + { + const Data* w_tile = w_s + 16 * row_half * kLdW; + const Data* v_tile = v_s + 16 * col_tile; +#pragma unroll + for (int step = 0; step < kValueSteps; ++step) { + uint32_t wa[4]; + uint32_t b[4]; + LoadAFrag(wa, w_tile + kMmaM * step); + // K is the row axis of the value tile: a step moves 16 rows. + LoadBFragsTrans(b, v_tile + kMmaM * step * T::kLdV); + Mma16816(result[0], wa, b[0], b[1]); + Mma16816(result[1], wa, b[2], b[3]); + } + } + + // ---- write-back ---- + { + // The reference zeroes inactive requests and the rows that are not + // active in this step; rows past the block are not written at all. + const bool keep[2] = {request_active && valid_s[r0] != 0, + request_active && valid_s[r0 + 8] != 0}; + Data* const tile0 = head_base() + Offset(16 * row_half, out_t_stride) + + Offset(c0 + 16 * col_tile, out_v_stride); + const bool adjacent = out_v_stride == 1; + if (adjacent && (out_t_stride & 7) == 0 && + (reinterpret_cast(tile0) & 15) == 0) { + // Whole 16-byte stores: the warp collects its 16 x 16 tile in the k + // staging area, then writes each row's 32 bytes with two lanes. + // Scattered 4-byte stores cost the memory system several times their + // data once the GPU is busy. The k tile is dead: its last readers, + // the scores, finished before the second barrier, unlike q which the + // other warps of a row half may still be reading for their history. + uint32_t* const stage = + reinterpret_cast(k_s) + warp * (kMmaM * kMmaM / 2); +#pragma unroll + for (int n = 0; n < 2; ++n) { +#pragma unroll + for (int half = 0; half < 2; ++half) { + stage[(group + 8 * half) * (kMmaM / 2) + 4 * n + tig] = + FromFloat2(keep[half] ? result[n][2 * half] : 0.0f, + keep[half] ? result[n][2 * half + 1] : 0.0f); + } + } + __syncwarp(); + const Words4 words = *reinterpret_cast(stage + 4 * lane); + if (16 * row_half + (lane >> 1) < block_size) + *reinterpret_cast(tile0 + Offset(lane >> 1, out_t_stride) + + 8 * (lane & 1)) = words; + } else { + Data* const row0 = + tile0 + Offset(group, out_t_stride) + 2 * tig * out_v_stride; + const bool pack = adjacent && (out_t_stride & 1) == 0 && + (reinterpret_cast(row0) & 3) == 0; +#pragma unroll + for (int n = 0; n < 2; ++n) { + Data* const dst0 = row0 + Offset(8 * n, out_v_stride); +#pragma unroll + for (int half = 0; half < 2; ++half) { + if (r0 + 8 * half >= block_size) continue; + Data* const dst = dst0 + Offset(8 * half, out_t_stride); + const float x0 = keep[half] ? result[n][2 * half] : 0.0f; + const float x1 = keep[half] ? result[n][2 * half + 1] : 0.0f; + if (pack) { + *reinterpret_cast(dst) = FromFloat2(x0, x1); + } else { + dst[0] = Scalar::From(x0); + dst[out_v_stride] = Scalar::From(x1); + } + } + } + } + } +#endif +} + +} // namespace infini::ops::nvidia_clover_local_memory_detail + +#endif // INFINI_OPS_NVIDIA_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ diff --git a/src/native/cuda/nvidia/ops/clover_local_memory/kernel.h b/src/native/cuda/nvidia/ops/clover_local_memory/kernel.h new file mode 100644 index 000000000..4bb041f9b --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_local_memory/kernel.h @@ -0,0 +1,253 @@ +#ifndef INFINI_OPS_Nvidia_CLOVER_LOCAL_MEMORY_KERNEL_H_ +#define INFINI_OPS_Nvidia_CLOVER_LOCAL_MEMORY_KERNEL_H_ + +#include + +#include +#include +#include + +#include "base/clover_local_memory.h" +#include "data_type.h" +#include "dispatcher.h" +// The NVIDIA caster, which also brings the NVIDIA type map: this header +// names Caster and TypeMapType itself, and the +// runtime header brings neither. +#include "native/cuda/nvidia/caster.cuh" +#include "native/cuda/nvidia/ops/clover_local_memory/kernel.cuh" +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/clover_local_memory/kernel.h" + +namespace infini::ops { + +namespace nvidia_clover_local_memory_detail { + +struct DeviceInfo { + int multiprocessors = 0; // zero: no tensor-core kernel on this device +}; + +// Cached per device: the attribute queries cost more than the launch. +inline DeviceInfo Device(int index) { + static std::mutex mutex; + static std::array cache; + static std::array queried{}; + const auto query = [index] { + int count = 0; + int major = 0; + DeviceInfo info; + // The kernel needs mma.sync.m16n8k16 for bf16, which starts at sm_80. + if (cudaDeviceGetAttribute(&count, cudaDevAttrMultiProcessorCount, index) == + cudaSuccess && + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, + index) == cudaSuccess && + major >= 8) + info = DeviceInfo{count}; + return info; + }; + if (index < 0 || index >= static_cast(queried.size())) return query(); + std::lock_guard lock(mutex); + if (!queried[index]) { + cache[index] = query(); + queried[index] = true; + } + return cache[index]; +} + +// Whole 16-byte rows: the innermost axis is contiguous, the base and every +// outer stride keep the row starts aligned, and no index or stride exceeds +// 32 bits. +inline bool VectorRows(const Tensor& tensor, std::size_t unit) { + if (tensor.ndim() == 0 || tensor.strides().back() != 1 || + reinterpret_cast(tensor.data()) % 16 != 0 || + tensor.numel() > static_cast(INT32_MAX)) + return false; + for (std::size_t axis = 0; axis + 1 < tensor.ndim(); ++axis) { + const auto stride = tensor.strides()[axis]; + if (stride < 0 || stride % static_cast(unit) != 0 || + stride > INT32_MAX) + return false; + } + return true; +} + +inline bool NarrowStrides(const Tensor& tensor) { + for (const auto stride : tensor.strides()) + if (stride < 0 || stride > INT32_MAX) return false; + return tensor.numel() <= static_cast(INT32_MAX); +} + +// Whether the tensor-core kernel can take the call. It reads the rows of q, +// k, v and the state as 16-byte vectors, takes the per-head scalars in the +// element type and maps shared q/k heads with a shift. +inline bool Eligible(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + std::size_t block_size, const Tensor out) { + const auto dtype = q.dtype(); + if (dtype != DataType::kFloat16 && dtype != DataType::kBFloat16) return false; + const auto num_v_heads = static_cast(v.size(2)); + const auto num_q_heads = static_cast(q.size(2)); + const auto num_k_heads = static_cast(k.size(2)); + if (q.size(3) != kDim || k.size(3) != kDim || v.size(3) != kDim || + state.size(2) != kDim || state.size(3) != kDim || + state.size(1) != v.size(2) || block_size == 0 || block_size > kRows || + q.size(1) != k.size(1) || q.size(1) != v.size(1)) + return false; + // Rows of the requests, [request * block_size, +block_size) each. + if (indices.numel() > q.size(1) / block_size) return false; + // The scalars are read in the element type; fp32 scalars stay on the + // shared kernel, which converts them. + if (k.dtype() != dtype || v.dtype() != dtype || out.dtype() != dtype || + logit_scale.dtype() != dtype || history_bias.dtype() != dtype || + history_c.dtype() != dtype || g.dtype() != DataType::kFloat32 || + state.dtype() != DataType::kFloat32 || valid.dtype() != DataType::kInt8 || + (indices.dtype() != DataType::kInt32 && + indices.dtype() != DataType::kInt64)) + return false; + if (!PowerOfTwoRatio(num_v_heads, num_q_heads) || + !PowerOfTwoRatio(num_v_heads, num_k_heads)) + return false; + // 16-bit rows hold 8 elements in 16 bytes, fp32 rows 4. + return VectorRows(q, 8) && VectorRows(k, 8) && VectorRows(v, 8) && + VectorRows(state, 4) && NarrowStrides(g) && NarrowStrides(out) && + NarrowStrides(indices); +} + +// Which tiling serves the call: 0 for 32, 1 for 64 and 2 for 128 value +// columns per block. A block is bound by latency, so a small batch wants +// many blocks; once the blocks outnumber the SMs, fewer and wider ones +// repeat less of the work per head. +inline int SelectTiling(std::size_t requests, int multiprocessors) { + if (requests <= 1) return 0; // four blocks per head spread one request + if (requests <= 3) return 1; // two blocks per head + if (requests * 16 <= static_cast(multiprocessors)) + return 2; // one block per head, one per SM + return 1; +} + +template +bool Launch(const Tensor q, const Tensor k, const Tensor v, const Tensor g, + const Tensor state, const Tensor indices, const Tensor valid, + const Tensor logit_scale, const Tensor history_bias, + const Tensor history_c, std::size_t block_size, Tensor out, + cudaStream_t stream) { + using Tiling = Tiling; + auto* const kernel = + CloverLocalMemoryMmaKernel; + // Beyond the 48 KB default a kernel has to opt into its dynamic shared + // memory size, once per function. + static const bool shared_ready = + Tiling::kSmemBytes <= 48 * 1024 || + cudaFuncSetAttribute(reinterpret_cast(kernel), + cudaFuncAttributeMaxDynamicSharedMemorySize, + Tiling::kSmemBytes) == cudaSuccess; + if (!shared_ready) return false; + dim3 grid(static_cast(kDim / kCols), + static_cast(indices.numel()), + static_cast(v.size(2))); + kernel<<>>( + reinterpret_cast(q.data()), + reinterpret_cast(k.data()), + reinterpret_cast(v.data()), + reinterpret_cast(g.data()), + reinterpret_cast(state.data()), + reinterpret_cast(indices.data()), + reinterpret_cast(valid.data()), + reinterpret_cast(logit_scale.data()), + reinterpret_cast(history_bias.data()), + reinterpret_cast(history_c.data()), + reinterpret_cast(out.data()), + // Layout is [1, tokens, heads, dim]; the batch dim is 1. + static_cast(q.stride(1)), static_cast(q.stride(2)), + static_cast(k.stride(1)), static_cast(k.stride(2)), + static_cast(v.stride(1)), static_cast(v.stride(2)), + static_cast(g.stride(1)), static_cast(g.stride(2)), + static_cast(state.stride(0)), + static_cast(state.stride(1)), + static_cast(state.stride(2)), + static_cast(out.stride(1)), static_cast(out.stride(2)), + static_cast(out.stride(3)), + 1.0f / sqrtf(128.0f), // KEY_DIM == VALUE_DIM == 128 + 32.0f, // the reference sizes the history bucket against a full block + static_cast(block_size), static_cast(state.size(0)), + RatioShift(static_cast(v.size(2)), static_cast(q.size(2))), + RatioShift(static_cast(v.size(2)), static_cast(k.size(2)))); + // A failed launch leaves the shared kernel to report or run the call. + return cudaGetLastError() == cudaSuccess; +} + +template +bool Launch(int tiling, const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + std::size_t block_size, Tensor out, cudaStream_t stream) { + switch (tiling) { + case 0: + return Launch( + q, k, v, g, state, indices, valid, logit_scale, history_bias, + history_c, block_size, out, stream); + case 1: + return Launch( + q, k, v, g, state, indices, valid, logit_scale, history_bias, + history_c, block_size, out, stream); + default: + return Launch( + q, k, v, g, state, indices, valid, logit_scale, history_bias, + history_c, block_size, out, stream); + } +} + +} // namespace nvidia_clover_local_memory_detail + +// NVIDIA takes the tensor-core kernel on sm_80 and later, where it mirrors +// the Triton reference operation for operation. Every layout it cannot read +// keeps the shared SIMT kernel. +template <> +class Operator + : public CudaCloverLocalMemory> { + public: + using Base = CudaCloverLocalMemory>; + using Base::Base; + + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + size_t block_size, Tensor out) const override { + namespace detail = nvidia_clover_local_memory_detail; + const auto requests = indices.numel(); + const auto device = detail::Device(q.device().index()); + if (requests != 0 && q.size(1) != 0 && device.multiprocessors != 0 && + detail::Eligible(q, k, v, g, state, indices, valid, logit_scale, + history_bias, history_c, block_size, out)) { + const auto stream = static_cast(stream_ ? stream_ : 0); + bool launched = false; + DispatchFunc>( + {static_cast(q.dtype()), + static_cast(indices.dtype())}, + [&](auto list_tag) { + using Data = + TypeMapType::kDeviceType, + ListGet<0>(list_tag)>; + using Index = + TypeMapType::kDeviceType, + ListGet<1>(list_tag)>; + launched = detail::Launch( + detail::SelectTiling(requests, device.multiprocessors), q, k, v, + g, state, indices, valid, logit_scale, history_bias, history_c, + block_size, out, stream); + }, + "NvidiaCloverLocalMemory::operator()"); + if (launched) return; + } + Base::operator()(q, k, v, g, state, indices, valid, logit_scale, + history_bias, history_c, block_size, out); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_Nvidia_CLOVER_LOCAL_MEMORY_KERNEL_H_ diff --git a/src/native/cuda/nvidia/ops/clover_mask_routes/kernel.h b/src/native/cuda/nvidia/ops/clover_mask_routes/kernel.h new file mode 100644 index 000000000..499e3c480 --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_mask_routes/kernel.h @@ -0,0 +1,19 @@ +#ifndef INFINI_OPS_NVIDIA_CLOVER_mask_routes_KERNEL_H_ +#define INFINI_OPS_NVIDIA_CLOVER_mask_routes_KERNEL_H_ + +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/clover_mask_routes/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverMaskRoutes> { + public: + using CudaCloverMaskRoutes< + Runtime>::CudaCloverMaskRoutes; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/nvidia/ops/clover_merge_moe/kernel.h b/src/native/cuda/nvidia/ops/clover_merge_moe/kernel.h new file mode 100644 index 000000000..36ff1b86b --- /dev/null +++ b/src/native/cuda/nvidia/ops/clover_merge_moe/kernel.h @@ -0,0 +1,18 @@ +#ifndef INFINI_OPS_NVIDIA_CLOVER_merge_moe_KERNEL_H_ +#define INFINI_OPS_NVIDIA_CLOVER_merge_moe_KERNEL_H_ + +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/clover_merge_moe/kernel.h" + +namespace infini::ops { + +template <> +class Operator + : public CudaCloverMergeMoe> { + public: + using CudaCloverMergeMoe>::CudaCloverMergeMoe; +}; + +} // namespace infini::ops + +#endif diff --git a/src/native/cuda/nvidia/ops/fused_gated_delta_net_gating/kernel.h b/src/native/cuda/nvidia/ops/fused_gated_delta_net_gating/kernel.h index 41699f41f..5a215d49b 100644 --- a/src/native/cuda/nvidia/ops/fused_gated_delta_net_gating/kernel.h +++ b/src/native/cuda/nvidia/ops/fused_gated_delta_net_gating/kernel.h @@ -1,120 +1,20 @@ -#pragma once -#include -#include -#include +#ifndef INFINI_OPS_NVIDIA_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ +#define INFINI_OPS_NVIDIA_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ -#include -#include -#include - -#include "base/fused_gated_delta_net_gating.h" #include "native/cuda/nvidia/caster.cuh" #include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/fused_gated_delta_net_gating/kernel.h" namespace infini::ops { -namespace gating_detail { -struct Layout { - ptrdiff_t strides[6][3]{}; - size_t total, seq, hidden; - float beta, threshold; -}; -template -__global__ void kernel(const T* A, const T* a, const T* b, const T* dt, - float* g, float* betao, Layout p) { - const size_t linear = - static_cast(blockIdx.x) * blockDim.x + threadIdx.x; - if (linear >= p.total) return; - const size_t h = linear % p.hidden, s = (linear / p.hidden) % p.seq; - const size_t batch = linear / p.hidden / p.seq; - ptrdiff_t offsets[6]; - for (int i = 0; i < 6; ++i) - offsets[i] = static_cast(batch) * p.strides[i][0] + - static_cast(s) * p.strides[i][1] + - static_cast(h) * p.strides[i][2]; - const float x = static_cast(a[offsets[1]]) + - static_cast(dt[h * p.strides[3][0]]); - const float bx = p.beta * x; - const float softplus = bx <= p.threshold ? log1pf(expf(bx)) / p.beta : x; - g[offsets[4]] = -expf(static_cast(A[h * p.strides[0][0]])) * softplus; - const float bv = static_cast(b[offsets[2]]); - const float z = expf(bv >= 0 ? -bv : bv); - betao[offsets[5]] = bv >= 0 ? 1.0f / (1.0f + z) : z / (1.0f + z); -} -} // namespace gating_detail template <> class Operator - : public FusedGatedDeltaNetGating { + : public CudaFusedGatedDeltaNetGating> { public: - Operator(Tensor A, Tensor a, Tensor b, Tensor dt, float beta, float threshold, - Tensor g, Tensor betao) - : FusedGatedDeltaNetGating(A, a, b, dt, beta, threshold, g, betao) { - if (device_.type() != Device::Type::kNvidia) - throw std::invalid_argument("gating requires NVIDIA device"); - check_device(); - if (total_ / 256 + (total_ % 256 != 0) > - std::numeric_limits::max()) - throw std::overflow_error("gating grid exceeds CUDA limit"); - p_.total = total_; - p_.seq = seq_; - p_.hidden = hidden_; - p_.beta = beta; - p_.threshold = threshold; - for (size_t i = 0; i < 6; ++i) - for (size_t j = 0; j < metadata_[i].strides().size(); ++j) - p_.strides[i][j] = metadata_[i].strides()[j]; - } - // All metadata is a kernel value argument. There is no allocation, host copy, - // synchronization or data-dependent host work in operator(); stream launch - // is capturable. Make owns no device resources and requires zero workspace. - bool capture_safe() const override { return true; } - void operator()(Tensor A, Tensor a, Tensor b, Tensor dt, float beta, - float threshold, Tensor g, Tensor betao) const override { - check_device(); - std::array tensors{A, a, b, dt, g, betao}; - for (size_t i = 0; i < 6; ++i) - if (!std::equal_to{}(tensors[i], metadata_[i])) - throw std::invalid_argument("gating metadata changed after Make"); - if (std::memcmp(&beta, &beta_, sizeof(float)) || - std::memcmp(&threshold, &threshold_, sizeof(float))) - throw std::invalid_argument("gating attributes changed after Make"); - if (!total_) return; - const dim3 grid( - static_cast(total_ / 256 + (total_ % 256 != 0))); - const auto stream = static_cast(stream_ ? stream_ : nullptr); - switch (metadata_[1].dtype()) { - case DataType::kFloat32: - launch(A, a, b, dt, g, betao, grid, stream); - break; - case DataType::kFloat16: - launch(A, a, b, dt, g, betao, grid, stream); - break; - case DataType::kBFloat16: - launch<__nv_bfloat16>(A, a, b, dt, g, betao, grid, stream); - break; - default: - throw std::invalid_argument("gating dtype unsupported"); - } - if (cudaPeekAtLastError() != cudaSuccess) - throw std::runtime_error("gating CUDA launch failed"); - } - - private: - gating_detail::Layout p_{}; - void check_device() const { - int current = -1; - if (cudaGetDevice(¤t) != cudaSuccess) - throw std::runtime_error("gating device query failed"); - if (current != device_.index()) - throw std::invalid_argument("gating owner device mismatch"); - } - template - void launch(Tensor A, Tensor a, Tensor b, Tensor dt, Tensor g, Tensor betao, - dim3 grid, cudaStream_t stream) const { - gating_detail::kernel<<>>( - static_cast(A.data()), static_cast(a.data()), - static_cast(b.data()), static_cast(dt.data()), - static_cast(g.data()), static_cast(betao.data()), p_); - } + using CudaFusedGatedDeltaNetGating< + Runtime>::CudaFusedGatedDeltaNetGating; }; + } // namespace infini::ops + +#endif // INFINI_OPS_NVIDIA_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ diff --git a/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.cu b/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.cu deleted file mode 100644 index 9b9c91baf..000000000 --- a/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.cu +++ /dev/null @@ -1,81 +0,0 @@ -#include - -#include -#include -#include - -#include "native/cuda/nvidia/ops/moe_align_block_size/kernel.cuh" -#include "native/cuda/nvidia/ops/moe_align_block_size/kernel.h" - -namespace infini::ops { -namespace { - -class DeviceGuard { - public: - explicit DeviceGuard(int device_index) { - auto status = cudaGetDevice(&previous_device_); - assert(status == cudaSuccess && - "`MoeAlignBlockSize` failed to query the current CUDA device"); - - if (previous_device_ != device_index) { - status = cudaSetDevice(device_index); - assert(status == cudaSuccess && - "`MoeAlignBlockSize` failed to select the input CUDA device"); - restore_ = true; - } - } - - ~DeviceGuard() { - if (restore_) { - const auto status = cudaSetDevice(previous_device_); - assert(status == cudaSuccess && - "`MoeAlignBlockSize` failed to restore the CUDA device"); - } - } - - private: - int previous_device_{0}; - - bool restore_{false}; -}; - -} // namespace - -Operator::Operator( - const Tensor topk_ids, const std::optional expert_map, - const int64_t num_experts, const int64_t block_size, - Tensor sorted_token_ids, Tensor experts_ids, Tensor num_tokens_post_pad) - : MoeAlignBlockSize{topk_ids, expert_map, num_experts, - block_size, sorted_token_ids, experts_ids, - num_tokens_post_pad}, - device_index_{topk_ids.device().index()} {} - -void Operator::Run( - const Tensor topk_ids, const std::optional maybe_expert_map, - const int64_t num_experts, const int64_t block_size, - Tensor sorted_token_ids, Tensor experts_ids, - Tensor num_tokens_post_pad) const { - DeviceGuard device_guard{device_index_}; - - constexpr int32_t kThreads = 256; - const auto shared_memory_size = - static_cast(num_experts_) * sizeof(int32_t); - moe_align_block_size_detail::MoeAlignBlockSizeKernel<<< - 1, kThreads, shared_memory_size, static_cast(stream_)>>>( - reinterpret_cast(topk_ids.data()), - maybe_expert_map - ? reinterpret_cast(maybe_expert_map->data()) - : nullptr, - reinterpret_cast(sorted_token_ids.data()), - reinterpret_cast(experts_ids.data()), - reinterpret_cast(num_tokens_post_pad.data()), numel_, - static_cast(num_experts_), static_cast(block_size_), - sorted_token_ids_size_, experts_ids_size_, - maybe_expert_map ? static_cast(maybe_expert_map->numel()) : 0); - - const auto status = cudaGetLastError(); - assert(status == cudaSuccess && - "`MoeAlignBlockSize` CUDA kernel launch failed"); -} - -} // namespace infini::ops diff --git a/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.h b/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.h index 79283640b..0a5108702 100644 --- a/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.h +++ b/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.h @@ -1,33 +1,17 @@ #ifndef INFINI_OPS_NVIDIA_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ #define INFINI_OPS_NVIDIA_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ -#include - -#include "base/moe_align_block_size.h" +#include "native/cuda/nvidia/runtime_.h" +#include "native/cuda/ops/moe_align_block_size/kernel.h" namespace infini::ops { template <> class Operator - : public MoeAlignBlockSize { + : public CudaMoeAlignBlockSize> { public: - Operator(const Tensor topk_ids, const std::optional expert_map, - const int64_t num_experts, const int64_t block_size, - Tensor sorted_token_ids, Tensor experts_ids, - Tensor num_tokens_post_pad); - - using MoeAlignBlockSize::operator(); - - bool capture_safe() const override { return true; } - - protected: - void Run(const Tensor topk_ids, const std::optional maybe_expert_map, - const int64_t num_experts, const int64_t block_size, - Tensor sorted_token_ids, Tensor experts_ids, - Tensor num_tokens_post_pad) const override; - - private: - int device_index_{0}; + using CudaMoeAlignBlockSize< + Runtime>::CudaMoeAlignBlockSize; }; } // namespace infini::ops diff --git a/src/native/cuda/nvidia/ops/recurrent_gated_delta_rule/kernel.h b/src/native/cuda/nvidia/ops/recurrent_gated_delta_rule/kernel.h index 823db8be2..7774608cc 100644 --- a/src/native/cuda/nvidia/ops/recurrent_gated_delta_rule/kernel.h +++ b/src/native/cuda/nvidia/ops/recurrent_gated_delta_rule/kernel.h @@ -12,10 +12,10 @@ namespace infini::ops { -// NVIDIA provider for the shared CUDA single-token decode gated-delta-rule -// kernel. The shared host path performs the shape/extent validation; -// NVIDIA adds the device guard, the per-device block-size precheck, and -// the post-launch error check. +// NVIDIA provider for the shared CUDA gated-delta-rule kernels: the batched +// single-token decode and the packed multi-token recurrence. The shared host +// path performs the shape/extent validation; NVIDIA adds the device guard, +// the per-device block-size precheck, and the post-launch error check. template <> class Operator : public CudaRecurrentGatedDeltaRule> { @@ -38,6 +38,18 @@ class Operator "recurrent delta requires 256-thread CUDA blocks"); } + Operator(const Tensor q, const Tensor k, const Tensor v, const Tensor g, + const Tensor beta, Tensor initial_state, const Tensor cu_seqlens, + const Tensor initial_slots, const Tensor final_slots, Tensor out, + bool use_qk_l2norm) + : CudaRecurrentGatedDeltaRule>( + q, k, v, g, beta, initial_state, cu_seqlens, initial_slots, + final_slots, out, use_qk_l2norm) { + if (device_.type() != Device::Type::kNvidia) + throw std::invalid_argument("recurrent delta requires NVIDIA"); + CheckDevice(); + } + void operator()(const Tensor q, const Tensor k, const Tensor v, const Tensor g, const Tensor beta, Tensor initial_state, const std::optional initial_state_indices, @@ -52,6 +64,19 @@ class Operator throw std::runtime_error("recurrent delta CUDA launch failed"); } + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, Tensor initial_state, + const Tensor cu_seqlens, const Tensor initial_slots, + const Tensor final_slots, Tensor out, + bool use_qk_l2norm) const override { + CheckDevice(); + CudaRecurrentGatedDeltaRule>::operator()( + q, k, v, g, beta, initial_state, cu_seqlens, initial_slots, final_slots, + out, use_qk_l2norm); + if (cudaPeekAtLastError() != cudaSuccess) + throw std::runtime_error("recurrent delta CUDA launch failed"); + } + private: void CheckDevice() const { int device = -1; diff --git a/src/native/cuda/ops/cast/kernel.cuh b/src/native/cuda/ops/cast/kernel.cuh new file mode 100644 index 000000000..4011fc482 --- /dev/null +++ b/src/native/cuda/ops/cast/kernel.cuh @@ -0,0 +1,45 @@ +#ifndef INFINI_OPS_CUDA_CAST_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CAST_KERNEL_CUH_ + +#include +#include + +#include "data_type.h" + +namespace infini::ops { +namespace cast_detail { + +// Shape and strides of a strided operand pair, in device memory. +struct Layout { + const std::size_t* shape; + const std::ptrdiff_t* input_strides; + const std::ptrdiff_t* output_strides; + std::size_t rank{}; + bool contiguous{}; +}; + +template +__global__ void CastKernel(const InT* input, OutT* out, std::size_t first, + std::size_t count, Layout layout) { + const auto local = + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (local >= count) return; + std::size_t input_offset = first + local, output_offset = input_offset; + if (!layout.contiguous) { + std::size_t remaining = input_offset; + input_offset = output_offset = 0; + for (std::size_t axis = layout.rank; axis > 0; --axis) { + const auto coordinate = remaining % layout.shape[axis - 1]; + remaining /= layout.shape[axis - 1]; + input_offset += coordinate * layout.input_strides[axis - 1]; + output_offset += coordinate * layout.output_strides[axis - 1]; + } + } + out[output_offset] = + Caster::template Cast(input[input_offset]); +} + +} // namespace cast_detail +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CAST_KERNEL_CUH_ diff --git a/src/native/cuda/ops/cast/kernel.h b/src/native/cuda/ops/cast/kernel.h new file mode 100644 index 000000000..c0fe3db2f --- /dev/null +++ b/src/native/cuda/ops/cast/kernel.h @@ -0,0 +1,222 @@ +#ifndef INFINI_OPS_CUDA_CAST_KERNEL_H_ +#define INFINI_OPS_CUDA_CAST_KERNEL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "base/cast.h" +#include "data_type.h" +#include "device.h" +#include "dispatcher.h" +#include "native/cuda/caster.cuh" +#include "native/cuda/device_buffer.h" +#include "native/cuda/ops/cast/kernel.cuh" + +namespace infini::ops { + +// Elementwise conversion between float32, float16 and bfloat16. Input and +// output may alias only as the same view. Both must be contiguous unless +// `kStridedLayouts` is set, which also accepts strided operands with a +// non-overlapping output. +template +class CudaCast : public Cast { + public: + static bool supports(const Tensor input, Tensor out) { + if (input.device().type() != Backend::kDeviceType || + input.device() != out.device() || input.shape() != out.shape() || + !SupportedDtype(input.dtype()) || !SupportedDtype(out.dtype())) + return false; + if constexpr (kStridedLayouts) { + if (!NonOverlapping(out)) return false; + } + std::size_t input_bytes = 0, out_bytes = 0; + if (!LayoutBytes(input, &input_bytes) || !LayoutBytes(out, &out_bytes) || + !ValidAddress(input, input_bytes) || !ValidAddress(out, out_bytes)) + return false; + int current = -1; + if (Backend::GetDevice(¤t) != Backend::kSuccess || + current != input.device().index()) + return false; + const auto ip = reinterpret_cast(input.data()); + const auto op = reinterpret_cast(out.data()); + const bool overlap = input_bytes && out_bytes && ip < op + out_bytes && + op < ip + input_bytes; + return !overlap || SameView(input, out); + } + + CudaCast(const Tensor input, Tensor out) + : Cast{Checked(input, out), out}, device_{input.device()} { + layout_.contiguous = is_input_contiguous_ && is_out_contiguous_; + if (layout_.contiguous) return; + // Strided operands index through shape and strides in device memory. + layout_.rank = input.ndim(); + const std::size_t shape_bytes = input.ndim() * sizeof(std::size_t); + const std::size_t strides_bytes = input.ndim() * sizeof(std::ptrdiff_t); + const std::size_t bytes = shape_bytes + 2 * strides_bytes; + std::vector metadata(bytes); + std::memcpy(metadata.data(), input.shape().data(), shape_bytes); + std::memcpy(metadata.data() + shape_bytes, input.strides().data(), + strides_bytes); + std::memcpy(metadata.data() + shape_bytes + strides_bytes, + out.strides().data(), strides_bytes); + auto* device = metadata_.Allocate(bytes); + if (Backend::Memcpy(device, metadata.data(), bytes, + Backend::kMemcpyHostToDevice) != Backend::kSuccess) + throw std::runtime_error("Cast metadata copy failed"); + layout_.shape = reinterpret_cast(device); + layout_.input_strides = + reinterpret_cast(device + shape_bytes); + layout_.output_strides = reinterpret_cast( + device + shape_bytes + strides_bytes); + } + + void operator()(const Tensor input, Tensor out) const override { + if (input.dtype() != input_dtype_ || out.dtype() != out_dtype_ || + input.shape() != input_shape_ || out.shape() != out_shape_ || + input.strides() != input_strides_ || out.strides() != out_strides_ || + input.device() != device_ || !supports(input, out)) + throw std::invalid_argument( + "Cast: call metadata or alias changed after Make"); + if (output_size_ == 0 || SameView(input, out)) return; + const auto stream = static_cast(stream_); + DispatchFunc< + List, + List>( + {static_cast(input_dtype_), static_cast(out_dtype_)}, + [&](auto list_tag) { + using InT = TypeMapType(list_tag)>; + using OutT = TypeMapType(list_tag)>; + constexpr std::size_t cap = 65535u * 256u; + for (std::size_t first = 0; first < output_size_;) { + const auto count = std::min(cap, output_size_ - first); + const auto blocks = static_cast((count + 255) / 256); + cast_detail::CastKernel + <<>>( + static_cast(input.data()), + static_cast(out.data()), first, count, layout_); + first += count; + } + }, + "Cast"); + } + + private: + static bool SupportedDtype(DataType type) { + return type == DataType::kFloat32 || type == DataType::kFloat16 || + type == DataType::kBFloat16; + } + + static std::size_t Width(DataType type) { + return type == DataType::kFloat32 ? 4u : 2u; + } + + static bool LayoutBytes(const Tensor t, std::size_t* bytes) { + if constexpr (kStridedLayouts) return SpanBytes(t, bytes); + return ContiguousBytes(t, bytes); + } + + static bool ContiguousBytes(const Tensor t, std::size_t* bytes) { + if (t.shape().size() != t.strides().size()) return false; + bool empty = false; + for (std::size_t axis = 0; axis < t.ndim(); ++axis) { + if (t.stride(axis) < 0) return false; + empty = empty || t.size(axis) == 0; + } + if (empty) { + *bytes = 0; + return true; + } + const auto limit = + static_cast(std::numeric_limits::max()) / + Width(t.dtype()); + std::size_t count = 1; + for (std::size_t axis = t.ndim(); axis > 0; --axis) { + const auto size = t.size(axis - 1); + if (size > 1 && t.stride(axis - 1) != static_cast(count)) + return false; + if (size > limit / count) return false; + count *= size; + } + *bytes = count * Width(t.dtype()); + return true; + } + + // Bytes from the first to the last element; overflow-checked. + static bool SpanBytes(const Tensor t, std::size_t* bytes) { + if (t.shape().size() != t.strides().size()) return false; + bool empty = false; + for (std::size_t axis = 0; axis < t.ndim(); ++axis) { + if (t.stride(axis) < 0) return false; + empty = empty || t.size(axis) == 0; + } + if (empty) { + *bytes = 0; + return true; + } + const auto limit = + static_cast(std::numeric_limits::max()) / + Width(t.dtype()); + std::size_t span = 1; + for (std::size_t axis = 0; axis < t.ndim(); ++axis) { + const auto size = t.size(axis); + const auto stride = static_cast(t.stride(axis)); + if (size > 1 && stride > (limit - span) / (size - 1)) return false; + span += (size - 1) * stride; + } + *bytes = span * Width(t.dtype()); + return true; + } + + static bool NonOverlapping(const Tensor tensor) { + std::vector> axes; + for (size_t axis = 0; axis < tensor.ndim(); ++axis) { + if (tensor.stride(axis) < 0) return false; + if (tensor.size(axis) > 1) + axes.emplace_back(tensor.stride(axis), tensor.size(axis)); + } + std::sort(axes.begin(), axes.end()); + size_t extent = 1; + for (const auto& [stride, size] : axes) { + if (stride < extent || + (size - 1) > (std::numeric_limits::max() - extent) / stride) + return false; + extent += (size - 1) * stride; + } + return true; + } + + static bool ValidAddress(const Tensor t, std::size_t bytes) { + if (bytes == 0) return true; + const auto start = reinterpret_cast(t.data()); + return start && start % Width(t.dtype()) == 0 && + start <= std::numeric_limits::max() - bytes; + } + + static bool SameView(const Tensor input, const Tensor out) { + return input.dtype() == out.dtype() && input.data() == out.data() && + input.shape() == out.shape() && input.strides() == out.strides(); + } + + static Tensor Checked(const Tensor input, const Tensor out) { + if (!supports(input, out)) + throw std::invalid_argument( + "Cast: unsupported dtype/device/layout or alias"); + return input; + } + + Device device_; + + // `shape` stays null for contiguous operands. + cast_detail::Layout layout_{}; + + CudaDeviceBuffer metadata_; +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CAST_KERNEL_H_ diff --git a/src/native/cuda/ops/causal_conv1d/kernel.cuh b/src/native/cuda/ops/causal_conv1d/kernel.cuh new file mode 100644 index 000000000..c39093259 --- /dev/null +++ b/src/native/cuda/ops/causal_conv1d/kernel.cuh @@ -0,0 +1,102 @@ +#ifndef INFINI_OPS_CUDA_CAUSAL_CONV1D_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CAUSAL_CONV1D_KERNEL_CUH_ + +#include +#include + +#include "data_type.h" + +namespace infini::ops { +namespace causal_conv1d_detail { + +struct Layout { + ptrdiff_t strides[9][3]{}; + size_t tokens, channels, pool; + bool cu_i64, initial_i64, final_i64; +}; + +__device__ inline int64_t index(const void* p, bool i64, int i, int fallback) { + return p ? (i64 ? static_cast(p)[i] + : static_cast(static_cast(p)[i])) + : fallback; +} + +template +__device__ inline float history(const T* state, const T* qkv, int64_t pos, + int64_t begin, int batch, int channel, + ptrdiff_t base, const Layout& p) { + if (pos < 3) return static_cast(state[base + pos * p.strides[2][2]]); + const auto off = static_cast(batch) * p.strides[0][0] + + static_cast(begin + pos - 3) * p.strides[0][1] + + static_cast(channel) * p.strides[0][2]; + return static_cast(qkv[off]); +} + +// Port of baseline InfiniCore-0.2.9 causal_conv1d_k4_kernel. One thread per +// request/channel reads the entire sequence before committing its final state. +template +__global__ void CausalConv1dKernel(const T* qkv, const T* weight, T* state, + const T* bias, const void* cu, + const void* initial, + const void* final_indices, T* out, + T* final_state, Layout p) { + const int request = blockIdx.x, channel = blockIdx.y; + if (static_cast(channel) >= p.channels || threadIdx.x != 0) return; + int64_t begin = 0, end = static_cast(p.tokens); + int batch = request; + if (cu) { + begin = index(cu, p.cu_i64, request, 0); + end = index(cu, p.cu_i64, request + 1, 0); + batch = 0; + // Preserve baseline device-value behavior: malformed range leaves the + // corresponding output/state untouched. This is not host validation. + if (begin < 0 || end < begin || end > static_cast(p.tokens)) + return; + } + const int64_t length = end - begin; + const int64_t read = index(initial, p.initial_i64, request, request); + const int64_t write = index(final_indices, p.final_i64, request, request); + if (read < 0 || write < 0 || read >= static_cast(p.pool) || + (final_indices && write >= static_cast(p.pool))) + return; + const auto base = static_cast(read) * p.strides[2][0] + + static_cast(channel) * p.strides[2][1]; + const auto wb = static_cast(channel) * p.strides[1][0]; + for (int64_t t = 0; t < length; ++t) { + float acc = static_cast(weight[wb]) * + history(state, qkv, t, begin, batch, channel, base, p) + + static_cast(weight[wb + p.strides[1][2]]) * + history(state, qkv, t + 1, begin, batch, channel, base, p) + + static_cast(weight[wb + 2 * p.strides[1][2]]) * + history(state, qkv, t + 2, begin, batch, channel, base, p) + + static_cast(weight[wb + 3 * p.strides[1][2]]) * + history(state, qkv, t + 3, begin, batch, channel, base, p); + if (bias) + acc += static_cast( + bias[static_cast(channel) * p.strides[3][0]]); + const auto off = static_cast(batch) * p.strides[7][0] + + static_cast(begin + t) * p.strides[7][1] + + static_cast(channel) * p.strides[7][2]; + out[off] = static_cast(acc); + } + T* target = final_indices ? state : final_state; + const int stride_index = final_indices ? 2 : 8; + const auto target_base = + static_cast(final_indices ? write : request) * + p.strides[stride_index][0] + + static_cast(channel) * p.strides[stride_index][1]; + // Same ordered commit as baseline. Exact initial/final alias is valid for + // short sequences because copied history source positions lie ahead of + // writes. + target[target_base] = static_cast( + history(state, qkv, length, begin, batch, channel, base, p)); + target[target_base + p.strides[stride_index][2]] = static_cast( + history(state, qkv, length + 1, begin, batch, channel, base, p)); + target[target_base + 2 * p.strides[stride_index][2]] = static_cast( + history(state, qkv, length + 2, begin, batch, channel, base, p)); +} + +} // namespace causal_conv1d_detail +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CAUSAL_CONV1D_KERNEL_CUH_ diff --git a/src/native/cuda/ops/causal_conv1d/kernel.h b/src/native/cuda/ops/causal_conv1d/kernel.h new file mode 100644 index 000000000..c6d8f4e4b --- /dev/null +++ b/src/native/cuda/ops/causal_conv1d/kernel.h @@ -0,0 +1,126 @@ +#ifndef INFINI_OPS_CUDA_CAUSAL_CONV1D_KERNEL_H_ +#define INFINI_OPS_CUDA_CAUSAL_CONV1D_KERNEL_H_ + +#include +#include +#include + +#include "base/causal_conv1d.h" +#include "device.h" +#include "native/cuda/ops/causal_conv1d/kernel.cuh" + +namespace infini::ops { + +// Depthwise causal K=4 convolution over batched or packed request sequences. +// The last three inputs of every request are committed to its state slot. +template +class CudaCausalConv1d : public CausalConv1d { + public: + CudaCausalConv1d(const Tensor qkv, const Tensor weight, Tensor conv_state, + const std::optional bias, + const std::optional cu_seqlens, + const std::optional initial_state_indices, + const std::optional final_state_indices, Tensor out, + std::optional final_conv_state) + : CausalConv1d(qkv, weight, conv_state, bias, cu_seqlens, + initial_state_indices, final_state_indices, out, + final_conv_state) { + if (device_.type() != Backend::kDeviceType) + throw std::invalid_argument("causal conv requires its provider's device"); + if (weight.shape()[2] != 4 || conv_state.shape()[2] != 3) + throw std::invalid_argument( + "causal conv kernel requires K4 and state_len3"); + if (tokens_ > static_cast(std::numeric_limits::max() - 3)) + throw std::overflow_error("causal conv history index exceeds int64"); + check_device(); + // Baseline uses int request/channel variables and CUDA's grid.y dimension. + if (requests_ >= static_cast(INT_MAX) || channels_ > 65535) + throw std::invalid_argument( + "causal conv request/channel launch extent unsupported"); + p_.tokens = tokens_; + p_.channels = channels_; + p_.pool = pool_; + for (size_t i = 0; i < metadata_.size(); ++i) + if (metadata_[i]) + for (size_t j = 0; j < metadata_[i]->strides().size(); ++j) + p_.strides[i][j] = metadata_[i]->strides()[j]; + p_.cu_i64 = metadata_[4] && metadata_[4]->dtype() == DataType::kInt64; + p_.initial_i64 = metadata_[5] && metadata_[5]->dtype() == DataType::kInt64; + p_.final_i64 = metadata_[6] && metadata_[6]->dtype() == DataType::kInt64; + } + + // Device capture/state-pool lifetime is not supported for this stateful path. + // Zero device allocations does not alone establish capture eligibility. + void operator()(const Tensor qkv, const Tensor weight, Tensor conv_state, + const std::optional bias, + const std::optional cu_seqlens, + const std::optional initial_state_indices, + const std::optional final_state_indices, Tensor out, + std::optional final_conv_state) const override { + const Views views{qkv, + weight, + conv_state, + bias, + cu_seqlens, + initial_state_indices, + final_state_indices, + out, + final_conv_state}; + for (size_t i = 0; i < views.size(); ++i) { + const auto& t = views[i]; + if (t.has_value() != metadata_[i].has_value() || + (t && (!std::equal_to{}(*t, *metadata_[i]) || + (t->numel() && !t->data())))) + throw std::invalid_argument( + "causal conv metadata changed or nonempty storage is null"); + } + check_device(); + if (!requests_ || !channels_) return; + switch (dtype_) { + case DataType::kFloat32: + launch(views); + break; + case DataType::kFloat16: + launch>(views); + break; + case DataType::kBFloat16: + launch>(views); + break; + default: + throw std::invalid_argument("causal conv dtype unsupported"); + } + } + + private: + causal_conv1d_detail::Layout p_{}; + + void check_device() const { + int current = -1; + if (Backend::GetDevice(¤t) != Backend::kSuccess) + throw std::runtime_error("causal conv device query failed"); + if (current != device_.index()) + throw std::invalid_argument("causal conv owner device mismatch"); + } + + template + void launch(const Views& v) const { + auto pointer = [&](size_t i) -> void* { + return v[i] ? const_cast(v[i]->data()) : nullptr; + }; + const dim3 grid(static_cast(requests_), + static_cast(channels_), 1); + const auto stream = + static_cast(stream_ ? stream_ : nullptr); + causal_conv1d_detail::CausalConv1dKernel + <<>>( + static_cast(pointer(0)), + static_cast(pointer(1)), static_cast(pointer(2)), + static_cast(pointer(3)), pointer(4), pointer(5), + pointer(6), static_cast(pointer(7)), + static_cast(pointer(8)), p_); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CAUSAL_CONV1D_KERNEL_H_ diff --git a/src/native/cuda/ops/clover_block_conv1d/kernel.cuh b/src/native/cuda/ops/clover_block_conv1d/kernel.cuh new file mode 100644 index 000000000..321b6dab7 --- /dev/null +++ b/src/native/cuda/ops/clover_block_conv1d/kernel.cuh @@ -0,0 +1,113 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_BLOCK_CONV1D_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CLOVER_BLOCK_CONV1D_KERNEL_CUH_ + +#include + +#include "native/cuda/caster.cuh" + +namespace infini::ops { + +// Shared-layer SIMT kernel for CloverBlockConv1d, mirroring the Triton +// reference (SGLang lineage). Per (request, token, channel): +// left part : sum over 4 taps of input/state history . weight[c,0,tap] +// right part : sum over 3 taps of future-in-block input . +// right_weight[c,0,d-1] out = silu(left + right), zeroed for inactive +// rows. +// The state pool row for a request holds its last 3 pre-block values +// (clean prefix); only rows whose `valid` flag is set contribute. +// +// A thread owns one channel of a tile of kTileTokens consecutive tokens. +// What the tile reads is loaded first, in one batch: the block's rows from +// three tokens before the tile to three after it, with their validity +// flags, the weights and the request's slot. The validity flags only +// select; a row inside the block is read whatever its flag says. Only the +// state row, which needs the slot's index, waits for a second load. +// (Computing token by token, each with the loads it happens to need, +// strings several memory latencies one after another.) +// +// Grid: x covers channels in blocks of threads, y iterates (request, tile). +template +__global__ void CloverBlockConv1dKernel( + const Data* __restrict__ input, const Data* __restrict__ state, + const Index* __restrict__ indices, const Data* __restrict__ weight, + const Data* __restrict__ right_weight, const int8_t* __restrict__ valid, + Data* __restrict__ out, int64_t channels, int block_size, int num_slots, + int64_t stride_t, int64_t stride_c, int64_t state_slot_stride, + int64_t state_c_stride, int64_t state_w_stride, int64_t weight_c_stride, + int64_t weight_w_stride, int64_t right_c_stride, int64_t right_w_stride, + int64_t out_t_stride, int64_t out_c_stride, int num_token_tiles) { + constexpr int kWidth = 4; // taps of the left part + constexpr int kPast = kWidth - 1; // tokens before the tile it may read + constexpr int kRows = kTileTokens + 2 * kPast; + + const int64_t ch = static_cast(blockIdx.x) * blockDim.x + + static_cast(threadIdx.x); + if (ch >= channels) return; + + const int token_program = static_cast(blockIdx.y); + const int request = token_program / num_token_tiles; + const int first = (token_program % num_token_tiles) * kTileTokens; + const int64_t base = static_cast(request) * block_size; + const int64_t channel = ch * stride_c; + + const Index slot = indices[request]; + const bool request_active = slot >= 0 && slot < num_slots; + + // The block's rows first - 3 .. first + kTileTokens + 2. One past the + // end of the block is zero, so is an invalid row. + float row[kRows]; + unsigned live = 0; // validity flags of the rows inside the block +#pragma unroll + for (int i = 0; i < kRows; ++i) { + const int token = first + i - kPast; + const bool inside = token >= 0 && token < block_size; + const bool on = inside && valid[base + token] != 0; + const float value = inside ? Caster::template Cast( + input[(base + token) * stride_t + channel]) + : 0.0f; + live |= static_cast(on) << i; + row[i] = on ? value : 0.0f; + } + float taps[kWidth], right_taps[kWidth - 1]; +#pragma unroll + for (int tap = 0; tap < kWidth; ++tap) + taps[tap] = Caster::template Cast( + weight[ch * weight_c_stride + tap * weight_w_stride]); +#pragma unroll + for (int distance = 1; distance < kWidth; ++distance) + right_taps[distance - 1] = Caster::template Cast( + right_weight[ch * right_c_stride + (distance - 1) * right_w_stride]); + // The rows before the block are the clean state, valid as they are. A + // request without a slot in the pool reads none of it. +#pragma unroll + for (int i = 0; i < kPast; ++i) { + const int token = first + i - kPast; + if (token < 0) { + row[i] = request_active + ? Caster::template Cast( + state[static_cast(slot) * state_slot_stride + + ch * state_c_stride + + (token + kPast) * state_w_stride]) + : 0.0f; + } + } + + const int tokens = + block_size - first < kTileTokens ? block_size - first : kTileTokens; + for (int token = 0; token < tokens; ++token) { + float acc = 0.0f; +#pragma unroll + for (int tap = 0; tap < kWidth; ++tap) acc += row[token + tap] * taps[tap]; +#pragma unroll + for (int distance = 1; distance < kWidth; ++distance) + acc += row[token + distance + kPast] * right_taps[distance - 1]; + const float sigmoid = 1.0f / (1.0f + expf(-acc)); + const bool active = request_active && ((live >> (token + kPast)) & 1u) != 0; + out[(base + first + token) * out_t_stride + ch * out_c_stride] = + Caster::template Cast(active ? acc * sigmoid : 0.0f); + } +} + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_BLOCK_CONV1D_KERNEL_CUH_ diff --git a/src/native/cuda/ops/clover_block_conv1d/kernel.h b/src/native/cuda/ops/clover_block_conv1d/kernel.h new file mode 100644 index 000000000..1a30c6516 --- /dev/null +++ b/src/native/cuda/ops/clover_block_conv1d/kernel.h @@ -0,0 +1,73 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_BLOCK_CONV1D_KERNEL_H_ +#define INFINI_OPS_CUDA_CLOVER_BLOCK_CONV1D_KERNEL_H_ + +#include "base/clover_block_conv1d.h" +#include "common/generic_utils.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/ops/clover_block_conv1d/kernel.cuh" + +namespace infini::ops { + +template +class CudaCloverBlockConv1d : public CloverBlockConv1d { + public: + using CloverBlockConv1d::CloverBlockConv1d; + + void operator()(const Tensor input, const Tensor state, const Tensor indices, + const Tensor weight, const Tensor right_weight, + const Tensor valid, size_t block_size, + Tensor out) const override { + const auto tokens = input.size(0); + const auto channels = input.size(1); + const auto requests = indices.numel(); + if (tokens == 0 || channels == 0 || requests == 0) return; + + auto cuda_stream = + static_cast(stream_ ? stream_ : 0); + constexpr unsigned int kThreads = 128; + const unsigned int ch_blocks = + static_cast((channels + kThreads - 1) / kThreads); + constexpr int kTileTokens = 4; + const int num_tiles = + static_cast((block_size + kTileTokens - 1) / kTileTokens); + const unsigned int programs = + static_cast(requests * num_tiles); + + DispatchFunc>( + {static_cast(input.dtype()), + static_cast(indices.dtype())}, + [&](auto list_tag) { + using Data = TypeMapType(list_tag)>; + using Index = TypeMapType(list_tag)>; + CloverBlockConv1dKernel + <<>>( + reinterpret_cast(input.data()), + reinterpret_cast(state.data()), + reinterpret_cast(indices.data()), + reinterpret_cast(weight.data()), + reinterpret_cast(right_weight.data()), + reinterpret_cast(valid.data()), + reinterpret_cast(out.data()), + static_cast(channels), static_cast(block_size), + static_cast(state.size(0)), + static_cast(input.stride(0)), + static_cast(input.stride(1)), + static_cast(state.stride(0)), + static_cast(state.stride(1)), + static_cast(state.stride(2)), + static_cast(weight.stride(0)), + static_cast(weight.stride(2)), + static_cast(right_weight.stride(0)), + static_cast(right_weight.stride(2)), + static_cast(out.stride(0)), + static_cast(out.stride(1)), num_tiles); + }, + "CudaCloverBlockConv1d::operator()"); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_BLOCK_CONV1D_KERNEL_H_ diff --git a/src/native/cuda/ops/clover_coreset/kernel.cuh b/src/native/cuda/ops/clover_coreset/kernel.cuh new file mode 100644 index 000000000..99d45525b --- /dev/null +++ b/src/native/cuda/ops/clover_coreset/kernel.cuh @@ -0,0 +1,690 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_CORESET_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CLOVER_CORESET_KERNEL_CUH_ + +#include +#include +#include +#include + +#include "data_type.h" + +namespace infini::ops { + +// The lane-to-lane shared-memory handoffs below synchronize with +// __syncthreads(), not __syncwarp(): on gfx936 (DTK) __syncwarp does not +// order shared-memory stores between lanes of a warp, so a value lane 0 +// publishes for the warp reads back stale in the other lanes. Every barrier +// here stands in code the whole block reaches, so the block-wide barrier is +// also correct, on NVIDIA as well. + +// Shared-layer SIMT kernel for CloverCoreset, mirroring the three Triton +// stages of the reference in one launch per routing block: +// (0) every row's softmax over its 256 experts and its top-8 experts, +// accumulated into a routing mass per expert; +// (1) the experts sorted by descending mass (ties by expert id) and kept +// while the cumulative normalized mass stays below top_p; +// (2) the allow list applied to the block's logits. +// The reference is three launches that hand a mass and an allow list through +// memory. A block here is at most 32 rows x 256 logits, which one thread +// block keeps in its shared memory: one warp per row, eight warps for the +// sort. +// +// The reference decides with fp32 sums, and a prefix sum that lands on top_p +// is decided by the order those sums associate. So every reduction below +// associates like the reference's generated code (the comment at each one +// spells the order out), which makes the two agree wherever their divisions +// round alike. Nothing is atomic, so the kernel is deterministic. +// +// Lanes mostly hand data over through shared memory rather than warp +// shuffles: on the GPUs this was measured on a warp issues a shuffle only +// every few dozen cycles. A row's top-8 is a merge tree in registers with +// one shared-memory round trip per level, and the sort ranks keys by +// counting and searching instead of passing them through a network of 36 +// compare-exchange steps. +// +// The warp barriers all stand in code that every lane of the warp reaches. +// There a compiler that can see the warp is converged needs nothing for +// them; inside a branch that only some lanes take it has to reconverge the +// warp by hand, which costs more than the work between the barriers. +// +// Grid: x = routing blocks. Block: max(rows, 8) warps of 32 lanes. Shared +// memory: kSmemBytes. + +constexpr int kCloverCoresetExperts = 256; + +namespace clover_coreset_detail { + +constexpr unsigned kFull = 0xffffffffu; // the logical warp: 32 aligned lanes +constexpr int kWarp = 32; +constexpr int kPerLane = kCloverCoresetExperts / kWarp; // experts per lane: 8 +constexpr int kTop = 8; // experts a row routes to +constexpr int kSortWarps = + kCloverCoresetExperts / kWarp; // one expert per lane +constexpr int kScanWarps = kCloverCoresetExperts / 2 / kWarp; // two per lane +constexpr int kMaxRows = 32; +constexpr int kRunBits = 5; // log2(kWarp): a binary search's steps +static_assert((1 << kRunBits) == kWarp, "a run holds one warp of keys"); + +// Shared memory, in this order: the softmax shares of the rows (each row's +// slice is its warp's scratch until they are written), the allow list, the +// warp sums of the two reductions over the experts, the experts' masses, +// the sorted keys and the eight sorted runs of 32 keys the sort merges. +constexpr int kShareBytes = kMaxRows * kCloverCoresetExperts * sizeof(float); +constexpr int kAllowBytes = kShareBytes; +constexpr int kTotalsBytes = kAllowBytes + kCloverCoresetExperts; +constexpr int kMassBytes = kTotalsBytes + 2 * kScanWarps * sizeof(float); +constexpr int kKeysBytes = kMassBytes + kCloverCoresetExperts * sizeof(float); +constexpr int kRunsBytes = + kKeysBytes + kCloverCoresetExperts * sizeof(unsigned long long); +constexpr int kSmemBytes = + kRunsBytes + kCloverCoresetExperts * sizeof(unsigned long long); + +// The reference lowers exp() to the ex2.approx.f32 hardware approximation. +__device__ __forceinline__ float FastExp(float x) { + return exp2f(x * 1.4426950408889634f); +} + +// A row's candidates carry their expert index in the comparison. The order +// key of an IEEE float is its sign and magnitude mapped onto a monotone +// unsigned integer; a key keeps the top bits of that order and, in its low +// 8 bits, 255 - expert. The largest key is so the best logit and, at equal +// logits, the lower expert id: the reference's tie break. +// +// The tree below takes 32-bit keys. A 16-bit logit has at least 13 zero +// mantissa bits once it is a float, so its top 19 bits order it exactly and +// its 32-bit key is exact. An fp32 logit does not fit: the kernel runs the +// tree on a key that drops the low 8 mantissa bits and checks afterwards +// whether that could have mattered (the kernel body says how); when it +// could, the rounds decide, on the exact 64-bit key. +constexpr int kExpertBits = 8; + +// The order key: sign and magnitude onto a monotone unsigned integer. +__device__ __forceinline__ uint32_t OrderKey(float x) { + const uint32_t bits = __float_as_uint(x); + return (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u); +} + +template +__device__ __forceinline__ uint32_t MakeKey(float x, int expert) { + constexpr int kDrop = sizeof(Data) == 2 ? 13 : kExpertBits; + return ((OrderKey(x) >> kDrop) << kExpertBits) | + static_cast(255 - expert); +} + +__device__ __forceinline__ unsigned long long MakeExactKey(float x, + int expert) { + return (static_cast(OrderKey(x)) << kExpertBits) | + static_cast(255 - expert); +} + +// The exchanges that remain stay inside the 32-lane slice of the logical +// warp: xor offsets below 32 and an explicit width, which is safe on +// warp-64 devices. + +template +__device__ __forceinline__ Key WarpMaxKey(Key x) { +#pragma unroll + for (int off = kWarp / 2; off > 0; off >>= 1) { + const Key other = __shfl_xor_sync(kFull, x, off, kWarp); + x = other > x ? other : x; + } + return x; +} + +// ---- the top-8 of a row: a merge tree on its 32-bit keys ---- +// The unsigned min and max order the keys, one instruction each. + +// One step of a bitonic network over the lane's own keys: position i +// exchanges with i ^ kDistance. The blocks of kSize keys alternate +// direction and the block that holds position 0 sorts descending. +template +__device__ __forceinline__ void LocalStep(uint32_t (&key)[kPerLane]) { +#pragma unroll + for (int i = 0; i < kPerLane; ++i) { + const int j = i ^ kDistance; + if (j > i) { + const uint32_t a = key[i], b = key[j]; + const bool ascending = (i & kSize) != 0; + key[i] = ascending ? ::min(a, b) : ::max(a, b); + key[j] = ascending ? ::max(a, b) : ::min(a, b); + } + } +} + +__device__ __forceinline__ void LocalSort(uint32_t (&key)[kPerLane]) { + LocalStep<2, 1>(key); + LocalStep<4, 2>(key); + LocalStep<4, 1>(key); + LocalStep<8, 4>(key); + LocalStep<8, 2>(key); + LocalStep<8, 1>(key); +} + +// The rest of a merge of the lane's eight keys and eight others: the first +// step of that merge pairs the two lists and is done across lanes. +__device__ __forceinline__ void LocalMerge(uint32_t (&key)[kPerLane]) { + LocalStep<8, 4>(key); + LocalStep<8, 2>(key); + LocalStep<8, 1>(key); +} + +// A lane's eight keys, two 16-byte accesses. A lane that is off reads +// zeros and stores nothing. +__device__ __forceinline__ void StoreKeys(uint32_t* slot, + const uint32_t (&key)[kPerLane], + bool on) { + if (!on) return; + uint4* const out = reinterpret_cast(slot); + out[0] = make_uint4(key[0], key[1], key[2], key[3]); + out[1] = make_uint4(key[4], key[5], key[6], key[7]); +} + +__device__ __forceinline__ void LoadKeys(uint32_t (&key)[kPerLane], + const uint32_t* slot, bool on) { + const uint4* const in = reinterpret_cast(slot); + const uint4 zero = make_uint4(0, 0, 0, 0); + const uint4 low = on ? in[0] : zero, high = on ? in[1] : zero; + key[0] = low.x; + key[1] = low.y; + key[2] = low.z; + key[3] = low.w; + key[4] = high.x; + key[5] = high.y; + key[6] = high.z; + key[7] = high.w; +} + +// The eighth best key of a row. Every lane starts with its eight keys +// sorted; five merge levels then pair the lanes that still hold +// candidates. A live lane merges its list with its partner's, keeps the +// better eight, and after the last level lane 0 holds the best eight of the +// row. `scratch` is the warp's own 256 words, `key` is sorted on entry. +// +// Every lane runs every level on its own keys, the lanes without candidates +// on zeros: keys that are only updated under a branch some lanes skip end +// up in local memory. +__device__ __forceinline__ uint32_t EighthKey(uint32_t (&key)[kPerLane], + uint32_t* scratch, int lane) { + uint32_t* const slot = scratch + kPerLane * lane; + StoreKeys(slot, key, true); + __syncthreads(); +#pragma unroll + for (int distance = 1; distance < kWarp; distance <<= 1) { + // Only every distance-th lane still holds candidates. + const bool live = (lane & (distance - 1)) == 0; + uint32_t other[kPerLane]; + LoadKeys(other, slot + kPerLane * ((lane ^ distance) - lane), live); + __syncthreads(); + // The partner's list reversed against this one is a bitonic sequence + // of sixteen; its first merge step pairs the two lists. Zeros leave + // a list that is already in order as it is. +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + key[r] = ::max(key[r], other[kPerLane - 1 - r]); + LocalMerge(key); + StoreKeys(slot, key, live && 2 * distance < kWarp); + __syncthreads(); + } + if (lane == 0) slot[0] = key[kPerLane - 1]; + __syncthreads(); + const uint32_t eighth = scratch[0]; + __syncthreads(); // every lane has it: the scratch is free + return eighth; +} + +// The reference's eight rounds of argmax on the exact keys: every round +// takes the best remaining expert of the row. Zero is below the key of any +// logit and is where each maximum starts. +__device__ __forceinline__ uint32_t +TopEightByRounds(const unsigned long long (&key)[kPerLane], int lane) { + uint32_t taken = 0; +#pragma unroll + for (int round = 0; round < kTop; ++round) { + unsigned long long best = 0; +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + if (!((taken >> r) & 1u)) best = key[r] > best ? key[r] : best; + best = WarpMaxKey(best); + const int local = 255 - static_cast(best & 255) - kPerLane * lane; + if (static_cast(local) < static_cast(kPerLane)) + taken |= 1u << local; + } + return taken; +} + +// ---- the two reductions of a row's softmax ---- +// One lane reduces the 32 values the warp has just written, which is one +// round trip instead of a butterfly of five shuffles. The maximum does not +// depend on the order. The sum is the reference's butterfly (descending +// offsets) as lane 0 sees it, the same tree and so bitwise the same value. +// The trees are spelled out: left to a compiler, the loops over the levels +// stay loops and index registers by a variable. + +__device__ __forceinline__ float4 Add4(float4 a, float4 b) { + return make_float4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); +} + +__device__ __forceinline__ float4 Max4(float4 a, float4 b) { + return make_float4(fmaxf(a.x, b.x), fmaxf(a.y, b.y), fmaxf(a.z, b.z), + fmaxf(a.w, b.w)); +} + +__device__ __forceinline__ float RowMaximum(const float* values) { + const float4* const part = reinterpret_cast(values); + const float4 low = Max4(Max4(part[0], part[1]), Max4(part[2], part[3])); + const float4 high = Max4(Max4(part[4], part[5]), Max4(part[6], part[7])); + const float4 both = Max4(low, high); + return fmaxf(fmaxf(both.x, both.y), fmaxf(both.z, both.w)); +} + +// tree[i] takes tree[i + 16], then [i + 8], [i + 4], [i + 2], [i + 1]. +__device__ __forceinline__ float RowSum(const float* values) { + const float4* const part = reinterpret_cast(values); + const float4 p0 = part[0], p1 = part[1], p2 = part[2], p3 = part[3]; + const float4 p4 = part[4], p5 = part[5], p6 = part[6], p7 = part[7]; + const float4 t16_0 = Add4(p0, p4), t16_1 = Add4(p1, p5); + const float4 t16_2 = Add4(p2, p6), t16_3 = Add4(p3, p7); + const float4 t8_0 = Add4(t16_0, t16_2), t8_1 = Add4(t16_1, t16_3); + const float4 t4 = Add4(t8_0, t8_1); + const float2 t2 = make_float2(t4.x + t4.z, t4.y + t4.w); + return t2.x + t2.y; +} + +// Eight consecutive elements: 16-byte accesses when the rows allow them +// (else one access per element). A 16-bit element also comes back as its bit +// pattern (`raw`), which the kernel's last step writes out again; its value +// ranks -0.0 with +0.0, as the reference's argmax does. +template +__device__ __forceinline__ void LoadRow(const Data* __restrict__ src, + float (&x)[kPerLane], + uint32_t (&raw)[kPerLane / 2], + bool vector) { + if constexpr (sizeof(Data) == 2) { + if (vector) { + const uint4 bits = __ldg(reinterpret_cast(src)); + raw[0] = bits.x; + raw[1] = bits.y; + raw[2] = bits.z; + raw[3] = bits.w; + } else { +#pragma unroll + for (int r = 0; r < kPerLane; r += 2) { + const Data pair[2] = {__ldg(src + r), __ldg(src + r + 1)}; + uint16_t low, high; + std::memcpy(&low, &pair[0], sizeof(low)); + std::memcpy(&high, &pair[1], sizeof(high)); + raw[r / 2] = + static_cast(low) | (static_cast(high) << 16); + } + } +#pragma unroll + for (int r = 0; r < kPerLane; ++r) { + uint16_t bits = static_cast(raw[r / 2] >> (16 * (r % 2))); + Data value; + std::memcpy(&value, &bits, sizeof(value)); + x[r] = static_cast(value) + 0.0f; + } + } else if (vector) { + const float4* const row = reinterpret_cast(src); + const float4 low = __ldg(row), high = __ldg(row + 1); + x[0] = low.x; + x[1] = low.y; + x[2] = low.z; + x[3] = low.w; + x[4] = high.x; + x[5] = high.y; + x[6] = high.z; + x[7] = high.w; + } else { +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + x[r] = static_cast(__ldg(src + r)); + } +} + +} // namespace clover_coreset_detail + +template +__global__ void __launch_bounds__( + clover_coreset_detail::kMaxRows* clover_coreset_detail::kWarp) + CloverCoresetKernel(const Data* __restrict__ logits, Data* __restrict__ out, + int rows, float top_p, int vector) { + using namespace clover_coreset_detail; + static_assert(kCloverCoresetExperts == kWarp * kPerLane, "256 experts"); + + extern __shared__ __align__(16) unsigned char smem[]; + float* const share = reinterpret_cast(smem); // [rows][256] + uint8_t* const allow = smem + kAllowBytes; + float* const totals = reinterpret_cast(smem + kTotalsBytes); + float* const mass = reinterpret_cast(smem + kMassBytes); // [256] + unsigned long long* const keys = + reinterpret_cast(smem + kKeysBytes); // sorted + unsigned long long* const runs = + reinterpret_cast(smem + kRunsBytes); // [8][32] + + const int tid = static_cast(threadIdx.x); + const int warp = tid >> 5; + const int lane = tid & (kWarp - 1); + const bool in_sort = tid < kCloverCoresetExperts; + const bool wide = vector != 0; + const int64_t block_first = + static_cast(blockIdx.x) * rows * kCloverCoresetExperts; + + // ---- softmax and top-8: one warp per row, lane l owns experts 8l .. ---- + // The row's slice of the shares is the warp's scratch until the end. + // + // Every warp of the block walks these steps: one without a row on zero + // logits and its own, unused, slice. The barriers in between then stand + // in code the whole warp reaches. + const bool owns_row = warp < rows; + float x[kPerLane]; + uint32_t raw[kPerLane / 2]; + if (owns_row) { + LoadRow( + logits + block_first + warp * kCloverCoresetExperts + kPerLane * lane, + x, raw, wide); + } else { +#pragma unroll + for (int r = 0; r < kPerLane; ++r) x[r] = 0.0f; +#pragma unroll + for (int w = 0; w < kPerLane / 2; ++w) raw[w] = 0; + } + float local_max = x[0]; +#pragma unroll + for (int r = 1; r < kPerLane; ++r) local_max = fmaxf(local_max, x[r]); + float* const work = share + warp * kCloverCoresetExperts; + + uint32_t key[kPerLane]; + uint32_t original[kPerLane]; +#pragma unroll + for (int r = 0; r < kPerLane; ++r) { + // The reference's argmax ranks -0.0 with +0.0; LoadRow has done that + // for the 16-bit types, whose raw bits the end of the kernel writes. + const float ordered = sizeof(Data) == 2 ? x[r] : x[r] + 0.0f; + original[r] = key[r] = MakeKey(ordered, kPerLane * lane + r); + } + + work[lane] = local_max; + __syncthreads(); + LocalSort(key); + if (lane == 0) work[kWarp] = RowMaximum(work); + __syncthreads(); + const float row_max = work[kWarp]; + __syncthreads(); // every lane has it: the scratch is free + + // The reference's row reduction: the lane's eight in order, then the + // butterfly. It normalizes every expert, but only the top-8 masses are + // summed afterwards, so the division waits for those. + float weight[kPerLane]; +#pragma unroll + for (int r = 0; r < kPerLane; ++r) weight[r] = FastExp(x[r] - row_max); + + // The eighth best key of the row is the threshold of its top-8. + uint32_t taken = 0; + const uint32_t eighth = + EighthKey(key, reinterpret_cast(work), lane); +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + taken |= static_cast(original[r] >= eighth) << r; + if constexpr (sizeof(Data) != 2) { + // The keys dropped the low 8 bits of the order. The eighth key's owner + // publishes them. +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + if (original[r] == eighth) + reinterpret_cast(work)[kWarp + 1] = + static_cast(OrderKey(x[r]) & ((1u << kExpertBits) - 1)); + __syncthreads(); + const int eighth_low = reinterpret_cast(work)[kWarp + 1]; + __syncthreads(); + // The keys order the row exactly unless a logit outside the top-8 has + // the same top bits as the eighth one and larger dropped bits. + int outside = 0; +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + outside += ((original[r] >> kExpertBits) == (eighth >> kExpertBits)) && + !((taken >> r) & 1u) && + static_cast(OrderKey(x[r]) & ((1u << kExpertBits) - 1)) > + eighth_low; + reinterpret_cast(work)[lane] = outside; + __syncthreads(); + if (lane == 0) { + const int4* const part = reinterpret_cast(work); + int sum = 0; +#pragma unroll + for (int i = 0; i < kWarp / 4; ++i) { + const int4 four = part[i]; + sum += four.x + four.y + four.z + four.w; + } + reinterpret_cast(work)[kWarp] = sum == 0; + } + __syncthreads(); + const bool exact = reinterpret_cast(work)[kWarp] != 0; + __syncthreads(); + if (!exact) { + unsigned long long precise[kPerLane]; +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + precise[r] = MakeExactKey(x[r] + 0.0f, kPerLane * lane + r); + taken = TopEightByRounds(precise, lane); + } + } + + float partial = weight[0]; +#pragma unroll + for (int r = 1; r < kPerLane; ++r) partial += weight[r]; + work[lane] = partial; + __syncthreads(); + if (lane == 0) work[kWarp] = RowSum(work); + __syncthreads(); + const float denominator = work[kWarp]; + __syncthreads(); // every lane has it: the scratch is free + + // Only the experts the row routed to are normalized; a lane has a few. + float* const own = work + kPerLane * lane; + reinterpret_cast(own)[0] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + reinterpret_cast(own)[1] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + while (taken) { + const int r = __ffs(taken) - 1; + taken &= taken - 1; + own[r] = weight[r] / denominator; + } + __syncthreads(); + + // ---- expert masses and the sort's first level: one thread per expert ---- + // The reference reduces over the rows in two steps: its four warps hold + // the rows w, w + 4, w + 8, .. each and add them in order, and the four + // partials combine as (P0 + P2) + (P1 + P3). + unsigned long long sort_key = 0; // this expert's place in the order + float expert = 0.0f; // its mass + int rank = 0; // its rank among the warp's 32 experts + if (in_sort) { + float partial[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int row = 0; row < kMaxRows; ++row) + if (row < rows) + partial[row & 3] += share[row * kCloverCoresetExperts + tid]; + expert = (partial[0] + partial[2]) + (partial[1] + partial[3]); + sort_key = + (static_cast(0x7FFFFFFFu - __float_as_uint(expert)) + << 32) | + static_cast(tid); + mass[tid] = expert; + } + __syncthreads(); + // Each warp orders its own 32 experts by counting the better ones: a + // larger mass, or the same mass at a lower expert id. + if (in_sort) { + const float4* const group = + reinterpret_cast(mass + warp * kWarp); +#pragma unroll + for (int i = 0; i < kWarp / 4; ++i) { + const float4 other = group[i]; + rank += (other.x > expert) || ((other.x == expert) && (4 * i < lane)); + rank += (other.y > expert) || ((other.y == expert) && (4 * i + 1 < lane)); + rank += (other.z > expert) || ((other.z == expert) && (4 * i + 2 < lane)); + rank += (other.w > expert) || ((other.w == expert) && (4 * i + 3 < lane)); + } + runs[warp * kWarp + rank] = sort_key; + } + __syncthreads(); + + // ---- block total ---- + // The reference holds two adjacent experts per thread of four warps: it + // adds the pair, runs a butterfly over the warp's 32 lanes and combines + // the four warps as (W0 + W2) + (W1 + W3). Threads 0..127 take its + // layout here, so the butterfly stays inside a warp. + if (tid < kCloverCoresetExperts / 2) { + const float2 pair = *reinterpret_cast(mass + 2 * tid); + float sum = pair.x + pair.y; +#pragma unroll + for (int off = kWarp / 2; off > 0; off >>= 1) + sum += __shfl_xor_sync(kFull, sum, off, kWarp); + if (lane == 0) totals[warp] = sum; + } + + // ---- sort by descending mass, ties by expert id ---- + // Eight sorted runs of 32 keys are in place. Every expert counts the keys + // ahead of it: its own rank and, in each other run, the keys below it, + // which a binary search finds. That number is its position in the order. + // The keys are unique, so the positions are too. + if (in_sort) { + // The searches step together: their loads are independent. + int low[kSortWarps], length[kSortWarps]; +#pragma unroll + for (int run = 0; run < kSortWarps; ++run) { + low[run] = 0; + length[run] = kWarp; + } +#pragma unroll + for (int step = 0; step < kRunBits; ++step) { +#pragma unroll + for (int run = 0; run < kSortWarps; ++run) { + if (run != warp) { + // Halve the interval; its lower end stays inside the run. + const int half = length[run] >> 1; + if (runs[run * kWarp + low[run] + half] < sort_key) low[run] += half; + length[run] -= half; + } + } + } +#pragma unroll + for (int run = 0; run < kSortWarps; ++run) { + // One candidate is left: the keys below it and, if it is below too, + // itself. + if (run != warp) + rank += low[run] + (runs[run * kWarp + low[run]] < sort_key); + } + keys[rank] = sort_key; + } + __syncthreads(); + + // ---- the cumulative threshold, in the reference's association ---- + // The reference holds two consecutive sorted experts per thread of four + // warps (thread t: positions 2t and 2t + 1). It scans the pair sums + // upwards with the offsets 1, 2, 4, 8, 16 inside each warp, and a warp + // adds the running total of the warps before it afterwards. The first + // element's cumulative value adds the exclusive prefix to its own + // probability. Threads 0..127 take that layout here. + const float total = + fmaxf((totals[0] + totals[2]) + (totals[1] + totals[3]), 1.0e-9f); + + unsigned expert0 = 0, expert1 = 0; + float p0 = 0.0f, p1 = 0.0f, mass0 = 0.0f, mass1 = 0.0f, running = 0.0f; + const bool in_scan = tid < kCloverCoresetExperts / 2; + // [0, kScanWarps): the block total's warp sums; then the scan's. + float* const sums = totals + kScanWarps; + if (in_scan) { + const ulonglong2 pair = + *reinterpret_cast(keys + 2 * tid); + expert0 = static_cast(pair.x); + expert1 = static_cast(pair.y); + mass0 = mass[expert0]; + mass1 = mass[expert1]; + p0 = mass0 / total; + p1 = mass1 / total; + running = p0 + p1; +#pragma unroll + for (int off = 1; off < kWarp; off <<= 1) { + const float below = __shfl_up_sync(kFull, running, off, kWarp); + if (lane >= off) running += below; + } + if (lane == kWarp - 1) sums[warp] = running; + } + __syncthreads(); + if (in_scan) { + const float before = warp == 1 ? sums[0] + : warp == 2 ? sums[0] + sums[1] + : (sums[0] + sums[1]) + sums[2]; + const float cumulative = warp > 0 ? before + running : running; + const float previous = __shfl_up_sync(kFull, cumulative, 1, kWarp); + const float first = + warp == 0 && lane == 0 ? p0 : p0 + (lane > 0 ? previous : before); + bool keep0 = first - p0 < top_p; + bool keep1 = cumulative - p1 < top_p; + if (top_p >= 1.0f) { // the reference keeps the experts with mass ... + keep0 = mass0 > 0.0f; + keep1 = mass1 > 0.0f; + } + if (tid == 0) keep0 = true; // ... and the first expert of the sort + allow[expert0] = keep0; + allow[expert1] = keep1; + } + __syncthreads(); + + // ---- the allow list applied to the block's logits ---- + // A row's warp still holds the logits it loaded, so nothing is read back. + if (owns_row) { + // One flag byte per expert, all eight in one load. + const uint2 flags = + *reinterpret_cast(allow + kPerLane * lane); + const unsigned long long kept = + static_cast(flags.y) << 32 | flags.x; + const int64_t first = + block_first + warp * kCloverCoresetExperts + kPerLane * lane; + if constexpr (sizeof(Data) == 2) { + uint16_t infinity; + const Data negative = static_cast(-INFINITY); + std::memcpy(&infinity, &negative, sizeof(infinity)); + uint32_t word[kPerLane / 2]; +#pragma unroll + for (int w = 0; w < kPerLane / 2; ++w) { + const uint32_t low = + (kept >> (16 * w)) & 1u ? raw[w] & 0xFFFFu : infinity; + const uint32_t high = + (kept >> (16 * w + 8)) & 1u ? raw[w] >> 16 : infinity; + word[w] = low | (high << 16); + } + if (wide) { + *reinterpret_cast(out + first) = + make_uint4(word[0], word[1], word[2], word[3]); + } else { +#pragma unroll + for (int r = 0; r < kPerLane; ++r) { + const uint16_t bits = + static_cast(word[r / 2] >> (16 * (r % 2))); + Data value; + std::memcpy(&value, &bits, sizeof(value)); + out[first + r] = value; + } + } + } else { + Data value[kPerLane]; +#pragma unroll + for (int r = 0; r < kPerLane; ++r) + value[r] = ((kept >> (8 * r)) & 0xFFu) != 0 ? x[r] : -INFINITY; + if (wide) { + float4* const row = reinterpret_cast(out + first); + row[0] = make_float4(value[0], value[1], value[2], value[3]); + row[1] = make_float4(value[4], value[5], value[6], value[7]); + } else { +#pragma unroll + for (int r = 0; r < kPerLane; ++r) out[first + r] = value[r]; + } + } + } +} + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_CORESET_KERNEL_CUH_ diff --git a/src/native/cuda/ops/clover_coreset/kernel.h b/src/native/cuda/ops/clover_coreset/kernel.h new file mode 100644 index 000000000..e583127a2 --- /dev/null +++ b/src/native/cuda/ops/clover_coreset/kernel.h @@ -0,0 +1,64 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_CORESET_KERNEL_H_ +#define INFINI_OPS_CUDA_CLOVER_CORESET_KERNEL_H_ + +#include +#include + +#include "base/clover_coreset.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/ops/clover_coreset/kernel.cuh" + +namespace infini::ops { + +namespace coreset_launch_detail { + +// A lane's row of eight elements goes through 16-byte accesses when the +// element is 16 or 32 bits wide and both tensors start on a 16-byte boundary. +inline bool VectorRows(const Tensor& logits, const Tensor& out) { + const auto element = logits.element_size(); + return (element == 2 || element == 4) && + reinterpret_cast(logits.data()) % 16 == 0 && + reinterpret_cast(out.data()) % 16 == 0; +} + +} // namespace coreset_launch_detail + +template +class CudaCloverCoreset : public CloverCoreset { + public: + using CloverCoreset::CloverCoreset; + + void operator()(const Tensor logits, size_t block_size, double top_p, + Tensor out) const override { + const auto blocks = logits.size(0) / block_size; + if (blocks == 0) return; + auto cuda_stream = + static_cast(stream_ ? stream_ : 0); + // One thread block per routing block (no workspace: the masses and the + // allow list stay in its shared memory): a warp per row, at least the + // eight warps of the sort. The shared memory size stays below the 48 KB + // every device gives a block without opting in. + const int rows = static_cast(block_size); + const int threads = (std::max)(rows, clover_coreset_detail::kSortWarps) * + clover_coreset_detail::kWarp; + const int vector = coreset_launch_detail::VectorRows(logits, out) ? 1 : 0; + + DispatchFunc, ReducedFloatTypes>>( + {static_cast(logits.dtype())}, + [&](auto list_tag) { + using Data = TypeMapType(list_tag)>; + CloverCoresetKernel + <<(blocks), threads, + clover_coreset_detail::kSmemBytes, cuda_stream>>>( + reinterpret_cast(logits.data()), + reinterpret_cast(out.data()), rows, + static_cast(top_p), vector); + }, + "CudaCloverCoreset::operator()"); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_CORESET_KERNEL_H_ diff --git a/src/native/cuda/ops/clover_live_mask/kernel.cuh b/src/native/cuda/ops/clover_live_mask/kernel.cuh new file mode 100644 index 000000000..9f842caef --- /dev/null +++ b/src/native/cuda/ops/clover_live_mask/kernel.cuh @@ -0,0 +1,33 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_LIVE_MASK_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CLOVER_LIVE_MASK_KERNEL_CUH_ + +#include + +#include "data_type.h" + +namespace infini::ops { + +// Shared-layer SIMT kernel for CloverLiveMask, mirroring stage 0 of the +// Triton `clover_live_rows` kernel: a row is live when it is a mask now, was +// a mask in the previous snapshot, or the caller forces a refresh. The +// current ids are written back into the snapshot for the next call. +template +__global__ void CloverLiveMaskKernel(const Index* __restrict__ ids, + Index* __restrict__ previous, + int64_t mask_id, int refresh, + int8_t* __restrict__ live, int64_t n) { + const int64_t i = static_cast(blockIdx.x) * blockDim.x + + static_cast(threadIdx.x); + if (i >= n) return; + const Index mask = static_cast(mask_id); + const Index current = ids[i]; + // The snapshot is read whatever `refresh` says: a load that waits for + // the flag would cost a second memory latency. + const Index prev = previous[i]; + live[i] = (refresh != 0) | (current == mask) | (prev == mask); + previous[i] = current; +} + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_LIVE_MASK_KERNEL_CUH_ diff --git a/src/native/cuda/ops/clover_live_mask/kernel.h b/src/native/cuda/ops/clover_live_mask/kernel.h new file mode 100644 index 000000000..25e5d4c59 --- /dev/null +++ b/src/native/cuda/ops/clover_live_mask/kernel.h @@ -0,0 +1,43 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_LIVE_MASK_KERNEL_H_ +#define INFINI_OPS_CUDA_CLOVER_LIVE_MASK_KERNEL_H_ + +#include "base/clover_live_mask.h" +#include "common/generic_utils.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/ops/clover_live_mask/kernel.cuh" + +namespace infini::ops { + +template +class CudaCloverLiveMask : public CloverLiveMask { + public: + using CloverLiveMask::CloverLiveMask; + + void operator()(const Tensor ids, Tensor previous, int64_t mask_id, + bool refresh, Tensor live) const override { + const auto n = ids.numel(); + if (n == 0) return; + auto cuda_stream = + static_cast(stream_ ? stream_ : 0); + constexpr unsigned int kThreads = 128; + const auto blocks = utils::CeilDiv(n, static_cast(kThreads)); + + DispatchFunc>( + {static_cast(ids.dtype())}, + [&](auto list_tag) { + using Index = TypeMapType(list_tag)>; + CloverLiveMaskKernel + <<(blocks), kThreads, 0, cuda_stream>>>( + reinterpret_cast(ids.data()), + reinterpret_cast(previous.data()), + static_cast(mask_id), refresh ? 1 : 0, + reinterpret_cast(live.data()), n); + }, + "CudaCloverLiveMask::operator()"); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_LIVE_MASK_KERNEL_H_ diff --git a/src/native/cuda/ops/clover_local_memory/kernel.cuh b/src/native/cuda/ops/clover_local_memory/kernel.cuh new file mode 100644 index 000000000..0c0a2dd3c --- /dev/null +++ b/src/native/cuda/ops/clover_local_memory/kernel.cuh @@ -0,0 +1,408 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ + +#include + +#include "data_type.h" +#include "native/cuda/caster.cuh" + +namespace infini::ops { + +namespace clover_local_memory_detail { + +// The logical warp is always 32 lanes, aligned to a 32-thread slice of the +// block. Every warp intrinsic below uses offsets below 32 and an explicit +// width of 32, so the exchange never leaves that slice on warp-32 and +// warp-64 devices alike. +constexpr unsigned kFull = 0xffffffffu; +constexpr int kWarpLanes = 32; + +constexpr int kDim = 128; // KEY_DIM == VALUE_DIM == 128 (validated) +constexpr int kMaxRows = 32; // block_size <= 32 (validated) +constexpr int kRowsPerBlock = 16; // query rows per block, one warp each +constexpr int kWarps = kRowsPerBlock; +constexpr int kTileV = 64; // value columns per block +constexpr int kHalf = kDim / 2; // key elements staged at a time +// Padded fp32 row strides in words. A stride of 4 (mod 32) maps consecutive +// rows to distinct 4-bank groups, so a "one lane per row" float4 load is +// conflict free, and every stride keeps rows 16-byte aligned. The value tile +// uses an odd word stride so its per-lane float2 reads stay conflict free. +constexpr int kStride = kHalf + 4; // 68: one fp32 element per key +constexpr int kPairStride = kDim + 4; // 132: two interleaved columns per key +constexpr int kValStride = kTileV + 2; // 66 + +struct Float2 { + float x, y; +}; +struct Float4 { + float x, y, z, w; +}; + +__device__ __forceinline__ Float4 Load4(const float* __restrict__ p) { + return *reinterpret_cast(p); +} +__device__ __forceinline__ void Store4(float* p, Float4 v) { + *reinterpret_cast(p) = v; +} +__device__ __forceinline__ Float2 Load2(const float* __restrict__ p) { + return *reinterpret_cast(p); +} +__device__ __forceinline__ void Store2(float* p, Float2 v) { + *reinterpret_cast(p) = v; +} + +__device__ __forceinline__ float WarpMax(float x) { +#pragma unroll + for (int off = kWarpLanes / 2; off > 0; off >>= 1) + x = fmaxf(x, __shfl_xor_sync(kFull, x, off, kWarpLanes)); + return x; +} + +// The reference lowers exp() to the ex2.approx.f32 hardware approximation. +// exp2f() compiles to that same instruction, which keeps the softmax weights +// and the gate within an ulp of the reference's. +__device__ __forceinline__ float FastExp(float x) { + return exp2f(x * 1.4426950408889634f); +} + +__device__ __forceinline__ float WarpSum(float x) { +#pragma unroll + for (int off = kWarpLanes / 2; off > 0; off >>= 1) + x += __shfl_xor_sync(kFull, x, off, kWarpLanes); + return x; +} + +// Rounds an fp32 value to the element type and back, the rounding the Triton +// reference applies before its dot products. +template +__device__ __forceinline__ float Rounded(float x) { + return Caster::template Cast( + Caster::template Cast(x)); +} + +// Per-head scalars may be fp32 or either reduced type (see the base contract). +template +__device__ __forceinline__ float LoadScalar(const void* ptr, int dtype, + int head) { + if (dtype == static_cast(DataType::kFloat32)) + return reinterpret_cast(ptr)[head]; + if (dtype == static_cast(DataType::kFloat16)) + return Caster::template Cast( + reinterpret_cast*>( + ptr)[head]); + return Caster::template Cast( + reinterpret_cast*>( + ptr)[head]); +} + +// Reciprocal L2 norm of one 128-wide row held by a warp (4 elements per +// lane), with the GDN epsilon. +template +__device__ __forceinline__ float RowNorm(const Data* __restrict__ row, + int64_t stride_k, int lane) { + float sumsq = 0.0f; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const float x = Caster::template Cast( + row[static_cast(lane * 4 + e) * stride_k]); + sumsq += x * x; + } + return rsqrtf(WarpSum(sumsq) + 1.0e-6f); +} + +// The i-th element of a q/k row, scaled by its reciprocal norm and rounded +// to the element type like the reference. +template +__device__ __forceinline__ float Normalized(const Data* __restrict__ row, + int64_t stride_k, int i, + float norm) { + return Rounded(Caster::template Cast( + row[static_cast(i) * stride_k]) * + norm); +} + +} // namespace clover_local_memory_detail + +// Shared-layer SIMT kernel for CloverLocalMemory, mirroring the Triton +// reference (read-only BD-GDN preview) including its rounding points. +// +// One thread block serves 16 query rows of one (request, value head, 64-wide +// value tile); one warp owns one query row. Inside a warp every lane plays +// two roles at once: lane j is local key j and lane v is the pair of value +// columns (2v, 2v+1). Each lane therefore holds whole dot products and no +// reduction is needed for them: +// score[t][j] = q[t] . k[j] +// history[t][c] = q[t] . state[c] +// local[t][c] = sum_j w[t][j] * values[j][c] +// The operands are staged in shared memory as fp32, so the key loop is pure +// float4 loads and FMAs. Like the reference, the normalized q/k rows and the +// state tile are rounded to the element type before the products, and the +// softmax weights are rounded before the value dot. The key axis is staged +// in two halves so the fp32 tiles fit in shared memory. All reductions have +// a fixed order and the kernel uses no atomics, so it is deterministic. +// +// Grid: x = value tiles (VALUE_DIM / 64), y = requests * row tiles, +// z = value heads. Block: 16 warps. +template +// The launch bounds matter on gfx936 (DTK): a 512-thread block this size +// without them is compiled with a 256-thread cap, and the threads past the +// cap then run with wrapped indices and silently corrupt their rows. +__global__ void __launch_bounds__( + clover_local_memory_detail::kWarps* clover_local_memory_detail::kWarpLanes) + CloverLocalMemoryKernel( + const Data* __restrict__ q, const Data* __restrict__ k, + const Data* __restrict__ v, const float* __restrict__ g, + const float* __restrict__ state, const Index* __restrict__ indices, + const int8_t* __restrict__ valid, const void* __restrict__ logit_scale, + const void* __restrict__ history_bias_in, + const void* __restrict__ history_c_in, Data* __restrict__ out, + int64_t q_stride_t, int64_t q_stride_h, int64_t q_stride_k, + int64_t k_stride_t, int64_t k_stride_h, int64_t k_stride_k, + int64_t v_stride_t, int64_t v_stride_h, int64_t v_stride_v, + int64_t g_stride_t, int64_t g_stride_h, int64_t state_slot_stride, + int64_t state_h_stride, int64_t state_v_stride, int64_t state_k_stride, + int64_t out_t_stride, int64_t out_h_stride, int64_t out_v_stride, + float scale, float reference_block_size, int block_size, int num_slots, + int num_q_heads, int num_k_heads, int num_v_heads, + int logit_scale_dtype, int history_bias_dtype, int history_c_dtype) { + using namespace clover_local_memory_detail; + + __shared__ __align__(16) float q_s[kRowsPerBlock * kStride]; // normalized q + __shared__ __align__(16) float k_s[kMaxRows * kStride]; // normalized k + // st_s[pair][2i], st_s[pair][2i + 1]: columns (2*pair, 2*pair + 1) at key i. + __shared__ __align__(16) float st_s[kTileV / 2 * kPairStride]; + // vs_s[key][2c], vs_s[key][2c + 1]: values of columns (2c, 2c + 1). + __shared__ __align__(16) float vs_s[kMaxRows * kValStride]; + __shared__ float norm_q[kRowsPerBlock]; + __shared__ float norm_k[kMaxRows]; + __shared__ int8_t valid_s[kMaxRows]; + + const int v0 = static_cast(blockIdx.x) * kTileV; + const int row_tiles = (block_size + kRowsPerBlock - 1) / kRowsPerBlock; + const int request = static_cast(blockIdx.y) / row_tiles; + const int row_tile = static_cast(blockIdx.y) % row_tiles; + const int value_head = static_cast(blockIdx.z); + const int tid = static_cast(threadIdx.x); + const int lane = tid % kWarpLanes; + const int warp = tid / kWarpLanes; + const int row = row_tile * kRowsPerBlock + warp; // this warp's query row + const int64_t row_base = static_cast(request) * block_size; + + const Index cache_index = indices[request]; + const bool request_active = + cache_index >= 0 && cache_index < static_cast(num_slots); + Data* const head_out = + out + static_cast(request) * block_size * out_t_stride + + value_head * out_h_stride; + if (!request_active) { + // The reference stores zeros for every row of an inactive request. + const int rows = min(kRowsPerBlock, block_size - row_tile * kRowsPerBlock); + for (int i = tid; i < rows * kTileV; i += kWarps * kWarpLanes) + head_out[static_cast(row_tile * kRowsPerBlock + i / kTileV) * + out_t_stride + + static_cast(v0 + i % kTileV) * out_v_stride] = Data(0); + return; + } + const int64_t safe_slot = cache_index; + + // Value heads may share q/k heads. + const int q_head = value_head / (num_v_heads / num_q_heads); + const int k_head = value_head / (num_v_heads / num_k_heads); + const bool row_live = row < block_size; + + // ---- reciprocal norms of this block's q rows and of the k rows ---- + norm_q[warp] = + row_live ? RowNorm( + q + (row_base + row) * q_stride_t + q_head * q_stride_h, + q_stride_k, lane) + : 0.0f; + { + const Data* k_rows = k + row_base * k_stride_t + k_head * k_stride_h; +#pragma unroll + for (int r = warp; r < kMaxRows; r += kWarps) + norm_k[r] = r < block_size + ? RowNorm( + k_rows + static_cast(r) * k_stride_t, + k_stride_k, lane) + : 0.0f; + } + if (tid < block_size) valid_s[tid] = valid[row_base + tid]; + + // ---- value tile ---- +#pragma unroll + for (int i = 0; i < kMaxRows / kWarps; ++i) { + const int j = warp + i * kWarps; // key row + Float2 value{0.0f, 0.0f}; + if (j < block_size) { + const Data* src = v + (row_base + j) * v_stride_t + + value_head * v_stride_h + + static_cast(v0 + 2 * lane) * v_stride_v; + value = Float2{Caster::template Cast(src[0]), + Caster::template Cast( + src[static_cast(1) * v_stride_v])}; + } + Store2(vs_s + j * kValStride + 2 * lane, value); + } + // Everything staged above is read across warps below. + __syncthreads(); + + // ---- per-head scalars and the history-bucket logit ---- + const float ls = + LoadScalar(logit_scale, logit_scale_dtype, value_head); + // Lane j is local key j. Invalid keys and lanes past the block carry no + // weight and are not counted in the valid block size. + const bool key_live = lane < block_size && valid_s[lane] != 0; + const float valid_block_size = fmaxf( + static_cast(static_cast(WarpSum(key_live ? 1.0f : 0.0f))), + 1.0f); + const float hb = + LoadScalar(history_bias_in, history_bias_dtype, value_head) + + LoadScalar(history_c_in, history_c_dtype, value_head) * + logf(valid_block_size / reference_block_size); + + // ---- key axis in two halves: stage, then every warp sweeps its row ---- + // Two independent accumulator chains per dot keep the FMA chains short. + float score[2] = {0.0f, 0.0f}; + float history_0[2] = {0.0f, 0.0f}; + float history_1[2] = {0.0f, 0.0f}; + // Row bases in words; each load below covers four consecutive keys. + const float* q4 = q_s + warp * kStride; + const float* k4 = k_s + lane * kStride; + const float* s4 = st_s + lane * kPairStride; + for (int half = 0; half < kDim / kHalf; ++half) { + // q: 16 rows x kHalf elements, two per thread. + { + const int t = tid / (kHalf / 2); + const int c = (tid % (kHalf / 2)) * 2; + const int r = row_tile * kRowsPerBlock + t; + Float2 value{0.0f, 0.0f}; + if (r < block_size) { + const Data* src = q + (row_base + r) * q_stride_t + + q_head * q_stride_h + + static_cast(half * kHalf + c) * q_stride_k; + value = + Float2{Normalized(src, q_stride_k, 0, norm_q[t]), + Normalized(src, q_stride_k, 1, norm_q[t])}; + } + Store2(q_s + t * kStride + c, value); + } + // k: 32 rows x kHalf elements, four per thread. + { + const int r = tid / (kHalf / 4); + const int c = (tid % (kHalf / 4)) * 4; + Float4 value{0.0f, 0.0f, 0.0f, 0.0f}; + if (r < block_size) { + const Data* src = k + (row_base + r) * k_stride_t + + k_head * k_stride_h + + static_cast(half * kHalf + c) * k_stride_k; + value = + Float4{Normalized(src, k_stride_k, 0, norm_k[r]), + Normalized(src, k_stride_k, 1, norm_k[r]), + Normalized(src, k_stride_k, 2, norm_k[r]), + Normalized(src, k_stride_k, 3, norm_k[r])}; + } + Store4(k_s + r * kStride + c, value); + } + // state: 32 column pairs x kHalf keys, four keys per thread. + { + const int pair = tid / (kHalf / 4); + const int c = (tid % (kHalf / 4)) * 4; + const float* col0 = + state + safe_slot * state_slot_stride + value_head * state_h_stride + + static_cast(v0 + 2 * pair) * state_v_stride + + static_cast(half * kHalf + c) * state_k_stride; + const float* col1 = col0 + state_v_stride; + float* dst = st_s + pair * kPairStride + 2 * c; +#pragma unroll + for (int e = 0; e < 4; ++e) { + // The reference casts the fp32 state tile to the element type first. + Store2(dst + 2 * e, + Float2{Rounded( + col0[static_cast(e) * state_k_stride]), + Rounded( + col1[static_cast(e) * state_k_stride])}); + } + } + __syncthreads(); + + // One sweep over this key half. q is a broadcast read that feeds the + // score against key j and the history of columns (2v, 2v+1) at once. + if (row_live) { +#pragma unroll + for (int i = 0; i < kHalf / 8; ++i) { +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int n = 2 * i + u; // group of four keys + const Float4 a = Load4(q4 + 4 * n); // q at keys 4n .. 4n + 3 + const Float4 b = Load4(k4 + 4 * n); // k at keys 4n .. 4n + 3 + const Float4 sa = Load4(s4 + 8 * n); // keys 4n, 4n + 1 + const Float4 sb = Load4(s4 + 8 * n + 4); // keys 4n + 2, 4n + 3 + score[u] += a.x * b.x; + score[u] += a.y * b.y; + score[u] += a.z * b.z; + score[u] += a.w * b.w; + history_0[u] += a.x * sa.x; + history_0[u] += a.y * sa.z; + history_0[u] += a.z * sb.x; + history_0[u] += a.w * sb.z; + history_1[u] += a.x * sa.y; + history_1[u] += a.y * sa.w; + history_1[u] += a.z * sb.y; + history_1[u] += a.w * sb.w; + } + } + } + __syncthreads(); // the tiles are restaged for the next half + } + if (!row_live) return; + + // ---- softmax over the local keys plus the history bucket ---- + // Invalid keys and lanes past the block contribute -inf, a zero weight. + const float logit = key_live ? (score[0] + score[1]) * ls : -INFINITY; + const float row_max = fmaxf(WarpMax(logit), hb); + const float exp_history = FastExp(hb - row_max); + const float exp_local = FastExp(logit - row_max); + const float denominator = WarpSum(exp_local) + exp_history; + // The reference rounds the local weights to the element type before its + // value dot product. + const float weight = Rounded(exp_local / denominator); + const float history_weight = exp_history / denominator; + + // ---- value dot: lane v gathers every key's weight and its two values ---- + float local[2] = {0.0f, 0.0f}; + const float* col = vs_s + 2 * lane; + for (int j = 0; j < block_size; ++j) { + const float wj = __shfl_sync(kFull, weight, j, kWarpLanes); + const Float2 value = Load2(col + j * kValStride); + local[0] += wj * value.x; + local[1] += wj * value.y; + } + + // out = history * (scale * exp(g) * history_weight) + local + const float gate = + scale * + FastExp(g[(row_base + row) * g_stride_t + value_head * g_stride_h]); + const float gain = gate * history_weight; + const bool keep = valid_s[row] != 0; + const Data result[2] = { + keep ? Caster::template Cast( + (history_0[0] + history_0[1]) * gain + local[0]) + : Data(0), + keep ? Caster::template Cast( + (history_1[0] + history_1[1]) * gain + local[1]) + : Data(0)}; + Data* const dst = head_out + static_cast(row) * out_t_stride + + static_cast(v0 + 2 * lane) * out_v_stride; + if (out_v_stride == 1 && (reinterpret_cast(dst) & 3) == 0) { + // Adjacent columns: one 32-bit store for the coalesced pair. + *reinterpret_cast(dst) = + *reinterpret_cast(result); + } else { + dst[0] = result[0]; + dst[out_v_stride] = result[1]; + } +} + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_LOCAL_MEMORY_KERNEL_CUH_ diff --git a/src/native/cuda/ops/clover_local_memory/kernel.h b/src/native/cuda/ops/clover_local_memory/kernel.h new file mode 100644 index 000000000..8a1c4ec1d --- /dev/null +++ b/src/native/cuda/ops/clover_local_memory/kernel.h @@ -0,0 +1,95 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_LOCAL_MEMORY_KERNEL_H_ +#define INFINI_OPS_CUDA_CLOVER_LOCAL_MEMORY_KERNEL_H_ + +#include "base/clover_local_memory.h" +#include "common/generic_utils.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/ops/clover_local_memory/kernel.cuh" + +namespace infini::ops { + +template +class CudaCloverLocalMemory : public CloverLocalMemory { + public: + using CloverLocalMemory::CloverLocalMemory; + + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + size_t block_size, Tensor out) const override { + const auto tokens = q.size(1); + const auto requests = indices.numel(); + const auto num_v_heads = v.size(2); + const auto value_dim = v.size(3); + if (tokens == 0 || requests == 0 || num_v_heads == 0) return; + + auto cuda_stream = + static_cast(stream_ ? stream_ : 0); + // One block per (value tile, request x row tile, value head); each warp + // of the block owns one query row. + const auto row_tiles = + (block_size + clover_local_memory_detail::kRowsPerBlock - 1) / + clover_local_memory_detail::kRowsPerBlock; + dim3 grid( + static_cast(value_dim / clover_local_memory_detail::kTileV), + static_cast(requests * row_tiles), + static_cast(num_v_heads)); + dim3 block(clover_local_memory_detail::kWarps * + clover_local_memory_detail::kWarpLanes); + + const float scale = 1.0f / sqrtf(128.0f); + // The Triton reference sizes the history bucket against the full block. + const float reference = 32.0f; + + DispatchFunc>( + {static_cast(q.dtype()), + static_cast(indices.dtype())}, + [&](auto list_tag) { + using Data = TypeMapType(list_tag)>; + using Index = TypeMapType(list_tag)>; + CloverLocalMemoryKernel + <<>>( + reinterpret_cast(q.data()), + reinterpret_cast(k.data()), + reinterpret_cast(v.data()), + reinterpret_cast(g.data()), + reinterpret_cast(state.data()), + reinterpret_cast(indices.data()), + reinterpret_cast(valid.data()), + logit_scale.data(), history_bias.data(), history_c.data(), + reinterpret_cast(out.data()), + // Layout is [1, tokens, heads, dim]; the batch dim is 1. + static_cast(q.stride(1)), + static_cast(q.stride(2)), + static_cast(q.stride(3)), + static_cast(k.stride(1)), + static_cast(k.stride(2)), + static_cast(k.stride(3)), + static_cast(v.stride(1)), + static_cast(v.stride(2)), + static_cast(v.stride(3)), + static_cast(g.stride(1)), + static_cast(g.stride(2)), + static_cast(state.stride(0)), + static_cast(state.stride(1)), + static_cast(state.stride(2)), + static_cast(state.stride(3)), + static_cast(out.stride(1)), + static_cast(out.stride(2)), + static_cast(out.stride(3)), scale, reference, + static_cast(block_size), static_cast(state.size(0)), + static_cast(q.size(2)), static_cast(k.size(2)), + static_cast(num_v_heads), + static_cast(logit_scale.dtype()), + static_cast(history_bias.dtype()), + static_cast(history_c.dtype())); + }, + "CudaCloverLocalMemory::operator()"); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_LOCAL_MEMORY_KERNEL_H_ diff --git a/src/native/cuda/ops/clover_mask_routes/kernel.cuh b/src/native/cuda/ops/clover_mask_routes/kernel.cuh new file mode 100644 index 000000000..d5bbac762 --- /dev/null +++ b/src/native/cuda/ops/clover_mask_routes/kernel.cuh @@ -0,0 +1,57 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_MASK_ROUTES_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CLOVER_MASK_ROUTES_KERNEL_CUH_ + +#include + +#include "data_type.h" + +namespace infini::ops { + +// Shared-layer SIMT kernel for CloverMaskRoutes, mirroring stage 1 of the +// Triton `clover_live_rows` kernel: live rows pass their route through +// unchanged (negative/dead ids included), non-live rows are replaced by +// `num_experts` (the routing mask value). `ids` layout is [rows, topk] and +// `live` is per row. +// +// A row's width that is a power of two (the usual top-k) makes the row a +// shift of the element index; any other width takes the kernel that divides. +namespace clover_mask_routes_detail { + +template +__device__ __forceinline__ void MaskRoute(const Index* __restrict__ ids, + const int8_t* __restrict__ live, + Index mask, int64_t row, int64_t i, + Index* __restrict__ out) { + // Both are read before the flag selects: a load that waits for the flag + // would cost a second memory latency. + const Index route = ids[i]; + const int8_t flag = live[row]; + out[i] = flag != 0 ? route : mask; +} + +} // namespace clover_mask_routes_detail + +template +__global__ void CloverMaskRoutesKernel(const Index* __restrict__ ids, + const int8_t* __restrict__ live, + Index mask, int shift, + Index* __restrict__ out, int64_t n) { + const int64_t i = static_cast(blockIdx.x) * blockDim.x + + static_cast(threadIdx.x); + if (i >= n) return; + clover_mask_routes_detail::MaskRoute(ids, live, mask, i >> shift, i, out); +} + +template +__global__ void CloverMaskRoutesByDivisionKernel( + const Index* __restrict__ ids, const int8_t* __restrict__ live, Index mask, + int64_t width, Index* __restrict__ out, int64_t n) { + const int64_t i = static_cast(blockIdx.x) * blockDim.x + + static_cast(threadIdx.x); + if (i >= n) return; + clover_mask_routes_detail::MaskRoute(ids, live, mask, i / width, i, out); +} + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_MASK_ROUTES_KERNEL_CUH_ diff --git a/src/native/cuda/ops/clover_mask_routes/kernel.h b/src/native/cuda/ops/clover_mask_routes/kernel.h new file mode 100644 index 000000000..a3a5569e2 --- /dev/null +++ b/src/native/cuda/ops/clover_mask_routes/kernel.h @@ -0,0 +1,56 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_MASK_ROUTES_KERNEL_H_ +#define INFINI_OPS_CUDA_CLOVER_MASK_ROUTES_KERNEL_H_ + +#include "base/clover_mask_routes.h" +#include "common/generic_utils.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/ops/clover_mask_routes/kernel.cuh" + +namespace infini::ops { + +template +class CudaCloverMaskRoutes : public CloverMaskRoutes { + public: + using CloverMaskRoutes::CloverMaskRoutes; + + void operator()(const Tensor ids, const Tensor live, int64_t num_experts, + Tensor out) const override { + const auto n = ids.numel(); + if (n == 0) return; + const auto width = ids.size(1); + auto cuda_stream = + static_cast(stream_ ? stream_ : 0); + constexpr unsigned int kThreads = 256; + const auto blocks = utils::CeilDiv(n, static_cast(kThreads)); + // A row's width that is a power of two turns the row index into a + // shift; any other width keeps the division. + const int shift = utils::Log2IfPowerOfTwo(width); + + DispatchFunc>( + {static_cast(ids.dtype())}, + [&](auto list_tag) { + using Index = TypeMapType(list_tag)>; + const Index* id_data = reinterpret_cast(ids.data()); + const int8_t* live_data = + reinterpret_cast(live.data()); + Index* out_data = reinterpret_cast(out.data()); + const Index mask = static_cast(num_experts); + if (shift >= 0) { + CloverMaskRoutesKernel + <<(blocks), kThreads, 0, cuda_stream>>>( + id_data, live_data, mask, shift, out_data, n); + } else { + CloverMaskRoutesByDivisionKernel + <<(blocks), kThreads, 0, cuda_stream>>>( + id_data, live_data, mask, static_cast(width), + out_data, n); + } + }, + "CudaCloverMaskRoutes::operator()"); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_MASK_ROUTES_KERNEL_H_ diff --git a/src/native/cuda/ops/clover_merge_moe/kernel.cuh b/src/native/cuda/ops/clover_merge_moe/kernel.cuh new file mode 100644 index 000000000..9506942b1 --- /dev/null +++ b/src/native/cuda/ops/clover_merge_moe/kernel.cuh @@ -0,0 +1,62 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_MERGE_MOE_KERNEL_CUH_ +#define INFINI_OPS_CUDA_CLOVER_MERGE_MOE_KERNEL_CUH_ + +#include + +#include "data_type.h" + +namespace infini::ops { + +// Shared-layer SIMT kernel for CloverMergeMoe, mirroring stage 2 of the +// Triton `clover_live_rows` kernel: freshly computed values replace the +// cache on live rows and are propagated to the output; cached values are +// reused on non-live rows. `fresh`/`cache`/`out` share [rows, width]. +// +// A thread block covers columns of one row, so the row's flag is a single +// load for all of its threads, and no thread has to divide to find its row. +// Only a live row's cache entry is written back: a dead row's already holds +// the value it keeps. +// +// Grid: x = rows (the grid's x axis takes far more than the 65535 of y +// and z), y = the row's columns, one element or one 16-byte vector per +// thread. + +template +__global__ void CloverMergeMoeKernel(const Data* __restrict__ fresh, + const int8_t* __restrict__ live, + Data* __restrict__ cache, + Data* __restrict__ out, int64_t width) { + const int64_t column = + static_cast(blockIdx.y) * blockDim.x + threadIdx.x; + if (column >= width) return; + const int64_t row = blockIdx.x; + const int64_t i = row * width + column; + const bool on = live[row] != 0; + const Data value = on ? fresh[i] : cache[i]; + out[i] = value; + if (on) cache[i] = value; +} + +// The same with 16 bytes per thread: `vectors` is a row's width in such +// vectors and the three tensors start on a 16-byte boundary. +template +__global__ void CloverMergeMoeVectorKernel(const Data* __restrict__ fresh, + const int8_t* __restrict__ live, + Data* __restrict__ cache, + Data* __restrict__ out, + int64_t vectors) { + const int64_t column = + static_cast(blockIdx.y) * blockDim.x + threadIdx.x; + if (column >= vectors) return; + const int64_t row = blockIdx.x; + const int64_t i = row * vectors + column; + const bool on = live[row] != 0; + const uint4 value = on ? reinterpret_cast(fresh)[i] + : reinterpret_cast(cache)[i]; + reinterpret_cast(out)[i] = value; + if (on) reinterpret_cast(cache)[i] = value; +} + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_MERGE_MOE_KERNEL_CUH_ diff --git a/src/native/cuda/ops/clover_merge_moe/kernel.h b/src/native/cuda/ops/clover_merge_moe/kernel.h new file mode 100644 index 000000000..0c88053bc --- /dev/null +++ b/src/native/cuda/ops/clover_merge_moe/kernel.h @@ -0,0 +1,84 @@ +#ifndef INFINI_OPS_CUDA_CLOVER_MERGE_MOE_KERNEL_H_ +#define INFINI_OPS_CUDA_CLOVER_MERGE_MOE_KERNEL_H_ + +#include + +#include "base/clover_merge_moe.h" +#include "common/generic_utils.h" +#include "data_type.h" +#include "dispatcher.h" +#include "native/cuda/ops/clover_merge_moe/kernel.cuh" + +namespace infini::ops { + +namespace clover_merge_moe_detail { + +constexpr unsigned int kThreads = 128; +constexpr int kVectorBytes = 16; + +// Whether a thread can take 16 bytes of a row: the element is 16 or 32 +// bits wide, the row's width is a whole number of vectors, and every tensor +// starts on a 16-byte boundary. +inline bool VectorRows(const Tensor& fresh, const Tensor& cache, + const Tensor& out) { + const auto element = fresh.element_size(); + if (element != 2 && element != 4) return false; + if (fresh.size(1) % (kVectorBytes / element) != 0) return false; + for (const Tensor* tensor : {&fresh, &cache, &out}) { + if (reinterpret_cast(tensor->data()) % kVectorBytes != 0) + return false; + } + return true; +} + +} // namespace clover_merge_moe_detail + +template +class CudaCloverMergeMoe : public CloverMergeMoe { + public: + using CloverMergeMoe::CloverMergeMoe; + + void operator()(const Tensor fresh, const Tensor live, Tensor cache, + Tensor out) const override { + const auto rows = fresh.size(0); + const auto width = fresh.size(1); + if (rows == 0 || width == 0) return; + auto cuda_stream = + static_cast(stream_ ? stream_ : 0); + namespace detail = clover_merge_moe_detail; + const int per_thread = + detail::VectorRows(fresh, cache, out) + ? static_cast(detail::kVectorBytes / fresh.element_size()) + : 1; + const auto columns = width / per_thread; + // Rows on the x axis: it takes 2^31 blocks where y would stop at 65535. + const dim3 grid( + static_cast(rows), + static_cast(utils::CeilDiv(columns, detail::kThreads))); + + DispatchFunc, ReducedFloatTypes>>( + {static_cast(fresh.dtype())}, + [&](auto list_tag) { + using Data = TypeMapType(list_tag)>; + const Data* fresh_data = reinterpret_cast(fresh.data()); + const int8_t* live_data = + reinterpret_cast(live.data()); + Data* cache_data = reinterpret_cast(cache.data()); + Data* out_data = reinterpret_cast(out.data()); + if (per_thread == 1) { + CloverMergeMoeKernel + <<>>( + fresh_data, live_data, cache_data, out_data, width); + } else { + CloverMergeMoeVectorKernel + <<>>( + fresh_data, live_data, cache_data, out_data, columns); + } + }, + "CudaCloverMergeMoe::operator()"); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_CLOVER_MERGE_MOE_KERNEL_H_ diff --git a/src/native/cuda/ops/fused_gated_delta_net_gating/kernel.cuh b/src/native/cuda/ops/fused_gated_delta_net_gating/kernel.cuh new file mode 100644 index 000000000..47ba357e1 --- /dev/null +++ b/src/native/cuda/ops/fused_gated_delta_net_gating/kernel.cuh @@ -0,0 +1,47 @@ +#ifndef INFINI_OPS_CUDA_FUSED_GATED_DELTA_NET_GATING_KERNEL_CUH_ +#define INFINI_OPS_CUDA_FUSED_GATED_DELTA_NET_GATING_KERNEL_CUH_ + +#include +#include +#include + +#include "data_type.h" + +namespace infini::ops { +namespace gating_detail { + +struct Layout { + ptrdiff_t strides[6][3]{}; + size_t total, seq, hidden; + float beta, threshold; +}; + +// One thread per (batch, sequence, hidden) element turns the gating +// projections into the log decay `g` and the delta-rule coefficient `betao`. +template +__global__ void GatingKernel(const T* A, const T* a, const T* b, const T* dt, + float* g, float* betao, Layout p) { + const size_t linear = + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (linear >= p.total) return; + const size_t h = linear % p.hidden, s = (linear / p.hidden) % p.seq; + const size_t batch = linear / p.hidden / p.seq; + ptrdiff_t offsets[6]; + for (int i = 0; i < 6; ++i) + offsets[i] = static_cast(batch) * p.strides[i][0] + + static_cast(s) * p.strides[i][1] + + static_cast(h) * p.strides[i][2]; + const float x = static_cast(a[offsets[1]]) + + static_cast(dt[h * p.strides[3][0]]); + const float bx = p.beta * x; + const float softplus = bx <= p.threshold ? log1pf(expf(bx)) / p.beta : x; + g[offsets[4]] = -expf(static_cast(A[h * p.strides[0][0]])) * softplus; + const float bv = static_cast(b[offsets[2]]); + const float z = expf(bv >= 0 ? -bv : bv); + betao[offsets[5]] = bv >= 0 ? 1.0f / (1.0f + z) : z / (1.0f + z); +} + +} // namespace gating_detail +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_FUSED_GATED_DELTA_NET_GATING_KERNEL_CUH_ diff --git a/src/native/cuda/ops/fused_gated_delta_net_gating/kernel.h b/src/native/cuda/ops/fused_gated_delta_net_gating/kernel.h new file mode 100644 index 000000000..582961ea7 --- /dev/null +++ b/src/native/cuda/ops/fused_gated_delta_net_gating/kernel.h @@ -0,0 +1,102 @@ +#ifndef INFINI_OPS_CUDA_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ +#define INFINI_OPS_CUDA_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ + +#include +#include +#include +#include + +#include "base/fused_gated_delta_net_gating.h" +#include "device.h" +#include "native/cuda/ops/fused_gated_delta_net_gating/kernel.cuh" + +namespace infini::ops { + +// Gates of a gated delta net: the log decay from `A`, `a` and `dt_bias`, and +// the delta-rule coefficient as the sigmoid of `b`. +template +class CudaFusedGatedDeltaNetGating : public FusedGatedDeltaNetGating { + public: + CudaFusedGatedDeltaNetGating(Tensor A, Tensor a, Tensor b, Tensor dt, + float beta, float threshold, Tensor g, + Tensor betao) + : FusedGatedDeltaNetGating(A, a, b, dt, beta, threshold, g, betao) { + if (device_.type() != Backend::kDeviceType) + throw std::invalid_argument("gating requires its provider's device"); + check_device(); + if (total_ / 256 + (total_ % 256 != 0) > + std::numeric_limits::max()) + throw std::overflow_error("gating grid exceeds the launch limit"); + p_.total = total_; + p_.seq = seq_; + p_.hidden = hidden_; + p_.beta = beta; + p_.threshold = threshold; + for (size_t i = 0; i < 6; ++i) + for (size_t j = 0; j < metadata_[i].strides().size(); ++j) + p_.strides[i][j] = metadata_[i].strides()[j]; + } + + // All metadata is a kernel value argument. There is no allocation, host copy, + // synchronization or data-dependent host work in operator(); stream launch + // is capturable. Make owns no device resources and requires zero workspace. + bool capture_safe() const override { return true; } + + void operator()(Tensor A, Tensor a, Tensor b, Tensor dt, float beta, + float threshold, Tensor g, Tensor betao) const override { + check_device(); + std::array tensors{A, a, b, dt, g, betao}; + for (size_t i = 0; i < 6; ++i) + if (!std::equal_to{}(tensors[i], metadata_[i])) + throw std::invalid_argument("gating metadata changed after Make"); + if (std::memcmp(&beta, &beta_, sizeof(float)) || + std::memcmp(&threshold, &threshold_, sizeof(float))) + throw std::invalid_argument("gating attributes changed after Make"); + if (!total_) return; + const dim3 grid( + static_cast(total_ / 256 + (total_ % 256 != 0))); + const auto stream = + static_cast(stream_ ? stream_ : nullptr); + switch (metadata_[1].dtype()) { + case DataType::kFloat32: + launch(A, a, b, dt, g, betao, grid, stream); + break; + case DataType::kFloat16: + launch>( + A, a, b, dt, g, betao, grid, stream); + break; + case DataType::kBFloat16: + launch>( + A, a, b, dt, g, betao, grid, stream); + break; + default: + throw std::invalid_argument("gating dtype unsupported"); + } + } + + private: + gating_detail::Layout p_{}; + + void check_device() const { + int current = -1; + if (Backend::GetDevice(¤t) != Backend::kSuccess) + throw std::runtime_error("gating device query failed"); + if (current != device_.index()) + throw std::invalid_argument("gating owner device mismatch"); + } + + template + void launch(Tensor A, Tensor a, Tensor b, Tensor dt, Tensor g, Tensor betao, + dim3 grid, typename Backend::Stream stream) const { + gating_detail::GatingKernel + <<>>( + static_cast(A.data()), static_cast(a.data()), + static_cast(b.data()), static_cast(dt.data()), + static_cast(g.data()), static_cast(betao.data()), + p_); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_FUSED_GATED_DELTA_NET_GATING_KERNEL_H_ diff --git a/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.cuh b/src/native/cuda/ops/moe_align_block_size/kernel.cuh similarity index 92% rename from src/native/cuda/nvidia/ops/moe_align_block_size/kernel.cuh rename to src/native/cuda/ops/moe_align_block_size/kernel.cuh index 3e90713e4..e96cf86e7 100644 --- a/src/native/cuda/nvidia/ops/moe_align_block_size/kernel.cuh +++ b/src/native/cuda/ops/moe_align_block_size/kernel.cuh @@ -1,9 +1,11 @@ -#ifndef INFINI_OPS_NVIDIA_MOE_ALIGN_BLOCK_SIZE_KERNEL_CUH_ -#define INFINI_OPS_NVIDIA_MOE_ALIGN_BLOCK_SIZE_KERNEL_CUH_ +#ifndef INFINI_OPS_CUDA_MOE_ALIGN_BLOCK_SIZE_KERNEL_CUH_ +#define INFINI_OPS_CUDA_MOE_ALIGN_BLOCK_SIZE_KERNEL_CUH_ #include #include +#include "data_type.h" + namespace infini::ops { namespace moe_align_block_size_detail { @@ -21,6 +23,7 @@ __device__ __forceinline__ int32_t MapExpertId(int32_t expert_id, return expert_id >= 0 && expert_id < num_experts ? expert_id : -1; } +template __global__ void MoeAlignBlockSizeKernel( const int32_t* __restrict__ topk_ids, const int32_t* __restrict__ expert_map, @@ -83,4 +86,4 @@ __global__ void MoeAlignBlockSizeKernel( } // namespace moe_align_block_size_detail } // namespace infini::ops -#endif // INFINI_OPS_NVIDIA_MOE_ALIGN_BLOCK_SIZE_KERNEL_CUH_ +#endif // INFINI_OPS_CUDA_MOE_ALIGN_BLOCK_SIZE_KERNEL_CUH_ diff --git a/src/native/cuda/ops/moe_align_block_size/kernel.h b/src/native/cuda/ops/moe_align_block_size/kernel.h new file mode 100644 index 000000000..d27253d52 --- /dev/null +++ b/src/native/cuda/ops/moe_align_block_size/kernel.h @@ -0,0 +1,81 @@ +#ifndef INFINI_OPS_CUDA_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ +#define INFINI_OPS_CUDA_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ + +#include + +#include "base/moe_align_block_size.h" +#include "device.h" +#include "native/cuda/ops/moe_align_block_size/kernel.cuh" + +namespace infini::ops { +namespace moe_align_block_size_detail { + +// Selects the tensor's device for the launch and restores the previous one. +template +class DeviceGuard { + public: + explicit DeviceGuard(int device) { + if (Backend::GetDevice(&previous_) != Backend::kSuccess || + previous_ == device) { + return; + } + restore_ = Backend::SetDevice(device) == Backend::kSuccess; + } + + ~DeviceGuard() { + if (restore_) { + Backend::SetDevice(previous_); + } + } + + private: + int previous_{-1}; + + bool restore_{false}; +}; + +} // namespace moe_align_block_size_detail + +// One block counts the routes per expert, writes the block plan and sorts the +// token indices into expert-aligned blocks. +template +class CudaMoeAlignBlockSize : public MoeAlignBlockSize { + public: + using MoeAlignBlockSize::MoeAlignBlockSize; + using MoeAlignBlockSize::operator(); + + bool capture_safe() const override { return true; } + + protected: + void Run(const Tensor topk_ids, const std::optional maybe_expert_map, + const int64_t num_experts, const int64_t block_size, + Tensor sorted_token_ids, Tensor experts_ids, + Tensor num_tokens_post_pad) const override { + moe_align_block_size_detail::DeviceGuard guard{ + static_cast(topk_ids_metadata_.device().index())}; + + constexpr int32_t kThreads = 256; + const auto shared_memory_size = + static_cast(num_experts_) * sizeof(int32_t); + moe_align_block_size_detail::MoeAlignBlockSizeKernel + <<<1, kThreads, shared_memory_size, + static_cast(stream_ ? stream_ + : nullptr)>>>( + reinterpret_cast(topk_ids.data()), + maybe_expert_map + ? reinterpret_cast(maybe_expert_map->data()) + : nullptr, + reinterpret_cast(sorted_token_ids.data()), + reinterpret_cast(experts_ids.data()), + reinterpret_cast(num_tokens_post_pad.data()), numel_, + static_cast(num_experts_), + static_cast(block_size_), sorted_token_ids_size_, + experts_ids_size_, + maybe_expert_map ? static_cast(maybe_expert_map->numel()) + : 0); + } +}; + +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_MOE_ALIGN_BLOCK_SIZE_KERNEL_H_ diff --git a/src/native/cuda/ops/recurrent_gated_delta_rule/kernel.h b/src/native/cuda/ops/recurrent_gated_delta_rule/kernel.h index 94a169cc7..0d5f170f5 100644 --- a/src/native/cuda/ops/recurrent_gated_delta_rule/kernel.h +++ b/src/native/cuda/ops/recurrent_gated_delta_rule/kernel.h @@ -6,6 +6,7 @@ #include "base/recurrent_gated_delta_rule.h" #include "native/cuda/ops/recurrent_gated_delta_rule/recurrent_delta_rule_common.cuh" +#include "native/cuda/ops/recurrent_gated_delta_rule/recurrent_delta_rule_packed_kernel.cuh" #include "native/cuda/ops/recurrent_gated_delta_rule/recurrent_gated_delta_rule_legacy_kernel.cuh" // cuda_fp16.h / cuda_bf16.h come from the CUDA runtime on NVIDIA and from @@ -37,8 +38,9 @@ __global__ void kernel(const Data* q, const Data* k, const Data* v, } } // namespace recurrent_gated_delta_rule_detail -// Single-token decode kernel for gated delta rule, shared by the CUDA-like -// backends. The `Backend` type must expose `kDeviceType` and `Stream` +// Gated delta rule kernels shared by the CUDA-like backends: the batched +// single-token decode and the packed multi-token recurrence over an FP32 +// state pool. The `Backend` type must expose `kDeviceType` and `Stream` // (the metax and nvidia runtimes both do). Backend-specific host-side // checks stay in the per-device providers. template @@ -85,6 +87,28 @@ class CudaRecurrentGatedDeltaRule : public RecurrentGatedDeltaRule { p_.s[i][j] = metadata_[i]->strides()[j]; } + // Packed form; see the base class. + CudaRecurrentGatedDeltaRule(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, + Tensor initial_state, const Tensor cu_seqlens, + const Tensor initial_slots, + const Tensor final_slots, Tensor out, + bool use_qk_l2norm) + : RecurrentGatedDeltaRule(q, k, v, g, beta, initial_state, cu_seqlens, + initial_slots, final_slots, out, + use_qk_l2norm) { + if (D_ != 128 || gate_type_ != DataType::kFloat32) + throw std::invalid_argument( + "packed recurrent delta kernels require Dk=Dv128 and F32 gates"); + if (requests_ >= static_cast(INT_MAX) || Hv_ > 65535) + throw std::invalid_argument("recurrent delta launch extent unsupported"); + for (const auto i : {size_t{0}, size_t{1}, size_t{2}, size_t{9}}) { + if (metadata_[i]->numel() && metadata_[i]->strides()[3] != 1) + throw std::invalid_argument( + "recurrent delta innermost data dimension must be contiguous"); + } + } + void operator()(const Tensor q, const Tensor k, const Tensor v, const Tensor g, const Tensor beta, Tensor initial_state, const std::optional initial_state_indices, @@ -118,6 +142,31 @@ class CudaRecurrentGatedDeltaRule : public RecurrentGatedDeltaRule { } } + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, Tensor initial_state, + const Tensor cu_seqlens, const Tensor initial_slots, + const Tensor final_slots, Tensor out, + bool use_qk_l2norm) const override { + const Views views{ + q, k, v, g, beta, initial_state, cu_seqlens, initial_slots, + final_slots, out}; + CheckInvocation(views, use_qk_l2norm); + if (!requests_ || !tokens_) return; + switch (data_type_) { + case DataType::kFloat16: + packed(views); + break; + case DataType::kBFloat16: + packed<__nv_bfloat16>(views); + break; + case DataType::kFloat32: + packed(views); + break; + default: + throw std::invalid_argument("recurrent delta data dtype unsupported"); + } + } + protected: ~CudaRecurrentGatedDeltaRule() = default; @@ -165,6 +214,37 @@ class CudaRecurrentGatedDeltaRule : public RecurrentGatedDeltaRule { ptr(6), ptr(7), static_cast(ptr(8)), static_cast(ptr(9)), p_); } + template + void packed(const Views& v) const { + auto ptr = [&](size_t i) -> void* { + return const_cast(v[i]->data()); + }; + const auto stride = [&](size_t i, size_t j) -> int64_t { + return metadata_[i]->strides()[j]; + }; + // One warp per value row: 4 rows per block, grid.z tiles the head dim. + constexpr int kWarps = 4; + dim3 grid(static_cast(requests_), + static_cast(Hv_), D_ / kWarps); + const auto stream = + static_cast(stream_ ? stream_ : nullptr); + recurrent_gated_delta_rule_detail::PackedRecurrentGatedDeltaRuleKernel< + Backend::kDeviceType, Data, 128, kWarps> + <<>>( + static_cast(ptr(0)), static_cast(ptr(1)), + static_cast(ptr(2)), static_cast(ptr(3)), + static_cast(ptr(4)), ptr(6), ptr(7), ptr(8), + metadata_[6]->dtype() == DataType::kInt64, + metadata_[7]->dtype() == DataType::kInt64, + metadata_[8]->dtype() == DataType::kInt64, norm_, + static_cast(ptr(5)), static_cast(ptr(9)), + stride(0, 1), stride(0, 2), stride(1, 1), stride(1, 2), + stride(2, 1), stride(2, 2), stride(3, 1), stride(3, 2), + stride(4, 1), stride(4, 2), stride(5, 0), stride(5, 1), + stride(5, 2), stride(5, 3), stride(9, 1), stride(9, 2), + static_cast(tokens_), static_cast(pool_), + static_cast(Hk_)); + } }; } // namespace infini::ops diff --git a/src/native/cuda/ops/recurrent_gated_delta_rule/recurrent_delta_rule_packed_kernel.cuh b/src/native/cuda/ops/recurrent_gated_delta_rule/recurrent_delta_rule_packed_kernel.cuh new file mode 100644 index 000000000..dd47a3933 --- /dev/null +++ b/src/native/cuda/ops/recurrent_gated_delta_rule/recurrent_delta_rule_packed_kernel.cuh @@ -0,0 +1,170 @@ +#ifndef INFINI_OPS_CUDA_RECURRENT_DELTA_RULE_PACKED_KERNEL_CUH_ +#define INFINI_OPS_CUDA_RECURRENT_DELTA_RULE_PACKED_KERNEL_CUH_ + +#include + +#include "data_type.h" +#include "native/cuda/caster.cuh" + +namespace infini::ops { +namespace recurrent_gated_delta_rule_detail { + +__device__ inline int64_t PackedIndex(const void* p, bool i64, int i, + int64_t fallback) { + return p ? (i64 ? static_cast(p)[i] + : static_cast(static_cast(p)[i])) + : fallback; +} + +// Sequential gated delta rule over packed request sequences with an FP32 +// state pool: the math of the single-token kernel, run token by token. +// Warp-cooperative layout: one warp owns one value row of the [V=128, K=128] +// state; the 32 lanes split the K axis, so every dot product over K becomes a +// fixed-order warp shuffle reduction (deterministic) and the normalized k +// vector is staged once per token in shared memory instead of being recomputed +// per row. The state of the row lives in four registers per lane, read from +// the initial slot and written once to the final slot, which leaves a +// differing initial slot unchanged. +// state *= exp(g); delta = (v - state·k) * beta; state += delta⊗k; y = +// state·q +// Grid: x = requests, y = value heads, z = value-row tiles; block = kWarps +// warps of 32 lanes. `kDim` is the head dimension; the query scale below is +// written for 128. +template +__global__ void PackedRecurrentGatedDeltaRuleKernel( + const Data* __restrict__ q, const Data* __restrict__ k, + const Data* __restrict__ v, const float* __restrict__ g, + const float* __restrict__ beta, const void* __restrict__ cu_seqlens, + const void* __restrict__ initial_indices, + const void* __restrict__ final_indices, bool offsets_i64, bool initial_i64, + bool final_i64, bool norm, float* __restrict__ state, + Data* __restrict__ out, int64_t qs, int64_t qh, int64_t ks, int64_t kh, + int64_t vs, int64_t vh, int64_t gs, int64_t gh, int64_t bs, int64_t bh, + int64_t ss, int64_t sh, int64_t sv, int64_t sk, int64_t os, int64_t oh, + int64_t tokens, int64_t pool, int num_k_heads) { + constexpr int kLanes = 32; // warp width on supported backends + constexpr int kPerLane = kDim / kLanes; // keys per lane + static_assert(kDim == 128, "the query scale is written for D == 128"); + constexpr float kQueryScale = 0.08838834764831845f; + + const int request = static_cast(blockIdx.x); + const int head = static_cast(blockIdx.y); + const int warp = static_cast(threadIdx.x) / kLanes; + const int lane = static_cast(threadIdx.x) % kLanes; + if (warp >= kWarps) return; + const int value_row = + static_cast(blockIdx.z) * kWarps + warp; // absolute row 0..V-1 + + const int64_t begin = PackedIndex(cu_seqlens, offsets_i64, request, 0); + const int64_t end = PackedIndex(cu_seqlens, offsets_i64, request + 1, 0); + const int64_t initial = + PackedIndex(initial_indices, initial_i64, request, -1); + const int64_t final_slot = PackedIndex(final_indices, final_i64, request, -1); + const bool range_ok = begin >= 0 && end >= begin && end <= tokens; + const bool slots_ok = + initial >= 0 && initial < pool && final_slot >= 0 && final_slot < pool; + if (!range_ok) return; + if (!slots_ok) { + // Same as the batched form: an unusable slot zeroes the output only. + const Data zero = Caster::template Cast(0.0f); + for (int64_t token = begin; token < end; ++token) + if (lane == 0) out[token * os + head * oh + value_row] = zero; + return; + } + + const int k_head = head / max(1, (int)gridDim.y / max(1, num_k_heads)); + + extern __shared__ float smem[]; + float* k_norm = smem; // [kWarps][kDim] + + float* state_row = + state + initial * ss + head * sh + static_cast(value_row) * sv; + float* final_row = state + final_slot * ss + head * sh + + static_cast(value_row) * sv; + + float st[kPerLane]; +#pragma unroll + for (int e = 0; e < kPerLane; ++e) + st[e] = state_row[(lane * kPerLane + e) * sk]; + + for (int64_t token = begin; token < end; ++token) { + // ---- k: cooperative load + fixed-order square-sum reduction ---- + const Data* k_row = k + token * ks + k_head * kh; + float kv[kPerLane]; + float k_sq = 0.0f; +#pragma unroll + for (int e = 0; e < kPerLane; ++e) { + kv[e] = Caster::template Cast(k_row[lane * kPerLane + e]); + k_sq += kv[e] * kv[e]; + } +#pragma unroll + for (int off = kLanes / 2; off > 0; off >>= 1) + k_sq += __shfl_xor_sync(0xffffffffu, k_sq, off); + const float k_scale = norm ? rsqrtf(k_sq + 1.0e-6f) : 1.0f; +#pragma unroll + for (int e = 0; e < kPerLane; ++e) { + kv[e] *= k_scale; + k_norm[warp * kDim + lane * kPerLane + e] = kv[e]; + } + __syncwarp(); + + // ---- decay + remembered = state · k ---- + const float decay = expf(g[token * gs + head * gh]); + const float b = beta[token * bs + head * bh]; + float part = 0.0f; +#pragma unroll + for (int e = 0; e < kPerLane; ++e) { + st[e] *= decay; + part += st[e] * kv[e]; + } +#pragma unroll + for (int off = kLanes / 2; off > 0; off >>= 1) + part += __shfl_xor_sync(0xffffffffu, part, off); + const float remembered = part; + + // ---- delta rule update ---- + const float v_row = Caster::template Cast( + v[token * vs + head * vh + value_row]); + const float delta = (v_row - remembered) * b; + + const Data* q_row = q + token * qs + k_head * qh; + float qv[kPerLane]; + float q_sq = 0.0f; +#pragma unroll + for (int e = 0; e < kPerLane; ++e) { + qv[e] = Caster::template Cast(q_row[lane * kPerLane + e]); + q_sq += qv[e] * qv[e]; + } +#pragma unroll + for (int off = kLanes / 2; off > 0; off >>= 1) + q_sq += __shfl_xor_sync(0xffffffffu, q_sq, off); + const float q_scale = (norm ? rsqrtf(q_sq + 1.0e-6f) : 1.0f) * kQueryScale; + + // ---- state += delta * k; y = state · q (same fixed order) ---- + float y = 0.0f; +#pragma unroll + for (int e = 0; e < kPerLane; ++e) { + st[e] += delta * k_norm[warp * kDim + lane * kPerLane + e]; + qv[e] *= q_scale; + y += st[e] * qv[e]; + } +#pragma unroll + for (int off = kLanes / 2; off > 0; off >>= 1) + y += __shfl_xor_sync(0xffffffffu, y, off); + + if (lane == 0) { + out[token * os + head * oh + value_row] = + Caster::template Cast(y); + } + } + + // Write the final state to the final slot (may equal the initial one). +#pragma unroll + for (int e = 0; e < kPerLane; ++e) + final_row[(lane * kPerLane + e) * sk] = st[e]; +} + +} // namespace recurrent_gated_delta_rule_detail +} // namespace infini::ops + +#endif // INFINI_OPS_CUDA_RECURRENT_DELTA_RULE_PACKED_KERNEL_CUH_ diff --git a/src/triton/jit/backend.h b/src/triton/jit/backend.h index ee080734f..21cf6ee62 100644 --- a/src/triton/jit/backend.h +++ b/src/triton/jit/backend.h @@ -31,6 +31,8 @@ struct Target { int warp_size{0}; }; +Target HygonTarget(int device_id); + enum class DataType { kPointer, kInt8, @@ -111,6 +113,11 @@ struct BackendTraits { static constexpr const char* kName = "cuda"; }; +template <> +struct BackendTraits { + static constexpr const char* kName = "hip"; +}; + template ::kName)>> class Backend { @@ -124,6 +131,9 @@ class Backend { static Target CurrentTarget() { const int device_id = CurrentDevice(); if (device_id < 0) return {}; + if constexpr (kDev == Device::Type::kHygon) { + return HygonTarget(device_id); + } int major = 0; auto status = Runtime::DeviceGetAttribute( @@ -179,12 +189,12 @@ class Backend { constexpr unsigned kDefaultSharedMemoryLimit = 48 * 1024; if (metadata.shared_memory_size > kDefaultSharedMemoryLimit) { int maximum_shared_memory = 0; - status = Runtime::DeviceGetAttribute( + const auto runtime_status = Runtime::DeviceGetAttribute( &maximum_shared_memory, Runtime::kDevAttrMaxSharedMemoryPerBlockOptin, CurrentDevice()); - assert(status == Runtime::kSuccess && + assert(runtime_status == Runtime::kSuccess && "Triton JIT failed to get the shared memory limit."); - if (status != Runtime::kSuccess) { + if (runtime_status != Runtime::kSuccess) { Driver::ModuleUnload(module); return nullptr; } diff --git a/src/triton/jit/compile.py b/src/triton/jit/compile.py index 8b49f8e94..06691366f 100644 --- a/src/triton/jit/compile.py +++ b/src/triton/jit/compile.py @@ -4,6 +4,7 @@ import json import os import tempfile +import threading from contextlib import contextmanager from pathlib import Path @@ -14,8 +15,43 @@ _DRIVER_BACKENDS = { "cuda": "nvidia", + "hip": "amd", } +# Callers reach the JIT from several threads at once, and the native target +# lookup is cached per thread, so concurrent first launches all initialize +# Triton's driver together. Observed hanging inside `triton.runtime.driver`. +# Serialize every entry point before it touches `triton`. +_JIT_LOCK = threading.RLock() + + +def _serialized(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + with _JIT_LOCK: + return func(*args, **kwargs) + + return wrapper + + +@_serialized +def get_hygon_target(device_id): + """Read the compiler target from the active DTK Triton driver.""" + driver = triton.runtime.driver.active + previous = driver.get_current_device() + try: + driver.set_current_device(device_id) + target = driver.get_current_target() + if target.backend != "hip": + raise RuntimeError("Hygon JIT requires a HIP Triton target.") + return { + "backend": target.backend, + "architecture": target.arch, + "warp_size": target.warp_size, + } + finally: + driver.set_current_device(previous) + def _cache_directory(): configured_path = os.environ.get("INFINI_OPS_TRITON_CACHE_DIR") @@ -164,6 +200,7 @@ def _get_kernel_source_path(op_name): return source_path +@_serialized def get_compilation_fingerprint(op_name): kernel = _load_kernel(op_name) digest = hashlib.sha256() @@ -211,7 +248,13 @@ def _use_device(target, device_id, stream): previous_driver = triton.runtime.driver.active previous_device = previous_driver.get_current_device() driver_backend = _DRIVER_BACKENDS[target["backend"]] - active_driver = triton.backends.backends[driver_backend].driver() + if target["backend"] == "hip": + # DTK supplies a vendor driver with its own device-property ABI. + active_driver = previous_driver + if active_driver.get_current_target().backend != "hip": + raise RuntimeError("HIP auto-tuning requires the active HIP driver.") + else: + active_driver = triton.backends.backends[driver_backend].driver() try: triton.runtime.driver.set_active(active_driver) @@ -312,8 +355,12 @@ def _write_artifacts(compiled_kernel, target, output_prefix, cache_identity): "num_warps": compiled_kernel.metadata.num_warps, "binary_ext": binary_extension, "shared": compiled_kernel.metadata.shared, - "global_scratch_size": compiled_kernel.metadata.global_scratch_size, - "profile_scratch_size": compiled_kernel.metadata.profile_scratch_size, + "global_scratch_size": getattr( + compiled_kernel.metadata, "global_scratch_size", 0 + ), + "profile_scratch_size": getattr( + compiled_kernel.metadata, "profile_scratch_size", 0 + ), "cache_identity": cache_identity, } temporary_paths = [] @@ -340,6 +387,7 @@ def _write_artifacts(compiled_kernel, target, output_prefix, cache_identity): temporary_path.unlink(missing_ok=True) +@_serialized def compile_kernel(op_name, output_prefix, signature, config, target, cache_identity): kernel = _load_kernel(op_name) compilation_target = _create_target(target) @@ -395,6 +443,7 @@ def _benchmark_candidate( ) +@_serialized def auto_tune( op_name, candidates, diff --git a/src/triton/jit/compiler.cc b/src/triton/jit/compiler.cc index d22323661..966a4a788 100644 --- a/src/triton/jit/compiler.cc +++ b/src/triton/jit/compiler.cc @@ -142,6 +142,23 @@ py::list BuildArguments(const std::vector& arguments) { } // namespace +Target HygonTarget(int device_id) { + static thread_local std::unordered_map targets; + const auto cached = targets.find(device_id); + if (cached != targets.end()) return cached->second; + const auto target = RunPython("Hygon target lookup", [&] { + const auto value = CompilerFunction("get_hygon_target")(device_id); + return Target{value["backend"].cast(), + value["architecture"].cast(), + value["warp_size"].cast()}; + }); + assert(target.has_value() && + "Triton JIT failed to identify the Hygon target."); + if (!target) return {}; + targets.emplace(device_id, *target); + return *target; +} + std::string CompilationFingerprint(const std::string& op_name) { static std::mutex cache_mutex; static std::unordered_map cache; diff --git a/src/triton/ops/add/jit.h b/src/triton/ops/add/jit.h index da3274c5c..821dbe1fb 100644 --- a/src/triton/ops/add/jit.h +++ b/src/triton/ops/add/jit.h @@ -95,6 +95,13 @@ class Operator using triton::jit::Add::Add; }; +template <> +class Operator + : public triton::jit::Add { + public: + using triton::jit::Add::Add; +}; + } // namespace infini::ops #endif diff --git a/src/triton/ops/clover_block_conv1d/jit.h b/src/triton/ops/clover_block_conv1d/jit.h new file mode 100644 index 000000000..e3455dd0e --- /dev/null +++ b/src/triton/ops/clover_block_conv1d/jit.h @@ -0,0 +1,64 @@ +#pragma once + +#include "base/clover_block_conv1d.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class CloverBlockConv1d : public ::infini::ops::CloverBlockConv1d { + public: + using ::infini::ops::CloverBlockConv1d::CloverBlockConv1d; + + void operator()(const Tensor input, const Tensor state, const Tensor indices, + const Tensor weight, const Tensor right_weight, + const Tensor valid, size_t block_size, + Tensor out) const override { + if (input.numel() == 0) return; + const Config config{4u, + 1u, + {{"NUM_CHANNELS", input.size(1)}, + {"BLOCK_SIZE", block_size}, + {"NUM_SLOTS", state.size(0)}, + {"WIDTH", 4}, + {"HAS_BIAS", 0}, + {"INDEPENDENT_SYMMETRIC", 1}, + {"BLOCK_T", 4}, + {"NUM_TOKEN_TILES", (block_size + 3) / 4}, + {"BLOCK_C", 128}}}; + Launch( + "clover_block_conv1d", input.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{ + static_cast((input.size(1) + 127) / 128), + static_cast(indices.numel() * ((block_size + 3) / 4))}; + }, + input, state, indices, weight, weight, right_weight, valid, out, + input.stride(0), input.stride(1), state.stride(0), state.stride(1), + state.stride(2), weight.stride(0), weight.stride(2), + right_weight.stride(0), right_weight.stride(2), out.stride(0), + out.stride(1)); + } +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::CloverBlockConv1d { + public: + using triton::jit::CloverBlockConv1d< + Device::Type::kNvidia>::CloverBlockConv1d; +}; + +template <> +class Operator + : public triton::jit::CloverBlockConv1d { + public: + using triton::jit::CloverBlockConv1d::CloverBlockConv1d; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/clover_block_conv1d/jit.py b/src/triton/ops/clover_block_conv1d/jit.py new file mode 100644 index 000000000..898fa496b --- /dev/null +++ b/src/triton/ops/clover_block_conv1d/jit.py @@ -0,0 +1,145 @@ +# SPDX-License-Identifier: Apache-2.0 +# Adapted from SGLang PR #46927, commit 058939af24d5cdc44bb4b8852d0ddfab555ed71e. +# Changes: InfiniOps JIT entry point, Hygon launch geometry and pool bounds. +import triton +import triton.language as tl + + +@triton.jit +def clover_block_conv1d_kernel( + input_ptr, + clean_state_ptr, + cache_indices_ptr, + weight_ptr, + bias_ptr, + right_weight_ptr, + active_valid_ptr, + output_ptr, + input_stride_t, + input_stride_c, + state_stride_slot, + state_stride_c, + state_stride_w, + weight_stride_c, + weight_stride_w, + right_weight_stride_c, + right_weight_stride_w, + output_stride_t, + output_stride_c, + NUM_CHANNELS: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + NUM_SLOTS: tl.constexpr, + WIDTH: tl.constexpr, + HAS_BIAS: tl.constexpr, + INDEPENDENT_SYMMETRIC: tl.constexpr, + BLOCK_T: tl.constexpr, + NUM_TOKEN_TILES: tl.constexpr, + BLOCK_C: tl.constexpr, +): + channel_offsets = tl.program_id(0) * BLOCK_C + tl.arange(0, BLOCK_C) + token_program = tl.program_id(1) + request_idx = token_program // NUM_TOKEN_TILES + token_tile = token_program % NUM_TOKEN_TILES + token_offsets = token_tile * BLOCK_T + tl.arange(0, BLOCK_T) + channel_mask = channel_offsets < NUM_CHANNELS + token_mask = token_offsets < BLOCK_SIZE + token_indices = request_idx * BLOCK_SIZE + token_offsets + + cache_index = tl.load(cache_indices_ptr + request_idx) + request_active = (cache_index >= 0) & (cache_index < NUM_SLOTS) + safe_cache_index = tl.maximum(cache_index, 0) + output_active = ( + tl.load(active_valid_ptr + token_indices, mask=token_mask, other=0) != 0 + ) & request_active + + if HAS_BIAS: + bias = tl.load(bias_ptr + channel_offsets, mask=channel_mask, other=0.0).to( + tl.float32 + ) + else: + bias = tl.zeros((BLOCK_C,), dtype=tl.float32) + accumulator = tl.broadcast_to(bias[None, :], (BLOCK_T, BLOCK_C)) + + for tap in tl.static_range(WIDTH): + relative_source = token_offsets + tap - (WIDTH - 1) + from_current = relative_source >= 0 + current_token = request_idx * BLOCK_SIZE + tl.maximum(relative_source, 0) + current_valid = ( + tl.load( + active_valid_ptr + current_token, + mask=token_mask & from_current, + other=0, + ) + != 0 + ) & request_active + current_value = tl.load( + input_ptr + + current_token[:, None] * input_stride_t + + channel_offsets[None, :] * input_stride_c, + mask=(token_mask & from_current & current_valid)[:, None] + & channel_mask[None, :], + other=0.0, + ).to(tl.float32) + + history_offset = relative_source + (WIDTH - 1) + history_value = tl.load( + clean_state_ptr + + safe_cache_index * state_stride_slot + + channel_offsets[None, :] * state_stride_c + + tl.maximum(history_offset, 0)[:, None] * state_stride_w, + mask=(token_mask & ~from_current & request_active)[:, None] + & channel_mask[None, :], + other=0.0, + ).to(tl.float32) + source_value = tl.where(from_current[:, None], current_value, history_value) + weight = tl.load( + weight_ptr + channel_offsets * weight_stride_c + tap * weight_stride_w, + mask=channel_mask, + other=0.0, + ).to(tl.float32) + accumulator += source_value * weight[None, :] + + if INDEPENDENT_SYMMETRIC: + right_accumulator = tl.zeros((BLOCK_T, BLOCK_C), dtype=tl.float32) + for tap in tl.static_range(WIDTH - 1): + distance = WIDTH - 1 - tap + right_offset = token_offsets + distance + right_token = request_idx * BLOCK_SIZE + right_offset + right_valid = ( + tl.load( + active_valid_ptr + right_token, + mask=token_mask & (right_offset < BLOCK_SIZE), + other=0, + ) + != 0 + ) & request_active + right_value = tl.load( + input_ptr + + right_token[:, None] * input_stride_t + + channel_offsets[None, :] * input_stride_c, + mask=(token_mask & (right_offset < BLOCK_SIZE) & right_valid)[:, None] + & channel_mask[None, :], + other=0.0, + ).to(tl.float32) + weight = tl.load( + right_weight_ptr + + channel_offsets * right_weight_stride_c + + (distance - 1) * right_weight_stride_w, + mask=channel_mask, + other=0.0, + ).to(tl.float32) + right_accumulator += right_value * weight[None, :] + accumulator += right_accumulator + + output = accumulator * tl.sigmoid(accumulator) + output = tl.where(output_active[:, None], output, 0.0) + tl.store( + output_ptr + + token_indices[:, None] * output_stride_t + + channel_offsets[None, :] * output_stride_c, + output, + mask=token_mask[:, None] & channel_mask[None, :], + ) + + +kernel = clover_block_conv1d_kernel diff --git a/src/triton/ops/clover_coreset/jit.h b/src/triton/ops/clover_coreset/jit.h new file mode 100644 index 000000000..c58c8b4d1 --- /dev/null +++ b/src/triton/ops/clover_coreset/jit.h @@ -0,0 +1,70 @@ +#pragma once + +#include "base/clover_coreset.h" +#include "native/cuda/device_buffer.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class CloverCoreset : public ::infini::ops::CloverCoreset { + public: + CloverCoreset(const Tensor logits, size_t block_size, double top_p, + Tensor out) + : ::infini::ops::CloverCoreset(logits, block_size, top_p, out), + blocks_(logits.size(0) / block_size) {} + + size_t workspace_size_in_bytes() const override { return blocks_ * 256 * 5; } + + void operator()(const Tensor logits, size_t block_size, double top_p, + Tensor out) const override { + if (!blocks_) return; + // The Python bindings call without a handle: use the caller's workspace + // when it is large enough, else a buffer owned by this operator. + void* scratch = + workspace_ && workspace_size_in_bytes_ >= workspace_size_in_bytes() + ? workspace_ + : fallback_.Allocate(workspace_size_in_bytes()); + Tensor mass{scratch, {blocks_, 256}, DataType::kFloat32, logits.device()}; + Tensor allow{static_cast(scratch) + blocks_ * 256 * 4, + {blocks_, 256}, + DataType::kInt8, + logits.device()}; + for (int stage = 0; stage < 3; ++stage) { + const Config config{4u, 1u, {{"WIDTH", block_size}, {"STAGE", stage}}}; + Launch( + "clover_coreset", logits.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{ + static_cast(stage == 2 ? logits.size(0) : blocks_)}; + }, + logits, mass, allow, out, static_cast(top_p)); + } + } + + private: + size_t blocks_; + + mutable CudaDeviceBuffer> fallback_; +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::CloverCoreset { + public: + using triton::jit::CloverCoreset::CloverCoreset; +}; + +template <> +class Operator + : public triton::jit::CloverCoreset { + public: + using triton::jit::CloverCoreset::CloverCoreset; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/clover_coreset/jit.py b/src/triton/ops/clover_coreset/jit.py new file mode 100644 index 000000000..08dc7d469 --- /dev/null +++ b/src/triton/ops/clover_coreset/jit.py @@ -0,0 +1,52 @@ +import triton +import triton.language as tl + + +@triton.jit +def clover_coreset_kernel( + Logits, Mass, Allow, Out, top_p, WIDTH: tl.constexpr, STAGE: tl.constexpr +): + expert = tl.arange(0, 256) + if STAGE == 0: + block = tl.program_id(0) + tokens = tl.arange(0, 32) + logits = tl.load( + Logits + (block * WIDTH + tokens[:, None]) * 256 + expert[None, :], + tokens[:, None] < WIDTH, + -float("inf"), + ).to(tl.float32) + row_max = tl.max(logits, 1) + probability = tl.exp(logits - row_max[:, None]) + probability = probability / tl.sum(probability, 1)[:, None] + selected = tl.full((32, 256), False, tl.int1) + remaining = logits + for rank in tl.static_range(8): + best = tl.argmax(remaining, 1, tie_break_left=True) + chosen = expert[None, :] == best[:, None] + selected |= chosen + remaining = tl.where(chosen, -float("inf"), remaining) + mass = tl.sum( + tl.where(selected & (tokens[:, None] < WIDTH), probability, 0.0), 0 + ) + tl.store(Mass + block * 256 + expert, mass) + elif STAGE == 1: + block = tl.program_id(0) + mass = tl.load(Mass + block * 256 + expert) + # Positive float bits sort by magnitude; low bits break ties by expert ID. + bits = mass.to(tl.int32, bitcast=True).to(tl.int64) + key = ((0x7FFFFFFF - bits) << 32) | expert.to(tl.int64) + order = (tl.sort(key, descending=False) & 0xFFFFFFFF).to(tl.int32) + sorted_mass = tl.load(Mass + block * 256 + order) + probabilities = sorted_mass / tl.maximum(tl.sum(mass, 0), 1.0e-9) + keep = tl.cumsum(probabilities, 0) - probabilities < top_p + keep = tl.where(top_p >= 1.0, sorted_mass > 0.0, keep) + keep = keep | (expert == 0) + tl.store(Allow + block * 256 + order, keep) + else: + token = tl.program_id(0) + logits = tl.load(Logits + token * 256 + expert) + keep = tl.load(Allow + (token // WIDTH) * 256 + expert) + tl.store(Out + token * 256 + expert, tl.where(keep != 0, logits, -float("inf"))) + + +kernel = clover_coreset_kernel diff --git a/src/triton/ops/clover_live_mask/jit.h b/src/triton/ops/clover_live_mask/jit.h new file mode 100644 index 000000000..7ed4bdf3a --- /dev/null +++ b/src/triton/ops/clover_live_mask/jit.h @@ -0,0 +1,51 @@ +#pragma once +#include "base/clover_live_mask.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class CloverLiveMask : public ::infini::ops::CloverLiveMask { + public: + using ::infini::ops::CloverLiveMask::CloverLiveMask; + + void operator()(const Tensor ids, Tensor previous, int64_t mask_id, + bool refresh, Tensor live) const override { + if (ids.numel() == 0) return; + const Config config{4u, + 1u, + {{"N", ids.numel()}, + {"WIDTH", 1}, + {"MASK", mask_id}, + {"REFRESH", refresh}, + {"STAGE", 0}, + {"BLOCK", 256}}}; + Launch( + "clover_live_rows", ids.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{static_cast((ids.numel() + 255) / 256)}; + }, + ids, previous, live, live); + } +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::CloverLiveMask { + public: + using triton::jit::CloverLiveMask::CloverLiveMask; +}; + +template <> +class Operator + : public triton::jit::CloverLiveMask { + public: + using triton::jit::CloverLiveMask::CloverLiveMask; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/clover_live_rows/jit.py b/src/triton/ops/clover_live_rows/jit.py new file mode 100644 index 000000000..230ba3a84 --- /dev/null +++ b/src/triton/ops/clover_live_rows/jit.py @@ -0,0 +1,39 @@ +import triton +import triton.language as tl + + +@triton.jit +def clover_live_rows_kernel( + A, + B, + C, + D, + N: tl.constexpr, + WIDTH: tl.constexpr, + MASK: tl.constexpr, + REFRESH: tl.constexpr, + STAGE: tl.constexpr, + BLOCK: tl.constexpr, +): + offset = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + valid = offset < N + if STAGE == 0: + current = tl.load(A + offset, valid, 0) + previous = tl.load(B + offset, valid & (not REFRESH), MASK) + live = (current == MASK) | (previous == MASK) | REFRESH + tl.store(C + offset, live, valid) + tl.store(B + offset, current, valid) + elif STAGE == 1: + route = tl.load(A + offset, valid, MASK) + live = tl.load(B + offset // WIDTH, valid, 0) + tl.store(C + offset, tl.where(live != 0, route, MASK), valid) + else: + fresh = tl.load(A + offset, valid, 0) + live = tl.load(B + offset // WIDTH, valid, 0) + cached = tl.load(C + offset, valid & (live == 0), 0) + output = tl.where(live != 0, fresh, cached) + tl.store(D + offset, output, valid) + tl.store(C + offset, output, valid) + + +kernel = clover_live_rows_kernel diff --git a/src/triton/ops/clover_local_memory/jit.h b/src/triton/ops/clover_local_memory/jit.h new file mode 100644 index 000000000..caddada93 --- /dev/null +++ b/src/triton/ops/clover_local_memory/jit.h @@ -0,0 +1,70 @@ +#pragma once + +#include + +#include "base/clover_local_memory.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class CloverLocalMemory : public ::infini::ops::CloverLocalMemory { + public: + using ::infini::ops::CloverLocalMemory::CloverLocalMemory; + + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor state, const Tensor indices, + const Tensor valid, const Tensor logit_scale, + const Tensor history_bias, const Tensor history_c, + size_t block_size, Tensor out) const override { + if (q.numel() == 0) return; + const Config config{4u, + 1u, + {{"NUM_Q_HEADS", q.size(2)}, + {"NUM_K_HEADS", k.size(2)}, + {"NUM_V_HEADS", v.size(2)}, + {"BLOCK_SIZE", block_size}, + {"NUM_SLOTS", state.size(0)}, + {"KEY_DIM", 128}, + {"VALUE_DIM", 128}, + {"BLOCK_T", 32}, + {"BLOCK_Q", 32}, + {"NUM_QUERY_TILES", 1}, + {"BLOCK_K", 128}, + {"BLOCK_V", 64}}}; + Launch( + "clover_local_memory", q.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{2, static_cast(indices.numel()), + static_cast(v.size(2))}; + }, + q, k, v, g, state, indices, valid, logit_scale, history_bias, history_c, + out, q.stride(1), q.stride(2), q.stride(3), k.stride(1), k.stride(2), + k.stride(3), v.stride(1), v.stride(2), v.stride(3), g.stride(1), + g.stride(2), state.stride(0), state.stride(1), state.stride(2), + state.stride(3), out.stride(1), out.stride(2), out.stride(3), + 1.0f / std::sqrt(128.0f), 32.0f); + } +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::CloverLocalMemory { + public: + using triton::jit::CloverLocalMemory< + Device::Type::kNvidia>::CloverLocalMemory; +}; + +template <> +class Operator + : public triton::jit::CloverLocalMemory { + public: + using triton::jit::CloverLocalMemory::CloverLocalMemory; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/clover_local_memory/jit.py b/src/triton/ops/clover_local_memory/jit.py new file mode 100644 index 000000000..8595de10c --- /dev/null +++ b/src/triton/ops/clover_local_memory/jit.py @@ -0,0 +1,188 @@ +# SPDX-License-Identifier: Apache-2.0 +# Adapted from SGLang PR #46927, commit 058939af24d5cdc44bb4b8852d0ddfab555ed71e. +# Changes: InfiniOps JIT entry point, Hygon launch geometry and pool bounds. +import triton +import triton.language as tl + + +@triton.jit +def clover_local_memory_kernel( + query_ptr, + key_ptr, + value_ptr, + g_ptr, + clean_state_ptr, + cache_indices_ptr, + active_valid_ptr, + softmax_logit_scale_ptr, + softmax_history_bias_ptr, + softmax_history_c_ptr, + output_ptr, + query_stride_t, + query_stride_h, + query_stride_k, + key_stride_t, + key_stride_h, + key_stride_k, + value_stride_t, + value_stride_h, + value_stride_v, + g_stride_t, + g_stride_h, + state_stride_slot, + state_stride_h, + state_stride_v, + state_stride_k, + output_stride_t, + output_stride_h, + output_stride_v, + scale, + softmax_reference_block_size, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + NUM_V_HEADS: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + NUM_SLOTS: tl.constexpr, + KEY_DIM: tl.constexpr, + VALUE_DIM: tl.constexpr, + BLOCK_T: tl.constexpr, + BLOCK_Q: tl.constexpr, + NUM_QUERY_TILES: tl.constexpr, + BLOCK_K: tl.constexpr, + BLOCK_V: tl.constexpr, +): + """Compute the read-only BD-GDN preview output for one fixed-size block. + + Block-local softmax includes the gate-decayed clean readout as one + history bucket. Its logit is history_bias plus + history_c * log(valid_block_size / reference_block_size). + + One program handles one request, one value head, and one value-dimension + tile. Persistent state is read directly in the [slot, H, V, K] + layout and is never written. + """ + value_tile = tl.program_id(0) + query_program = tl.program_id(1) + request_idx = query_program // NUM_QUERY_TILES + query_tile = query_program % NUM_QUERY_TILES + value_head = tl.program_id(2) + + token_offsets = query_tile * BLOCK_Q + tl.arange(0, BLOCK_Q) + local_key_offsets = tl.arange(0, BLOCK_T) + key_offsets = tl.arange(0, BLOCK_K) + value_offsets = value_tile * BLOCK_V + tl.arange(0, BLOCK_V) + token_mask = token_offsets < BLOCK_SIZE + local_key_mask = local_key_offsets < BLOCK_SIZE + key_mask = key_offsets < KEY_DIM + value_mask = value_offsets < VALUE_DIM + token_indices = request_idx * BLOCK_SIZE + token_offsets + + cache_index = tl.load(cache_indices_ptr + request_idx) + request_active = (cache_index >= 0) & (cache_index < NUM_SLOTS) + safe_cache_index = tl.maximum(cache_index, 0) + active = ( + tl.load(active_valid_ptr + token_indices, mask=token_mask, other=0) != 0 + ) & request_active + + # Value heads may share Q/K heads. Clover maps pairs of value heads to + # one of 16 Q/K heads without materializing repeat_interleave. + query_head = value_head // (NUM_V_HEADS // NUM_Q_HEADS) + key_head = value_head // (NUM_V_HEADS // NUM_K_HEADS) + + query_offsets = ( + token_indices[:, None] * query_stride_t + + query_head * query_stride_h + + key_offsets[None, :] * query_stride_k + ) + key_offsets_transposed = ( + (request_idx * BLOCK_SIZE + local_key_offsets)[None, :] * key_stride_t + + key_head * key_stride_h + + key_offsets[:, None] * key_stride_k + ) + value_matrix_offsets = ( + (request_idx * BLOCK_SIZE + local_key_offsets)[:, None] * value_stride_t + + value_head * value_stride_h + + value_offsets[None, :] * value_stride_v + ) + + query = tl.load( + query_ptr + query_offsets, + mask=token_mask[:, None] & key_mask[None, :] & request_active, + other=0.0, + ) + key_transposed = tl.load( + key_ptr + key_offsets_transposed, + mask=key_mask[:, None] & local_key_mask[None, :] & request_active, + other=0.0, + ) + values = tl.load( + value_ptr + value_matrix_offsets, + mask=local_key_mask[:, None] & value_mask[None, :] & request_active, + other=0.0, + ) + + # Match the GDN epsilon and normalize before Tensor Core dot products. + query_f32 = query.to(tl.float32) + query_norm = tl.rsqrt(tl.sum(query_f32 * query_f32, axis=1) + 1.0e-6) + query = (query_f32 * query_norm[:, None]).to(query.dtype) + key_f32 = key_transposed.to(tl.float32) + key_norm = tl.rsqrt(tl.sum(key_f32 * key_f32, axis=0) + 1.0e-6) + key_transposed = (key_f32 * key_norm[None, :]).to(key_transposed.dtype) + + state_offsets = ( + safe_cache_index * state_stride_slot + + value_head * state_stride_h + + value_offsets[None, :] * state_stride_v + + key_offsets[:, None] * state_stride_k + ) + clean_state = tl.load( + clean_state_ptr + state_offsets, + mask=key_mask[:, None] & value_mask[None, :] & request_active, + other=0.0, + ) + + scalar_offsets = token_indices * g_stride_t + value_head * g_stride_h + g = tl.load(g_ptr + scalar_offsets, mask=token_mask & request_active, other=0.0).to( + tl.float32 + ) + local_active = ( + tl.load( + active_valid_ptr + request_idx * BLOCK_SIZE + local_key_offsets, + mask=local_key_mask, + other=0, + ) + != 0 + ) & request_active + + history = tl.dot(query, clean_state.to(query.dtype)) + scores = tl.dot(query, key_transposed) + logit_scale = tl.load(softmax_logit_scale_ptr + value_head).to(tl.float32) + history_bias = tl.load(softmax_history_bias_ptr + value_head).to(tl.float32) + history_c = tl.load(softmax_history_c_ptr + value_head).to(tl.float32) + valid_block_size = tl.maximum(tl.sum(local_active, axis=0), 1.0) + history_bias += history_c * tl.log(valid_block_size / softmax_reference_block_size) + logits = scores * logit_scale + logits = tl.where(local_active[None, :], logits, float("-inf")) + row_max = tl.maximum(tl.max(logits, axis=1), history_bias) + exp_local = tl.exp(logits - row_max[:, None]) + exp_history = tl.exp(history_bias - row_max) + denominator = tl.sum(exp_local, axis=1) + exp_history + local_weights = exp_local / denominator[:, None] + history_weight = exp_history / denominator + local = tl.dot(local_weights.to(values.dtype), values) + output = history * (scale * tl.exp(g) * history_weight)[:, None] + local + output = tl.where(active[:, None], output, 0.0) + + output_offsets = ( + token_indices[:, None] * output_stride_t + + value_head * output_stride_h + + value_offsets[None, :] * output_stride_v + ) + tl.store( + output_ptr + output_offsets, + output, + mask=token_mask[:, None] & value_mask[None, :], + ) + + +kernel = clover_local_memory_kernel diff --git a/src/triton/ops/clover_mask_routes/jit.h b/src/triton/ops/clover_mask_routes/jit.h new file mode 100644 index 000000000..65098ec47 --- /dev/null +++ b/src/triton/ops/clover_mask_routes/jit.h @@ -0,0 +1,51 @@ +#pragma once +#include "base/clover_mask_routes.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class CloverMaskRoutes : public ::infini::ops::CloverMaskRoutes { + public: + using ::infini::ops::CloverMaskRoutes::CloverMaskRoutes; + + void operator()(const Tensor ids, const Tensor live, int64_t num_experts, + Tensor out) const override { + if (ids.numel() == 0) return; + const Config config{4u, + 1u, + {{"N", ids.numel()}, + {"WIDTH", ids.size(1)}, + {"MASK", num_experts}, + {"REFRESH", false}, + {"STAGE", 1}, + {"BLOCK", 256}}}; + Launch( + "clover_live_rows", ids.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{static_cast((ids.numel() + 255) / 256)}; + }, + ids, live, out, out); + } +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::CloverMaskRoutes { + public: + using triton::jit::CloverMaskRoutes::CloverMaskRoutes; +}; + +template <> +class Operator + : public triton::jit::CloverMaskRoutes { + public: + using triton::jit::CloverMaskRoutes::CloverMaskRoutes; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/clover_merge_moe/jit.h b/src/triton/ops/clover_merge_moe/jit.h new file mode 100644 index 000000000..8bb8f8d42 --- /dev/null +++ b/src/triton/ops/clover_merge_moe/jit.h @@ -0,0 +1,51 @@ +#pragma once +#include "base/clover_merge_moe.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class CloverMergeMoe : public ::infini::ops::CloverMergeMoe { + public: + using ::infini::ops::CloverMergeMoe::CloverMergeMoe; + + void operator()(const Tensor fresh, const Tensor live, Tensor cache, + Tensor out) const override { + if (fresh.numel() == 0) return; + const Config config{4u, + 1u, + {{"N", fresh.numel()}, + {"WIDTH", fresh.size(1)}, + {"MASK", 0}, + {"REFRESH", false}, + {"STAGE", 2}, + {"BLOCK", 256}}}; + Launch( + "clover_live_rows", fresh.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{static_cast((fresh.numel() + 255) / 256)}; + }, + fresh, live, cache, out); + } +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::CloverMergeMoe { + public: + using triton::jit::CloverMergeMoe::CloverMergeMoe; +}; + +template <> +class Operator + : public triton::jit::CloverMergeMoe { + public: + using triton::jit::CloverMergeMoe::CloverMergeMoe; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/moe_fused_dense/jit.h b/src/triton/ops/moe_fused_dense/jit.h new file mode 100644 index 000000000..53ab4c238 --- /dev/null +++ b/src/triton/ops/moe_fused_dense/jit.h @@ -0,0 +1,107 @@ +#pragma once + +#include "base/moe_fused_dense.h" +#include "native/cuda/device_buffer.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +template +class MoeFusedDense : public ::infini::ops::MoeFusedDense { + public: + using ::infini::ops::MoeFusedDense::MoeFusedDense; + + static bool supports(Tensor output, const Tensor hidden, const Tensor w13, + const Tensor w2, const Tensor weights, const Tensor ids, + const Tensor sorted, const Tensor experts, + const Tensor total, size_t block_size, + const std::optional bias1 = std::nullopt, + const std::optional bias2 = std::nullopt) { + return block_size == 16 && !bias1 && !bias2 && + ::infini::ops::MoeFusedDense::supports( + output, hidden, w13, w2, weights, ids, sorted, experts, total, + block_size, bias1, bias2); + } + + size_t workspace_size_in_bytes() const override { + const auto pairs = metadata_[1].size(0) * metadata_[5].size(1); + return pairs * (metadata_[3].size(2) * 2 + metadata_[1].size(1)) * + metadata_[1].element_size(); + } + + void operator()(Tensor output, const Tensor hidden, const Tensor w13, + const Tensor w2, const Tensor weights, const Tensor ids, + const Tensor sorted, const Tensor experts, const Tensor total, + size_t block_size, const std::optional bias1, + const std::optional bias2) const override { + Invocation(output, hidden, w13, w2, weights, ids, sorted, experts, total, + block_size, bias1, bias2); + if (bias1 || bias2) + throw std::invalid_argument( + "Hygon Triton MoE does not support expert biases."); + // The Python bindings call without a handle: use the caller's workspace + // when it is large enough, else a buffer owned by this operator. + void* scratch = + workspace_ && workspace_size_in_bytes_ >= workspace_size_in_bytes() + ? workspace_ + : fallback_.Allocate(workspace_size_in_bytes()); + const auto n = hidden.size(0), h = hidden.size(1), i = w2.size(2), + topk = ids.size(1); + const auto pairs = n * topk; + Tensor mid{scratch, {pairs, 2 * i}, hidden.dtype(), hidden.device()}; + Tensor pair_output{ + static_cast(scratch) + pairs * 2 * i * hidden.element_size(), + {pairs, h}, + hidden.dtype(), + hidden.device()}; + for (int stage = 0; stage < 3; ++stage) { + const Config config{4u, + 2u, + {{"TOKENS", n}, + {"E", w13.size(0)}, + {"H", h}, + {"I", i}, + {"TOPK", topk}, + {"BM", block_size}, + {"BN", 64}, + {"BK", 64}, + {"STAGE", stage}}}; + Launch( + "moe_fused_dense", hidden.device().index(), this->stream_, nullptr, + config, {}, + [&](const Config&) -> std::optional { + if (stage == 2) + return Grid{static_cast(n), + static_cast((h + 63) / 64)}; + const auto cols = stage == 0 ? 2 * i : h; + return Grid{static_cast(sorted.numel() / block_size), + static_cast((cols + 63) / 64)}; + }, + hidden, w13, w2, weights, ids, sorted, experts, total, mid, + pair_output, output); + } + } + + private: + mutable CudaDeviceBuffer> fallback_; +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::MoeFusedDense { + public: + using triton::jit::MoeFusedDense::MoeFusedDense; +}; + +template <> +class Operator + : public triton::jit::MoeFusedDense { + public: + using triton::jit::MoeFusedDense::MoeFusedDense; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/moe_fused_dense/jit.py b/src/triton/ops/moe_fused_dense/jit.py new file mode 100644 index 000000000..e06e63d7e --- /dev/null +++ b/src/triton/ops/moe_fused_dense/jit.py @@ -0,0 +1,103 @@ +import triton +import triton.language as tl + + +@triton.jit +def moe_fused_dense_kernel( + X, + W13, + W2, + Weights, + Ids, + Sorted, + Experts, + Total, + Mid, + Pairs, + Out, + TOKENS: tl.constexpr, + E: tl.constexpr, + H: tl.constexpr, + I: tl.constexpr, # noqa: E741 + TOPK: tl.constexpr, + BM: tl.constexpr, + BN: tl.constexpr, + BK: tl.constexpr, + STAGE: tl.constexpr, +): + if STAGE == 2: + token = tl.program_id(0) + h = tl.program_id(1) * BN + tl.arange(0, BN) + ranks = tl.arange(0, triton.next_power_of_2(TOPK)) + route = tl.load(Ids + token * TOPK + ranks, ranks < TOPK, E) + active = (route >= 0) & (route < E) + values = tl.load( + Pairs + (token * TOPK + ranks[:, None]) * H + h[None, :], + active[:, None] & (h[None, :] < H), + 0, + ).to(tl.float32) + weights = tl.load(Weights + token * TOPK + ranks, ranks < TOPK, 0) + tl.store(Out + token * H + h, tl.sum(values * weights[:, None], 0), h < H) + else: + block = tl.program_id(0) + n = tl.program_id(1) * BN + tl.arange(0, BN) + if block * BM < tl.load(Total): + expert = tl.load(Experts + block) + rows = tl.load(Sorted + block * BM + tl.arange(0, BM)) + valid = rows < TOKENS * TOPK + kk = tl.arange(0, BK) + acc = tl.zeros((BM, BN), tl.float32) + if expert >= 0: + if STAGE == 0: + for start in range(tl.cdiv(H, BK)): + k = start * BK + kk + x = tl.load( + X + (rows[:, None] // TOPK) * H + k[None, :], + valid[:, None] & (k[None, :] < H), + 0, + ) + w = tl.load( + W13 + expert * (2 * I * H) + n[None, :] * H + k[:, None], + (n[None, :] < 2 * I) & (k[:, None] < H), + 0, + ) + acc += tl.dot(x, w) + tl.store( + Mid + rows[:, None] * (2 * I) + n[None, :], + acc, + valid[:, None] & (n[None, :] < 2 * I), + ) + else: + for start in range(tl.cdiv(I, BK)): + k = start * BK + kk + gate = tl.load( + Mid + rows[:, None] * (2 * I) + k[None, :], + valid[:, None] & (k[None, :] < I), + 0, + ).to(tl.float32) + up = tl.load( + Mid + rows[:, None] * (2 * I) + I + k[None, :], + valid[:, None] & (k[None, :] < I), + 0, + ).to(tl.float32) + x = (gate * tl.sigmoid(gate) * up).to(Mid.dtype.element_ty) + w = tl.load( + W2 + expert * (H * I) + n[None, :] * I + k[:, None], + (n[None, :] < H) & (k[:, None] < I), + 0, + ) + acc += tl.dot(x, w) + tl.store( + Pairs + rows[:, None] * H + n[None, :], + acc, + valid[:, None] & (n[None, :] < H), + ) + elif STAGE == 1: + tl.store( + Pairs + rows[:, None] * H + n[None, :], + acc, + valid[:, None] & (n[None, :] < H), + ) + + +kernel = moe_fused_dense_kernel diff --git a/src/triton/ops/recurrent_gated_delta_rule/jit.h b/src/triton/ops/recurrent_gated_delta_rule/jit.h new file mode 100644 index 000000000..eae4a524f --- /dev/null +++ b/src/triton/ops/recurrent_gated_delta_rule/jit.h @@ -0,0 +1,78 @@ +#pragma once + +#include + +#include "base/recurrent_gated_delta_rule.h" +#include "triton/jit/jit.h" + +namespace infini::ops::triton::jit { + +// Triton reference for the packed form of `RecurrentGatedDeltaRule`. +template +class PackedRecurrentGatedDeltaRule + : public ::infini::ops::RecurrentGatedDeltaRule { + public: + using ::infini::ops::RecurrentGatedDeltaRule::RecurrentGatedDeltaRule; + + // The batched single-token decode is left to the native providers. + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, Tensor initial_state, + const std::optional initial_state_indices, + const std::optional final_state_indices, Tensor out, + std::optional final_state, + bool use_qk_l2norm) const override { + throw std::invalid_argument( + "the Triton RecurrentGatedDeltaRule provider implements the packed " + "form only"); + } + + void operator()(const Tensor q, const Tensor k, const Tensor v, + const Tensor g, const Tensor beta, Tensor initial_state, + const Tensor cu_seqlens, const Tensor initial_slots, + const Tensor final_slots, Tensor out, + bool use_qk_l2norm) const override { + const Config config{4u, + 1u, + {{"TOKENS", q.size(1)}, + {"POOL", initial_state.size(0)}, + {"HK", q.size(2)}, + {"HV", v.size(2)}, + {"BV", 16}, + {"NORM", use_qk_l2norm}}}; + Launch( + "recurrent_gated_delta_rule", q.device().index(), this->stream_, + this->config_ptr_.get(), config, {}, + [&](const Config&) -> std::optional { + return Grid{static_cast(cu_seqlens.numel() - 1), + static_cast(v.size(2)), 8}; + }, + q, k, v, g, beta, cu_seqlens, initial_slots, final_slots, initial_state, + out, q.stride(1), q.stride(2), k.stride(1), k.stride(2), v.stride(1), + v.stride(2), g.stride(1), g.stride(2), beta.stride(1), beta.stride(2), + initial_state.stride(0), initial_state.stride(1), + initial_state.stride(2), initial_state.stride(3), out.stride(1), + out.stride(2)); + } +}; + +} // namespace infini::ops::triton::jit + +namespace infini::ops { + +template <> +class Operator + : public triton::jit::PackedRecurrentGatedDeltaRule { + public: + using triton::jit::PackedRecurrentGatedDeltaRule< + Device::Type::kNvidia>::PackedRecurrentGatedDeltaRule; +}; + +template <> +class Operator + : public triton::jit::PackedRecurrentGatedDeltaRule { + public: + using triton::jit::PackedRecurrentGatedDeltaRule< + Device::Type::kHygon>::PackedRecurrentGatedDeltaRule; +}; + +} // namespace infini::ops diff --git a/src/triton/ops/recurrent_gated_delta_rule/jit.py b/src/triton/ops/recurrent_gated_delta_rule/jit.py new file mode 100644 index 000000000..702eda068 --- /dev/null +++ b/src/triton/ops/recurrent_gated_delta_rule/jit.py @@ -0,0 +1,92 @@ +import triton +import triton.language as tl + + +@triton.jit +def recurrent_gated_delta_rule_kernel( + Q, + K, + V, + G, + Beta, + Offsets, + Initial, + Final, + State, + Out, + qs, + qh, + ks, + kh, + vs, + vh, + gs, + gh, + bs, + bh, + ss, + sh, + sv, + sk, + os, + oh, + TOKENS: tl.constexpr, + POOL: tl.constexpr, + HK: tl.constexpr, + HV: tl.constexpr, + BV: tl.constexpr, + NORM: tl.constexpr, +): + request, head, tile = tl.program_id(0), tl.program_id(1), tl.program_id(2) + begin, end = tl.load(Offsets + request), tl.load(Offsets + request + 1) + initial, final = tl.load(Initial + request), tl.load(Final + request) + key = tl.arange(0, 128) + value = tile * BV + tl.arange(0, BV) + # Triton accepts two operands per `and`; longer chains are nested. + range_ok = begin >= 0 and end <= TOKENS + range_ok = range_ok and begin <= end + slots_ok = initial >= 0 and initial < POOL + slots_ok = slots_ok and final >= 0 + slots_ok = slots_ok and final < POOL + if range_ok: + if slots_ok: + state = tl.load( + State + + initial * ss + + head * sh + + value[:, None] * sv + + key[None, :] * sk + ) + key_head = head // (HV // HK) + for token in range(begin, end): + q = tl.load(Q + token * qs + key_head * qh + key).to(tl.float32) + k = tl.load(K + token * ks + key_head * kh + key).to(tl.float32) + v = tl.load(V + token * vs + head * vh + value).to(tl.float32) + if NORM: + q = q * tl.rsqrt(tl.sum(q * q, 0) + 1.0e-6) + k = k * tl.rsqrt(tl.sum(k * k, 0) + 1.0e-6) + q = q * 0.08838834764831845 + decay = tl.exp(tl.load(G + token * gs + head * gh)) + beta = tl.load(Beta + token * bs + head * bh) + state = state * decay + remembered = tl.sum(state * k[None, :], 1) + delta = (v - remembered) * beta + state += delta[:, None] * k[None, :] + y = tl.sum(state * q[None, :], 1) + tl.store(Out + token * os + head * oh + value, y) + tl.store( + State + + final * ss + + head * sh + + value[:, None] * sv + + key[None, :] * sk, + state, + ) + else: + # Same as the batched form: an unusable slot zeroes the output only. + zeros = tl.zeros([BV], dtype=tl.float32).to(Out.dtype.element_ty) + for token in range(begin, end): + tl.store(Out + token * os + head * oh + value, zeros) + + +kernel = recurrent_gated_delta_rule_kernel diff --git a/tests/conftest.py b/tests/conftest.py index cfc2691c1..8e9ef0628 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -47,7 +47,7 @@ def _host_range_profile_compiled(): def pytest_configure(config): - torch.backends.fp32_precision = "tf32" + torch.backends.fp32_precision = "ieee" if torch.version.hip else "tf32" profile_output = config.getoption("--host-range-profile") config._infini_host_range_profile_output = None diff --git a/tests/test_clover_block_conv1d.py b/tests/test_clover_block_conv1d.py new file mode 100644 index 000000000..ab85f5a9a --- /dev/null +++ b/tests/test_clover_block_conv1d.py @@ -0,0 +1,108 @@ +"""Correctness tests for the native and Triton CloverBlockConv1d providers. + +Golden model: per (request, token, channel), silu(left-history 4-tap conv + +right-symmetric 3-tap conv), zeroed on invalid rows. Both providers are checked +against it on identical inputs, covering bf16/fp16, block sizes 1/8/32, dead +slots (-1), per-row validity masks and the read-only state. +""" + +import infini.ops +import pytest +import torch + +if not hasattr(infini.ops, "CloverBlockConv1d"): + pytest.skip("`CloverBlockConv1d` is not available", allow_module_level=True) + +NATIVE, TRITON = 0, 10 + + +def torch_golden(x, state, indices, weight, right_weight, valid, block_size): + tokens, channels = x.shape + requests = indices.numel() + out = torch.zeros_like(x, dtype=torch.float32) + xf, wf, rwf = x.float(), weight.float(), right_weight.float() + for r in range(requests): + slot = int(indices[r]) + active_request = 0 <= slot < state.size(0) + for t in range(block_size): + token = r * block_size + t + if not active_request or int(valid[token]) == 0: + continue + acc = 0.0 + for tap in range(4): + rel = t + tap - 3 + if rel >= 0: + src = r * block_size + rel + value = xf[src] if int(valid[src]) != 0 else 0.0 + else: + value = state[slot, :, rel + 3].float() + acc = acc + value * wf[:, 0, tap] + for d in range(1, 4): + right = t + d + if right < block_size: + src = r * block_size + right + value = xf[src] if int(valid[src]) != 0 else 0.0 + acc = acc + value * rwf[:, 0, d - 1] + out[token] = acc * torch.sigmoid(acc) + return out + + +@pytest.mark.parametrize("block_size", (1, 8, 32)) +@pytest.mark.parametrize("dtype,rtol", ((torch.bfloat16, 3e-2), (torch.float16, 3e-2))) +@pytest.mark.parametrize("id_dtype", (torch.int32, torch.int64)) +def test_block_conv1d(device, block_size, dtype, rtol, id_dtype): + if device != "cuda": + pytest.skip("requires a CUDA-like backend") + impls = infini.ops.CloverBlockConv1d.active_implementation_indices(device) + if NATIVE not in impls or TRITON not in impls: + pytest.skip(f"requires the native and Triton providers, active={impls}") + stream = torch.cuda.current_stream().cuda_stream + torch.manual_seed(31) + requests, channels, slots = 6, 256, 8 + + x = torch.randn(requests * block_size, channels, device=device, dtype=dtype) + state = torch.randn(slots, channels, 3, device=device, dtype=dtype) + state0 = state.clone() + # One dead slot and one out-of-range slot exercise the guard paths. + indices = torch.arange(requests, device=device, dtype=id_dtype) % slots + indices[4] = -1 + indices[5] = slots + 3 + weight = torch.randn(channels, 1, 4, device=device, dtype=dtype) * 0.2 + right_weight = torch.randn(channels, 1, 3, device=device, dtype=dtype) * 0.2 + valid = torch.ones(requests * block_size, device=device, dtype=torch.int8) + valid[::5] = 0 # scattered invalid rows inside blocks + out_n = torch.empty_like(x) + out_t = torch.empty_like(x) + + infini.ops.clover_block_conv1d( + x, + state, + indices, + weight, + right_weight, + valid, + block_size, + out_n, + stream=stream, + implementation_index=NATIVE, + ) + infini.ops.clover_block_conv1d( + x, + state, + indices, + weight, + right_weight, + valid, + block_size, + out_t, + stream=stream, + implementation_index=TRITON, + ) + torch.cuda.synchronize() + + golden = torch_golden( + x, state, indices, weight, right_weight, valid, block_size + ).to(device) + torch.testing.assert_close(out_n.float(), golden, rtol=rtol, atol=rtol) + torch.testing.assert_close(out_n.float(), out_t.float(), rtol=rtol, atol=rtol) + assert torch.equal(state, state0), "the preview reads the state only" diff --git a/tests/test_clover_coreset.py b/tests/test_clover_coreset.py new file mode 100644 index 000000000..3fb1be921 --- /dev/null +++ b/tests/test_clover_coreset.py @@ -0,0 +1,283 @@ +"""Correctness tests for the native CloverCoreset provider. + +The native kernel mirrors the Triton reference's three stages in one launch +and keeps the association order of every fp32 sum, so the two agree on the +allow list. The torch golden model is an independent statement of the +semantics; its sums associate differently, so it is compared away from the +decision boundary, where a rounding may move one expert. +""" + +import infini.ops +import pytest +import torch + +if not hasattr(infini.ops, "CloverCoreset"): + pytest.skip("`CloverCoreset` is not available", allow_module_level=True) + +NATIVE, TRITON = 0, 10 +EXPERTS = 256 +TOP_K = 8 +# A cumulative mass this close to top_p may fall on either side of it +# depending on how the fp32 sums round. +BOUNDARY = 5.0e-5 + + +def torch_coreset(logits, width, top_p): + """Golden model of the three-stage pipeline in torch. + + Returns the masked logits and, per expert, the distance between the + normalized mass ahead of the expert and top_p (zero where no rounding + can change the decision). + """ + tokens, experts = logits.shape + assert experts == EXPERTS + out = torch.empty_like(logits) + margin = torch.zeros(tokens, experts, device=logits.device) + for b in range(tokens // width): + rows = slice(b * width, (b + 1) * width) + block = logits[rows].float() + prob = torch.softmax(block, dim=1) + # The top-8 union of the rows; argmax takes the first of equal logits. + selected = torch.zeros_like(prob, dtype=torch.bool) + remaining = block.clone() + for _ in range(TOP_K): + best = remaining.argmax(dim=1) + selected.scatter_(1, best.unsqueeze(1), True) + remaining.scatter_(1, best.unsqueeze(1), float("-inf")) + mass = (prob * selected).sum(0) + order = torch.argsort(mass, descending=True, stable=True) + ahead = mass[order].cumsum(0) - mass[order] + if top_p >= 1.0: + keep = mass[order] > 0 + keep[0] = True + else: + ahead = ahead / max(mass.sum(), 1e-9) + keep = ahead < top_p + ahead_expert = torch.empty_like(mass) + ahead_expert[order] = ahead + margin[rows] = (ahead_expert - top_p).abs().unsqueeze(0) + keep_expert = torch.zeros_like(mass, dtype=torch.bool) + keep_expert[order] = keep + out[rows] = torch.where( + keep_expert.unsqueeze(0), + logits[rows], + torch.full_like(logits[rows], float("-inf")), + ) + return out, margin + + +def assert_coreset_close(actual, expected, margin): + """Equal everywhere except at the decision boundary.""" + same = (actual == expected) | (margin <= BOUNDARY) + assert bool(same.all()), f"{int((~same).sum())} experts differ away from top_p" + + +def run_native(logits, width, top_p, stream): + # The native provider needs no workspace: the plain binding serves it. + out = torch.empty_like(logits) + infini.ops.clover_coreset( + logits, width, top_p, out, stream=stream, implementation_index=NATIVE + ) + torch.cuda.synchronize() + return out + + +def run_triton(logits, width, top_p, stream): + # The Triton provider allocates its workspace when the caller brings none. + out = torch.empty_like(logits) + infini.ops.clover_coreset( + logits, width, top_p, out, stream=stream, implementation_index=TRITON + ) + torch.cuda.synchronize() + return out + + +def require_providers(device): + if not _impls_ok(device): + pytest.skip("requires the native and Triton providers on a CUDA-like backend") + return torch.cuda.current_stream().cuda_stream + + +def _impls_ok(device): + impls = infini.ops.CloverCoreset.active_implementation_indices(device) + return NATIVE in impls and TRITON in impls + + +@pytest.mark.parametrize("dtype", (torch.bfloat16, torch.float16, torch.float32)) +@pytest.mark.parametrize("width", (1, 8, 13, 32)) +def test_coreset(device, dtype, width): + """Every block size the operator takes and every element type, over a + range of routing masses, against the golden model and the reference.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = require_providers(device) + torch.manual_seed(6) + blocks = 3 + logits = (torch.randn(blocks * width, EXPERTS, device=device) * 4).to(dtype) + before = logits.clone() + for top_p in (0.05, 0.5, 0.9, 0.999, 1.0): + out_n = run_native(logits, width, top_p, stream) + out_t = run_triton(logits, width, top_p, stream) + golden, margin = torch_coreset(logits, width, top_p) + assert_coreset_close(out_n, golden, margin) + assert_coreset_close(out_t, golden, margin) + assert_coreset_close(out_n, out_t, margin) + assert torch.equal(logits, before) # the operator is out of place + + +def test_coreset_matches_triton(device): + """Bit level: the same rounding points leave only the divisions, which + differ by an ulp and move an expert only at the boundary.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = require_providers(device) + torch.manual_seed(61) + for dtype, width in ( + (torch.bfloat16, 32), + (torch.bfloat16, 7), + (torch.float16, 32), + (torch.float32, 32), + ): + logits = (torch.randn(40 * width, EXPERTS, device=device) * 4).to(dtype) + out_n = run_native(logits, width, 0.9, stream) + out_t = run_triton(logits, width, 0.9, stream) + _, margin = torch_coreset(logits, width, 0.9) + assert_coreset_close(out_n, out_t, margin) + bits = torch.int32 if dtype == torch.float32 else torch.int16 + same = (out_n.view(bits) == out_t.view(bits)).float().mean().item() + assert same >= 0.9999, f"{dtype} width={width}: only {same:.5%} bit-identical" + + +def competing_row(logits, row, eighth, ninth): + """Row `row` of `logits` gets seven high logits; experts 10 and 50 + compete, with the logits `eighth` and `ninth`, for its eighth expert.""" + logits[row] = -10.0 + for column, value in ( + (3, 5.0), + (20, 4.5), + (60, 4.0), + (100, 3.5), + (140, 3.0), + (180, 2.5), + (200, 2.0), + ): + logits[row, column] = value + logits[row, 10] = eighth + logits[row, 50] = ninth + + +def check_competing_rows(logits, stream): + """Each of the first four rows is its own routing block. Its eighth + expert is one of the experts 10 and 50, whichever the rows were given + the larger logit: the kernel, the reference and the golden model agree + on it, keep it and drop the other.""" + top_p = 0.999 # far enough to keep the eighth expert of a peaked row + out_n = run_native(logits, 1, top_p, stream) + out_t = run_triton(logits, 1, top_p, stream) + golden, margin = torch_coreset(logits, 1, top_p) + assert_coreset_close(out_n, golden, margin) + assert_coreset_close(out_n, out_t, margin) + kept_n = torch.isfinite(out_n[:4]) + for out in (out_t, golden): + assert bool(torch.equal(kept_n, torch.isfinite(out[:4]))) + larger = logits[:4, [10, 50]].float().argmax(dim=1) + expected = torch.zeros_like(kept_n) + for row in range(4): + expected[row, (10, 50)[int(larger[row])]] = True + kept_pair = kept_n[:, [10, 50]] + assert bool(torch.equal(kept_pair, expected[:, [10, 50]])) + return kept_pair + + +def test_coreset_ties(device): + """Equal logits are common in 16-bit routing scores. The reference + breaks ties by the lower expert id and ranks -0.0 with +0.0. Two rows + have +0.0 at the higher expert id competing with -0.0 for their eighth + expert.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = require_providers(device) + torch.manual_seed(66) + for dtype in (torch.bfloat16, torch.float16): + # Coarse logits: many equal ones in the other rows too. + logits = ( + (torch.randn(6, EXPERTS, device=device) * 2) + .to(dtype) + .float() + .mul_(2) + .round() + .div_(2) + ) + for row in range(4): + if row < 2: + competing_row(logits, row, -0.0, 0.0) # the tie goes to 10 + else: + competing_row(logits, row, -0.0, 1.0) # 50 is strictly larger + logits = logits.to(dtype) + zeros = logits[:2, [10, 50]].float() + assert bool(torch.signbit(zeros[:, 0]).all()) # -0.0 survived the conversion + assert not bool(torch.signbit(zeros[:, 1]).any()) + kept_pair = check_competing_rows(logits, stream) + assert bool(kept_pair[:2, 0].all()), "the tie goes to the lower expert id" + + # The same rows grouped into wider blocks. + for width in (2, 3): + out_n = run_native(logits, width, 0.6, stream) + out_t = run_triton(logits, width, 0.6, stream) + golden, margin = torch_coreset(logits, width, 0.6) + assert_coreset_close(out_n, golden, margin) + assert_coreset_close(out_n, out_t, margin) + + +def test_coreset_near_ties(device): + """fp32 logits that differ only in the mantissa bits the merge tree's + keys drop: the exact value still decides, whichever expert id it is at.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = require_providers(device) + torch.manual_seed(67) + logits = ( + (torch.randn(6, EXPERTS, device=device) * 2).float().mul_(2).round().div_(2) + ) + larger = torch.nextafter(torch.tensor(1.0), torch.tensor(2.0)).item() + assert larger > 1.0 + for row in range(4): + if row < 2: + competing_row(logits, row, 1.0, larger) # the larger logit at the higher id + else: + competing_row(logits, row, larger, 1.0) + kept_pair = check_competing_rows(logits, stream) + assert bool(kept_pair[:2, 1].all()), "the larger logit wins at expert 50" + assert bool(kept_pair[2:, 0].all()), "and at expert 10" + + +@pytest.mark.parametrize("dtype", (torch.bfloat16, torch.float32)) +def test_coreset_unaligned(device, dtype): + """A logit tensor that does not start on a 16-byte boundary takes the + kernel's scalar load and store path.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = require_providers(device) + torch.manual_seed(69) + width, blocks = 8, 3 + storage = torch.randn(blocks * width * EXPERTS + 8, device=device).to(dtype) + logits = storage[1 : 1 + blocks * width * EXPERTS].view(blocks * width, EXPERTS) + assert logits.data_ptr() % 16 != 0 and logits.is_contiguous() + out_n = run_native(logits, width, 0.7, stream) + out_t = run_triton(logits, width, 0.7, stream) + golden, margin = torch_coreset(logits, width, 0.7) + assert_coreset_close(out_n, golden, margin) + bits = torch.int32 if dtype == torch.float32 else torch.int16 + assert torch.equal(out_n.view(bits), out_t.view(bits)) + + +def test_coreset_deterministic(device): + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = require_providers(device) + torch.manual_seed(70) + for width in (1, 13, 32): + logits = (torch.randn(6 * width, EXPERTS, device=device) * 4).to(torch.bfloat16) + first = run_native(logits, width, 0.9, stream) + for _ in range(4): + assert torch.equal(run_native(logits, width, 0.9, stream), first), width diff --git a/tests/test_clover_live_mask.py b/tests/test_clover_live_mask.py new file mode 100644 index 000000000..0f914ba91 --- /dev/null +++ b/tests/test_clover_live_mask.py @@ -0,0 +1,152 @@ +"""Correctness tests for the shared-layer native Clover metadata operators. + +Providers: native SIMT (impl 0, this PR) cross-checked against the Triton +reference (impl 10) on identical inputs, plus explicit torch golden models. +The three ops copy and select values, so everything is compared exactly. +CloverCoreset has its own tests in test_clover_coreset.py. +""" + +import infini.ops +import pytest +import torch + +if not hasattr(infini.ops, "CloverLiveMask"): + pytest.skip("`CloverLiveMask` is not available", allow_module_level=True) + +NATIVE, TRITON = 0, 10 + + +def _impls_ok(op, device): + impls = getattr(infini.ops, op).active_implementation_indices(device) + return NATIVE in impls and TRITON in impls + + +def _require(op, device): + """The current CUDA stream once the op has both providers.""" + if not _impls_ok(op, device): + pytest.skip("requires CUDA with native and triton providers") + return torch.cuda.current_stream().cuda_stream + + +@pytest.mark.parametrize("id_dtype", (torch.int32, torch.int64)) +def test_live_mask(device, id_dtype): + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = _require("CloverLiveMask", device) + torch.manual_seed(3) + mask_id, n = 151669, 4096 + ids = torch.randint(0, 200, (n,), device=device, dtype=id_dtype) + ids[::7] = mask_id + previous = torch.randint(0, 200, (n,), device=device, dtype=id_dtype) + previous[::5] = mask_id + live = torch.empty(n, device=device, dtype=torch.int8) + + outs = {} + for impl, prev in ((NATIVE, previous.clone()), (TRITON, previous.clone())): + infini.ops.clover_live_mask( + ids, prev, mask_id, False, live, stream=stream, implementation_index=impl + ) + outs[impl] = (live.clone(), prev.clone()) + + ids_now_mask = ids == mask_id + prev_was_mask = previous == mask_id + golden_live = (ids_now_mask | prev_was_mask).to(torch.int8) + assert torch.equal(outs[NATIVE][0], golden_live) + assert torch.equal(outs[NATIVE][1], ids) # snapshot updated + assert torch.equal(outs[NATIVE][0], outs[TRITON][0]) + assert torch.equal(outs[NATIVE][1], outs[TRITON][1]) + + # refresh=True: everything live regardless of history. + for impl, prev in ((NATIVE, previous.clone()), (TRITON, previous.clone())): + infini.ops.clover_live_mask( + ids, prev, mask_id, True, live, stream=stream, implementation_index=impl + ) + assert torch.count_nonzero(live) == n, f"impl {impl} refresh" + assert torch.equal(prev, ids), f"impl {impl} refresh snapshot" + + +@pytest.mark.parametrize("id_dtype", (torch.int32, torch.int64)) +@pytest.mark.parametrize("topk", (8, 5)) # a power of two, and any other width +def test_mask_routes(device, id_dtype, topk): + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = _require("CloverMaskRoutes", device) + torch.manual_seed(4) + rows, experts = 512, 256 + ids = torch.randint(-1, experts, (rows, topk), device=device, dtype=id_dtype) + live = (torch.rand(rows, device=device) < 0.3).to(torch.int8) + out_n = torch.empty_like(ids) + out_t = torch.empty_like(ids) + infini.ops.clover_mask_routes( + ids, live, experts, out_n, stream=stream, implementation_index=NATIVE + ) + infini.ops.clover_mask_routes( + ids, live, experts, out_t, stream=stream, implementation_index=TRITON + ) + + golden = torch.where(live.unsqueeze(1) != 0, ids, torch.full_like(ids, experts)) + assert torch.equal(out_n, golden) + assert torch.equal(out_n, out_t) + + +def check_merge_moe(stream, fresh, cache0, live): + out = torch.empty_like(fresh) + cache_n, cache_t = cache0.clone(), cache0.clone() + infini.ops.clover_merge_moe( + fresh, live, cache_n, out, stream=stream, implementation_index=NATIVE + ) + out_n = out.clone() + infini.ops.clover_merge_moe( + fresh, live, cache_t, out, stream=stream, implementation_index=TRITON + ) + pick = torch.where(live.unsqueeze(1) != 0, fresh, cache0) + assert torch.equal(out_n, pick) + assert torch.equal(cache_n, pick) # live rows replaced, dead ones kept + assert torch.equal(out_n, out) + assert torch.equal(cache_n, cache_t) + + +@pytest.mark.parametrize("dtype", (torch.bfloat16, torch.float16, torch.float32)) +@pytest.mark.parametrize("width", (320, 12, 13)) +def test_merge_moe(device, dtype, width): + """Row widths of 320, 12 and 13 elements: 16-byte vectors for every + element type, for the 32-bit one only, and for none.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = _require("CloverMergeMoe", device) + torch.manual_seed(5) + rows = 256 + fresh = torch.randn(rows, width, device=device, dtype=dtype) + cache0 = torch.randn(rows, width, device=device, dtype=dtype) + live = (torch.rand(rows, device=device) < 0.4).to(torch.int8) + check_merge_moe(stream, fresh, cache0, live) + + +def test_merge_moe_many_rows(device): + """More rows than a grid's y axis takes: the launch itself would fail.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = _require("CloverMergeMoe", device) + torch.manual_seed(9) + rows, width = 65536 + 64, 64 + fresh = torch.randn(rows, width, device=device, dtype=torch.bfloat16) + cache0 = torch.randn(rows, width, device=device, dtype=torch.bfloat16) + live = (torch.rand(rows, device=device) < 0.4).to(torch.int8) + check_merge_moe(stream, fresh, cache0, live) + + +def test_merge_moe_unaligned(device): + """Tensors that do not start on a 16-byte boundary take one element + per thread.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + stream = _require("CloverMergeMoe", device) + torch.manual_seed(8) + rows, width = 64, 320 + elements = rows * width + storage = torch.randn(elements + 8, device=device, dtype=torch.bfloat16) + fresh = storage[1 : 1 + elements].view(rows, width) # 2 bytes off + assert fresh.is_contiguous() and fresh.data_ptr() % 16 != 0 + cache0 = torch.randn(rows, width, device=device, dtype=torch.bfloat16) + live = (torch.rand(rows, device=device) < 0.4).to(torch.int8) + check_merge_moe(stream, fresh, cache0, live) diff --git a/tests/test_clover_live_rows.py b/tests/test_clover_live_rows.py new file mode 100644 index 000000000..2abe04381 --- /dev/null +++ b/tests/test_clover_live_rows.py @@ -0,0 +1,30 @@ +import infini.ops as ops +import pytest +import torch + + +def test_clover_live_rows(): + if not torch.cuda.is_available() or not torch.version.hip: + pytest.skip("requires Hygon") + if not hasattr(ops, "CloverLiveMask"): + pytest.skip("requires Clover providers") + s = torch.cuda.current_stream().cuda_stream + ids = torch.tensor([151669, 3, 4, 151669], device="cuda", dtype=torch.int64) + previous = torch.empty_like(ids) + live = torch.empty(4, device="cuda", dtype=torch.int8) + ops.clover_live_mask(ids, previous, 151669, True, live, stream=s) + assert live.tolist() == [1, 1, 1, 1] + ids[:] = torch.tensor([5, 3, 4, 151669], device="cuda") + ops.clover_live_mask(ids, previous, 151669, False, live, stream=s) + assert live.tolist() == [1, 0, 0, 1] + routes = torch.arange(16, device="cuda", dtype=torch.int32).view(4, 4) + ops.clover_mask_routes(routes, live, 256, routes, stream=s) + assert routes[1:3].eq(256).all() + fresh = torch.randn(4, 128, device="cuda", dtype=torch.bfloat16) + cache = torch.randn_like(fresh) + old = cache.clone() + out = torch.empty_like(fresh) + ops.clover_merge_moe(fresh, live, cache, out, stream=s) + ref = torch.where(live.bool()[:, None], fresh, old) + torch.testing.assert_close(out, ref, rtol=0, atol=0) + assert torch.equal(cache, ref) diff --git a/tests/test_clover_local_memory.py b/tests/test_clover_local_memory.py new file mode 100644 index 000000000..b6ef5bb09 --- /dev/null +++ b/tests/test_clover_local_memory.py @@ -0,0 +1,256 @@ +"""Correctness tests for the native CloverLocalMemory providers. + +Golden model replicates the Triton reference semantics: L2-normalized q/k +rounded to the element type, block-local softmax with the gate-decayed +clean-state history bucket (history logit = bias + c * log(valid_count / 32), +the reference sizes it against a full 32-token block), per-head scalars, dead +slots and per-row validity. The state has unit magnitude, so the history term +is a fair share of the output and a broken history cannot hide in the +tolerance. Cross-checked against Triton, including bit level. +""" + +import math + +import infini.ops +import pytest +import torch + +if not hasattr(infini.ops, "CloverLocalMemory"): + pytest.skip("`CloverLocalMemory` is not available", allow_module_level=True) + +NATIVE, TRITON = 0, 10 +REFERENCE_BLOCK = 32.0 + + +def golden(q, k, v, g, state, indices, valid, ls, hb, hc, block): + _, tokens, nqh, kd = q.shape + _, _, nvh, vd = v.shape + nkh = k.shape[2] + dtype = q.dtype + reduced = dtype in (torch.bfloat16, torch.float16) + out = torch.zeros_like(v, dtype=torch.float32) + qf, kf, vf = q.float(), k.float(), v.float() + for r in range(indices.numel()): + slot = int(indices[r]) + ra = 0 <= slot < state.size(0) + if not ra: + continue # a dead slot leaves the zeros of the reference + for h in range(nvh): + qh = h // (nvh // nqh) + kh = h // (nvh // nkh) + blk_q = qf[0, r * block : (r + 1) * block, qh] # [T,K] + blk_k = kf[0, r * block : (r + 1) * block, kh] # [T,K] + blk_v = vf[0, r * block : (r + 1) * block, h] # [T,V] + qn = blk_q / (blk_q.pow(2).sum(-1, keepdim=True) + 1e-6).sqrt() + kn = blk_k / (blk_k.pow(2).sum(-1, keepdim=True) + 1e-6).sqrt() + key_valid = torch.tensor( + [int(valid[r * block + j]) != 0 for j in range(block)], device=q.device + ) + row_valid = torch.tensor( + [int(valid[r * block + t]) != 0 for t in range(block)], device=q.device + ) + if reduced: # the reference rounds these to the element type + qn, kn = qn.to(dtype).float(), kn.to(dtype).float() + st = state[slot, h].to(dtype).float() + else: + st = state[slot, h].float() + scores = (qn @ kn.T) * float(ls[h]) + logits = scores.masked_fill(~key_valid[None, :], float("-inf")) + bias = float(hb[h]) + float(hc[h]) * math.log( + max(int(key_valid.sum()), 1) / REFERENCE_BLOCK + ) + hist = qn @ st.T # [T,V]; state is [V, K] + row_max = logits.max(-1).values.clamp_min(bias) + el = torch.exp(logits - row_max[:, None]) + eh = torch.exp(bias - row_max) + denom = el.sum(-1) + eh + w = el / denom[:, None] + hw = eh / denom + if reduced: + w = w.to(dtype).float() + gate = 128**-0.5 * torch.exp(g[0, r * block : (r + 1) * block, h].float()) + o = hist * (gate * hw)[:, None] + w @ blk_v + out[0, r * block : (r + 1) * block, h] = o * row_valid[:, None].to(o.dtype) + return out + + +def inputs(requests, block, heads, dtype, slots=4, index_dtype=torch.int32): + nqh, nkh, nvh = heads + tokens = requests * block + q = torch.randn(1, tokens, nqh, 128, device="cuda", dtype=dtype) * 0.5 + k = torch.randn(1, tokens, nkh, 128, device="cuda", dtype=dtype) * 0.5 + v = torch.randn(1, tokens, nvh, 128, device="cuda", dtype=dtype) * 0.5 + g = torch.randn(1, tokens, nvh, device="cuda", dtype=torch.float32) * 0.5 - 0.3 + # Unit magnitude: the history term is a fair share of the output. + state = torch.randn(slots, nvh, 128, 128, device="cuda", dtype=torch.float32) + indices = torch.tensor( + [(r % slots) if r % 4 != 3 else -1 for r in range(requests)], device="cuda" + ).to(index_dtype) + valid = torch.ones(tokens, device="cuda", dtype=torch.int8) + valid[::5] = 0 # scattered inactive rows and keys + ls = torch.randn(nvh, device="cuda", dtype=dtype) * 0.3 + 1.0 + hb = torch.randn(nvh, device="cuda", dtype=dtype) * 0.2 + hc = torch.randn(nvh, device="cuda", dtype=dtype) * 0.1 + return q, k, v, g, state, indices, valid, ls, hb, hc + + +def run(args, block, impl, out=None): + q, k, v = args[:3] + out = torch.empty_like(v) if out is None else out + infini.ops.clover_local_memory( + *args, + block, + out, + stream=torch.cuda.current_stream().cuda_stream, + implementation_index=impl, + ) + torch.cuda.synchronize() + return out + + +def require_impls(device): + impls = infini.ops.CloverLocalMemory.active_implementation_indices(device) + if NATIVE not in impls or TRITON not in impls: + pytest.skip(f"requires impls 0 and 10, active={impls}") + + +@pytest.mark.parametrize("block", (8, 16, 32)) +@pytest.mark.parametrize("dtype", (torch.bfloat16, torch.float16)) +@pytest.mark.parametrize("heads", ((4, 4, 8), (8, 8, 16), (2, 2, 2))) # (nq, nk, nv) +def test_local_memory(device, block, dtype, heads): + if device != "cuda": + pytest.skip("requires the CUDA backend") + require_impls(device) + torch.manual_seed(41) + args = inputs(3, block, heads, dtype) + out_n = run(args, block, NATIVE) + out_t = run(args, block, TRITON) + + ref = golden(*args, block).cuda() + scale = max(ref.abs().max().item(), 1.0) + # One unit of the element type at the largest magnitude: with the same + # rounding points as the reference, only fp32 summation order is left. + tol = scale * torch.finfo(dtype).eps + torch.testing.assert_close(out_n.float(), ref, rtol=0, atol=tol) + torch.testing.assert_close(out_n.float(), out_t.float(), rtol=0, atol=tol) + + +@pytest.mark.parametrize("requests", (1, 2, 4, 8, 13)) +@pytest.mark.parametrize("index_dtype", (torch.int32, torch.int64)) +def test_local_memory_batch(device, requests, index_dtype): + """Every tiling the NVIDIA launcher picks, and out-of-range slots.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + require_impls(device) + torch.manual_seed(43) + args = list( + inputs(requests, 32, (8, 8, 16), torch.bfloat16, index_dtype=index_dtype) + ) + args[5][-1] = 99 # beyond the pool: inactive like a negative slot + args = tuple(args) + out_n = run(args, 32, NATIVE) + out_t = run(args, 32, TRITON) + ref = golden(*args, 32).cuda() + scale = max(ref.abs().max().item(), 1.0) + tol = scale * torch.finfo(torch.bfloat16).eps + torch.testing.assert_close(out_n.float(), ref, rtol=0, atol=tol) + torch.testing.assert_close(out_n.float(), out_t.float(), rtol=0, atol=tol) + # Rows of an inactive request are zeros, as in the reference. + for r, slot in enumerate(args[5].tolist()): + if slot < 0 or slot >= args[4].size(0): + assert torch.equal( + out_n[0, r * 32 : (r + 1) * 32], + torch.zeros_like(out_n[0, r * 32 : (r + 1) * 32]), + ) + + +def test_local_memory_fallback_layouts(device): + """Layouts the tensor-core kernel does not read take the shared SIMT + kernel: fp32 scalars, strided rows, a head sharing ratio that is not a + power of two. All of them must agree with the reference.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + require_impls(device) + torch.manual_seed(47) + dtype, block, heads = torch.bfloat16, 32, (8, 8, 16) + cases = {} + + args = list(inputs(2, block, heads, dtype)) + args[7] = args[7].float() # fp32 per-head scalars + cases["fp32_scalars"] = tuple(args) + + args = list(inputs(2, block, heads, dtype)) + # q and k rows that are slices of wider tensors: contiguous in the + # innermost axis but not 16-byte aligned. + wide = torch.randn(1, 2 * block, 16, 136, device="cuda", dtype=dtype) + args[0] = wide[..., 4:132] + args[1] = wide[..., 4:132][:, :, 8:16] + cases["misaligned_base"] = tuple(args) + + args = list(inputs(2, block, heads, dtype)) + args[0] = torch.randn(1, 2 * block, 8, 256, device="cuda", dtype=dtype)[..., ::2] + cases["strided_innermost"] = tuple(args) + + args = inputs(2, block, (2, 3, 6), dtype) # q sharing ratio 3 + cases["odd_head_ratio"] = args + + for name, args in cases.items(): + out_n = run(args, block, NATIVE) + out_t = run(args, block, TRITON) + ref = golden(*args, block).cuda() + scale = max(ref.abs().max().item(), 1.0) + torch.testing.assert_close( + out_n.float(), + ref, + rtol=3e-2, + atol=scale * 3e-2, + msg=lambda m: f"{name}: {m}", + ) + torch.testing.assert_close( + out_n.float(), out_t.float(), rtol=3e-2, atol=scale * 3e-2 + ) + + +@pytest.mark.parametrize("dtype", (torch.bfloat16, torch.float16)) +def test_local_memory_matches_triton(device, dtype): + """Bit level: the same MMA and rounding points leave only the + summation-order noise of the norms and of the softmax sums.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + require_impls(device) + torch.manual_seed(53) + for requests in (1, 4, 12): + args = inputs(requests, 32, (8, 8, 16), dtype) + out_n, out_t = run(args, 32, NATIVE), run(args, 32, TRITON) + bits_n = out_n.view(torch.int16).long() + bits_t = out_t.view(torch.int16).long() + same = (bits_n == bits_t).float().mean().item() + assert same >= 0.999, f"R={requests}: only {same:.5%} bit-identical" + diff = (out_n.float() - out_t.float()).abs() + scale = max(out_t.float().abs().max().item(), 1.0) + assert diff.max().item() <= scale * 2.0 * torch.finfo(dtype).eps + + +def test_local_memory_deterministic(device): + if device != "cuda": + pytest.skip("requires the CUDA backend") + require_impls(device) + torch.manual_seed(59) + for requests in (1, 2, 5): + args = inputs(requests, 32, (8, 8, 16), torch.bfloat16) + first = run(args, 32, NATIVE).clone() + for _ in range(4): + assert torch.equal(run(args, 32, NATIVE), first), f"R={requests}" + + +def test_local_memory_reads_state_only(device): + """The preview reads the clean state and never writes it.""" + if device != "cuda": + pytest.skip("requires the CUDA backend") + require_impls(device) + torch.manual_seed(44) + args = list(inputs(3, 32, (4, 4, 8), torch.bfloat16)) + state0 = args[4].clone() + run(args, 32, NATIVE) + run(args, 32, TRITON) + assert torch.equal(args[4], state0) diff --git a/tests/test_generate_wrappers.py b/tests/test_generate_wrappers.py index 2afce1fb1..e2b565eb1 100644 --- a/tests/test_generate_wrappers.py +++ b/tests/test_generate_wrappers.py @@ -1366,3 +1366,15 @@ def test_w4_public_api_selection_is_explicit(tmp_path): module._select_ops_from_config( {}, {name: {"headers": None, "implementations": (0,)}}, "ops.json" ) + + +def test_default_argument_scan_ignores_comment_examples(monkeypatch, tmp_path): + module = _load_generator_module() + header = tmp_path / "sample.h" + header.write_text( + "// bool is_neox=false is GPT-J, true is GPT-NeoX.\n" + "/* float alpha = invalid example, */\n" + "class Sample { public: Sample(bool is_neox, float alpha = 1.0f); };\n" + ) + monkeypatch.setattr(module, "_find_base_header", lambda name: header) + assert module._find_params_with_defaults("sample") == {"alpha": "1.0f"} diff --git a/tests/test_moe_fused_dense.py b/tests/test_moe_fused_dense.py index a2b2b03a2..2df5a4b2f 100644 --- a/tests/test_moe_fused_dense.py +++ b/tests/test_moe_fused_dense.py @@ -107,6 +107,11 @@ def _reference(hidden, w13, w2, topk_weights, topk_ids, block_size): def test_moe_fused_dense(dtype, rtol, atol, device): if device != "cuda": pytest.skip("`moe_fused_dense` numeric test targets the metax/cuda backend") + if torch.version.hip is not None: + pytest.skip( + "the Hygon provider takes block size 16 only; see " + "`test_moe_fused_dense_clover`" + ) torch.manual_seed(0) n, h, m, e, topk, block_size = 4, 8, 6, 3, 2, 4 hidden = torch.randn(n, h, dtype=dtype, device=device).contiguous() @@ -136,3 +141,155 @@ def test_moe_fused_dense(dtype, rtol, atol, device): expected = _reference(hidden, w13, w2, topk_weights, topk_ids, block_size) torch.testing.assert_close(output, expected.to(dtype), rtol=rtol, atol=atol) + + +# --------------------------------------------------------------------------- +# The Triton kernels on every backend that has them, and the native gfx936 +# kernels of the Hygon provider, with the routing of Clover: block size 16, +# top-k weights that sum to one, and routes spread over the experts or +# concentrated on a few by the block coreset of the model. + +_NATIVE, _TRITON = 0, 10 +_CLOVER_BLOCK = 16 + + +def _clover_implementations(device, hidden, intermediate): + """Returns `(implementation, native)`: the Triton kernels, and on Hygon the + provider's slot 0, which takes `hidden` and `intermediate` that are + multiples of 8 of at least 32 with its native kernels and leaves every + other shape to the Triton kernels.""" + if device != "cuda": + pytest.skip("requires a CUDA-like backend") + active = infini.ops.MoeFusedDense.active_implementation_indices(device) + native = ( + min(hidden, intermediate) >= 32 and hidden % 8 == 0 and intermediate % 8 == 0 + ) + pairs = [] + if torch.version.hip is not None and _NATIVE in active: + if native or _TRITON in active: + pairs.append((_NATIVE, native)) + if _TRITON in active: + pairs.append((_TRITON, False)) + if not pairs: + pytest.skip(f"requires the Triton or the Hygon provider, active={active}") + return pairs + + +def _clover_inputs(n, topk, experts, hidden, intermediate, dtype, device, hot, dropped): + """Inputs of one call. With `hot` > 0 that share of the routes goes to 16 + experts, which gives those experts several blocks; the first `dropped` + routes of every token are invalidated.""" + scores = -torch.rand(n, experts, device=device) + if hot > 0: + crowded = torch.rand(n, experts, device=device) < hot + scores[:, :16] += 2.0 * crowded[:, :16] + top = scores.topk(topk, dim=-1) + weights = top.values.softmax(-1).float().contiguous() + ids = top.indices.int().contiguous() + ids[:, :dropped] = -1 + hidden_states = torch.randn(n, hidden, device=device, dtype=dtype) * 0.2 + w13 = ( + torch.randn(experts, 2 * intermediate, hidden, device=device, dtype=dtype) * 0.1 + ) + w2 = torch.randn(experts, hidden, intermediate, device=device, dtype=dtype) * 0.1 + + pairs = n * topk + capacity = ( + pairs * _CLOVER_BLOCK + if pairs < experts + else pairs + experts * (_CLOVER_BLOCK - 1) + ) + sorted_ids = torch.empty(capacity, device=device, dtype=torch.int32) + expert_ids = torch.empty( + (capacity + _CLOVER_BLOCK - 1) // _CLOVER_BLOCK, + device=device, + dtype=torch.int32, + ) + num_post = torch.empty(1, device=device, dtype=torch.int32) + infini.ops.moe_align_block_size( + ids, + None, + experts, + _CLOVER_BLOCK, + sorted_ids, + expert_ids, + num_post, + stream=get_stream(device), + ) + return hidden_states, w13, w2, weights, ids, sorted_ids, expert_ids, num_post + + +def _clover_reference(hidden, w13, w2, weights, ids, round_projections): + """Float32 throughout, with the activation rounded to the element type + once. `round_projections` also rounds the gate and up projections, as the + Triton kernels do. Routes outside `[0, experts)` contribute nothing.""" + dtype, n, intermediate = hidden.dtype, hidden.shape[0], w2.shape[2] + topk = ids.shape[1] + out = torch.zeros(n, hidden.shape[1], device=hidden.device, dtype=torch.float32) + flat = ids.view(-1).long() + tokens = torch.arange(n, device=hidden.device).repeat_interleave(topk) + routed = weights.view(-1) + for expert in flat.unique().tolist(): + if not 0 <= expert < w2.shape[0]: + continue + select = (flat == expert).nonzero().squeeze(-1) + mid = hidden[tokens[select]].float() @ w13[expert].float().T + if round_projections: + mid = mid.to(dtype).float() + gate, up = mid[:, :intermediate], mid[:, intermediate:] + act = (torch.nn.functional.silu(gate) * up).to(dtype).float() + out.index_add_( + 0, tokens[select], (act @ w2[expert].float().T) * routed[select, None] + ) + return out + + +@pytest.mark.parametrize( + "n, topk, experts, hidden, intermediate, dtype, hot, dropped", + ( + # The per-rank shape of Clover-35B, routes spread or concentrated. + (32, 8, 256, 2048, 256, torch.bfloat16, 0.0, 0), + (1, 8, 256, 2048, 256, torch.bfloat16, 0.0, 0), + (64, 8, 256, 2048, 256, torch.bfloat16, 0.8, 0), + (32, 8, 256, 2048, 256, torch.float16, 0.0, 0), + (32, 8, 256, 2048, 256, torch.bfloat16, 0.0, 3), + # Rows and k steps that end inside a tile or a 16-byte unit. + (20, 4, 16, 136, 40, torch.bfloat16, 0.0, 0), + (5, 2, 8, 32, 32, torch.float16, 0.0, 0), + (8, 4, 16, 132, 64, torch.bfloat16, 0.0, 0), + (32, 8, 64, 192, 24, torch.bfloat16, 0.0, 0), + ), +) +def test_moe_fused_dense_clover( + n, topk, experts, hidden, intermediate, dtype, hot, dropped, device +): + torch.manual_seed(29) + cases = _clover_implementations(device, hidden, intermediate) + tensors = _clover_inputs( + n, topk, experts, hidden, intermediate, dtype, device, hot, dropped + ) + hidden_states, w13, w2, weights, ids = tensors[:5] + + for implementation, native in cases: + # The native kernels keep the gate and up projections in float32; the + # Triton kernels also round them to the element type. + expected = _clover_reference( + hidden_states, w13, w2, weights, ids, round_projections=not native + ) + output = torch.full_like(hidden_states, float("nan")) + infini.ops.moe_fused_dense( + output, + *tensors, + _CLOVER_BLOCK, + stream=get_stream(device), + implementation_index=implementation, + ) + torch.cuda.synchronize() + atol = 3e-3 if dtype == torch.bfloat16 else 1e-3 + torch.testing.assert_close( + output.float(), + expected, + rtol=2.5e-2, + atol=atol, + msg=lambda m: f"implementation {implementation}: {m}", + ) diff --git a/tests/test_recurrent_gated_delta_rule.py b/tests/test_recurrent_gated_delta_rule.py index 877c79ffc..a3e35f8ea 100644 --- a/tests/test_recurrent_gated_delta_rule.py +++ b/tests/test_recurrent_gated_delta_rule.py @@ -180,3 +180,211 @@ def test_recurrent_gated_delta_rule_state_pool(dtype, gate_dtype, rtol, atol, de # Untouched slots 1 and 3 keep their original values. torch.testing.assert_close(state_pool[1], before[1]) torch.testing.assert_close(state_pool[3], before[3]) + + +# Packed form: `[1, T, H, D]` requests over an FP32 state pool. The reference +# runs the recurrence in float64 and applies the state-slot contract of the +# base class: the initial slot is only read, the final state goes to the final +# slot, an unusable slot zeroes the output of the request, and a malformed +# token range changes nothing. The batched overload also accepts tensors in +# its optional positions, so the packed form is called with keyword arguments. + +_PACKED_NATIVE, _PACKED_TRITON = 0, 10 +_PACKED_QUERY_SCALE = 0.08838834764831845 + + +def _packed_reference( + q, k, v, g, beta, offsets, initial_slots, final_slots, state, norm +): + """Returns the output and the state pool after the call, in float64.""" + q, k, v, g, beta = (t.double().cpu() for t in (q, k, v, g, beta)) + _, tokens, num_v_heads, _ = v.shape + num_k_heads = k.shape[2] + out = torch.full(v.shape, float("nan"), dtype=torch.float64) + state = state.double().cpu().clone() + pool = state.shape[0] + for request in range(offsets.numel() - 1): + begin, end = int(offsets[request]), int(offsets[request + 1]) + initial, final = int(initial_slots[request]), int(final_slots[request]) + if not 0 <= begin <= end <= tokens: + continue + if not (0 <= initial < pool and 0 <= final < pool): + out[0, begin:end] = 0 + continue + for head in range(num_v_heads): + key_head = head // (num_v_heads // num_k_heads) + s = state[initial, head].clone() + for token in range(begin, end): + qv = q[0, token, key_head] + kv = k[0, token, key_head] + if norm: + qv = qv / (qv @ qv + 1e-6).sqrt() + kv = kv / (kv @ kv + 1e-6).sqrt() + qv = qv * _PACKED_QUERY_SCALE + s = s * torch.exp(g[0, token, head]) + delta = (v[0, token, head] - s @ kv) * beta[0, token, head] + s = s + delta[:, None] * kv[None, :] + out[0, token, head] = s @ qv + state[final, head] = s + return out, state + + +def _packed_implementations(device): + if device != "cuda": + pytest.skip("requires a CUDA-like backend") + impls = infini.ops.RecurrentGatedDeltaRule.active_implementation_indices(device) + if _PACKED_NATIVE not in impls and _PACKED_TRITON not in impls: + pytest.skip(f"requires a native or Triton packed provider, active={impls}") + return [impl for impl in (_PACKED_NATIVE, _PACKED_TRITON) if impl in impls] + + +def _packed_case(device, dtype, heads, index_dtype, strided): + """Three requests: an in-place update, an empty fork and a fork of the + same initial slot.""" + num_k_heads, num_v_heads = heads + tokens, dim, pool = 96, 128, 5 + q = torch.randn(1, tokens, num_k_heads, dim, device=device, dtype=dtype) * 0.5 + # ‖k‖ ≈ 1 keeps the unnormalized recurrence stable over many tokens. + k = torch.randn_like(q) * 0.09 + v = torch.randn(1, tokens, num_v_heads, dim, device=device, dtype=dtype) * 0.5 + g = torch.randn(1, tokens, num_v_heads, device=device) * 0.2 - 0.5 + beta = torch.rand(1, tokens, num_v_heads, device=device) + if strided: + # Columns of a wider buffer, as the narrowed projections of a model. + wide = torch.empty(1, tokens, num_k_heads, 2 * dim, device=device, dtype=dtype) + wide[..., :dim].copy_(q) + wide[..., dim:].copy_(k) + q, k = wide[..., :dim], wide[..., dim:] + # Offsets and slots of different widths exercise both index loads. + slot_dtype = torch.int64 if index_dtype == torch.int32 else torch.int32 + offsets = torch.tensor([0, 40, 40, tokens], device=device, dtype=index_dtype) + initial = torch.tensor([0, 1, 1], device=device, dtype=slot_dtype) + final = torch.tensor([0, 3, 2], device=device, dtype=slot_dtype) + state = torch.randn(pool, num_v_heads, dim, dim, device=device) * 0.1 + return q, k, v, g, beta, offsets, initial, final, state + + +def _packed_run(implementation, args, out, norm): + q, k, v, g, beta, offsets, initial, final, state = args + infini.ops.recurrent_gated_delta_rule( + q, + k, + v, + g, + beta, + state, + cu_seqlens=offsets, + initial_slots=initial, + final_slots=final, + out=out, + use_qk_l2norm=norm, + stream=torch.cuda.current_stream().cuda_stream, + implementation_index=implementation, + ) + torch.cuda.synchronize() + + +def _packed_check_output(out, ref_out): + """The data dtype rounds the output; the tolerance follows its scale.""" + scale = max(ref_out.abs().max().item(), 1.0) + torch.testing.assert_close( + out.double(), ref_out.to(out.device), rtol=2e-2, atol=scale * 3e-2 + ) + + +@pytest.mark.parametrize("norm", (True, False)) +@pytest.mark.parametrize("index_dtype", (torch.int32, torch.int64)) +@pytest.mark.parametrize("dtype", (torch.bfloat16, torch.float16)) +@pytest.mark.parametrize("heads", ((4, 4), (2, 8))) # (num_k_heads, num_v_heads) +@pytest.mark.parametrize("strided", (False, True)) +def test_packed_reference_and_state(device, dtype, heads, index_dtype, norm, strided): + torch.manual_seed(51) + args = _packed_case(device, dtype, heads, index_dtype, strided) + ref_out, ref_state = _packed_reference(*args, norm) + for implementation in _packed_implementations(device): + state = args[8].clone() + out = torch.empty_like(args[2]) + _packed_run(implementation, args[:8] + (state,), out, norm) + _packed_check_output(out, ref_out) + torch.testing.assert_close( + state.double(), ref_state.to(device), rtol=1e-3, atol=1e-3 + ) + # Slot 1 is only read: request 1 is empty and request 2 forks from it. + assert torch.equal(state[1], args[8][1]) + + +@pytest.mark.parametrize("broken", ("initial", "final")) +def test_packed_unusable_slot_zeroes_output(device, broken): + """An out-of-range slot zeroes the request's output and leaves the pool alone.""" + torch.manual_seed(52) + args = list(_packed_case(device, torch.bfloat16, (2, 2), torch.int32, False)) + slot = 6 if broken == "initial" else 7 + args[slot] = args[slot].clone() + args[slot][2] = 99 + args = tuple(args) + ref_out, ref_state = _packed_reference(*args, True) + assert torch.equal(ref_state[2].to(device), args[8][2]), "no state may be written" + for implementation in _packed_implementations(device): + state = args[8].clone() + out = torch.full_like(args[2], float("nan")) + _packed_run(implementation, args[:8] + (state,), out, True) + assert torch.equal(out[0, 40:], torch.zeros_like(out[0, 40:])), ( + "output must be zeroed" + ) + _packed_check_output(out[:, :40], ref_out[:, :40].to(device)) + assert torch.equal(state[2], args[8][2]) + assert torch.equal(state[1], args[8][1]) + + +def test_packed_malformed_range_is_untouched(device): + torch.manual_seed(53) + args = _packed_case(device, torch.bfloat16, (2, 2), torch.int32, False) + offsets = args[5].clone() + offsets[-1] += 8 # the last request reads past the packed sequence + args = args[:5] + (offsets,) + args[6:] + ref_out, ref_state = _packed_reference(*args, True) + assert torch.isnan(ref_out[0, 40:]).all() + # The empty request still copies its initial state to its final slot. + assert torch.equal(ref_state[3].to(device), args[8][1]) + for implementation in _packed_implementations(device): + state = args[8].clone() + out = torch.full_like(args[2], float("nan")) + _packed_run(implementation, args[:8] + (state,), out, True) + assert torch.isnan(out[0, 40:].float()).all(), "malformed range must not write" + _packed_check_output(out[:, :40], ref_out[:, :40].to(device)) + assert torch.equal(state[3], args[8][1]) + assert torch.equal(state[1:3], args[8][1:3]) + assert torch.equal(state[4], args[8][4]) + + +def test_packed_rejects_other_head_dims(device): + """Both packed providers implement a head dim of 128 only.""" + torch.manual_seed(54) + dim = 64 + q = torch.randn(1, 8, 2, dim, device=device, dtype=torch.bfloat16) + k = torch.randn_like(q) + v = torch.randn(1, 8, 4, dim, device=device, dtype=torch.bfloat16) + g = torch.randn(1, 8, 4, device=device) + beta = torch.rand_like(g) + state = torch.randn(2, 4, dim, dim, device=device) + offsets = torch.tensor([0, 8], device=device, dtype=torch.int32) + initial = torch.tensor([0], device=device, dtype=torch.int32) + final = torch.tensor([1], device=device, dtype=torch.int32) + out = torch.empty_like(v) + for implementation in _packed_implementations(device): + with pytest.raises(ValueError, match="head dim"): + infini.ops.recurrent_gated_delta_rule( + q, + k, + v, + g, + beta, + state, + cu_seqlens=offsets, + initial_slots=initial, + final_slots=final, + out=out, + use_qk_l2norm=True, + stream=torch.cuda.current_stream().cuda_stream, + implementation_index=implementation, + ) diff --git a/tests/test_triton_jit_compile.py b/tests/test_triton_jit_compile.py index 4b9b186e0..2ecf00faf 100644 --- a/tests/test_triton_jit_compile.py +++ b/tests/test_triton_jit_compile.py @@ -360,3 +360,27 @@ def test_auto_tuning_cache_rejects_zero_compile_options(monkeypatch, tmp_path, f module.write_auto_tuning_config(identity, config) assert module.read_auto_tuning_config(identity) is None + + +def test_hip_target_keeps_gfx_architecture(monkeypatch): + module, _ = _load_compile_module(monkeypatch) + target = module._create_target( + {"backend": "hip", "architecture": "gfx936", "warp_size": 64} + ) + assert (target.backend, target.arch, target.warp_size) == ("hip", "gfx936", 64) + + +def test_hip_artifacts_without_cuda_scratch_fields(monkeypatch, tmp_path): + module, fake_triton = _load_compile_module(monkeypatch) + fake_triton.compiler.make_backend = lambda target: types.SimpleNamespace( + binary_ext="hsaco" + ) + compiled = types.SimpleNamespace( + metadata=types.SimpleNamespace(name="hip_kernel", num_warps=4, shared=0), + asm={"hsaco": b"hip-binary"}, + ) + prefix = tmp_path / "kernel" + module._write_artifacts(compiled, object(), prefix, "hip-identity") + artifact = module.read_kernel_artifact(prefix, "hip-identity") + assert artifact["binary"] == b"hip-binary" + assert artifact["global_scratch_size"] == artifact["profile_scratch_size"] == 0