Skip to content

hk.ops: the shipped kernels

Stability: stable: the entry points above "In the submodules". Those below it, which the engine integrations call, are experimental (stability).

The kernels hk ships, written in the language, each behind a torch-facing function that picks a plan for the shape and the architecture. Call them on torch tensors on the GPU; they return the output (or write out=). Every kernel family -- the GPUs it runs on, its dtypes, the engine routes that call it, the GPU tests that run it -- is in the op catalog.

Where an op's arguments or behaviour differ between gfx1100 and gfx950 the entry says so in a Per architecture table; the full audit, with the code evidence, is docs/archive/design/api-consistency.md. The row-wise and elementwise ops are being unified by the hk.templates work.

Elementwise

On gfx950 these run on register strips and take any size. hk.ops.gelu is the tanh form, like hk.math.gelu.

Per architecture, every op below (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
path 16x64 register tiles register strips below 2 GiB, tiles above
shape rows a multiple of 16 and columns of 64 (after re-viewing a contiguous tensor at a wider row) any size
dtypes bf16, fp16, fp32 (gelu: fp32 only) the same

hk.ops.add

hk.ops.add(a, b, out=None)

Elementwise a + b.

hk.ops.sub

hk.ops.sub(a, b, out=None)

Elementwise a - b.

hk.ops.mul

hk.ops.mul(a, b, out=None)

Elementwise a * b.

hk.ops.maximum

hk.ops.maximum(a, b, out=None)

Elementwise max(a, b).

hk.ops.minimum

hk.ops.minimum(a, b, out=None)

Elementwise min(a, b).

hk.ops.exp

hk.ops.exp(a, out=None)

Elementwise exp(a).

hk.ops.relu

hk.ops.relu(a, out=None)

Elementwise max(a, 0).

hk.ops.gelu

hk.ops.gelu(a, out=None)

Elementwise GELU, the tanh approximation -- base_ops::gelu is x * (0.5 + 0.5 * fast_tanh(...)), i.e. torch's approximate='tanh', not the erf form. fp32 only.

hk.ops.neg

hk.ops.neg(a, out=None)

Elementwise -a.

hk.ops.abs

hk.ops.abs(a, out=None)

Elementwise |a|.

Rows: norms, softmax

Per architecture, every op below (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
path strips while a row fits one (64 values a lane), tiles past that (at least 16 x 64) strips while a row fits one (up to 128 values a lane), tiles past that

hk.ops.rmsnorm

hk.ops.rmsnorm(x, eps: float = 1e-06, out=None)

x * rsqrt(mean(x^2) + eps), over the last axis.

No learned weight: a weight multiply is elementwise and belongs in whatever fuses next, and adding it here would mean a second global and a broadcast that the caller may not want.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
path strips while a row fits one (64 values a lane), tiles past that (at least 16 x 64) strips while a row fits one (up to 128 values a lane), tiles past that

hk.ops.rms_norm

hk.ops.rms_norm(x, weight, eps: float = 1e-06, out=None, *, weight_offset: float = 0.0)

x * rsqrt(mean(x^2) + eps) * (weight + weight_offset) over the last axis -- the RMSNorm a model has. Any number of rows, including fewer than a tile's. weight_offset is added in fp32 inside the kernel: a weight stored as an offset from one (Gemma-style, y = x_hat * (1 + w)) passes weight_offset=1.0 and its stored w, exactly, where folding the one into a 16-bit weight first would round it.

hk.ops.fused_add_rms_norm

hk.ops.fused_add_rms_norm(x, residual, weight, eps: float = 1e-06, *, weight_offset: float = 0.0)

vLLM's fused_add_rms_norm, in place: residual becomes x + residual and x its RMSNorm times weight (+ weight_offset, as rms_norm's). One read of x, residual and weight, one write of each result.

hk.ops.layernorm

hk.ops.layernorm(x, eps: float = 1e-05, out=None)

(x - mean) * rsqrt(var + eps), over the last axis, unweighted.

var is the biased estimate (divide by N), which is what torch's F.layer_norm uses.

hk.ops.softmax

hk.ops.softmax(x, out=None)

Softmax over the last axis, max-shifted.

Fused pointwise

hk.ops.silu_mul

hk.ops.silu_mul(a, b, out=None)

silu(a) * b -- the second half of SwiGLU, with the gate already split.

torch's equivalent is F.silu(a) * b; this does it in one pass, so the intermediate never reaches memory.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
path 16x64 register tiles register strips
layout a, b, out contiguous (a must be contiguous; call .contiguous()) rows of unit column stride: the two halves of a (M, 2I) gate/up output are taken as strided views
shape at least 16 x 64 elements any shape

hk.ops.rope

hk.ops.rope(x, cos, sin, out=None)

Rotary embedding over the last axis, half-split (NeoX) convention.

x is (..., seq, D) with at least one leading axis; cos and sin are (seq, D/2) in fp32 and are shared across every leading axis. D/2 must be a multiple of 64 -- head dims of 128 and 256 qualify, 64 does not, and the error says so rather than silently producing a rotation by the wrong angle.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
path the same tile kernel on both the same

hk.ops.rotary

hk.ops.rotary(x, cos_sin, positions=None, out=None)

vLLM's rotary_embedding, NeoX (half-split) style, token-major: x is (..., heads, D) with the tokens on the leading axes, cos_sin is (P, D) float32 holding [cos | sin] (vLLM's cos_sin_cache), and token t turns by row positions[t] of it -- int32, one per token -- or by row t without positions:

out[..., :D/2] = x1 * cos - x2 * sin,  out[..., D/2:] = x2 * cos + x1 * sin

In place when out is x. D is 64 * a power of two up to 16 (128 and 256 qualify) on gfx950, 64 * a power of two up to 8 on gfx1100. On strips: gfx950, and gfx1100 and gfx1201 (where a head's halves are two strips, there being no lane exchange there).

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
path strips, a head's two halves as two strips (no lane exchange) strips, a head in one
head_dim 64 x 1, 2, 4 or 8 64 x 1, 2, 4, 8 or 16

Quantization

hk.ops.quantize

hk.ops.quantize(x, out=None, scales=None)

Symmetric per-row int8 quantization over the last axis.

Returns (q, scales): q has x's shape and dtype int8, scales is x's shape without the last axis, in fp32. x ~ q * scales[..., None].

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
shape at least 16 x 64 any shape

hk.ops.dequantize

hk.ops.dequantize(q, scales, dtype=None, out=None)

q * scales[..., None], back to a float dtype.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
all of it the same tile kernel, at least 16 x 64 the same

GEMM and attention

hk.ops.matmul

hk.ops.matmul(a, b, out=None)

A @ B.T for bf16, fp32 accumulate.

On gfx950 this is hk.ops.gemm_cdna.matmul (MFMA, routed by M from a measured table): K must be a multiple of 64 there, and its bf16 store rounds to nearest even where this one rounds ties away from zero (the split-K routes sum fp32 shares, then round). docs/archive/design/api-consistency.md.

b is (N, K), not (K, N). That is not an inconvenience to be hidden: it keeps both shared loads contiguous and makes mma_ABt the primitive, which is what puts both operand tiles in row layout and therefore on the ds_read_b128 fast path. Transposing here instead would copy, and the copy is a bigger cost than the GEMM saves.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
kernel hk.ops.gemm (WMMA), tuned per shape hk.ops.gemm_cdna (MFMA), routed by M
shape K a multiple of the tuned k_step (64) and > 0, N of 128 K a multiple of 64 and > 0, N of 128
layout contiguous operands (a non-contiguous b is refused) the same (a route to hk.ops.decode_gemm would copy it)
numerics bf16 store rounds ties away from zero round to nearest even; split-K sums fp32 shares

hk.ops.attention

hk.ops.attention(q, k, v, *, causal: bool = False, scale: Optional[float] = None, out=None)

Flash attention forward, (B, H, N, D) bf16, MHA or GQA.

The operand layout is F.scaled_dot_product_attention's, so a framework that already calls torch can be redirected without reshaping. What this takes and what it does not is _why; it raises rather than falls back, because a silent fallback inside an explicit hk.attention call is how a 20 TFLOPs path gets mistaken for a 64 TFLOPs one.

Ragged N is fine in both directions: the last Q block backs up to end at n_q and recomputes the overlap (idempotent -- a query row's output depends on that row alone), and the last KV block backs up and masks the rows it does not own. So on gfx1100 n_q must be at least Q_TILE (192) and n_kv at least KV_BLOCK (32). On gfx950 this runs hk.ops.attn_cdna, whose loads are bounded: any non-empty length. head_dim is 64 or 128 on both.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
shape n_q >= 192 (one Q tile) and n_kv >= 32 (one KV block) any non-empty length
head_dim 64 or 128 64 or 128
numerics dense online softmax lazily rescaled softmax (threshold 8): same math, different bits

Also exported

hk.ops.scaled_mm

hk.ops.scaled_mm(a, b, scale_a, scale_b, *, bias=None, out=None, accumulate: bool = False)

Changed after 0.9.24: new parameter accumulate

bf16 (A @ B.T) * scale_a * scale_b (+ bias), fp8 operands, fp32 accumulate: torch._scaled_mm's product with hk.ops.matmul's layout.

a is (M, K) and b (N, K), float8_e4m3fn or float8_e5m2 (OCP; the WMMA is v_wmma_f32_16x16x16_fp8_fp8, bf8_bf8, or for a mixed pair -- a training backward's gradient against a weight -- bf8_fp8 / fp8_bf8, all twice the bf16 rate). scale_a is one value or one a row of A ((M,) or (M, 1)); scale_b one value or one a row of B ((N,) or (1, N)) -- per-tensor or per-token x per-channel, the two forms vLLM's fp8 linear layers use. bias is (N,). Up to FP8_DECODE_M rows, with K a multiple of 1024, it runs hk.ops.decode_gemm's kernel instead of the tiled one (one fp8 format only). An fp32 out (M, N, contiguous) takes the product unrounded, and with accumulate=True it is added to: out += (A @ B.T) * scale_a * scale_b -- a weight gradient into its fp32 main_grad (Megatron's gradient-accumulation fusion); no bias either way. A with a row stride (rows FP8_POW2_STRIDE bytes or more apart, a power of two) runs FP8_POW2's schedule; a caller that can pad such rows by 64 bytes gets the faster default one (a dense K-16384 operand: 1.47 vs 1.27 ms at M4096 N2048). gfx1201 only: gfx1100 has no fp8 WMMA, and gfx950's fp8 GEMMs are hk.ops.gemm_cdna's.

In the submodules

Imported on first use (import hk.ops.paged); what the engine integrations call. Experimental: these may change in any release (stability).

hk.ops.sdpa.scaled_dot_product_attention

hk.ops.sdpa.scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, enable_gqa=False)

F.scaled_dot_product_attention, argument for argument.

Signature-identical to torch's, defaults included, so it can replace it by assignment. Anything the kernel does not cover is forwarded to torch.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
short sequences torch's SDPA below n_q 192 or n_kv 32 (a silent fallback) hk's kernel at any length

hk.ops.attn_bwd.attention

hk.ops.attn_bwd.attention(q, k, v, *, causal: bool = False, scale: Optional[float] = None)

New after 0.9.24 (the hk.ops.attn_bwd module is not in the 0.9.24 wheel)

Flash attention with a backward, for training: (B, S, H, D) bf16 q and (B, S, H_kv, D) k, v (MHA or GQA) -> o (B, S, H, D), differentiable in q, k and v.

BSHD, the layout a QKV projection writes: q, k and v may be views of one fused (B, S, H + 2 H_kv, D) tensor (read in place), and so may views of SBHD memory (Megatron's layout, at any batch: read as one batch of B * H heads, with o and the gradients returned in the same layout); other strides (heads not D apart) are copied once. Causal is top-left with equal lengths. scale defaults to head_dim ** -0.5. gfx1201 (RDNA4) and gfx1100 (RDNA3), head_dim 64 or 128, S >= 192. The forward keeps a base-2 log-sum-exp a row (fp32), the backward runs a Delta kernel and the dQ, dK and dV kernels; dK and dV of a shared KV head are summed over its query heads inside the kernels.

hk.ops.attn_bwd.why_unsupported

hk.ops.attn_bwd.why_unsupported(q, k, v) -> str

New after 0.9.24 (the hk.ops.attn_bwd module is not in the 0.9.24 wheel)

Why attention cannot run these operands, or ''.

hk.ops.fp8_cast.cast_transpose

hk.ops.fp8_cast.cast_transpose(x, scale, amax, *, dtype='e4m3', pad: int = 64, scale_inv=None, out=None)

New after 0.9.24 (the hk.ops.fp8_cast module is not in the 0.9.24 wheel)

(rowwise (M, N) with row stride N + pad, columnwise (N, M)) of bf16 x (M, N), fp8 of x * scale; amax <- max(amax, max |x|) in place; scale_inv <- 1 / scale if given. M a multiple of 128, N of 64; dtype "e4m3" or "e5m2".

hk.ops.fp8_cast.swiglu_bwd_cast_transpose

hk.ops.fp8_cast.swiglu_bwd_cast_transpose(g, y, scale, amax, *, dtype='e5m2', pad: int = 64, pad_col: int = 0, scale_inv=None, out=None, **knobs)

New after 0.9.24 (the hk.ops.fp8_cast module is not in the 0.9.24 wheel)

Megatron's swiglu_back(g, y) cast to fp8 in the same pass: g (M, F) and y (M, 2F) bf16 -> (rowwise (M, 2F), row stride 2F + pad; columnwise (2F, M), row stride M + pad_col); amax <- max(amax, max |dy|); scale_inv <- 1 / scale if given. dy is computed in fp32 and rounded to bf16 before the cast, as Megatron writes it. out=(rowwise, columnwise): the caller's buffers (fp8, or uint8 views of them; any row strides) instead of new ones. M a multiple of 128, F of 32.

hk.ops.paged.split_kernel

hk.ops.paged.split_kernel(head_dim: int, splits: int)

The split decode's walk for (head_dim, splits): each split's partial output and its (max, sum) into the scratch merge_kernel combines. On gfx950, paged_cdna's (head_dim 64 or 128).

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
head_dim a multiple of 16 64 or 128
q and o padded to 16 rows a group (unbounded loads) any rows up to 16 (bounded)

hk.ops.paged.fused_kernel

hk.ops.paged.fused_kernel(head_dim: int, splits: int, ablate: tuple = (), defines: Optional[dict] = None, ppstep: int = 1)

defines builds the walk with library knobs, for an A/B in one process (tools/hk-bench/paged_variants.py): HK_RDNA_XPOSE_WORDS=0 is the generic register transpose V took before the packed one. ppstep (gfx950) is the pages a step, pages_per_step's choice.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
head_dim a multiple of 16 64 or 128
ablate=, defines= measurement variants refused

hk.ops.paged.merge_kernel

hk.ops.paged.merge_kernel(head_dim: int, splits: int)

The kernel that combines splits partial outputs of the split decode into the answer. On gfx950, paged_cdna's: it reads splits eight at a time, so above 8 splits is a multiple of 8.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
splits any count a multiple of 8 above 8

hk.ops.paged.plan_splits

hk.ops.paged.plan_splits(n_reqs: int, n_kv_heads: int, n_pages: int) -> int

How many ways to cut the KV axis, given how empty the machine is.

On gfx950 the merge reads splits eight at a time, so above 8 a plan must be a multiple of 8 there (vllm_backend.decode_splits rounds to a power of two); gfx1100's merge takes any count.

Without a split the grid is n_reqs * n_kv_heads one-warp workgroups. This asks for enough splits to reach TARGET_WORKGROUPS, capped by the page count -- a split with no pages is pure overhead -- and by MAX_SPLITS (on gfx950, paged_cdna's target_workgroups and MAX_SPLITS).

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
result 1..32, used as it is round to a power of two above 8 for the merge

hk.ops.paged.merge_splits

hk.ops.paged.merge_splits(o_part, ml_part, splits: int, out)

Combine the per-split partial softmaxes into the answer.

In torch, for now, and deliberately: it is a few elementwise passes over a tensor whose size is splits times the output, which is small next to the KV traffic the splits exist to parallelise. If it shows up in a profile it becomes a kernel; writing it as one first would be optimising a thing nobody has measured.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
all of it torch, arch-neutral the same

hk.ops.paged_prefill.kernel_for

hk.ops.paged_prefill.kernel_for(head_dim: int, group: int, scale: Optional[float] = None)

The paged prefill for (head_dim, group, scale). On gfx1100 group (query heads a KV head) is compiled in and must match the tensors, and head_dim is a multiple of 32 up to 192. On gfx950 this is attn_cdna.paged_kernel_for: group is read off the shapes (the argument is ignored) and head_dim is 64 or 128.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
group compiled in; must match the tensors ignored (read off the shapes)
head_dim a multiple of 32 up to 192 64 or 128

hk.ops.paged_prefill.work_list

hk.ops.paged_prefill.work_list(q_lens, device)

The (request, tile) entries for a batch's prefill requests: one per Q_TILE rows of each, ints on the host, one int32 copy to the device.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
query tile 192 rows, in order 256 rows, longest first

hk.ops.decode_gemm.matmul

hk.ops.decode_gemm.matmul(x, w, out=None, **override)

x @ w.T for a decode batch. w is (N, K), as in gemm.matmul; out, if given, is the (M, N) bf16 tensor to write.

override replaces fields of the schedule (slices, warps, combine_depth, resident, splits) -- for measuring, not for use.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
all of it one code path (non-contiguous operands are copied) the same

hk.ops.moe.moe_gemm

hk.ops.moe.moe_gemm(a, w, c, sorted_ids, expert_ids, num_tokens_post_padded, *, top_k: int, block_m: int, topk_weights=None) -> None

vLLM's fused MoE GEMM, into c ((tokens * top_k, N), or the (tokens, top_k, N) it is a view of). sorted_ids None is vLLM's naive assignment, one pair per block, expert_ids then being the flattened top-k ids. topk_weights given multiplies each row by its routing weight. Raises ValueError for a GEMM takes refuses.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
all of it one code path the same

hk.ops.moe.moe_align

hk.ops.moe.moe_align(topk_ids, block_m: int, num_experts: int)

A torch moe_align_block_size, for tests and for running without vLLM: (sorted_ids, expert_ids, num_tokens_post_padded).

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
all of it one code path the same

hk.ops.w4a16.matmul

hk.ops.w4a16.matmul(x, qw, s, zs, group: int, out=None)

x @ W.T for W in hk's 4-bit layout: the decode kernel up to 64 rows of x, dequantize-then-F.linear above (or for a shape it does not take). zs None: the symmetric form (every zero point 8; repack_gptq(symmetric=True)).

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
all of it one code path the same

hk.ops.hipkittens.gemm_bf16

hk.ops.hipkittens.gemm_bf16(a, b, out=None)

out (M, N) = a (M, K) @ b (N, K).T, bf16, on HipKittens' CDNA4 GEMM.

Raises Unsupported for a shape or tensor the kernel does not take (see the module docstring), WrongArch off gfx950, and Unavailable when the kernel did not build or failed its check under this hipcc. out, if given, must be a contiguous (M, N) bf16 tensor that aliases neither input.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
availability WrongArch runs

hk.ops.hipkittens.gqa_fwd

hk.ops.hipkittens.gqa_fwd(q, k, v, *, causal: bool = False, return_lse: bool = False)

GQA attention forward on HipKittens' CDNA4 kernel.

q (B, N, H, D), k and v (B, N, H_KV, D), bf16, contiguous; the scale is 1/sqrt(D). Returns o (B, N, H, D) bf16 and, with return_lse, the natural-log log-sum-exp of each query row, (B, H, N) fp32. The first call at a new (H, H_KV, N, D, causal) compiles, and the first on each device checks the build (see the module docstring). Raises like gemm_bf16.

Per architecture (audit):

gfx1100 (RDNA3) gfx950 (CDNA4)
availability WrongArch runs

hk.ops.sparse_mla.prefill

hk.ops.sparse_mla.prefill(q, kv, indices, indptr, attn_sink, scale: float, out)

out [T, 32, 512] bf16 <- sparse attention of q over the rows of kv each query's CSR list names.

hk.ops.sparse_mla.prefill_mxfp8

hk.ops.sparse_mla.prefill_mxfp8(q, kv, indices, indptr, attn_sink, scale: float, positions, cos_sin_cache, mx_data, mx_scale)

prefill's rows as wo_a reads them, and no bf16 rows: positions [T] int64, cos_sin_cache [P, 64] fp32 (cos | sin), mx_data [T, 32 * 512] e4m3 and mx_scale [T, 512] uint8 E8M0 (row-major), as vLLM's rocm_inverse_rope_mxfp8_rows writes them from prefill's output.