add-cuda-kernel
БесплатноБез исполняемых скриптовНе проверенStep-by-step tutorial for adding new CUDA kernels to FlashInfer
Об этом скилле
Tutorial: Adding a New Kernel to FlashInfer
This tutorial walks through adding a simple element-wise scale operation to FlashInfer. We'll implement scale(x, factor) = x * factor to demonstrate the complete workflow.
Goal
Add a new operation that scales each element of a tensor by a scalar factor:
- Input: tensor
xand scalarfactor - Output:
x * factor(element-wise) - Support multiple dtypes (FP16, BF16, FP32)
Step 1: Define CUDA Kernel in include/
Create include/flashinfer/scale.cuh:
#pragma once
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cuda_bf16.h>
namespace flashinfer {
/*!
* \brief Element-wise scale kernel
* \tparam T Data type (half, __nv_bfloat16, float)
* \param input Input tensor
* \param output Output tensor
* \param factor Scale factor
* \param n Number of elements
*/
template <typename T>
__global__ void ScaleKernel(const T* input, T* output, T factor, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
output[idx] = input[idx] * factor;
}
}
/*!
* \brief Launch scale kernel
* \tparam T Data type
* \param input Input pointer
* \param output Output pointer
* \param factor Scale factor
* \param n Number of elements
* \param stream CUDA stream
*/
template <typename T>
cudaError_t ScaleLauncher(const T* input, T* output, T factor, int n,
cudaStream_t stream = nullptr) {
const int threads = 256;
const int blocks = (n + threads - 1) / threads;
ScaleKernel<T><<<blocks, threads, 0, stream>>>(input, output, factor, n);
return cudaGetLastError();
}
} // namespace flashinfer
Key points:
- Framework-agnostic (no Torch headers)
- Uses raw pointers
- Template-based for dtype flexibility
- Only includes what's needed (cuda_runtime, cuda_fp16, cuda_bf16)
Step 2: Create Launcher in csrc/
Create csrc/scale.cu:
#include "flashinfer/scale.cuh"
using namespace flashinfer;
void scale_launcher(TensorView input, TensorView output,
float factor) {
CHECK_INPUT(input);
CHECK_INPUT(output);
TVM_FFI_ICHECK_EQ(input.dtype(), output.dtype());
int n = input.numel();
auto stream = get_stream(input.device());
DISPATCH_DLPACK_DTYPE_TO_CTYPE_FP32_FP16(input.dtype(), DType, [&] {
cudaError_t status = ScaleLauncher<DType>(
input.data_ptr<DType>(),
output.data_ptr<DType>(),
static_cast<DType>(factor),
n,
stream
);
TVM_FFI_ICHECK(status == cudaSuccess)
<< "Failed to run ScaleLauncher: " << cudaGetErrorString(status);
return true;
});
}
Key points:
- Includes TVM FFI utils headers
tvm_ffi_utils.h(only allowed incsrc/) - Uses
tvm::ffi::TensorViewas input and output tensor types - Uses macros defined in
tvm_ffi_utils.hto check the input and output if both on CUDA device, both contiguous, and share the same data type - Gets CUDA stream by TVM FFI, and prepare all scalar inputs for kernel function
- Dispatches on dtype with macros defined in
tvm_ffi_utils.h, or adds new one if not covered - Converts tvm::ffi::TensorView to raw pointers
- Handles the result status of kernel by
TVM_FFI_ICHECK - Add descriptive error messages with
<<operator - Use TVM-FFI exceptions:
TVM_FFI_THROW(ErrorType) << "message"for custom error checking
TVM-FFI Error Handling:
TVM_FFI_THROW(ValueError) << "message"- Throw ValueError with custom messageTVM_FFI_THROW(TypeError) << "message"- Throw TypeError- Use
<<to chain multiple values in the error message - Errors are properly propagated back to Python
When to use TVM_FFI_THROW vs TVM_FFI_LOG_AND_THROW:
TVM_FFI_THROW: Use for normal runtime error handling. This is the standard way to report errors that will be caught and propagated to Python.TVM_FFI_LOG_AND_THROW: Use only in cases where:- The function may be called during object construction time (e.g., validation in constructors or setup methods)
- The exception may not be caught properly (e.g., during module initialization)
- The error condition almost never fails in practice (e.g., internal errors, unsupported dtype combinations in dispatch macros)
This variant logs the error message before throwing, ensuring visibility even if the exception doesn't propagate correctly.
Example from fused_moe (see csrc/trtllm_fused_moe_kernel_launcher.cu):
// In a setup/validation function that may be called during construction
void check_weights_shape(std::string which_weights) const {
if (which_weights != "gemm1" && which_weights != "gemm2") {
// Internal error that should never happen - use LOG_AND_THROW
TVM_FFI_LOG_AND_THROW(InternalError) << "Internal error: which_weights = " << which_weights;
}
// ...
if (weight_layout is unsupported) {
// Unsupported config during setup - use LOG_AND_THROW
TVM_FFI_LOG_AND_THROW(NotImplementedError)
<< "Unsupported weight_layout: " << (int)weigh
Установить add-cuda-kernel в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл add-cuda-kernel?
Step-by-step tutorial for adding new CUDA kernels to FlashInfer
Как установить скилл add-cuda-kernel?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл add-cuda-kernel запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
patterns
Find patterns worth sharing from recent PRs and repo history, both repeats to fix and good practices worth spreading. Use when a champion wants to know what…
от Anthropiccopilot-cli-quickstart
Use this skill when someone wants to learn GitHub Copilot CLI from scratch. Offers interactive step-by-step tutorials with separate Developer and…
от GitHubvardoger-analyze
Use when the user asks to personalize the GitHub Copilot CLI assistant, adapt Copilot to their style, use vardoger, or analyze their Copilot CLI conversation…
от GitHubpolicy-lookup
Find and explain company policies in plain language. Trigger with "what's our PTO policy", "can I work remotely from another country", "how do expenses work"…
от Anthropic