[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ETYC6TGSET6NDPTM4RK8JN":3,"skill-same:01M6ETYC6TGSET6NDPTM4RK8JN":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":25,"linkOnly":26,"markdownContent":27,"markdownBody":28,"frontMatter":29,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":33,"repositoryHtmlUrl":34,"repositoryHomepageUrl":35,"ownerHtmlUrl":36,"ownerBlogUrl":6,"ownerDescription":37,"updatedAt":38,"install":39,"resources":52},"01M6ETYC6TGSET6NDPTM4RK8JN","add-cuda-kernel",null,"Step-by-step tutorial for adding new CUDA kernels to FlashInfer","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Fflashinfer-ai\u002Fadd-cuda-kernel\u002FSKILL.md",[],[19,20,21,22,23,24],"kernel","cuda","add","add cuda kernel","tutorial","cuda kernels","2026-11-10 10:12:30",false,"---\nname: add-cuda-kernel\ndescription: Step-by-step tutorial for adding new CUDA kernels to FlashInfer\n---\n\n# Tutorial: Adding a New Kernel to FlashInfer\n\nThis 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.\n\n## Goal\n\nAdd a new operation that scales each element of a tensor by a scalar factor:\n\n- Input: tensor `x` and scalar `factor`\n- Output: `x * factor` (element-wise)\n- Support multiple dtypes (FP16, BF16, FP32)\n\n## Step 1: Define CUDA Kernel in `include\u002F`\n\nCreate `include\u002Fflashinfer\u002Fscale.cuh`:\n\n```cpp\n#pragma once\n#include \u003Ccuda_runtime.h>\n#include \u003Ccuda_fp16.h>\n#include \u003Ccuda_bf16.h>\n\nnamespace flashinfer {\n\n\u002F*!\n * \\brief Element-wise scale kernel\n * \\tparam T Data type (half, __nv_bfloat16, float)\n * \\param input Input tensor\n * \\param output Output tensor\n * \\param factor Scale factor\n * \\param n Number of elements\n *\u002F\ntemplate \u003Ctypename T>\n__global__ void ScaleKernel(const T* input, T* output, T factor, int n) {\n  int idx = blockIdx.x * blockDim.x + threadIdx.x;\n  if (idx \u003C n) {\n    output[idx] = input[idx] * factor;\n  }\n}\n\n\u002F*!\n * \\brief Launch scale kernel\n * \\tparam T Data type\n * \\param input Input pointer\n * \\param output Output pointer\n * \\param factor Scale factor\n * \\param n Number of elements\n * \\param stream CUDA stream\n *\u002F\ntemplate \u003Ctypename T>\ncudaError_t ScaleLauncher(const T* input, T* output, T factor, int n,\n                          cudaStream_t stream = nullptr) {\n  const int threads = 256;\n  const int blocks = (n + threads - 1) \u002F threads;\n\n  ScaleKernel\u003CT>\u003C\u003C\u003Cblocks, threads, 0, stream>>>(input, output, factor, n);\n\n  return cudaGetLastError();\n}\n\n}  \u002F\u002F namespace flashinfer\n```\n\n**Key points:**\n\n- Framework-agnostic (no Torch headers)\n- Uses raw pointers\n- Template-based for dtype flexibility\n- Only includes what's needed (cuda_runtime, cuda_fp16, cuda_bf16)\n\n## Step 2: Create Launcher in `csrc\u002F`\n\nCreate `csrc\u002Fscale.cu`:\n\n```cpp\n#include \"flashinfer\u002Fscale.cuh\"\n\nusing namespace flashinfer;\n\nvoid scale_launcher(TensorView input, TensorView output,\n                    float factor) {\n  CHECK_INPUT(input);\n  CHECK_INPUT(output);\n  TVM_FFI_ICHECK_EQ(input.dtype(), output.dtype());\n  int n = input.numel();\n  auto stream = get_stream(input.device());\n\n  DISPATCH_DLPACK_DTYPE_TO_CTYPE_FP32_FP16(input.dtype(), DType, [&] {\n    cudaError_t status = ScaleLauncher\u003CDType>(\n      input.data_ptr\u003CDType>(),\n      output.data_ptr\u003CDType>(),\n      static_cast\u003CDType>(factor),\n      n,\n      stream\n    );\n    TVM_FFI_ICHECK(status == cudaSuccess)\n        \u003C\u003C \"Failed to run ScaleLauncher: \" \u003C\u003C cudaGetErrorString(status);\n    return true;\n  });\n}\n```\n\n**Key points:**\n\n- Includes TVM FFI utils headers `tvm_ffi_utils.h` (only allowed in `csrc\u002F`)\n- Uses `tvm::ffi::TensorView` as input and output tensor types\n- Uses macros defined in `tvm_ffi_utils.h` to check the input and output if both on CUDA device, both contiguous, and share the same data type\n- Gets CUDA stream by TVM FFI, and prepare all scalar inputs for kernel function\n- Dispatches on dtype with macros defined in `tvm_ffi_utils.h`, or adds new one if not covered\n- Converts tvm::ffi::TensorView to raw pointers\n- Handles the result status of kernel by `TVM_FFI_ICHECK`\n- Add descriptive error messages with `\u003C\u003C` operator\n- **Use TVM-FFI exceptions**: `TVM_FFI_THROW(ErrorType) \u003C\u003C \"message\"` for custom error checking\n\n**TVM-FFI Error Handling:**\n\n- `TVM_FFI_THROW(ValueError) \u003C\u003C \"message\"` - Throw ValueError with custom message\n- `TVM_FFI_THROW(TypeError) \u003C\u003C \"message\"` - Throw TypeError\n- Use `\u003C\u003C` to chain multiple values in the error message\n- Errors are properly propagated back to Python\n\n**When to use `TVM_FFI_THROW` vs `TVM_FFI_LOG_AND_THROW`:**\n\n- **`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.\n\n- **`TVM_FFI_LOG_AND_THROW`**: Use only in cases where:\n  1. The function may be called during object construction time (e.g., validation in constructors or setup methods)\n  2. The exception may not be caught properly (e.g., during module initialization)\n  3. The error condition almost never fails in practice (e.g., internal errors, unsupported dtype combinations in dispatch macros)\n\n  This variant logs the error message before throwing, ensuring visibility even if the exception doesn't propagate correctly.\n\n**Example from fused_moe (see `csrc\u002Ftrtllm_fused_moe_kernel_launcher.cu`):**\n```cpp\n\u002F\u002F In a setup\u002Fvalidation function that may be called during construction\nvoid check_weights_shape(std::string which_weights) const {\n  if (which_weights != \"gemm1\" && which_weights != \"gemm2\") {\n    \u002F\u002F Internal error that should never happen - use LOG_AND_THROW\n    TVM_FFI_LOG_AND_THROW(InternalError) \u003C\u003C \"Internal error: which_weights = \" \u003C\u003C which_weights;\n  }\n  \u002F\u002F ...\n  if (weight_layout is unsupported) {\n    \u002F\u002F Unsupported config during setup - use LOG_AND_THROW\n    TVM_FFI_LOG_AND_THROW(NotImplementedError)\n        \u003C\u003C \"Unsupported weight_layout: \" \u003C\u003C (int)weight_layout;\n  }\n}\n\n\u002F\u002F In a normal runtime function\nvoid scale_run(TensorView input, TensorView output, double factor) {\n  if (!input_tensor.is_cuda()) {\n    \u002F\u002F Normal validation error - use TVM_FFI_THROW\n    TVM_FFI_THROW(ValueError) \u003C\u003C \"Input must be a CUDA tensor\";\n  }\n}\n```\n\n## Step 3: Create TVM-FFI Binding in `csrc\u002F`\n\nCreate `csrc\u002Fscale_jit_binding.cu`:\n\n```cpp\n#include \"scale.cu\"\n#include \"tvm_ffi_utils.h\"\n\n\u002F\u002F Forward declaration\nvoid scale_launcher(TensorView input, TensorView output, float factor);\n\n\u002F\u002F Export to TVM-FFI\nTVM_FFI_DLL_EXPORT_TYPED_FUNC(run, scale_launcher);\n```\n\n**Key points:**\n\n- Forward declare the launcher function first\n- Export using `TVM_FFI_DLL_EXPORT_TYPED_FUNC(name, function)`\n\n## Step 4: Create JIT Generator (No Jinja for Simple Case)\n\nCreate `flashinfer\u002Fjit\u002Fscale.py`:\n\n```python\nimport os\nimport shutil\nfrom pathlib import Path\n\nfrom . import JitSpec, gen_jit_spec\nfrom . import env as jit_env\nfrom .core import write_if_different\n\n\ndef get_scale_uri(dtype_in: str, dtype_out: str) -> str:\n    \"\"\"Generate unique identifier for scale module.\"\"\"\n    return f\"scale_dtype_in_{dtype_in}_dtype_out_{dtype_out}\"\n\n\ndef gen_scale_module(dtype_in, dtype_out):\n    \"\"\"\n    Generate JIT module for scale operation.\n\n    Note: This is a simple example without Jinja templating.\n    The dtype dispatch is handled at runtime in the C++ code.\n    \"\"\"\n    # Compute URI\n    uri = get_scale_uri(dtype_in, dtype_out)\n\n    # Create generation directory\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    os.makedirs(gen_directory, exist_ok=True)\n\n    # Copy source files (no Jinja needed for this simple case)\n    sources = []\n    for fname in [\"scale.cu\", \"scale_jit_binding.cu\"]:\n        src_path = jit_env.FLASHINFER_CSRC_DIR \u002F fname\n        dest_path = gen_directory \u002F fname\n        shutil.copy(src_path, dest_path)\n        sources.append(dest_path)\n\n    # Return JitSpec\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=[],\n    )\n```\n\n**Key points:**\n\n- No Jinja template needed for simple operations\n- Just copy source files to generation directory\n- URI uniquely identifies the module configuration\n\n### (Optional) Specifying Supported CUDA Architectures\n\nFlashInfer uses `CompilationContext` to manage CUDA architecture targets. This is critical because some kernels only work on specific GPU architectures (e.g., Hopper SM90, Blackwell SM100).\n\n#### How CompilationContext Works\n\n**Automatic Detection** (default):\n```python\nfrom flashinfer.compilation_context import CompilationContext\n\nctx = CompilationContext()\n# Automatically detects all GPUs in the system\n# For SM90+, adds 'a' suffix (e.g., 9.0a for Hopper)\n# Result: ctx.TARGET_CUDA_ARCHS = {(9, '0a'), (10, '0a'), ...}\n```\n\n**Manual Override** (via environment variable):\n```bash\nexport FLASHINFER_CUDA_ARCH_LIST=\"8.0 9.0a 10.0a\"\n# Now only these architectures will be compiled\n```\n\n#### Specifying Architectures in Your JIT Module\n\nWhen creating a JIT module, specify which major SM versions are supported:\n\n```python\nfrom flashinfer.jit.core import gen_jit_spec\nfrom flashinfer.jit import current_compilation_context\n\ndef gen_my_hopper_only_module():\n    \"\"\"Example: Kernel works on SM90 and later supported architectures.\"\"\"\n    uri = get_my_uri(...)\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    # ... copy sources ...\n\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        # Explicitly list supported SM versions - no automatic future compatibility\n        supported_major_versions=[9, 10, 11, 12]  # SM90, SM100, SM110, SM120\n    )\n\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\ndef gen_my_blackwell_only_module():\n    \"\"\"Example: Kernel only works on SM100 (Blackwell)\"\"\"\n    uri = get_my_uri(...)\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    # ... copy sources ...\n\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[10]  # SM100 only\n    )\n\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\ndef gen_my_universal_module():\n    \"\"\"Example: Kernel works on all architectures\"\"\"\n    uri = get_my_uri(...)\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    # ... copy sources ...\n\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=None  # All available architectures\n    )\n\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n```\n\n**What Happens:**\n- ✅ If user's GPU is SM90 and they call a Hopper-only module → Compiles and runs\n- ❌ If user's GPU is SM80 and they call a Hopper-only module → `RuntimeError: No supported CUDA architectures found for major versions [9, 10, 11, 12]`\n\n#### Real Examples from FlashInfer\n\n```python\n# MLA kernel: Blackwell and newer only\ndef gen_mla_module() -> JitSpec:\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[10, 11]  # SM100, SM110\n    )\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\n# Blackwell FMHA: SM120 only\ndef gen_fmhav2_blackwell_module(...):\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[12]  # SM120 only\n    )\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\n# Standard attention: Hopper and later supported architectures\ndef gen_batch_prefill_module(...):\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[9, 10, 11, 12]  # SM90, SM100, SM110, SM120\n    )\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n```\n\n#### Common Architecture Specifications\n\n| Supported Versions | Architectures | Use Case |\n|-------------------|---------------|----------|\n| `None` | All available GPUs | Universal kernels (default) |\n| `[9, 10, 11, 12]` | SM90, SM100, SM110, SM120 | Hopper, Blackwell |\n| `[10, 11, 12]` | SM100, SM110, SM120 | Blackwell only |\n| `[12]` | SM120 | Specific architecture only |\n| `[8, 9, 10, 11, 12]` | SM80, SM90, SM100, SM110, SM120 | Ampere, Hopper, Blackwell |\n\n#### Testing with Architecture Requirements\n\nWhen your kernel has architecture requirements, add skip checks in tests (see Step 6 below):\n\n```python\nimport pytest\nimport torch\nfrom flashinfer.utils import is_sm90a_supported\n\ndef test_hopper_kernel():\n    if not is_sm90a_supported(torch.device(\"cuda\")):\n        pytest.skip(\"SM90a is not supported on this GPU\")\n\n    # Test code here\n    ...\n```\n\n## Step 5: Create Python API in `flashinfer\u002F`\n\nCreate `flashinfer\u002Fscale.py`:\n\n```python\nimport functools\nimport torch\nfrom typing import Optional\n\nfrom .jit.scale import gen_scale_module\nfrom .utils import backend_requirement, supported_compute_capability\nfrom .api_logging import flashinfer_api\n\n\n@functools.cache\ndef get_scale_module(dtype_in, dtype_out):\n    \"\"\"Get or compile scale module (cached).\"\"\"\n    return gen_scale_module(dtype_in, dtype_out).build_and_load()\n\n\n@supported_compute_capability([80, 86, 89, 90, 100, 103, 110, 120])\ndef _check_scale_problem_size(input: torch.Tensor, factor: float,\n                               out: Optional[torch.Tensor] = None) -> bool:\n    \"\"\"Validate inputs for scale operation.\"\"\"\n    # Validate input\n    if not input.is_cuda:\n        raise ValueError(\"Input must be a CUDA tensor\")\n\n    # Validate output if provided\n    if out is not None:\n        if out.shape != input.shape:\n            raise ValueError(\"Output shape mismatch\")\n        if out.dtype != input.dtype:\n            raise ValueError(\"Output dtype mismatch\")\n        if not out.is_cuda:\n            raise ValueError(\"Output must be a CUDA tensor\")\n\n    return True\n\n\n@flashinfer_api\n@backend_requirement(\n    backend_checks={},  # No backend choices for this simple kernel\n    common_check=_check_scale_problem_size,\n)\ndef scale(input: torch.Tensor, factor: float,\n          out: Optional[torch.Tensor] = None) -> torch.Tensor:\n    \"\"\"\n    Element-wise scale operation.\n\n    Parameters\n    ----------\n    input : torch.Tensor\n        Input tensor (CUDA)\n    factor : float\n        Scale factor\n    out : Optional[torch.Tensor]\n        Output tensor (if None, allocate new tensor)\n\n    Returns\n    -------\n    output : torch.Tensor\n        Scaled tensor (input * factor)\n\n    Examples\n    --------\n    >>> import torch\n    >>> import flashinfer\n    >>> x = torch.randn(1024, dtype=torch.float16, device=\"cuda\")\n    >>> y = flashinfer.scale(x, 2.0)\n    >>> torch.allclose(y, x * 2.0)\n    True\n    \"\"\"\n    # Allocate output if needed\n    if out is None:\n        out = torch.empty_like(input)\n\n    # Get module (compile if first call with this dtype)\n    dtype_str = str(input.dtype).replace(\"torch.\", \"\")\n    module = get_scale_module(dtype_str, dtype_str)\n\n    # Call TVM-FFI function (exported as \"run\")\n    module.run(input, out, float(factor))\n\n    return out\n```\n\n**Key points:**\n\n- Uses `@functools.cache` to cache compiled modules\n- Clean Python API with docstring\n- Adding the `@flashinfer_api` decorator enables logging and sets it apart from helper functions\n- **Destination passing style**: Output tensor(s) are passed as optional parameters (`out: Optional[torch.Tensor] = None`). This allows users to provide pre-allocated buffers to avoid allocation overhead in performance-critical paths. Only allocate internally when `out` is `None`.\n- Validates inputs using `@backend_requirement` decorator\n\n### Using `@backend_requirement` and `@supported_compute_capability` Decorators\n\nFlashInfer provides two decorators for enforcing compute capability and backend requirements:\n\n#### `@supported_compute_capability` Decorator\n\nMarks a function with its supported CUDA compute capabilities:\n\n```python\nfrom flashinfer.utils import supported_compute_capability\n\n@supported_compute_capability([80, 86, 89, 90, 100, 103, 110, 120])\ndef _my_check_function(input, output):\n    \"\"\"Supports SM80 (Ampere) through SM120 (Blackwell).\"\"\"\n    # Validation logic here\n    return True\n```\n\n#### `@backend_requirement` Decorator\n\nEnforces backend and problem size requirements at runtime. There are three usage patterns:\n\n**Pattern 1: Single Backend (No Backend Choices)**\n\nFor kernels with only one implementation (like our scale example):\n\n```python\nfrom flashinfer.utils import backend_requirement, supported_compute_capability\n\n@supported_compute_capability([80, 86, 89, 90, 100, 103, 110, 120])\ndef _check_my_kernel(input, output):\n    \"\"\"Validate inputs. Must return True if valid.\"\"\"\n    if input.shape[-1] > 256:\n        raise ValueError(\"Head dimension must be \u003C= 256\")\n    return True\n\n@backend_requirement(\n    backend_checks={},  # Empty dict = no backend parameter\n    common_check=_check_my_kernel,\n)\ndef my_kernel(input, output):\n    # Kernel implementation\n    pass\n```\n\n**Pattern 2: Multiple Backends**\n\nFor kernels with multiple implementation backends (e.g., CUTLASS, cuDNN):\n\n```python\n@supported_compute_capability([80, 86, 89, 90])\ndef _cutlass_check(q, k, v, backend):\n    \"\"\"CUTLASS backend: Ampere through Hopper.\"\"\"\n    if q.shape[-1] > 256:\n        raise ValueError(\"CUTLASS: head_dim must be \u003C= 256\")\n    return True\n\n@supported_compute_capability([75, 80, 86, 89, 90, 100])\ndef _cudnn_check(q, k, v, backend):\n    \"\"\"cuDNN backend: Turing through Blackwell.\"\"\"\n    return True\n\n@backend_requirement(\n    backend_checks={\n        \"cutlass\": _cutlass_check,\n        \"cudnn\": _cudnn_check,\n    },\n    common_check=None,  # Optional: shared validation for all backends\n)\ndef attention(q, k, v, backend=\"cutlass\"):\n    if backend == \"cutlass\":\n        # CUTLASS implementation\n        pass\n    elif backend == \"cudnn\":\n        # cuDNN implementation\n        pass\n```\n\n**Pattern 3: Auto Backend Selection**\n\nFor kernels that can automatically select the best backend:\n\n```python\ndef _heuristic_func(suitable_backends, q, k, v, backend):\n    \"\"\"Return backends in order of preference.\"\"\"\n    # Prefer CUTLASS for small head dims, cuDNN for larger\n    if q.shape[-1] \u003C= 128:\n        preferred = [\"cutlass\", \"cudnn\"]\n    else:\n        preferred = [\"cudnn\", \"cutlass\"]\n    return [b for b in preferred if b in suitable_backends]\n\n@backend_requirement(\n    backend_checks={\n        \"cutlass\": _cutlass_check,\n        \"cudnn\": _cudnn_check,\n    },\n    common_check=_common_validation,\n    heuristic_func=_heuristic_func,  # Required when backend=\"auto\" is used\n)\ndef attention(q, k, v, backend=\"auto\"):\n    if backend == \"auto\":\n        # Use the first backend from suitable_auto_backends\n        backend = attention.suitable_auto_backends[0]\n    # ... rest of implementation\n```\n\n#### Features Added by `@backend_requirement`\n\nThe decorator adds these methods to the wrapped function:\n\n```python\n# Check if a backend is supported (optionally for a specific CC)\nscale.is_backend_supported(\"cutlass\")           # True\u002FFalse\nscale.is_backend_supported(\"cutlass\", cc=90)    # True\u002FFalse for Hopper\n\n# Check if any backend supports this compute capability\nscale.is_compute_capability_supported(90)       # True\u002FFalse\n\n# Check if a backend exists\nscale.has_backend(\"cutlass\")                    # True\u002FFalse\n\n# Check if there are multiple backend choices\nscale.has_backend_choices()                     # True\u002FFalse\n```\n\n#### `skip_check` Keyword Argument\n\nThe decorator adds a `skip_check` keyword argument to bypass validation for performance-critical code paths:\n\n```python\n# Normal call with validation\nresult = scale(x, 2.0)\n\n# Skip validation for performance (use with caution!)\nresult = scale(x, 2.0, skip_check=True)\n```\n\n#### Check Function Requirements\n\nCheck functions must:\n1. Accept the same arguments as the decorated function\n2. Return `True` if validation passes\n3. Raise `ValueError` with descriptive message if validation fails\n4. Be decorated with `@supported_compute_capability` to specify supported architectures\n\n## Step 6: Write Tests in `tests\u002F`\n\nCreate tests in an appropriate subdirectory (e.g., `tests\u002Felementwise\u002Ftest_scale.py` or create a new subdir if needed):\n\n```python\nimport pytest\nimport torch\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16, torch.float32])\n@pytest.mark.parametrize(\"size\", [128, 1024, 4096])\ndef test_scale_correctness(dtype, size):\n    \"\"\"Test scale operation correctness.\"\"\"\n    import flashinfer\n\n    # Setup\n    x = torch.randn(size, dtype=dtype, device=\"cuda\")\n    factor = 3.14\n\n    # Run FlashInfer kernel\n    y = flashinfer.scale(x, factor)\n\n    # Reference implementation\n    expected = x * factor\n\n    # Compare\n    if dtype == torch.float32:\n        rtol, atol = 1e-5, 1e-6\n    else:\n        rtol, atol = 1e-3, 1e-3\n\n    torch.testing.assert_close(y, expected, rtol=rtol, atol=atol)\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\ndef test_scale_inplace(dtype):\n    \"\"\"Test scale with pre-allocated output.\"\"\"\n    import flashinfer\n\n    x = torch.randn(1024, dtype=dtype, device=\"cuda\")\n    out = torch.empty_like(x)\n    factor = 2.0\n\n    result = flashinfer.scale(x, factor, out=out)\n\n    # Should return the same tensor\n    assert result is out\n\n    # Check correctness\n    expected = x * factor\n    torch.testing.assert_close(result, expected, rtol=1e-3, atol=1e-3)\n\n\ndef test_scale_cpu_error():\n    \"\"\"Test that CPU tensors raise an error.\"\"\"\n    import flashinfer\n\n    x = torch.randn(128, dtype=torch.float32)\n\n    with pytest.raises(ValueError, match=\"CUDA\"):\n        flashinfer.scale(x, 2.0)\n```\n\n**Key points:**\n\n- Use `pytest.mark.parametrize` for multiple configurations\n- Compare against reference implementation\n- Set appropriate tolerances for each dtype\n- Test error cases\n\n## Step 7: Register in AOT\n\nRegister your kernel in AOT so users with `flashinfer-jit-cache` can skip JIT compilation.\n\nEdit `flashinfer\u002Faot.py`, add to the appropriate section:\n\n```python\ndef gen_scale_modules() -> Iterator[JitSpec]:\n    \"\"\"Generate scale operation modules for AOT compilation.\"\"\"\n    from .jit.scale import gen_scale_module\n\n    # Pre-compile common dtypes\n    for dtype in [\"float16\", \"bfloat16\", \"float32\"]:\n        yield gen_scale_module(dtype, dtype)\n\n\n# In the main AOT build loop, add:\n# for spec in gen_scale_modules():\n#     spec.build()\n```\n\n**Key points:**\n\n- Pre-compile common configurations\n- Users with `flashinfer-jit-cache` won't need to compile at runtime\n\n## Step 8: Export API\n\nEdit `flashinfer\u002F__init__.py`:\n\n```python\nfrom .scale import scale as scale\n\n# Or in the existing imports section:\n# from .scale import scale\n```\n\n## Step 9: Run and Test\n\n```bash\n# The kernel compiles automatically on first use\npytest tests\u002Ftest_scale.py -v\n\n# Run with different dtypes\npytest tests\u002Ftest_scale.py::test_scale_correctness[float16-128] -v\n```\n\n## Step 10: Add Benchmark\n\n**All new kernels should have benchmarks.** This helps track performance regressions and allows users to compare against other implementations.\n\nCreate a benchmark file in `benchmarks\u002F` (e.g., `benchmarks\u002Fbench_scale.py`):\n\n```python\nimport torch\nfrom flashinfer.testing import bench_gpu_time\n\ndef bench_scale():\n    \"\"\"Benchmark scale kernel.\"\"\"\n    import flashinfer\n\n    sizes = [1024, 4096, 16384, 65536, 262144]\n    dtypes = [torch.float16, torch.bfloat16]\n\n    print(\"Scale Kernel Benchmark\")\n    print(\"-\" * 60)\n    print(f\"{'Size':>10} {'Dtype':>10} {'Time (us)':>12} {'Std (us)':>10}\")\n    print(\"-\" * 60)\n\n    for size in sizes:\n        for dtype in dtypes:\n            x = torch.randn(size, dtype=dtype, device=\"cuda\")\n\n            # Benchmark with CUPTI (auto-fallback to CUDA events)\n            median_time, std_time = bench_gpu_time(\n                flashinfer.scale,\n                args=(x, 2.0),\n                enable_cupti=True,\n                dry_run_iters=10,\n                repeat_iters=100,\n            )\n\n            print(f\"{size:>10} {str(dtype):>10} {median_time*1e6:>12.2f} {std_time*1e6:>10.2f}\")\n\nif __name__ == \"__main__\":\n    bench_scale()\n```\n\n**For more complex kernels**, consider:\n\n- Adding comparisons against reference implementations (e.g., PyTorch native, cuBLAS, cuDNN)\n- Using the unified benchmarking framework in `benchmarks\u002Fflashinfer_benchmark.py` if applicable\n- Testing across different problem sizes and configurations\n\n→ **For complete benchmarking guide, see [`.claude\u002Fskills\u002Fbenchmark-kernel\u002FSKILL.md`](..\u002Fbenchmark-kernel\u002FSKILL.md)**\n\n## Summary of Files Created\u002FModified\n\n```\ninclude\u002Fflashinfer\u002Fscale.cuh              # NEW: CUDA kernel definition\ncsrc\u002Fscale.cu                              # NEW: PyTorch launcher\ncsrc\u002Fscale_jit_binding.cu                  # NEW: TVM-FFI binding\nflashinfer\u002Fjit\u002Fscale.py                    # NEW: JIT generator\nflashinfer\u002Fscale.py                        # NEW: Python API\nflashinfer\u002F__init__.py                     # MODIFIED: Export API\nflashinfer\u002Faot.py                          # MODIFIED: Register AOT\ntests\u002Ftest_scale.py                        # NEW: Unit tests\nbenchmarks\u002Fbench_scale.py                  # NEW: Benchmark script\n```\n","# Tutorial: Adding a New Kernel to FlashInfer\n\nThis 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.\n\n## Goal\n\nAdd a new operation that scales each element of a tensor by a scalar factor:\n\n- Input: tensor `x` and scalar `factor`\n- Output: `x * factor` (element-wise)\n- Support multiple dtypes (FP16, BF16, FP32)\n\n## Step 1: Define CUDA Kernel in `include\u002F`\n\nCreate `include\u002Fflashinfer\u002Fscale.cuh`:\n\n```cpp\n#pragma once\n#include \u003Ccuda_runtime.h>\n#include \u003Ccuda_fp16.h>\n#include \u003Ccuda_bf16.h>\n\nnamespace flashinfer {\n\n\u002F*!\n * \\brief Element-wise scale kernel\n * \\tparam T Data type (half, __nv_bfloat16, float)\n * \\param input Input tensor\n * \\param output Output tensor\n * \\param factor Scale factor\n * \\param n Number of elements\n *\u002F\ntemplate \u003Ctypename T>\n__global__ void ScaleKernel(const T* input, T* output, T factor, int n) {\n  int idx = blockIdx.x * blockDim.x + threadIdx.x;\n  if (idx \u003C n) {\n    output[idx] = input[idx] * factor;\n  }\n}\n\n\u002F*!\n * \\brief Launch scale kernel\n * \\tparam T Data type\n * \\param input Input pointer\n * \\param output Output pointer\n * \\param factor Scale factor\n * \\param n Number of elements\n * \\param stream CUDA stream\n *\u002F\ntemplate \u003Ctypename T>\ncudaError_t ScaleLauncher(const T* input, T* output, T factor, int n,\n                          cudaStream_t stream = nullptr) {\n  const int threads = 256;\n  const int blocks = (n + threads - 1) \u002F threads;\n\n  ScaleKernel\u003CT>\u003C\u003C\u003Cblocks, threads, 0, stream>>>(input, output, factor, n);\n\n  return cudaGetLastError();\n}\n\n}  \u002F\u002F namespace flashinfer\n```\n\n**Key points:**\n\n- Framework-agnostic (no Torch headers)\n- Uses raw pointers\n- Template-based for dtype flexibility\n- Only includes what's needed (cuda_runtime, cuda_fp16, cuda_bf16)\n\n## Step 2: Create Launcher in `csrc\u002F`\n\nCreate `csrc\u002Fscale.cu`:\n\n```cpp\n#include \"flashinfer\u002Fscale.cuh\"\n\nusing namespace flashinfer;\n\nvoid scale_launcher(TensorView input, TensorView output,\n                    float factor) {\n  CHECK_INPUT(input);\n  CHECK_INPUT(output);\n  TVM_FFI_ICHECK_EQ(input.dtype(), output.dtype());\n  int n = input.numel();\n  auto stream = get_stream(input.device());\n\n  DISPATCH_DLPACK_DTYPE_TO_CTYPE_FP32_FP16(input.dtype(), DType, [&] {\n    cudaError_t status = ScaleLauncher\u003CDType>(\n      input.data_ptr\u003CDType>(),\n      output.data_ptr\u003CDType>(),\n      static_cast\u003CDType>(factor),\n      n,\n      stream\n    );\n    TVM_FFI_ICHECK(status == cudaSuccess)\n        \u003C\u003C \"Failed to run ScaleLauncher: \" \u003C\u003C cudaGetErrorString(status);\n    return true;\n  });\n}\n```\n\n**Key points:**\n\n- Includes TVM FFI utils headers `tvm_ffi_utils.h` (only allowed in `csrc\u002F`)\n- Uses `tvm::ffi::TensorView` as input and output tensor types\n- Uses macros defined in `tvm_ffi_utils.h` to check the input and output if both on CUDA device, both contiguous, and share the same data type\n- Gets CUDA stream by TVM FFI, and prepare all scalar inputs for kernel function\n- Dispatches on dtype with macros defined in `tvm_ffi_utils.h`, or adds new one if not covered\n- Converts tvm::ffi::TensorView to raw pointers\n- Handles the result status of kernel by `TVM_FFI_ICHECK`\n- Add descriptive error messages with `\u003C\u003C` operator\n- **Use TVM-FFI exceptions**: `TVM_FFI_THROW(ErrorType) \u003C\u003C \"message\"` for custom error checking\n\n**TVM-FFI Error Handling:**\n\n- `TVM_FFI_THROW(ValueError) \u003C\u003C \"message\"` - Throw ValueError with custom message\n- `TVM_FFI_THROW(TypeError) \u003C\u003C \"message\"` - Throw TypeError\n- Use `\u003C\u003C` to chain multiple values in the error message\n- Errors are properly propagated back to Python\n\n**When to use `TVM_FFI_THROW` vs `TVM_FFI_LOG_AND_THROW`:**\n\n- **`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.\n\n- **`TVM_FFI_LOG_AND_THROW`**: Use only in cases where:\n  1. The function may be called during object construction time (e.g., validation in constructors or setup methods)\n  2. The exception may not be caught properly (e.g., during module initialization)\n  3. The error condition almost never fails in practice (e.g., internal errors, unsupported dtype combinations in dispatch macros)\n\n  This variant logs the error message before throwing, ensuring visibility even if the exception doesn't propagate correctly.\n\n**Example from fused_moe (see `csrc\u002Ftrtllm_fused_moe_kernel_launcher.cu`):**\n```cpp\n\u002F\u002F In a setup\u002Fvalidation function that may be called during construction\nvoid check_weights_shape(std::string which_weights) const {\n  if (which_weights != \"gemm1\" && which_weights != \"gemm2\") {\n    \u002F\u002F Internal error that should never happen - use LOG_AND_THROW\n    TVM_FFI_LOG_AND_THROW(InternalError) \u003C\u003C \"Internal error: which_weights = \" \u003C\u003C which_weights;\n  }\n  \u002F\u002F ...\n  if (weight_layout is unsupported) {\n    \u002F\u002F Unsupported config during setup - use LOG_AND_THROW\n    TVM_FFI_LOG_AND_THROW(NotImplementedError)\n        \u003C\u003C \"Unsupported weight_layout: \" \u003C\u003C (int)weight_layout;\n  }\n}\n\n\u002F\u002F In a normal runtime function\nvoid scale_run(TensorView input, TensorView output, double factor) {\n  if (!input_tensor.is_cuda()) {\n    \u002F\u002F Normal validation error - use TVM_FFI_THROW\n    TVM_FFI_THROW(ValueError) \u003C\u003C \"Input must be a CUDA tensor\";\n  }\n}\n```\n\n## Step 3: Create TVM-FFI Binding in `csrc\u002F`\n\nCreate `csrc\u002Fscale_jit_binding.cu`:\n\n```cpp\n#include \"scale.cu\"\n#include \"tvm_ffi_utils.h\"\n\n\u002F\u002F Forward declaration\nvoid scale_launcher(TensorView input, TensorView output, float factor);\n\n\u002F\u002F Export to TVM-FFI\nTVM_FFI_DLL_EXPORT_TYPED_FUNC(run, scale_launcher);\n```\n\n**Key points:**\n\n- Forward declare the launcher function first\n- Export using `TVM_FFI_DLL_EXPORT_TYPED_FUNC(name, function)`\n\n## Step 4: Create JIT Generator (No Jinja for Simple Case)\n\nCreate `flashinfer\u002Fjit\u002Fscale.py`:\n\n```python\nimport os\nimport shutil\nfrom pathlib import Path\n\nfrom . import JitSpec, gen_jit_spec\nfrom . import env as jit_env\nfrom .core import write_if_different\n\n\ndef get_scale_uri(dtype_in: str, dtype_out: str) -> str:\n    \"\"\"Generate unique identifier for scale module.\"\"\"\n    return f\"scale_dtype_in_{dtype_in}_dtype_out_{dtype_out}\"\n\n\ndef gen_scale_module(dtype_in, dtype_out):\n    \"\"\"\n    Generate JIT module for scale operation.\n\n    Note: This is a simple example without Jinja templating.\n    The dtype dispatch is handled at runtime in the C++ code.\n    \"\"\"\n    # Compute URI\n    uri = get_scale_uri(dtype_in, dtype_out)\n\n    # Create generation directory\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    os.makedirs(gen_directory, exist_ok=True)\n\n    # Copy source files (no Jinja needed for this simple case)\n    sources = []\n    for fname in [\"scale.cu\", \"scale_jit_binding.cu\"]:\n        src_path = jit_env.FLASHINFER_CSRC_DIR \u002F fname\n        dest_path = gen_directory \u002F fname\n        shutil.copy(src_path, dest_path)\n        sources.append(dest_path)\n\n    # Return JitSpec\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=[],\n    )\n```\n\n**Key points:**\n\n- No Jinja template needed for simple operations\n- Just copy source files to generation directory\n- URI uniquely identifies the module configuration\n\n### (Optional) Specifying Supported CUDA Architectures\n\nFlashInfer uses `CompilationContext` to manage CUDA architecture targets. This is critical because some kernels only work on specific GPU architectures (e.g., Hopper SM90, Blackwell SM100).\n\n#### How CompilationContext Works\n\n**Automatic Detection** (default):\n```python\nfrom flashinfer.compilation_context import CompilationContext\n\nctx = CompilationContext()\n# Automatically detects all GPUs in the system\n# For SM90+, adds 'a' suffix (e.g., 9.0a for Hopper)\n# Result: ctx.TARGET_CUDA_ARCHS = {(9, '0a'), (10, '0a'), ...}\n```\n\n**Manual Override** (via environment variable):\n```bash\nexport FLASHINFER_CUDA_ARCH_LIST=\"8.0 9.0a 10.0a\"\n# Now only these architectures will be compiled\n```\n\n#### Specifying Architectures in Your JIT Module\n\nWhen creating a JIT module, specify which major SM versions are supported:\n\n```python\nfrom flashinfer.jit.core import gen_jit_spec\nfrom flashinfer.jit import current_compilation_context\n\ndef gen_my_hopper_only_module():\n    \"\"\"Example: Kernel works on SM90 and later supported architectures.\"\"\"\n    uri = get_my_uri(...)\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    # ... copy sources ...\n\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        # Explicitly list supported SM versions - no automatic future compatibility\n        supported_major_versions=[9, 10, 11, 12]  # SM90, SM100, SM110, SM120\n    )\n\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\ndef gen_my_blackwell_only_module():\n    \"\"\"Example: Kernel only works on SM100 (Blackwell)\"\"\"\n    uri = get_my_uri(...)\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    # ... copy sources ...\n\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[10]  # SM100 only\n    )\n\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\ndef gen_my_universal_module():\n    \"\"\"Example: Kernel works on all architectures\"\"\"\n    uri = get_my_uri(...)\n    gen_directory = jit_env.FLASHINFER_GEN_SRC_DIR \u002F uri\n    # ... copy sources ...\n\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=None  # All available architectures\n    )\n\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n```\n\n**What Happens:**\n- ✅ If user's GPU is SM90 and they call a Hopper-only module → Compiles and runs\n- ❌ If user's GPU is SM80 and they call a Hopper-only module → `RuntimeError: No supported CUDA architectures found for major versions [9, 10, 11, 12]`\n\n#### Real Examples from FlashInfer\n\n```python\n# MLA kernel: Blackwell and newer only\ndef gen_mla_module() -> JitSpec:\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[10, 11]  # SM100, SM110\n    )\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\n# Blackwell FMHA: SM120 only\ndef gen_fmhav2_blackwell_module(...):\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[12]  # SM120 only\n    )\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n\n# Standard attention: Hopper and later supported architectures\ndef gen_batch_prefill_module(...):\n    nvcc_flags = current_compilation_context.get_nvcc_flags_list(\n        supported_major_versions=[9, 10, 11, 12]  # SM90, SM100, SM110, SM120\n    )\n    return gen_jit_spec(\n        name=uri,\n        sources=sources,\n        extra_cuda_cflags=nvcc_flags,\n    )\n```\n\n#### Common Architecture Specifications\n\n| Supported Versions | Architectures | Use Case |\n|-------------------|---------------|----------|\n| `None` | All available GPUs | Universal kernels (default) |\n| `[9, 10, 11, 12]` | SM90, SM100, SM110, SM120 | Hopper, Blackwell |\n| `[10, 11, 12]` | SM100, SM110, SM120 | Blackwell only |\n| `[12]` | SM120 | Specific architecture only |\n| `[8, 9, 10, 11, 12]` | SM80, SM90, SM100, SM110, SM120 | Ampere, Hopper, Blackwell |\n\n#### Testing with Architecture Requirements\n\nWhen your kernel has architecture requirements, add skip checks in tests (see Step 6 below):\n\n```python\nimport pytest\nimport torch\nfrom flashinfer.utils import is_sm90a_supported\n\ndef test_hopper_kernel():\n    if not is_sm90a_supported(torch.device(\"cuda\")):\n        pytest.skip(\"SM90a is not supported on this GPU\")\n\n    # Test code here\n    ...\n```\n\n## Step 5: Create Python API in `flashinfer\u002F`\n\nCreate `flashinfer\u002Fscale.py`:\n\n```python\nimport functools\nimport torch\nfrom typing import Optional\n\nfrom .jit.scale import gen_scale_module\nfrom .utils import backend_requirement, supported_compute_capability\nfrom .api_logging import flashinfer_api\n\n\n@functools.cache\ndef get_scale_module(dtype_in, dtype_out):\n    \"\"\"Get or compile scale module (cached).\"\"\"\n    return gen_scale_module(dtype_in, dtype_out).build_and_load()\n\n\n@supported_compute_capability([80, 86, 89, 90, 100, 103, 110, 120])\ndef _check_scale_problem_size(input: torch.Tensor, factor: float,\n                               out: Optional[torch.Tensor] = None) -> bool:\n    \"\"\"Validate inputs for scale operation.\"\"\"\n    # Validate input\n    if not input.is_cuda:\n        raise ValueError(\"Input must be a CUDA tensor\")\n\n    # Validate output if provided\n    if out is not None:\n        if out.shape != input.shape:\n            raise ValueError(\"Output shape mismatch\")\n        if out.dtype != input.dtype:\n            raise ValueError(\"Output dtype mismatch\")\n        if not out.is_cuda:\n            raise ValueError(\"Output must be a CUDA tensor\")\n\n    return True\n\n\n@flashinfer_api\n@backend_requirement(\n    backend_checks={},  # No backend choices for this simple kernel\n    common_check=_check_scale_problem_size,\n)\ndef scale(input: torch.Tensor, factor: float,\n          out: Optional[torch.Tensor] = None) -> torch.Tensor:\n    \"\"\"\n    Element-wise scale operation.\n\n    Parameters\n    ----------\n    input : torch.Tensor\n        Input tensor (CUDA)\n    factor : float\n        Scale factor\n    out : Optional[torch.Tensor]\n        Output tensor (if None, allocate new tensor)\n\n    Returns\n    -------\n    output : torch.Tensor\n        Scaled tensor (input * factor)\n\n    Examples\n    --------\n    >>> import torch\n    >>> import flashinfer\n    >>> x = torch.randn(1024, dtype=torch.float16, device=\"cuda\")\n    >>> y = flashinfer.scale(x, 2.0)\n    >>> torch.allclose(y, x * 2.0)\n    True\n    \"\"\"\n    # Allocate output if needed\n    if out is None:\n        out = torch.empty_like(input)\n\n    # Get module (compile if first call with this dtype)\n    dtype_str = str(input.dtype).replace(\"torch.\", \"\")\n    module = get_scale_module(dtype_str, dtype_str)\n\n    # Call TVM-FFI function (exported as \"run\")\n    module.run(input, out, float(factor))\n\n    return out\n```\n\n**Key points:**\n\n- Uses `@functools.cache` to cache compiled modules\n- Clean Python API with docstring\n- Adding the `@flashinfer_api` decorator enables logging and sets it apart from helper functions\n- **Destination passing style**: Output tensor(s) are passed as optional parameters (`out: Optional[torch.Tensor] = None`). This allows users to provide pre-allocated buffers to avoid allocation overhead in performance-critical paths. Only allocate internally when `out` is `None`.\n- Validates inputs using `@backend_requirement` decorator\n\n### Using `@backend_requirement` and `@supported_compute_capability` Decorators\n\nFlashInfer provides two decorators for enforcing compute capability and backend requirements:\n\n#### `@supported_compute_capability` Decorator\n\nMarks a function with its supported CUDA compute capabilities:\n\n```python\nfrom flashinfer.utils import supported_compute_capability\n\n@supported_compute_capability([80, 86, 89, 90, 100, 103, 110, 120])\ndef _my_check_function(input, output):\n    \"\"\"Supports SM80 (Ampere) through SM120 (Blackwell).\"\"\"\n    # Validation logic here\n    return True\n```\n\n#### `@backend_requirement` Decorator\n\nEnforces backend and problem size requirements at runtime. There are three usage patterns:\n\n**Pattern 1: Single Backend (No Backend Choices)**\n\nFor kernels with only one implementation (like our scale example):\n\n```python\nfrom flashinfer.utils import backend_requirement, supported_compute_capability\n\n@supported_compute_capability([80, 86, 89, 90, 100, 103, 110, 120])\ndef _check_my_kernel(input, output):\n    \"\"\"Validate inputs. Must return True if valid.\"\"\"\n    if input.shape[-1] > 256:\n        raise ValueError(\"Head dimension must be \u003C= 256\")\n    return True\n\n@backend_requirement(\n    backend_checks={},  # Empty dict = no backend parameter\n    common_check=_check_my_kernel,\n)\ndef my_kernel(input, output):\n    # Kernel implementation\n    pass\n```\n\n**Pattern 2: Multiple Backends**\n\nFor kernels with multiple implementation backends (e.g., CUTLASS, cuDNN):\n\n```python\n@supported_compute_capability([80, 86, 89, 90])\ndef _cutlass_check(q, k, v, backend):\n    \"\"\"CUTLASS backend: Ampere through Hopper.\"\"\"\n    if q.shape[-1] > 256:\n        raise ValueError(\"CUTLASS: head_dim must be \u003C= 256\")\n    return True\n\n@supported_compute_capability([75, 80, 86, 89, 90, 100])\ndef _cudnn_check(q, k, v, backend):\n    \"\"\"cuDNN backend: Turing through Blackwell.\"\"\"\n    return True\n\n@backend_requirement(\n    backend_checks={\n        \"cutlass\": _cutlass_check,\n        \"cudnn\": _cudnn_check,\n    },\n    common_check=None,  # Optional: shared validation for all backends\n)\ndef attention(q, k, v, backend=\"cutlass\"):\n    if backend == \"cutlass\":\n        # CUTLASS implementation\n        pass\n    elif backend == \"cudnn\":\n        # cuDNN implementation\n        pass\n```\n\n**Pattern 3: Auto Backend Selection**\n\nFor kernels that can automatically select the best backend:\n\n```python\ndef _heuristic_func(suitable_backends, q, k, v, backend):\n    \"\"\"Return backends in order of preference.\"\"\"\n    # Prefer CUTLASS for small head dims, cuDNN for larger\n    if q.shape[-1] \u003C= 128:\n        preferred = [\"cutlass\", \"cudnn\"]\n    else:\n        preferred = [\"cudnn\", \"cutlass\"]\n    return [b for b in preferred if b in suitable_backends]\n\n@backend_requirement(\n    backend_checks={\n        \"cutlass\": _cutlass_check,\n        \"cudnn\": _cudnn_check,\n    },\n    common_check=_common_validation,\n    heuristic_func=_heuristic_func,  # Required when backend=\"auto\" is used\n)\ndef attention(q, k, v, backend=\"auto\"):\n    if backend == \"auto\":\n        # Use the first backend from suitable_auto_backends\n        backend = attention.suitable_auto_backends[0]\n    # ... rest of implementation\n```\n\n#### Features Added by `@backend_requirement`\n\nThe decorator adds these methods to the wrapped function:\n\n```python\n# Check if a backend is supported (optionally for a specific CC)\nscale.is_backend_supported(\"cutlass\")           # True\u002FFalse\nscale.is_backend_supported(\"cutlass\", cc=90)    # True\u002FFalse for Hopper\n\n# Check if any backend supports this compute capability\nscale.is_compute_capability_supported(90)       # True\u002FFalse\n\n# Check if a backend exists\nscale.has_backend(\"cutlass\")                    # True\u002FFalse\n\n# Check if there are multiple backend choices\nscale.has_backend_choices()                     # True\u002FFalse\n```\n\n#### `skip_check` Keyword Argument\n\nThe decorator adds a `skip_check` keyword argument to bypass validation for performance-critical code paths:\n\n```python\n# Normal call with validation\nresult = scale(x, 2.0)\n\n# Skip validation for performance (use with caution!)\nresult = scale(x, 2.0, skip_check=True)\n```\n\n#### Check Function Requirements\n\nCheck functions must:\n1. Accept the same arguments as the decorated function\n2. Return `True` if validation passes\n3. Raise `ValueError` with descriptive message if validation fails\n4. Be decorated with `@supported_compute_capability` to specify supported architectures\n\n## Step 6: Write Tests in `tests\u002F`\n\nCreate tests in an appropriate subdirectory (e.g., `tests\u002Felementwise\u002Ftest_scale.py` or create a new subdir if needed):\n\n```python\nimport pytest\nimport torch\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16, torch.float32])\n@pytest.mark.parametrize(\"size\", [128, 1024, 4096])\ndef test_scale_correctness(dtype, size):\n    \"\"\"Test scale operation correctness.\"\"\"\n    import flashinfer\n\n    # Setup\n    x = torch.randn(size, dtype=dtype, device=\"cuda\")\n    factor = 3.14\n\n    # Run FlashInfer kernel\n    y = flashinfer.scale(x, factor)\n\n    # Reference implementation\n    expected = x * factor\n\n    # Compare\n    if dtype == torch.float32:\n        rtol, atol = 1e-5, 1e-6\n    else:\n        rtol, atol = 1e-3, 1e-3\n\n    torch.testing.assert_close(y, expected, rtol=rtol, atol=atol)\n\n\n@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.bfloat16])\ndef test_scale_inplace(dtype):\n    \"\"\"Test scale with pre-allocated output.\"\"\"\n    import flashinfer\n\n    x = torch.randn(1024, dtype=dtype, device=\"cuda\")\n    out = torch.empty_like(x)\n    factor = 2.0\n\n    result = flashinfer.scale(x, factor, out=out)\n\n    # Should return the same tensor\n    assert result is out\n\n    # Check correctness\n    expected = x * factor\n    torch.testing.assert_close(result, expected, rtol=1e-3, atol=1e-3)\n\n\ndef test_scale_cpu_error():\n    \"\"\"Test that CPU tensors raise an error.\"\"\"\n    import flashinfer\n\n    x = torch.randn(128, dtype=torch.float32)\n\n    with pytest.raises(ValueError, match=\"CUDA\"):\n        flashinfer.scale(x, 2.0)\n```\n\n**Key points:**\n\n- Use `pytest.mark.parametrize` for multiple configurations\n- Compare against reference implementation\n- Set appropriate tolerances for each dtype\n- Test error cases\n\n## Step 7: Register in AOT\n\nRegister your kernel in AOT so users with `flashinfer-jit-cache` can skip JIT compilation.\n\nEdit `flashinfer\u002Faot.py`, add to the appropriate section:\n\n```python\ndef gen_scale_modules() -> Iterator[JitSpec]:\n    \"\"\"Generate scale operation modules for AOT compilation.\"\"\"\n    from .jit.scale import gen_scale_module\n\n    # Pre-compile common dtypes\n    for dtype in [\"float16\", \"bfloat16\", \"float32\"]:\n        yield gen_scale_module(dtype, dtype)\n\n\n# In the main AOT build loop, add:\n# for spec in gen_scale_modules():\n#     spec.build()\n```\n\n**Key points:**\n\n- Pre-compile common configurations\n- Users with `flashinfer-jit-cache` won't need to compile at runtime\n\n## Step 8: Export API\n\nEdit `flashinfer\u002F__init__.py`:\n\n```python\nfrom .scale import scale as scale\n\n# Or in the existing imports section:\n# from .scale import scale\n```\n\n## Step 9: Run and Test\n\n```bash\n# The kernel compiles automatically on first use\npytest tests\u002Ftest_scale.py -v\n\n# Run with different dtypes\npytest tests\u002Ftest_scale.py::test_scale_correctness[float16-128] -v\n```\n\n## Step 10: Add Benchmark\n\n**All new kernels should have benchmarks.** This helps track performance regressions and allows users to compare against other implementations.\n\nCreate a benchmark file in `benchmarks\u002F` (e.g., `benchmarks\u002Fbench_scale.py`):\n\n```python\nimport torch\nfrom flashinfer.testing import bench_gpu_time\n\ndef bench_scale():\n    \"\"\"Benchmark scale kernel.\"\"\"\n    import flashinfer\n\n    sizes = [1024, 4096, 16384, 65536, 262144]\n    dtypes = [torch.float16, torch.bfloat16]\n\n    print(\"Scale Kernel Benchmark\")\n    print(\"-\" * 60)\n    print(f\"{'Size':>10} {'Dtype':>10} {'Time (us)':>12} {'Std (us)':>10}\")\n    print(\"-\" * 60)\n\n    for size in sizes:\n        for dtype in dtypes:\n            x = torch.randn(size, dtype=dtype, device=\"cuda\")\n\n            # Benchmark with CUPTI (auto-fallback to CUDA events)\n            median_time, std_time = bench_gpu_time(\n                flashinfer.scale,\n                args=(x, 2.0),\n                enable_cupti=True,\n                dry_run_iters=10,\n                repeat_iters=100,\n            )\n\n            print(f\"{size:>10} {str(dtype):>10} {median_time*1e6:>12.2f} {std_time*1e6:>10.2f}\")\n\nif __name__ == \"__main__\":\n    bench_scale()\n```\n\n**For more complex kernels**, consider:\n\n- Adding comparisons against reference implementations (e.g., PyTorch native, cuBLAS, cuDNN)\n- Using the unified benchmarking framework in `benchmarks\u002Fflashinfer_benchmark.py` if applicable\n- Testing across different problem sizes and configurations\n\n→ **For complete benchmarking guide, see [`.claude\u002Fskills\u002Fbenchmark-kernel\u002FSKILL.md`](..\u002Fbenchmark-kernel\u002FSKILL.md)**\n\n## Summary of Files Created\u002FModified\n\n```\ninclude\u002Fflashinfer\u002Fscale.cuh              # NEW: CUDA kernel definition\ncsrc\u002Fscale.cu                              # NEW: PyTorch launcher\ncsrc\u002Fscale_jit_binding.cu                  # NEW: TVM-FFI binding\nflashinfer\u002Fjit\u002Fscale.py                    # NEW: JIT generator\nflashinfer\u002Fscale.py                        # NEW: Python API\nflashinfer\u002F__init__.py                     # MODIFIED: Export API\nflashinfer\u002Faot.py                          # MODIFIED: Register AOT\ntests\u002Ftest_scale.py                        # NEW: Unit tests\nbenchmarks\u002Fbench_scale.py                  # NEW: Benchmark script\n```\n",{"name":5,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Faiskillstore\u002Fmarketplace\u002Fflashinfer-ai\u002Fadd-cuda-kernel",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill add-cuda-kernel",{"tool":45,"command":46},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill add-cuda-kernel",{"tool":48,"command":49},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill add-cuda-kernel","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Fflashinfer-ai\u002Fadd-cuda-kernel\u002FSKILL.md",true,[53],{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"skill-report.json","REFERENCE","参考文档",22161,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002Fflashinfer-ai\u002Fadd-cuda-kernel\u002Fskill-report.json",[60,69,78,87,93,99],{"skillNo":61,"name":62,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":25},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[66,67,68],"model","model hierarchy","model hierarchy skill",{"skillNo":70,"name":71,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":25},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[75,76,77],"MCP","zoom","zoom mcp",{"skillNo":79,"name":80,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":25},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[84,85,86,76],"sdk","zoom apps sdk","apps",{"skillNo":88,"name":89,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":25},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[89],{"skillNo":94,"name":95,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":25},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[95],{"skillNo":100,"name":101,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":25},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[101]]