Kernel organization

From sgl-project/sglang · View interactive version

Kernel organization is an AI agent skill from the GitHub repository sgl-project/sglang. Apply the SGLang kernels RFC when adding, moving, splitting, deduplicating, or reviewing kernel APIs, registry metadata, kernel tests, benchmarks, and model-specific implementations, and before optimizing an existing kernel (find the other implementations of its contract first). Use with add-jit-ker

How to use this skill

Skill file

Kernel organization

Read python/sglang/kernels/README.md and test/README.md before choosing a

location. RFC #29630

establishes the namespace; subsequent migrations #32148 and #40922 clarify

logical grouping and remove the old _jit_ filename prefix.

Choose the owner

and integration tests import from that namespace, including its submodules.

The sgl_kernel wheel retains its own public API and packaging tests.

routing in moe, attention index selection in attention, sampling in

sampling, normalization in layernorm.

kernel into separate launches just to separate its parts. Split unrelated

public entry points that happen to share a source file. Decided rules:

reduce-scatter, a2a, multicast/NVLS) puts the op in communication,

whatever compute it fuses.

layernorm, activation + quant in activation, GEMM with a quant epilogue

in gemm, MoE dispatch/permute + quant in moe). quantization holds only

pure format conversion: quant, dequant, scale-layout conversion, repack.

index/shape/schedule tables (page tables, cu_seqlens, kv_indices, split

metadata) and index selection. A fused compute + store stays with its

compute group.

logical group. Do not add a model bundle or an implementation file directly

under ops/. Propose a new logical group only for a distinct responsibility,

and update ops._GROUPS, the README group list, and tests together

(test_kernels_namespace.py checks the README against _GROUPS and the

README layout against the directories under kernels/).

Agents, KernelBackend.KDA) and kernels/cake_kernels/ (Cake adapters over

FlashInfer). They are backends, not groups: register their public ops in the

logical group with a KernelSpec whose target points into them, and do not

reorganize those directories.

step (sgl-nvidia-mega behind --enable-nvidia-megakernel, sgl-amd-mono behind

--enable-amd-monokernel) are split at the kernel/runtime boundary. Their

contracts (spec, registration, capability declarations, thin kernel wrappers)

live in kernels/plugin_kernels/<hardware>/<model>/ (KernelBackend.PLUGIN)

and import nothing from srt. SGLang's integration (config checks, weight

observation, CUDA graph coverage, forward dispatch, the runtime binding) lives

in srt/kernel_plugins/<hardware>/binding.py. An op exposed from the contract side

registers in its logical group with a KernelSpec that points into it.

helper) in kernels/jit; operator wrappers call it from their logical group.

Keep process groups, communicator state, workspace classes, model dispatch,

and buffer ownership in srt (srt/layers/communication/ for the K3 and Muse

Spark adapters); kernels must not import srt runtime modules to inspect

model objects, so pass flags in. Adapters there need not pretend to be generic

interfaces.

One implementation per contract

A contract is what the op computes: inputs and outputs (dtype, layout, scale

format) and the result on edge cases (ties, NaN, empty or fully masked rows).

Implementations of the same contract are duplicates whatever their file,

language or backend.

Before adding a kernel, or optimizing one, find the others:

(registry.all_specs(), see the kernels README), the owning group, inline

Triton or torch versions in srt/layers and model files, the AOT wheel, and

library wrappers (FlashInfer, DeepGEMM, TRT-LLM, CUTLASS).

CUDA-graph padded sizes, and put each next to its bound

(performance-cuda.md).

Then decide:

missing.

callers to it, show parity, delete the old kernel. Tuning an old kernel that

a better one already beats leaves two implementations to maintain and gains

nothing.

converge on (the most general contract, the better structure), not the one

that happens to be called today.

and the variants it retires leave in the same PR or a tracked follow-up.

architecture or dtype, or is measurably faster on shapes the dispatcher can

tell apart. Register them under one op (one BaseFusedOp, or KernelSpecs

sharing an op name) so one dispatcher chooses, and say at the dispatch site

why each exists.

Every implementation states its coverage (shapes, dtypes, architectures it

serves and what it rejects) at its entry point, so the next author can tell

when it is replaceable. The evidence bar for retiring a variant is in

code-cleanup B1 and B3: merging copies of one

kernel is checked bit for bit, including ties, NaN and fully masked rows;

moving callers onto a different kernel states its tolerance and shows the new

path ran; either way with per-shape benchmarks, and the default flipped only

where faster. When the search finds other implementations of the contract, a

PR that adds, migrates or optimizes a kernel lists them, the measured time of

each against the bound, and which one survives; when it finds none, the PR

says so in one line.

Register the public entry point

Add lazy KernelSpec metadata in the owning group's __init__.py, or use the

existing BaseFusedOp registration when the operation has interchangeable

backends (a BaseFusedOp built per layer registers module:Class.forward_<backend>

targets). Group imports must not import GPU implementations or compile kernels.

Use <group>.<name> for the op id and module:callable for the target. Preserve

existing backend dispatch and describe actual device/architecture restrictions

with CapabilityRequirement; JIT/AOT are not device types. Input shape/dtype

checks remain part of the entry point's contract. Registering a torch custom op

does not register it in the SGLang kernel inventory. Predicates, private JIT

factories, reference helpers, and runtime classes are not separate kernel APIs.

Place and preserve tests

runtime module. A CUDA allocation does not make a runtime test a kernel test.

standalone test/benchmark entry points in production operator modules.

vendored upstream trees and AOT wheel packaging boundaries instead of

reorganizing them incidentally.

For a move/split, preserve assertions, parametrization, fixtures, platform skips,

execution entry points, and CI stages/runners. Apportion existing time estimates

across split files; do not duplicate the original budget for every output file

or silently drop a registration. Follow write-sglang-test for CI registration.

Verify a migration

  1. Search all runtime, test, benchmark, documentation, patch-string, and lazy

registry references before deleting the old path. Check relative imports and

package re-exports as well as direct imports. Do not leave forwarding shims.

  1. Keep tuning files with the GEMM that loads them and preserve relative lookup

behavior. Check wheel/package inclusion as well as source-tree execution.

  1. Preserve module singleton state: every runtime caller must import the same

new communication adapter, not a second copy of its buffer registry.

  1. Separate relocation commits from semantic changes. Use

mechanical-refactor-verify to reproduce moves, and compare test inventories

and CI registration coverage before/after. Only delete an experimental path

after checking its call sites, flags, source, and dedicated tests together.

  1. Run the namespace/dispatch CPU tests, the registered-test validation hook,

pre-commit, and relevant GPU tests when available. State exactly which GPU

checks ran; import/AST checks do not prove numerical or performance parity.

Do not infer violations solely from a model name inside a group, a missing

_jit_ prefix, use of a runtime utility, or absence of BaseFusedOp inheritance.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.