rh-runninghub/minimax-h3-multigpu-lightning/add-jit-kernel
Claude Code and agent skill by rh-runninghub/minimax-h3-multigpu-lightning
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Step-by-step tutorial for adding a new lightweight JIT CUDA kernel to sglang's jit_kernel module
Install
npx vskill@latest install rh-runninghub/minimax-h3-multigpu-lightning/add-jit-kernelSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as rh-runninghub/minimax-h3-multigpu-lightning/add-jit-kernel.
Tutorial: Adding a New JIT Kernel to SGLang
This tutorial walks through adding a simple element-wise scale operation as a JIT kernel. 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
x(CUDA) and scalarfactor(float, passed at runtime) - Output:
x * factor(element-wise), allocated internally - Supported dtypes: FP16 (`torch.float16`), BF16 (`torch.bfloat16`), FP32 (`torch.float32`)
When to use JIT vs AOT (sgl-kernel)
- JIT (`jit_kernel`): prefer this first for kernels that do not depend on CUTLASS or another large C++ project. It is the default choice for lightweight kernels that benefit from rapid iteration and first-use compilation.
- AOT (`sgl-kernel`): prefer this when the kernel does depend on CUTLASS or another large C++ project, or when it should live in
python/sglang/kernels/aot/and participate in the wheel build / torch op registration flow. - Exception: kernels that depend on
flashinfer, or on CUTLASS that is already provided throughflashinfer, can still be implemented asjit_kernel.
Conventions
These hold for every step below.
- `namespace sglang` is where JIT code lives. Open it after the include block and close it at the end of the file, with the device kernels, traits and host wrapper inside. The shared
host::/device::helpers are nested in it too, so they resolve unqualified.load_jitemits theTVM_FFI_DLL_EXPORT_TYPED_FUNCwrapper insidenamespace sglangas well, so thekernel_nameyou pass from Python needs nosglang::prefix. - Tuning policy belongs in Python; C++ gets the answer, not the decision. For a hyperparameter — split factor, threads per item, block size, vector width, an algorithm variant — prefer (not required) making it a template parameter and letting the
@cache_oncemodule factory choose the value, over a runtimeif/switchin the launcher that picks among pre-instantiated kernels. The kernel then compiles exactly one specialisation and asserts its own preconditions withstatic_assert, while the heuristic that produced the value sits in Python where it is readable, adjustable, and inspectable without recompiling CUDA.store_cache'snum_threadsis the worked example: aget_kernel(num_split)ladder guarded by byte-alignmentif constexprs became one template argument plus a heuristic in_jit_kvcache_module. The exception is a knob that genuinely varies per call with the runtime shape — that has to stay a kernel argument. - Check where the check is cheapest: `static_assert` > C++ host check > cached Python > per-call Python. Anything fixed at compile time is a
static_assert. Anything about the tensors is aTensorMatcher/CHECK_HOSTin the C++ launcher, free next to a kernel launch. A check Python cannot delegate goes inside the@cache_oncemodule factory, where it runs once per specialisation. What remains in the per-call entry point costs interpreter time on every forward, so it should be nothing but picking the module and allocatingout. - Fixed-width integer types. Prefer
int32_t/int64_t/uint32_t/size_toverint,long, orlong long, so an index has the same width on both sides of the FFI boundary. Bareintis fine only where the width plainly cannot matter — an unrolled loop counter over aconstexprbound, a templateintparameter. Shapes arrive asint64_t(SymbolicSize::unwrap()); narrowing touint32_tfor in-kernel indexing is a deliberate act, so write thestatic_castexplicitly and only where the range is known. - Doxygen comments in C++. Document exported entities with
///or/** ... */blocks using\brief,\param,\tparam,\return, the wayinclude/sgl_kernel/does.python -m sglang.kernels.jitwritesCommentFormat: Doxygeninto.clangdwhen clangd is 21 or newer, so these render on hover in the editor. Plain//remains fine for implementation notes inside a function body. - ASCII only in C++ and CUDA sources. Write
--,->,<=instead of—,→,≤, including in comments.grep -nP '[^\x00-\x7F]' <file>before committing. - `namespace details` is private. Anything inside one is an implementation detail of its own header, free to change without notice. Do not name
details::from another module, and neverusing namespace details. If you find yourself wanting something in there, that is the signal to promote it to a documented name instead. - `const T* __restrict__` for read-only pointers. This is what
csrc/does throughout, and it lets the compiler emit non-coherent (LDG) loads. - Watch the register budget. For memory-bound kernels, keep to roughly 64 registers per thread so occupancy does not become the limit; prefer recomputing a value over letting it spill. Run
SGLANG_JIT_LOG_RESOURCE_USAGE=1 SGLANG_JIT_FORCE_RECOMPILE=1to log per-kernel registers, spills and shared memory at INFO. Both halves are load-bearing: a cache hit has no compiler output to report, and passing-Xptxas -vby hand does nothing on its own because the build captures compiler output and replays it only on failure. - Alignment is a contract you enforce, not a property you hope for. A vectorized copy derives its access width from the row size (
load_bytespicks 16B for a 1024B row), but the address it lands on isbase + index * row_stride— and a stride is not constrained by the size.TensorMatcheradmits any stride unless you say otherwise, so a padded cache row silently producesmisaligned address. Every kernel that vectorizes is highly recommended to end its validation with.ensure_alignment(w), wherewis the width the kernel actually uses.
Common Abstractions in python/sglang/kernels/jit/include/sgl_kernel/
Always prefer these abstractions over raw CUDA primitives. They provide safety, readability, and consistency with the rest of the codebase. The only reason to drop to raw primitives is performance the abstraction cannot reach — a trade you make deliberately, and justify in a comment.
utils.h — Host-side utilities
- `CHECK_HOST(cond) << "msg " << value` — Preferred runtime check: stream-style, throws
PanicErrorwith file/line info on failure. Zero overhead on the true path — the message expressions are only evaluated when the check fails. - `host::RuntimeCheck(cond, args...)` — Function-style alternative to
CHECK_HOST. Note its message args are always evaluated (even when the check passes), so preferCHECK_HOST— especially on hot paths. - `host::Panic(args...)` — Unconditionally throw a
PanicErrorwith a descriptive message. - `host::div_ceil(a, b)` — Integer ceiling division
(a + b - 1) / b. - `host::irange(n)` / `host::irange(start, end)` — Range views for cleaner loops.
- `host::pointer::offset(ptr, offsets...)` — Byte-safe pointer arithmetic on
void*. Use this instead of raw casts.
utils.cuh — Device-side utilities + LaunchKernel
- Type aliases:
fp16_t,bf16_t,fp32_t,fp8_e4m3_t,fp8_e5m2_tand their packed variantsfp16x2_t,bf16x2_t,fp32x2_t, etc. - `SGL_DEVICE` — Expands to
__forceinline__ __device__. Use on all device functions. - `SGL_DEVICE_HOST` —
__forceinline__ __device__ __host__. Use it when aconstexprhelper must be callable from both the kernel and its launcher, so the two cannot drift. - `device::kWarpThreads` — Constant
32(the codebase's logical warp width).kWarpSizeis an alias. Note this is a group size, not the hardware wave: on gfx950warpSizeis 64, andwarp::kFullWidthreflects that. - `device::get_lane_id<kNumThreads = kWarpThreads>()` — this thread's index within its logical group. Prefer it over `threadIdx.x % kNumThreads` whenever the value feeds an address. On CUDA the lane register is one read that folds into the address computation, whereas the modulo is a derived value the compiler re-materialises at every address scale — 8 instructions and 2 registers on a two-tile warp copy, measured on sm_100a. It picks the cheaper form per platform, so callers never need to care. Only equals the true in-warp lane when
blockDim.xis a multiple ofkNumThreads. - `device::load_as<T>(ptr, offset)` / `device::store_as<T>(ptr, val, offset)` — Type-safe loads/stores from
void*. - `device::pointer::offset(ptr, offsets...)` — Pointer arithmetic on device.
- `host::LaunchKernel(grid, block, device_or_stream [, smem])` — RAII kernel launcher that:
- Resolves the CUDA stream from a
DLDevicevia TVM-FFI automatically. - Checks the CUDA error with file/line info after launch via
operator()(kernel, args...). - Supports
.enable_pdl(bool)for PDL (Programmatic Dependent Launch, SM90+). - `device::PDLWaitPrimary<kUsePDL>()` / `device::PDLTriggerSecondary<kUsePDL>()` — The two halves of PDL, on sm_90+ (no-ops on older archs and ROCm). Their guarantees are not symmetric:
PDLTriggerSecondary(griddepcontrol.launch_dependents) only lets the next kernel in the stream start early. It carries no memory ordering and publishes nothing — matching that, the header's asm has no"memory"clobber.PDLWaitPrimary(griddepcontrol.wait) is the ordering point: it waits until the preceding kernel has fully finished and its writes are visible.
So every read of data the preceding kernel produced must come after PDLWaitPrimary(). What overlaps with the primary's tail is whatever you put before the wait — loading parameters, computing indices, touching buffers the primary never wrote — so a kernel that waits on its first line gains nothing. Neither call is a barrier: threads may reach or skip them independently. See "Programmatic Dependent Launch and Synchronization" in the CUDA C++ Programming Guide.
- `CHECK_CUDA(expr) << "context"` — Stream-style CUDA error check; evaluates
expronce and throwsPanicErrorwithcudaGetErrorString+ file/line info if it is notcudaSuccess. Extra streamed context is optional. - `host::RuntimeDeviceCheck(cudaError_t)` — Function-style alternative to
CHECK_CUDA. It takes no context message, so preferCHECK_CUDA, which builds its error object only on the failure path.
tensor.h — Tensor validation (TensorMatcher, Symbolic types)
This is the primary validation API for all kernel launchers. Use it to validate every tvm::ffi::TensorView argument.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingsglang/.claude/skills/add-jit-kernel/SKILL.md
Popularity
- Repository stars
- 99
- Repository forks
- 13
- 7-day trend score
- 23
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/rh-runninghub/minimax-h3-multigpu-lightning/add-jit-kernel)