Skip to content

hk: kernels, types, values

Stability: stable, except where an entry says otherwise (stability).

The language: what import hk gives a kernel author. A kernel body is traced once per set of constexprs; the language says how it is written, this page what each name is. The namespaces have pages of their own: hk.math, hk.arch, hk.lds, hk.group, hk.collective, hk.comm, hk.placement; the shipped kernels are hk.ops, the templates hk.templates, the checker hk.check, the profiler hk.profile, the per-arch facts hk.target.

Kernels

hk.kernel

hk.kernel(fn=None, *, arch: Optional[str] = None, warps: Optional[int] = None, grid=None, name: Optional[str] = None, max_vgprs: Optional[int] = None, min_occupancy: Optional[int] = None, max_occupancy: Optional[int] = None, defines: Optional[Dict[str, Any]] = None, noalias: bool = False, preload: bool = False, resident: bool = False, placement=None)

Mark a function as a tile kernel. See the module docstring for the parameter rules. resident=True: every workgroup must be on the GPU at once (a kernel that waits on its own workgroups); a launch that cannot be is refused with ResourceError rather than deadlocking. placement: which XCD runs which workgroup -- None, "auto" or an hk.Placement (hk.dsl.placement, docs/design/placement-pass.md).

hk.func

hk.func(fn)

A device helper: traced inline where it is called, with its for, if and while rewritten like a kernel's.

hk.Kernel

class hk.Kernel(fn: Callable, *, arch: Optional[str] = None, warps: int = 1, grid: Optional[Callable] = None, name: Optional[str] = None, max_vgprs: Optional[int] = None, min_occupancy: Optional[int] = None, max_occupancy: Optional[int] = None, defines: Optional[Dict[str, Any]] = None, noalias: bool = False, preload: bool = False, resident: bool = False, placement=None)

A tile kernel. Call it to launch; trace, source and build stop earlier, and need no GPU.

Kernel.arch (property)

The arch it builds for: arch= if given, else hk.target.current_arch() ($HK_ARCH, else the GPU).

Kernel.trace

Kernel.trace(self, **const_overrides: Any) -> TracedKernel

Run the body once into an hk module and run the passes over it. No GPU, no compiler.

Kernel.source

Kernel.source(self, scaffold: str = 'pybind', **const_overrides: Any) -> str

The generated HipKittens C++. Readable on purpose -- it is the artifact you take to /kernel-resource-check when something spills.

Kernel.with_defines

Kernel.with_defines(self, src: str) -> str

Surface: an escape hatch, used only within its boundary: #define NAME value knobs and A/B variants; never overridden to splice or rewrite C++.

src with this kernel's preprocessor definitions ahead of it, and its occupancy cap (max_occupancy) at the top of its body.

Kernel.build

Kernel.build(self, **const_overrides: Any)

Generate and compile. Returns a runtime.Build, which carries the per-instantiation resource numbers as well as the .so.

The compile step gates on ScratchSize and register spills: a kernel that spills is not slow here, it is wrong, because include/rdna3 hand-manages s_waitcnt. A spilling build raises rather than being returned.

Needs hipcc but not a GPU, which is what makes the whole development loop runnable on a machine with no Radeon in it.

Kernel.build_flags

Kernel.build_flags(self, traced: TracedKernel) -> Tuple[str, ...]

Surface: an escape hatch, used only within its boundary: tests and probes; not hk.ops kernels.

hipcc flags of this kernel's builds beyond the target's.

Kernel.preloaded

Kernel.preloaded(self) -> Kernel

This kernel with preload set: its own builds, the same body.

Kernel.compile

Kernel.compile(self, **const_overrides: Any)

Generate, compile and load. Returns the loaded extension module.

Kernel.for_arch

Kernel.for_arch(self, arch: str, name: Optional[str] = None) -> Kernel

This kernel built for arch: the same body, warps, grid, constexpr defaults and options (a specialization keeps its dtypes), its own traces and builds. name= renames it. What a test or a probe that targets another arch wants, in place of re-wrapping k.fn (which a dtype-parameter specialization cannot be).

Kernel.placed

Kernel.placed(self, placement=None) -> Kernel

This kernel with placement (default: the analysis's cluster placement) installed: its own name (a suffix for the placement), traces and builds, the same body.

Kernel.placement_choice

Kernel.placement_choice(self, *tensors: Any, **const_overrides: Any)

hk.dsl.placement.choose for these tensors: whether placement="auto" launches the cluster placement, and why.

Kernel.resident_capacity

Kernel.resident_capacity(self, **const_overrides: Any) -> int

How many workgroups of this kernel the current GPU holds at once: its CUs times the workgroups a CU fits by registers and by LDS (the smaller), from the build's own resource report.

Kernel.specialize

Kernel.specialize(self, **const_overrides: Any) -> Kernel

A view of this kernel with different constexpr defaults.

Memoized, and that is not an optimization detail. A fresh Kernel has empty trace / build / module caches, so calling specialize() on every invocation -- which is what a wrapper like rmsnorm(x, eps=...) naturally does -- re-traces the body and re-resolves the extension module on every launch. Measured on the W7900D that was ~3.5 ms of Python in front of a 0.5 ms kernel: rmsnorm and layernorm came out flat in the tensor size, which is the signature of a fixed host cost rather than a slow kernel.

The cheaper surface is to pass the constexpr to the call itself -- k(x, o, EPS=eps) -- which uses the caches directly and makes no object at all. specialize() is for handing a configured kernel to something that will call it many times.

hk.GenericKernel

class hk.GenericKernel(fn: Callable, **kw: Any)

A kernel with dtype parameters (hk.Tensor[hk.T]) and/or a warps argument: one definition, a specialization per (dtypes, warps) -- an ordinary Kernel, traced, built and named <kernel>__T<dtype>_warps<n> -- picked at the call.

@hk.kernel(grid=lambda p: (hk.cdiv(p.o.cols, 64 * p.warps), hk.cdiv(p.o.rows, 16), 1))
def gated_silu(a: hk.Tensor[hk.T], b: hk.Tensor[hk.T], o: hk.Tensor[hk.T], *, warps=4):
    ...
gated_silu(a, b, o)                  # T read from the tensors (they must agree); 4 warps
gated_silu(a16, b16, o16, warps=8)   # T = fp16; 8 warps
gated_silu(a, b, o, T=hk.bf16)       # T given: nothing read
gated_silu.variant(T=hk.fp16)        # the specialization itself: gated_silu__Tfp16_warps4

trace / source / build / compile / specialize take the same keywords (T= is required there: no tensors to read it from).

GenericKernel.variant

GenericKernel.variant(self, **kw: Any) -> Kernel

The specialization for these dtype parameters (and warps=): an ordinary Kernel, named <kernel>__T<dtype>[_warps<n>]. Other keywords are not taken here.

GenericKernel.trace

GenericKernel.trace(self, **kw: Any) -> TracedKernel

Run the body once into an hk module and run the passes over it. No GPU, no compiler.

GenericKernel.source

GenericKernel.source(self, scaffold: str = 'pybind', **kw: Any) -> str

The generated HipKittens C++. Readable on purpose -- it is the artifact you take to /kernel-resource-check when something spills.

GenericKernel.build

GenericKernel.build(self, **kw: Any)

Generate and compile. Returns a runtime.Build, which carries the per-instantiation resource numbers as well as the .so.

The compile step gates on ScratchSize and register spills: a kernel that spills is not slow here, it is wrong, because include/rdna3 hand-manages s_waitcnt. A spilling build raises rather than being returned.

Needs hipcc but not a GPU, which is what makes the whole development loop runnable on a machine with no Radeon in it.

GenericKernel.compile

GenericKernel.compile(self, **kw: Any)

Generate, compile and load. Returns the loaded extension module.

GenericKernel.resident_capacity

GenericKernel.resident_capacity(self, **kw: Any) -> int

How many workgroups of this kernel the current GPU holds at once: its CUs times the workgroups a CU fits by registers and by LDS (the smaller), from the build's own resource report.

GenericKernel.specialize

GenericKernel.specialize(self, **kw: Any) -> Kernel

The specialization for the dtype parameters and warps given, with the other keywords as its constexpr defaults.

GenericKernel.placement_choice

GenericKernel.placement_choice(self, *tensors: Any, **kw: Any)

hk.dsl.placement.choose for these tensors: whether placement="auto" launches the cluster placement, and why.

GenericKernel.for_arch

GenericKernel.for_arch(self, arch: str, name: Optional[str] = None) -> GenericKernel

This kernel, every specialization of it built for arch.

GenericKernel.placed

GenericKernel.placed(self, placement=None) -> Kernel

This kernel with placement (default: the analysis's cluster placement) installed: its own name (a suffix for the placement), traces and builds, the same body.

GenericKernel.preloaded

GenericKernel.preloaded(self) -> Kernel

This kernel with preload set: its own builds, the same body.

hk.TracedKernel

class hk.TracedKernel(name: str, arch: str, warps: int, consts: Dict[str, Any], tensors: List, module: ir.Module, grid: Tuple = (), analysis=None, plan=None, logical_grid: Tuple = ())

One specialization of a kernel, traced and lowered: its hk module and what the module boundary needs to know about it.

TracedKernel.threads (property)

warps x the target's wave: the workgroup's size.

TracedKernel.tensors

TracedKernel.tensors(self) -> List[Param]

The tensor parameters, in order, with their types.

TracedKernel.written_tensors

TracedKernel.written_tensors(self) -> List[str]

The tensors the kernel stores into, in declaration order.

TracedKernel.cpp

TracedKernel.cpp(self, includes) -> str

The kernel's HipKittens C++ body, with includes; Kernel.source() is the whole translation unit.

TracedKernel.dump

TracedKernel.dump(self) -> str

The module as MLIR, values named as the C++ names them: %ld1 here is ld1 in cpp(). Printed from a copy, renamed by the translation's own naming, so the two cannot disagree.

hk.Tensor

The annotation for a tensor parameter: x: hk.Tensor[hk.bf16], or x: hk.Tensor[hk.T] for a dtype the call decides (hk.TypeVar).

hk.Tensor[hk.bf16, "system"] (or "device") is a scoped tensor: memory another GPU ("system") or another XCD of this GPU ("device") reads or writes while the kernel runs -- a peer's buffer, a mailbox. Every load, store and atomic through it carries the scope, and hk.comm.signal / hk.comm.wait take only scoped tensors (see hk.comm for why the scope is the tensor's and not the access's).

hk.Tensor[hk.bf16, "strided"] is a strided tensor: the kernel takes every stride the caller's tensor has -- batch, depth, row, and a granule stride along the columns (16-byte granules at any distance) -- where a plain tensor's outer axes must be compact over its rows. It is how a kernel reads an engine's layout in place: vLLM's x-split K cache passed as the 5-D view (blocks, heads, block, head_dim / G, G), G 16 bytes of elements, or its flash-layout cache as a permuted 4-D view. RDNA; read by g.stage (any other op on it is refused when the kernel is translated).

hk.TypeVar

class hk.TypeVar(name: str)

A dtype parameter: hk.Tensor[hk.T] (or a second one, U = hk.TypeVar("U")).

A kernel whose tensors are annotated with one is a single definition for every dtype: k(a, b, o) reads T from the first tensor annotated with it (every tensor sharing T must agree), k(a, b, o, T=hk.fp16) sets it. Each dtype is its own specialization, traced, built and named (<kernel>__Tbf16) as a kernel written for that dtype would be. In the body the variable's name is the bound dtype: hk.RT(T, 16, 64), x.to(T) (or read it off a tensor: a.dtype).

hk.T

A dtype parameter: hk.Tensor[hk.T] (or a second one, U = hk.TypeVar("U")).

A kernel whose tensors are annotated with one is a single definition for every dtype: k(a, b, o) reads T from the first tensor annotated with it (every tensor sharing T must agree), k(a, b, o, T=hk.fp16) sets it. Each dtype is its own specialization, traced, built and named (<kernel>__Tbf16) as a kernel written for that dtype would be. In the body the variable's name is the bound dtype: hk.RT(T, 16, 64), x.to(T) (or read it off a tensor: a.dtype).

hk.Constexpr

Marks a constexpr parameter, with its type if you like: EPS: hk.Constexpr[float] = 1e-6. Every keyword-only parameter is a constexpr whether or not it says so -- the marker documents it, which matters when a kernel has a dozen knobs -- and a positional one is a constexpr when it is annotated so.

Types

hk.RT

hk.RT(dtype: DType, rows: int, cols: int, layout: str = 'row', frag=None) -> RegTileType

A register tile type: kittens::rt. frag, (rows, cols), names the matrix-core fragment where it is not 16x16; left out, the hk-fragments pass sets it on the operand tiles that need one.

hk.RS

hk.RS(dtype: DType, rows: int, cols: int, run: int = 8) -> RegTileType

A register strip type: kittens::rs.

The layout for kernels that stream rows -- a norm, a softmax -- rather than feed WMMA: lane l owns, of every row, the runs of run contiguous columns starting at jwaverun + lrun (wave = 32 on gfx1100, 64 on gfx950; hk.arch.target().wave), so a bf16 run of 8 is one 16-byte access and nothing is held twice. cols is a whole number of waverun chunks: 256 or 512 columns at run 8, so 512 fits both. A strip loads and stores (element coordinates only, the element type converting on the way), maps, reduces along rows (a butterfly that leaves the answer in every lane) and columns, broadcasts its col_vec and row_vec, and fills by column. Its row_vec has the strip's own column layout: a weight vector loads with the same accesses as the rows it scales.

hk.ST

hk.ST(dtype: DType, rows: int, cols: int, count: int = 1) -> SharedTileType

An LDS tile type; count > 1 is a multi-buffer.

hk.SV

hk.SV(dtype: DType, length: int, count: int = 1) -> SharedVecType

An LDS vector type.

hk.col_vec

hk.col_vec(tile: RegTileType) -> RegVecType

One value per row of tile: what t.sum(axis=1) gives.

hk.row_vec

hk.row_vec(tile: RegTileType) -> RegVecType

One value per column of tile.

hk.DType

class hk.DType(name: str, bits: int, cpp: str, kind: str) -> None

An element type: hk.bf16, hk.fp16, hk.fp32, hk.i32, hk.i8, hk.fp8e4m3, hk.fp8e5m2. name is hk's spelling, cpp the HipKittens one, bits and bytes its size.

Control flow

hk.range

hk.range(start, stop=None, step=None, *, unroll: int = 1) -> DynRange

A loop the kernel runs at run time, even over constant bounds.

unroll becomes #pragma unroll N. Leave it at 1 unless measured: unrolling a body that already fills the register file is how a kernel starts to spill, and a spill here is a wrong answer, not a slow one.

hk.range_constexpr

hk.range_constexpr(start, stop=None, step=None)

A loop unrolled at trace time; its bounds must be Python ints.

hk.if_

hk.if_(cond, *, opaque: bool = False, uniform: bool = False) -> Iterator[None]

A region that runs only where cond holds.

opaque=True hides the condition from the optimizer (an empty asm that claims to modify it), so the branch survives even when it folds to a constant -- the tool for keeping two live sets apart. uniform=True declares the condition the same in every warp (see hk.uniform): the region may then hold barriers.

hk.scope

hk.scope() -> Iterator[None]

An always-taken region that is a boundary for the register allocator: one VGPR and a never-taken branch, and two live sets that no longer have to be held at once.

hk.uniform

hk.uniform(cond)

cond, declared the same in every warp of the workgroup -- made of the block index, scalar loads every warp makes, constexprs and the tensors' extents, never of warp_id or a lane's value. A branch on it (if hk.uniform(bid < 160): or hk.if_(c, uniform=True)) may hold workgroup operations -- barriers, group copies -- as every warp takes it or none does: the role dispatch of a persistent kernel. So may a runtime loop on it, while hk.uniform(t < n):, every warp running the same iterations: a work queue's loop over hk.comm.claim. The declaration is the author's; a condition that differs between warps deadlocks at the first barrier inside.

Functions

hk.cdiv

hk.cdiv(a, b)

Ceiling division: of ints at trace time, of device Ints in the kernel, of tensor extents in a grid lambda.

hk.min

hk.min(a, b)

Of ints, of device Ints, elementwise of tiles and vectors (an i32 strip: C's signed min), or of hk.map elements.

hk.max

hk.max(a, b)

Of ints, of device Ints, elementwise of tiles and vectors (an i32 strip: C's signed max), or of hk.map elements.

hk.zeros

hk.zeros(ty, *, into=None)

A register tile or vector of type ty filled with 0, or into= an existing one: acc = hk.zeros(hk.RT(hk.fp32, 16, 64)).

hk.full

hk.full(ty, value: float, *, into=None)

A register tile or vector of type ty filled with value.

hk.neg_infty

hk.neg_infty(ty, *, into=None)

A register tile or vector of type ty filled with -inf: a running max's start.

hk.rand

hk.rand(ty, seed, offset, row_stride, *, into=None) -> Tile

Uniform [0, 1) draws into an fp32 tile: element (r, c) is the draw triton.language.rand(seed, offset + r * row_stride + c) makes, bit for bit -- Philox4x32-10 with Triton's constants and conversion -- so a dropout written here keeps exactly the elements Triton's keeps.

hk.transpose

hk.transpose(t: Tile, *, into=None) -> Tile

Transpose by relabelling: mirrored shape, opposite layout, no data moved beyond the register shuffle.

hk.transpose_sep

hk.transpose_sep(t: Tile, *, into=None) -> Tile

Transpose keeping the layout. Moves data; needs separate registers.

hk.broadcast_row

hk.broadcast_row(ty: RegTileType, vec: Vec) -> Tile

A tile whose every row is vec[row].

hk.broadcast_col

hk.broadcast_col(ty: RegTileType, vec: Vec) -> Tile

A tile whose every column is vec[col]: element (r, c) is vec[c], for a row_vec vec (one value per column).

hk.as_vec

hk.as_vec(vec: Vec, tile: RegTileType, *, uniform: bool = False) -> Vec

Re-attach a register vector to a tile of another shape, where the C++ types are the same: element type, length and layout.

hk.mma

hk.mma(variant: str, a, b, acc: Tile, *, into=None) -> Tile

acc + A x B on the WMMA unit. The variant is decided by the layouts you have; the wrong one is how a kernel buys eight ds_read_u16 per base tile instead of two ds_read_b128.

Scaled operands (Tile.scaled) make it gfx950's block-scaled MFMA (v_mfma_scale_f32_16x16x128_f8f6f4): hk.mma("mma_ABt", a.scaled(sa), b.scaled(sb, fmt="fp4"), acc) is acc + (sa . A)(sb . B)^T for A (M, K) and B (N, K) fp8 e4m3 row tiles (FP4 in the fp8 container with fmt="fp4"), K a multiple of 128, element (r, k) of A counting as A[r][k] * 2^(sa[r][k // 32] - 127), acc an fp32 col tile (M, N). Both operands are scaled, and the variant is mma_ABt.

hk.load_w4

hk.load_w4(ty, qw: Global, s: Global, zs: "Optional['Global']", n0, k0, *, group: int = 128, zero: Optional[int] = None, s_blocked: bool = False, zp: "Optional['Global']" = None, rows: bool = False, exllama: bool = False, into=None) -> Tile

Surface: a format primitive: hk's own int4 layout (hk.ops.w4a16's repack).

Surface: zero=: a format primitive: the symmetric form: one zero point for every group, no zs read (GPTQ's uint4b8).

Surface: s_blocked=: a format primitive: the symmetric form's scales in 16-row blocks, [N/16, K/group * 16] (hk.ops.w4a16.repack_gptq(symmetric=True)).

Surface: zp=: a format primitive: 4-bit zero codes per row and group, int8 [N/2, K/group] two rows to a byte (vLLM's moe_wna16 layout), no zs read.

Surface: rows=: a format primitive: the zero-code form's row-major codes, int32 [N, K/8] (vLLM's uint8 [N, K/2] viewed as int32).

Rows n0.. and columns k0.. of W, dequantized from 4-bit codes into a bf16 row-layout tile: element (n, k) is q * s - zs, q being nibble k % 8 of row n's word k // 8 (int32 [N, K/8], interleaved [N/16][K/32][16][4]), s and zs the group's scale and zero-times-scale s[n][k // group], zs[n][k // group] (bf16 [N, K/group]). The layout hk.ops.w4a16.repack_* writes. The tile is a whole number of 32-column chunks and k0 a multiple of 32, and of the tile's width when the group spans it.

Symmetric: zs=None, zero=z -- one zero point z for every group (GPTQ's uint4b8: 8), so the element is (q - z) * s and no zs is stored or read: 12.5% fewer bytes than codes + s + zs at 32-column groups. A bf16 tile is then bit for bit the asymmetric one on a checkpoint whose zs is z * s; an fp16 tile is (q - z) * s rounded once to nearest even (packed fp16), where the asymmetric path rounds toward zero after an fp32 FMA.

s_blocked (symmetric): s is laid out [N/16, K/group * 16] -- a 16-row block's scales of one group are 16 consecutive values, so the 16 rows a k-step reads take 32 contiguous bytes instead of 16 lines (hk.ops.w4a16.repack_gptq(..., symmetric=True) writes it).

Zero codes: zs=None, zp=Z -- the element is (q - z) * s with z the 4-bit zero code of row n and group k // group, read from Z, int8 [N/2, K/group] with two rows to a byte (row 2j in the low nibble, 2j + 1 in the high): vLLM's moe_wna16 layout of an AWQ (or zero-point GPTQ) checkpoint, no zero-times-scale tensor (16.5 bytes a 32-column group of a row against 20 with zs). An fp16 tile decodes as the symmetric form does, q - z exact and the product rounded once to nearest even; a bf16 tile through the fp32 path with zs = z * s. RDNA (wave32) only.

rows (zero codes): the codes are row-major, int32 [N, K/8] with nibble t of word w column 8w + t -- vLLM's uint8 [N, K/2] viewed as int32 -- not hk's interleaved order; each lane loads its own row's 16 bytes.

exllama (symmetric, zero=, plain scales, an fp16 tile, RDNA): the codes are vLLM's RDNA skinny W4A16 layout, read in place -- row-major int32 [N, K/8], word w of a row holding columns 8w + (0, 2, 4, 6, 1, 3, 5, 7) in nibbles 0..7 (ExLlama's shuffle) -- and s [N, K/group].

hk.coord

hk.coord(b: Scalar = 0, d: Scalar = 0, r: Scalar = 0, c: Scalar = 0, *, unit: str = 'tile') -> Coord

A (batch, depth, row, col) index. unit is "tile" (C++ coord<RT>) or "element" (coord<>); picking the wrong one reads the wrong memory without any diagnostic, which is why it is in the type.

hk.tile_coord

hk.tile_coord(b: Scalar = 0, d: Scalar = 0, r: Scalar = 0, c: Scalar = 0) -> Coord

A (batch, depth, row, col) index in tiles: row r is rows [rR, (r+1)R) for a load of an R-row tile. x[hk.tile_coord(...)].

hk.elem_coord

hk.elem_coord(b: Scalar = 0, d: Scalar = 0, r: Scalar = 0, c: Scalar = 0) -> Coord

A (batch, depth, row, col) index in elements: what x.at[r, c] builds. Strips index only this way.

MX and FP4 (gfx950)

hk.load_mx_scales

hk.load_mx_scales(src: Global, rows: int, kblocks: int, row0, kb0, *, into: MxScales = None, layout: str = 'ocp', group_rows: int = 0, loose: bool = False) -> MxScales

Surface: a format primitive: E8M0 scales of gfx950's scaled MFMA (v_mfma_scale_f32_16x16x128_f8f6f4)'s operands; a new layout is a layout= value, not a new op.

Rows row0.. and 32-wide blocks kb0.. of an E8M0 scale tensor (uint8, one byte a row and block: [R, K/32], the OCP MX layout -- or packed, i32, as hk.mx.pack_scales lays them out: one coalesced dword a lane per 64 rows and K step) for an fp8 operand tile of rows rows and kblocks * 32 columns. gfx950 only.

layout="aiter_gate_up" / "aiter": AITER's shuffled MoE weight scales (uint8 [E * group_rows, K/32], shuffle_scale(is_guinterleave=True), with and without gate_up) -- the scales of a load_fp4_frags tile of the same rows: row0 the tile's first row in [E * group_rows], base tiles alternating gate and up with "aiter_gate_up". AITER scales are kept as loaded (fmt 2: the MFMA's opsel picks the byte; kb0 a multiple of 8 when kblocks > 4). loose (byte scales): a register a 16-row tile and K step, the byte as loaded (fmt 1). Both leave nothing for the VALU to do with a loaded scale, so its wait sits at the MFMA instead of right after the load -- the packed form's byte insertion waited there, draining every load issued before it (K1 c8).

hk.load_fp4_frags

hk.load_fp4_frags(ty, src, row0, kc0, *, group_rows: Optional[int] = None, gate_up: bool = False, into=None) -> Tile

Surface: a format primitive: AITER's pre-shuffled MXFP4 MoE weights only.

Rows row0.. and 128-wide K steps kc0.. of AITER's shuffled MXFP4 MoE weights (gfx950, shuffle_weight(is_guinterleave=True); src uint8 [E * group_rows, K/2], the packed bytes) as an FP4 operand, w.scaled(sw, fmt="fp4") in hk.mma. ty is an fp8 e4m3 row tile of 16x128 fragments -- the container: each fragment's first four dwords hold the FP4 operand, the rest stay undefined. With gate_up (a stage-1 gate|up weight) the base tiles alternate the gate and up halves of 16-row block (row0 % group_rows) // 16 + i // 2, so gate column j and up column j of the product land in the same lanes.

src may instead be an LDS tile of raw AITER weight bytes (fp8-typed, a row a 16-row block with gate|up rows interleaved, 1 KB a 128-wide K step: the [E * N/16 * 2, K/2 * 16] view of the weights, brought in by a group load): fragment (i, s) is then its row row0 + i and 1 KB chunk kc0 + s, and group_rows / gate_up do not apply.

hk.mx_quant_store

hk.mx_quant_store(src: SharedTile, q: Global, s: Global, row0, col0) -> None

Surface: to be merged into a G1 composition (hk.mx) (DSL-surface migration S10).

MX-quantize an LDS tile's rows and store them -- the epilogue that hands a GEMM's output to an MXFP8 consumer without a separate quant pass. Every thread of the workgroup takes (row, 32-column group) pairs of src (bf16 or fp32: store it, then barrier, first). For each group it computes AITER's E8M0 exponent exactly, e = ceil(log2(amax / 448)) from amax's bits. It writes the FP8 e4m3 values to q[row0 + r, col0 + 32 g ..] and the scale byte to s: a uint8 s gets AITER's 32-row layout (hk.mx.aiter_scales of q's [R, K/32], K/32 padded to 8), an int32 s the packed layout hk.load_mx_scales reads ([ceil(R/64), K/128 * 64], hk.mx.pack_scales; rows past q's last get the unit scale, as pack_scales pads them). The result is bit-identical to hk.mx.quant followed by hk.mx.aiter_scales or hk.mx.pack_scales.

hk.copy_mx_scales

hk.copy_mx_scales(dst: MxScales, src: MxScales) -> None

Surface: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use MxScales.copy(into=).

Deprecated: src.copy(into=dst). dst = src, E8M0 scales copied register to register.

hk.mma_ABt_mx

hk.mma_ABt_mx(a: Tile, b: Tile, acc: Tile, sa: MxScales, sb: MxScales, *, into=None, a_fmt: str = 'fp8', b_fmt: str = 'fp8', sa_at=(0, 0), sb_at=(0, 0)) -> Tile

Surface: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use hk.mma with Tile.scaled operands.

Deprecated: hk.mma("mma_ABt", a.scaled(sa, fmt=a_fmt, at=sa_at), b.scaled(sb, fmt=b_fmt, at=sb_at), acc), the same instruction.

hk.load_fp4_frags_lds

hk.load_fp4_frags_lds(ty, src: SharedTile, row0, chunk0, *, into=None) -> Tile

Surface: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use hk.load_fp4_frags(SharedTile).

Deprecated: hk.load_fp4_frags(ty, src, row0, chunk0) with src an LDS tile.

Strips: elementwise expressions, iota, a raw MFMA (gfx950)

hk.map

hk.map(fn, *args)

Element (r, c) of the result is fn of element (r, c) of each strip argument (an hk.Int or a Python number argument is passed as itself): one hk.map op, fn traced once. fn sees elements (hk.dsl.maps.Scalar) with Python's operators at C's semantics -- // and % truncate, >> is arithmetic --, comparisons making masks, hk.where, hk.min / hk.max, .to(dtype), .bitcast(dtype) and the hk.math functions. The result's dtype is what fn returns: fp32, i32 or a mask (b1). Floating-point contraction is off: a * b + c is two roundings, hk.math.fma(a, b, c) one.

idx = hk.map(lambda c, w: ((c >> 4) & 63) * 4 + w * 512, col, hk.arch.warp_id())

The operators on i32 strips and masks build these one op at a time and the hk-map-fuse pass merges a chain; hk.map is for an expression to read as one, or to keep a float expression's roundings as written. On gfx950, gfx1100 and gfx1201; on RDNA a mask only feeds another map (its strips hold no bool).

hk.where

hk.where(m, a, b)

Elementwise a where the mask m holds, else b (C's m ? a : b): m a comparison of strips (or of hk.map elements), a and b strips of one dtype or numbers -- a Python number takes the other arm's dtype. One hk.map.

hk.map_cpp

hk.map_cpp(expr: str, *args, dtype: Optional[DType] = None, name: str = 'map') -> Tile

Surface: an escape hatch, used only within its boundary: an intrinsic or instruction hk has no op for, or another kernel's exact instruction sequence; not index arithmetic, selects, bit ops or float expressions the operators can write; never in a template.

An elementwise C++ expression over strips: element (r, c) of the result is expr with x0, x1, ... bound to element (r, c) of each strip argument -- or to the argument itself for an Int or a Python int -- converted to dtype (default: the strips' one dtype; strips of fp32 and i32 together must say it).

For what the operators cannot say and a kernel must reproduce bit for bit: bit manipulation, a fused multiply-add, one particular instruction. E.g. the biased exponent of the smallest power of two >= x:

e = hk.map_cpp("((__builtin_bit_cast(int, x0) >> 23) & 0xFF)"
               " + ((__builtin_bit_cast(int, x0) & 0x7FFFFF) != 0)", x, dtype=hk.i32)

The strips have one shape and run; strips and result are fp32 or i32 (convert a 16-bit strip with .to first). The expression is one C++ expression, compiled as written -- with floating-point contraction off, so a * b + c is two roundings and a fused multiply-add is spelled __builtin_fmaf -- no ; or braces, and the compiler, not hk, checks it.

hk.iota

hk.iota(ty) -> Tile

An i32 strip of type ty's shape whose element (r, c) is c: each element's own column, for index arithmetic (the strip operators, load_elems / store_elems) and per-column choices (gfx950). hk.lane_coords(ty)[1], kept as this one line.

hk.mfma_strip

hk.mfma_strip(kind: str, a: Tile, b: Tile, acc: Tile) -> Tile

Surface: to be merged into hk.mma on Tile.as_fragment views (DSL-surface migration S9).

One raw MFMA on strip registers (gfx950), for a result that must match another kernel's MFMA bit for bit. "f32_16x16x4": acc (hk.RS(fp32, 1, 256, 4): lane l's four values are C rows 4 (l // 16) + i, column l % 16) + A B^T over K = 4, where lane l of a and b (hk.RS(fp32, 1, 64, 1)) holds A[l % 16][l // 16] and B[l % 16][l // 16] -- v_mfma_f32_16x16x4_f32, nothing reordered. Returns the new accumulator.

Workgroup placement (multi-XCD GPUs)

Which XCD runs which workgroup: hk.kernel(placement=...) takes None (the hardware's order), "auto" (the cluster placement where the policy takes it) or an hk.Placement. Outputs are bitwise the unplaced kernel's; only the order changes. On a part with one L2 (gfx1100) every placement is the identity. hk.arch.xcd_count() is the XCD count it deals over, Kernel.placed() / Kernel.placement_choice() the placed kernel and the policy's decision, hk.placement.analyze / hk.placement.choose the analysis and the policy, python -m hk.check --placement checks a launch covers its grid exactly once (check, design).

hk.Placement

How a kernel's workgroups are numbered.

Placement.cluster() one sharing cluster an XCD at a time; the key from analyze (the dominant read's), or key= digits the analysis cannot see (an index read from memory) Placement.chunked(chunk, tail) block_idx.x only, within each (y, z) slice and with the grid as it is: rounds of xcds * chunk consecutive ids an XCD (a GEMM's xcd_chunk, whose y is the split-K share); chunk="even" is an eighth of the axis an XCD Placement.none() the identity

tail is what happens past the last whole round: "stay" (in round-robin order, what the hand-written GEMM remaps did) or "spread" (dealt as contiguous ranges, balanced to one). chunk 0 is contiguous ranges outright.

hk.Digit

A grid axis whole (kind "whole"), or one digit of it: axis // radix ("div") or axis % radix ("mod"). radix is an int, a tensor extent spelled "tensor.dim" (Digit.of("x", "mod", "k.depth"): the KV heads of a (B, H_KV, N, D) k), or a host expression of extents and constexprs.

Made with hk.Digit.of(axis, kind="whole", radix=None): hk.Digit.of("z"), hk.Digit.of("x", "mod", 8). A Placement.cluster(key=...) names its sharing key with these where the analysis cannot see it (an index read from memory).

Dtypes

name bits C++ kind
hk.bf16 16 bf16 float
hk.fp16 16 half float
hk.fp32 32 float float
hk.i32 32 int int
hk.i8 8 int8 int
hk.fp8e4m3 8 fp8e4m3 float
hk.fp8e5m2 8 fp8e5m2 float

fp8 is a matrix operand where the target has an fp8 matrix instruction: gfx950's MFMA (plain, and block-scaled through hk.mma with Tile.scaled operands, which may also be FP4) and gfx1201's WMMA. i8 is a WMMA operand on gfx1100 (v_wmma_i32_16x16x16_iu8, an i32 accumulator) and a storage type elsewhere. hk.mx has the MX scale layouts and torch references. hk.DTYPES maps the names to these.

Device values

What a kernel body computes with. They are made by loads, hk.zeros and friends, never constructed directly; their methods are the language. A method ending in _ writes the value in place; into= names the value an operation writes.

Operators (n a Python number, a, b values of the column's kind; a vector broadcasts against a tile along the axis it was reduced from):

operator Tile Vec Int Bool
a + b yes yes yes
n + a yes yes yes
a - b yes yes yes
n - a yes yes yes
a * b yes yes yes
n * a yes yes yes
a / b yes yes refused
n / a yes yes
a // b i32 strips refused yes
a % b i32 strips refused yes
-a yes yes yes
abs(a) yes yes
a += b (also -= *= /=) yes yes yes (rebinds)
a @ b yes
a < b (<= > >= == !=) strips (a mask) refused yes
a & b, a \| b, a ^ b i32 strips, masks refused yes
a << b, a >> b i32 strips refused
~a i32 strips, masks refused yes
v[:, None], v[None, :] yes

acc += a @ b.T is one matrix-core instruction into acc (the variant follows from the transposes); t.sum(axis=1) and friends are lazy reductions that +=, max_ or .value() land.

hk.Tile

A register tile: kittens::rt.

Tile.dtype (property)

The element dtype.

Tile.sum

Tile.sum(self, axis: int = 1, *, lanes: Optional[str] = None, xor: Optional[Sequence[int]] = None, times: "Optional['Tile']" = None) -> Reduction

The sum along axis: 1 (default) along each row, one value per row (a col_vec); 0 along each column (a row_vec). Lazy: v = t.sum() makes the vector, acc += t.sum() accumulates into one, and .value(into=v) writes an existing one.

Tile.max

Tile.max(self, axis: int = 1, *, lanes: Optional[str] = None, xor: Optional[Sequence[int]] = None) -> Reduction

The max along axis: 1 (default) along each row, one value per row (a col_vec); 0 along each column (a row_vec). Lazy: v = t.max() makes the vector, m.max_(t.max()) folds into one (the online max), and .value(into=v) writes an existing one.

Tile.first_lane

Tile.first_lane(self) -> Int

Lane 0's first element of this i32 strip, as a scalar (v_readfirstlane, gfx950). Uniform across the workgroup when every wave holds the same value -- one LDS word read after a barrier -- so it may drive hk.uniform branches (an early exit decided by one wave).

Tile.lane_strip

Tile.lane_strip(self, run: int = 8) -> Tile

This tile's registers as a 1-row strip, lane by lane (gfx950): no data moves. Lane l's elements, in the tile's per-lane order (a matrix-core tile: its fragments row by row of fragments, each fragment's elements in order; a strip: its rows, chunks and runs), become the lane's runs of run, chunk after chunk -- so hk.map_cpp, the group reductions and store_elems work on an MMA result where it sits. hk.lane_coords(tile, run) says which row and column of the tile each element is. 32-bit elements.

Tile.run_xor

Tile.run_xor(self, mask: int) -> Tile

Each element from another element of its lane's run (gfx950): element e of a run becomes element e ^ mask of the same run, a register move. A rotary pair's partner, when the pair sits in one run (an MMA result taken by lane_strip).

Tile.lane_gather

Tile.lane_gather(self, lanes: Tile) -> Tile

Each element from another lane (gfx950): element (r, c) of lane l is the same run element of lane lanes[r, c] (an i32 strip of this strip's shape, 0..63) -- ds_bpermute, one an element. A lane group's small-matrix work (a 4x4 Sinkhorn's row and column sums) without LDS. 32-bit elements.

Tile.group_max

Tile.group_max(self, cols: int, *, lanes: str = 'seq', xor: Optional[Sequence[int]] = None) -> Tile

A strip's rows reduced over groups of cols columns (a lane group's runs: an MX group is 32 columns of a run-8 strip), the group's max in every element. lanes and xor state the order, as for sum(axis=1, ...); the offsets are 1 .. cols / run / 2 (neighbouring lanes), or as many other distinct powers of two up to 32: the group is then a lane's run and those of lanes l ^ (a sum of the offsets). A 32x32 matrix-core result taken as a strip (lane_strip(16)) holds 32 rows of a column in lane l's run and lane l ^ 32's: group_max(32, xor=(32,)). gfx950.

Tile.group_min

Tile.group_min(self, cols: int, *, lanes: str = 'seq', xor: Optional[Sequence[int]] = None) -> Tile

As group_max, the minimum.

Tile.group_sum

Tile.group_sum(self, cols: int, *, lanes: str = 'seq', xor: Optional[Sequence[int]] = None) -> Tile

As group_max, the sum, in the stated order.

Tile.min

Tile.min(self, axis: int = 1, *, lanes: Optional[str] = None, xor: Optional[Sequence[int]] = None) -> Reduction

The min along axis: 1 (default) along each row, one value per row (a col_vec); 0 along each column (a row_vec). Lazy: v = t.min() makes the vector, and .value(into=v) writes an existing one.

Tile.prod

Tile.prod(self, axis: int = 1, *, lanes: Optional[str] = None, xor: Optional[Sequence[int]] = None) -> Reduction

The product along axis: 1 (default) along each row, one value per row (a col_vec); 0 along each column (a row_vec). Lazy: v = t.prod() makes the vector, and .value(into=v) writes an existing one.

Tile.to

Tile.to(self, dtype: DType, *, into=None) -> Tile

Change the element type, keeping shape and layout (kittens::copy).

Tile.bitcast

Tile.bitcast(self, dtype: DType, *, into=None) -> Tile

The same registers read as another element type of the same width (fp32 <-> i32, bf16 <-> fp16 ...): no instruction, unlike .to. E.g. an i32 accumulator started at the bits of 1.5 * 2^23 read as fp32 is 1.5 * 2^23 + S exactly for |S| < 2^22 -- the int -> float convert of an iu8 product, folded away (experiment 1's c7 needed a C++ rewrite).

Tile.T (property)

This tile transposed, as an MMA operand (acc += a @ b.T) or for .value(), which makes the transposed tile.

Tile.left_fill_

Tile.left_fill_(self, idx, value=0.0, *, into=None)

Set the elements in columns < idx to value (default 0), in place or into= a copy: the mask for a ragged last tile. idx may be a device Int. Strips take left_fill_ and right_fill_ only.

Tile.right_fill_

Tile.right_fill_(self, idx, value=0.0, *, into=None)

Set the elements in columns >= idx to value (default 0), in place or into= a copy: the mask for a ragged last tile. idx may be a device Int. Strips take left_fill_ and right_fill_ only.

Tile.upper_fill_

Tile.upper_fill_(self, idx, value=0.0, *, into=None)

Set the elements in rows < idx to value (default 0), in place or into= a copy: the mask for a ragged last tile. idx may be a device Int. Not on strips.

Tile.lower_fill_

Tile.lower_fill_(self, idx, value=0.0, *, into=None)

Set the elements in rows >= idx to value (default 0), in place or into= a copy: the mask for a ragged last tile. idx may be a device Int. Not on strips.

Tile.triu_

Tile.triu_(self, idx, value=0.0, *, into=None)

Keep the upper triangle from diagonal idx, the rest set to value (default 0), in place. Not on strips.

Tile.tril_

Tile.tril_(self, idx, value=0.0, *, into=None)

Keep the lower triangle from diagonal idx, the rest set to value (default 0), in place. Not on strips.

Tile.as_fragment

Tile.as_fragment(self, ty, *, fmt: str = 'fp8') -> Tile

This i32 strip's registers as a matrix-core operand fragment, no data moved (gfx950): lane l's elements, in the strip's per-lane order (rows, chunks, runs), become lane l's dwords of ty -- the inverse of lane_strip on 32-bit data. For operands gathered with load_elems(runs=True) from a layout no tile load knows, or kept in LDS as words.

ty is the 16x128 fp8 e4m3 row tile (hk.RT(hk.fp8e4m3, 16, 128)) a block-scaled MMA reads (Tile.scaled). fmt="fp8": eight dwords a lane, a strip of 1 x 512 at run 4 -- run 0 the K step's 16 bytes at K 16 (l / 16) .., run 1 those at 64 + 16 (l / 16) .., of row l % 16: the fragment a tile load makes. fmt="fp4": four dwords a lane, a strip of 1 x 256 at run 4 -- lane l's 32 FP4 values being row l % 16, columns 32 (l / 16) .. + 32 -- in the FP4 container (its upper half undefined).

Tile.as_scales

Tile.as_scales(self) -> MxScales

This i32 strip (1 x 64, run 1) as loose E8M0 scales of a 16x128 operand, no data moved (gfx950): lane l's element, the byte in bits 0..7, is the scale of row l % 16, block l / 16 -- Tile.scaled takes it.

Tile.scaled

Tile.scaled(self, scales: MxScales, *, fmt: str = 'fp8', at=(0, 0)) -> Scaled

This operand with its E8M0 block scales, for gfx950's block-scaled MFMA: hk.mma("mma_ABt", a.scaled(sa), b.scaled(sb, fmt="fp4"), acc). fmt is "fp8" (e4m3) or "fp4" (the FP4 container hk.load_fp4_frags fills). at = (tile, step): the scales may cover more than the operand -- its 16-row base tile i and 128-wide step s take the scales' tile i + tile and step s + step (a 32-row block's two-step AITER dwords, loaded once, feeding two token tiles over two steps).

Tile.as_operand

Tile.as_operand(self, dtype: Optional[DType] = None, *, k_order: str = 'natural', into=None) -> Tile

Surface: k_order=: RDNA3's (gfx1100) paired WMMA operand: a 32-row fp32 S^T pair as its even and odd P^T operands.

This accumulator's registers read as an MFMA operand: no data moves across lanes (gfx950). On RDNA (wave32) the same call is the accumulator's col-layout cast, .to(dtype): the WMMA operand it feeds, so a P.V written this way builds on both. k_order="even_odd" is RDNA3's paired form (gfx1100), below.

self is a col-layout tile in an accumulator fragment -- an MFMA result, or its cast to bf16. Each lane holds a column and four rows at a time; read as a stride-4 operand fragment (32x32 -> 16x32/4, 16x16 -> 32x16/4), its rows are the reduction index in another order, and an MMA whose other operand has the same stride (hk-fragments lays it out so) computes the same product. So with the scores kept transposed, o_t += v.T @ p_t.as_operand(bf16) is P·V straight off the softmax, with no reshuffle across lanes. dtype converts an fp32 accumulator on the way (to nearest even); a 16-bit one is read as it is.

k_order="even_odd" (gfx1100): a 32x16 fp32 col-layout pair of 16x16 WMMA accumulators (Sᵀ's kv rows [0, 16) and [16, 32)) as two fp16 operands, subtile(16, 0) the one whose K axis is the pair's 16 even rows and subtile(16, 1) the odd rows -- so a V whose rows are laid out in that order (even, then odd, a 32-row group) feeds P·V. Data moves: per packed dword one conversion, one permlanex16 and two selects, against a per-element exchange for the natural order.

Tile.subtile

Tile.subtile(self, rows: int, index: int) -> Tile

Rows [indexrows, (index+1)rows) of this tile, as a tile of rows rows that is the same registers: an op writing into it writes this tile (include/cdna4's subtile_inplace). index is a Python int -- a runtime one would index the register file. Not an LDS load's destination: load into the whole tile.

Tile.make_causal

Tile.make_causal(self, value: float = 0.0, *, into=None, transposed: bool = False)

Surface: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use Tile.tril_(0, v) / Tile.triu_(0, v).

Deprecated: tril_(0, value) (triu_(0, value) with transposed=True), which takes any diagonal. A copy of this tile with the elements above the diagonal set to value (below it with transposed=True), or into into; this tile is unchanged.

Tile.maximum

Tile.maximum(self, o, *, into=None)

Elementwise max with o (a value of this type or a number); hk.max(a, b).

Tile.minimum

Tile.minimum(self, o, *, into=None)

Elementwise min with o (a value of this type or a number); hk.min(a, b).

Tile.exp

Tile.exp(self, *, into=None)

hk.math.exp of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.exp2

Tile.exp2(self, *, into=None)

hk.math.exp2 of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.log

Tile.log(self, *, into=None)

hk.math.log of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.log2

Tile.log2(self, *, into=None)

hk.math.log2 of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.abs

Tile.abs(self, *, into=None)

hk.math.abs of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.relu

Tile.relu(self, *, into=None)

hk.math.relu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.gelu

Tile.gelu(self, *, into=None)

hk.math.gelu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.dgelu

Tile.dgelu(self, *, into=None)

hk.math.dgelu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.sqrt

Tile.sqrt(self, *, into=None)

hk.math.sqrt of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.rsqrt

Tile.rsqrt(self, *, into=None)

hk.math.rsqrt of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.silu

Tile.silu(self, *, into=None)

hk.math.silu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Tile.step

Tile.step(self, *, into=None)

1 where the element is positive, else 0: a comparison as a factor, x * (r - p).step() keeping where r > p. Register tiles and strips, not vectors.

Tile.copy

Tile.copy(self, *, into=None)

A copy in new registers, or into= an existing value.

Tile.swap_halves

Tile.swap_halves(self, span: Optional[int] = None, *, negate_first: bool = False, into=None)

A strip with the two halves of each span-column segment of its rows exchanged (span None: the whole row): in a segment's first half column c takes column c + span/2, in its second c - span/2. negate_first negates what lands in the first half -- NeoX's rotate_half, [x1 | x2] -> [-x2 | x1] (rotate_half(span) is this). Strips only, on the wave64 port (gfx950). The halves are whole chunks apart (a register swap) or 8, 16 or 32 lanes apart (a DPP row_ror:8, a v_permlane16_swap, a v_permlane32_swap): a whole row of one chunk or of an even number of them, or a head of span columns -- a 128-column head at eight bf16 a lane is 16 lanes, its halves eight apart.

Tile.rotate_half

Tile.rotate_half(self, span: int, *, into=None)

NeoX's rotate_half on each span-column segment of a strip's rows: [x1 | x2] -> [-x2 | x1], one head of span columns a segment -- swap_halves(span, negate_first=True).

Tile.exp_

Tile.exp_(self)

exp in place: this value's registers.

Tile.exp2_

Tile.exp2_(self)

exp2 in place: this value's registers.

Tile.rsqrt_

Tile.rsqrt_(self)

rsqrt in place: this value's registers.

Tile.zero_

Tile.zero_(self)

Fill with 0, in place.

Tile.fill_

Tile.fill_(self, v: float)

Fill with v, in place.

Tile.neg_infty_

Tile.neg_infty_(self)

Fill with -inf, in place.

Tile.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.Vec

A register vector: one value per row (col kind) or column (row kind) of the tile it came off.

Vec.max_

Vec.max_(self, r: Reduction) -> Vec

Fold t.max(axis=...), or another partial max (a vector), into this vector: the online max. A reduction's NaN and signed-zero rules either way (docs/language.md); maximum is the elementwise op.

Vec.min_

Vec.min_(self, r: Reduction) -> Vec

Fold t.min(axis=...) into this vector: the running min.

Vec.any_ne

Vec.any_ne(self, other: Vec) -> Int

Wave-level: did any entry differ from other. A uniform branch.

Vec.any_above

Vec.any_above(self, other: Vec, threshold: float) -> Int

Wave-level: did any entry exceed other's by more than threshold. A uniform branch. The online softmax's lazy rescale: keep taking exp2 against a stale running max until the new one is more than threshold (log2 units) above it.

Vec.maximum

Vec.maximum(self, o, *, into=None)

Elementwise max with o (a value of this type or a number); hk.max(a, b).

Vec.minimum

Vec.minimum(self, o, *, into=None)

Elementwise min with o (a value of this type or a number); hk.min(a, b).

Vec.exp

Vec.exp(self, *, into=None)

hk.math.exp of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.exp2

Vec.exp2(self, *, into=None)

hk.math.exp2 of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.log

Vec.log(self, *, into=None)

hk.math.log of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.log2

Vec.log2(self, *, into=None)

hk.math.log2 of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.abs

Vec.abs(self, *, into=None)

hk.math.abs of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.relu

Vec.relu(self, *, into=None)

hk.math.relu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.gelu

Vec.gelu(self, *, into=None)

hk.math.gelu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.dgelu

Vec.dgelu(self, *, into=None)

hk.math.dgelu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.sqrt

Vec.sqrt(self, *, into=None)

hk.math.sqrt of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.rsqrt

Vec.rsqrt(self, *, into=None)

hk.math.rsqrt of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.silu

Vec.silu(self, *, into=None)

hk.math.silu of this value: a new value, or into= an existing one. See docs/api/hk.math.md for the dtypes each takes.

Vec.step

Vec.step(self, *, into=None)

1 where the element is positive, else 0: a comparison as a factor, x * (r - p).step() keeping where r > p. Register tiles and strips, not vectors.

Vec.copy

Vec.copy(self, *, into=None)

A copy in new registers, or into= an existing value.

Vec.swap_halves

Vec.swap_halves(self, span: Optional[int] = None, *, negate_first: bool = False, into=None)

A strip with the two halves of each span-column segment of its rows exchanged (span None: the whole row): in a segment's first half column c takes column c + span/2, in its second c - span/2. negate_first negates what lands in the first half -- NeoX's rotate_half, [x1 | x2] -> [-x2 | x1] (rotate_half(span) is this). Strips only, on the wave64 port (gfx950). The halves are whole chunks apart (a register swap) or 8, 16 or 32 lanes apart (a DPP row_ror:8, a v_permlane16_swap, a v_permlane32_swap): a whole row of one chunk or of an even number of them, or a head of span columns -- a 128-column head at eight bf16 a lane is 16 lanes, its halves eight apart.

Vec.rotate_half

Vec.rotate_half(self, span: int, *, into=None)

NeoX's rotate_half on each span-column segment of a strip's rows: [x1 | x2] -> [-x2 | x1], one head of span columns a segment -- swap_halves(span, negate_first=True).

Vec.exp_

Vec.exp_(self)

exp in place: this value's registers.

Vec.exp2_

Vec.exp2_(self)

exp2 in place: this value's registers.

Vec.rsqrt_

Vec.rsqrt_(self)

rsqrt in place: this value's registers.

Vec.zero_

Vec.zero_(self)

Fill with 0, in place.

Vec.fill_

Vec.fill_(self, v: float)

Fill with v, in place.

Vec.neg_infty_

Vec.neg_infty_(self)

Fill with -inf, in place.

Vec.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.Global

A global tensor parameter, 4D (b, d, r, c).

x[idx] is a view at a coordinate; x.at[r, c] builds an element coordinate and x.tile[r, c] a tile one, left-padding with zeros.

Global.batch (property)

The tensor's extent along axis 0 of (batch, depth, rows, cols), a device Int.

Global.depth (property)

The tensor's extent along axis 1, a device Int.

Global.rows (property)

The tensor's rows (axis 2), a device Int. A 2-D tensor is (rows, cols).

Global.cols (property)

The tensor's columns (axis 3), a device Int.

Global.dtype (property)

The element dtype the parameter was annotated with.

Global.at (property)

Element indexing: x.at[r, c] (or [b, d, r, c]) is a View at that element; a load reads the tile that starts there.

Global.tile (property)

Tile indexing: x.tile[r, c] is a View at tile (r, c) of the tile type the load names.

Global.load_elems

Global.load_elems(self, idx: Tile, dtype: Optional[DType] = None, *, runs: bool = False, row=None) -> Tile

Element by element at computed indices (gfx950): element (r, c) of the result is element idx[r, c] of this tensor, counted flat (rows over batch and depth, at the row stride), converted to dtype (fp32 or i32; default fp32, i32 for an i32 tensor). An index below zero or past the tensor reads 0 -- a table lookup with a fallback, a key table's slots. idx is an i32 strip (hk.map_cpp computes one).

runs=True: the kernel says each lane's run comes from consecutive elements from its first element's index, aligned to the run's bytes; the run is one load (1, 2, 4, 8 or 16 k bytes), read as 0 if that first index is out of range -- a lane's 4 fp32 in one 16-byte load, not four gathered ones. row: as store_elems.

Global.store_elems

Global.store_elems(self, val: Tile, idx: Tile, *, runs: bool = False, row=None) -> None

Element by element at computed indices (gfx950): element (r, c) of val (an fp32 or i32 strip), converted to this tensor's type, to element idx[r, c] (flat, as load_elems). An index below zero or past the tensor writes nothing: -1 masks an element out. Two elements to one index race.

runs=True: the kernel says each lane's run goes to consecutive elements from its first element's index, aligned to the run's bytes; the run is one store (1, 2, 4, 8 or 16 k bytes), masked by that first index -- 8 fp8 values in one 8-byte store, not eight.

row (a device Int): the indices count from that row, whose base is formed in 64 bits and whose range is the one row -- a tensor past a 32-bit offset (a paged cache of many GB) addressed a row (block) at a time.

Global.post_elems

Global.post_elems(self, val: Tile, idx: Tile, tag, *, runs: bool = False, bf16: bool = False) -> None

Tagged mailbox pairs, an element at a time (gfx950): element (r, c) of val (fp32 or i32 strip) and tag go to pair idx[r, c] of this scoped int32 tensor (int32 elements 2 i, 2 i + 1) as one 8-byte store of its scope; an index below zero posts nothing. No drain -- the value travels with its tag -- so a hand-off between CTAs is one store and, on the other side, one poll (dsv41_mono's Mailbox; hk.comm.post for one scalar).

runs=True: each lane's run goes to consecutive pairs from its first element's index (the lane's other indices are not read), two pairs a 16-byte store; the run is a whole number of pairs of pairs. bf16=True (with runs): two values a pair, as bf16 -- the TOP HALVES of the fp32 values, so they must already be bf16 values (rounded by the caller); the pairs from a run's first index are then run / 2.

Global.take_elems

Global.take_elems(self, idx: Tile, tag, dtype: Optional[DType] = None, *, timeout_s: float = 2.0, runs: bool = False, bf16: bool = False) -> Tile

The other side of post_elems: element (r, c) is the value of pair idx[r, c] once its tag is tag; every element's pair is loaded with the tensor's scope, and all are re-loaded (s_sleep between) while any is stale. An index below zero is ready at 0. dtype: fp32 (default) or i32. After timeout_s the kernel traps (0: never) -- a lost post is an error, not a hang. runs=True / bf16=True: the layout post_elems wrote with them.

Global.gather

Global.gather(self, tile, ids, at=None, *, count=None, col=0, div=None, into=None) -> Tile

Surface: div=: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use hk.RowIndex(div=).

Rows by index: tile row r is row ids[at + r] of this tensor (rows flattened over batch and depth), from column col -- ids an hk.RowIndex, which also says how an index names a row (div), or an int32 tensor and at (and count). An index outside the tensor, or a position at or past count (default: all of ids), reads zeros -- the padding a MoE sort fills its index list with costs no branch. div= here is deprecated: hk.RowIndex(ids, at, div=...).

Global.scatter

Global.scatter(self, value: Tile, ids, at=None, *, count=None, col=0, sort_topk: Optional[int] = None, add: bool = False, staged: Optional[int] = None) -> None

Surface: sort_topk=: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use hk.RowIndex(sort_topk=).

Surface: staged=: deprecated, removed in the release after the last call from outside the repository is migrated, at most two minor releases after its deprecation; use an index staged by Group.stage_rows.

Surface: add=: atomic scatter-add, in no fixed order: not for a route that promises determinism.

Rows by index: tile row r goes to row ids[at + r], from column col -- ids an hk.RowIndex, or an int32 tensor and at (and count). An index outside the tensor, or a position at or past count, writes nothing. Two rows naming one row race. With an index of AITER's MoE sort ids (RowIndex(..., sort_topk=k): token | choice << 24) this tensor is [k * M, ...] choice-major -- row r goes to row choice * M + token, and padding (token >= M) nowhere.

add=True adds the rows atomically instead (an fp32 or bf16 global; bf16 adds element pairs, gfx950's global_atomic_pk_add_bf16). With sort ids the tensor is then [M, ...] and every choice of a token adds into its row: the top-k reduce, in no fixed order -- the result varies run to run by the rounding of the adds.

An index staged in LDS by g.stage_rows(ix, N, keep_choice=True) is read there: a global index load is a vmcnt wait, which on gfx950 retires every load and store issued before it, in order -- in an epilogue between K loops, the next loop's whole prefetch and this epilogue's own earlier stores (K1 k1-prefill c36). sort_topk= and staged= here are deprecated: they are hk.RowIndex's and g.stage_rows'.

Global.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.View

A global at a coordinate: what a load reads and a store writes.

View.load

View.load(self, tile, *, into: "Optional['Value']" = None, bounded=False, period: Optional[int] = None)

Global -> register tile or vector. The element type converts on the way in, for free. bounded=True predicates rows past the global's last (they read zero and touch no memory); bounded=n, an int or a device Int, also predicates rows at or past n counted from the tile's first -- for a tile whose rows end before the tensor's.

period (a strip, unbounded): column c of the strip reads column c % period from the view's -- period values repeated along it, as one token's angles under each of its heads.

View.store

View.store(self, value, *, bounded=False) -> None

Register tile or vector -> global. bounded as for load: True drops rows past the global's last, n also rows at or past n.

View.load_scalar

View.load_scalar(self, *, invariant: bool = False) -> Int

One int32 element -> a wave-uniform scalar (a page index, a length).

invariant: nothing writes the element while the kernel runs (a page table, the sequence lengths), so on gfx950 it is a scalar load (s_load_dword), counted on lgkmcnt -- not a vector load whose wait also waits out every copy issued before it.

View.store_scalar

View.store_scalar(self, vec: Vec) -> None

One entry of a uniform register vector -> one element.

View.atomic_add

View.atomic_add(self, value: Tile) -> None

Add an fp32 tile into this float global, element by element, atomically: the reduction for partials in different workgroups.

View.atomic_add_scalar

View.atomic_add_scalar(self, value) -> Int

One int32 atomic add per warp; the element's value before it, in every lane. W warps that call it add W times.

View.atomic_max_scalar

View.atomic_max_scalar(self, value) -> Int

One int32 atomic max per warp; the value before it.

View.atomic_min_scalar

View.atomic_min_scalar(self, value) -> Int

One int32 atomic min per warp; the value before it.

View.atomic_or_scalar

View.atomic_or_scalar(self, value) -> Int

One int32 atomic or per warp; the value before it (a set of flags: bit w = workgroup w).

View.atomic_and_scalar

View.atomic_and_scalar(self, value) -> Int

One int32 atomic and per warp; the value before it.

View.atomic_xor_scalar

View.atomic_xor_scalar(self, value) -> Int

One int32 atomic xor per warp; the value before it.

View.atomic_exch_scalar

View.atomic_exch_scalar(self, value) -> Int

One int32 atomic exchange per warp: stores value, returns the value before it (a lock's take, a slot's claim). W warps that call it exchange W times.

hk.SharedTile

An LDS tile, or a stack of them (As[i] picks one).

SharedTile.load_elems

SharedTile.load_elems(self, idx: Tile, dtype: Optional[DType] = None, *, runs: bool = False) -> Tile

Element by element from this fp32 LDS tile (gfx950): element (r, c) of the result is element idx[r, c] (row-major, through the tile's swizzle) -- fp32, or its bits as i32 with dtype=hk.i32; below zero or past the tile, 0. A CTA's own exchange between warps without a round trip to global memory (whose drain would also wait out every load in flight). Another warp's writes need hk.arch.barrier(drain=True) between.

runs=True: the kernel says each lane's run (a multiple of 4) is consecutive elements from 16-byte-aligned indices; each 4 is one 16-byte read (b32 reads of a lane's 4 consecutive elements conflict 4 ways across the wave). Index flat into a tile 16 columns wide: a wider one lays every 16th element a subtile (1 KB) on, on the same banks.

SharedTile.store_elems

SharedTile.store_elems(self, val: Tile, idx: Tile) -> None

Element by element into this fp32 LDS tile (gfx950): val's element (r, c) (fp32, or i32 bits) to element idx[r, c] (row-major); below zero or past the tile, nothing. Before another warp reads it: hk.arch.barrier(drain=True). A bf16 tile takes the fp32 value rounded to bf16 (round to nearest even) -- an MMA operand built element by element, read back with .load / .subtile(...).load.

SharedTile.atomic_add_elems

SharedTile.atomic_add_elems(self, val: Tile, idx: Tile) -> None

Element by element, atomically (gfx950): val's element (r, c), an i32, is added to element idx[r, c] of this fp32 LDS tile taken as an i32 (ds_add_u32); below zero or past the tile, nothing. Every element to one index lands: a histogram's counts. Read the counts with load_elems(..., i32) after hk.arch.barrier(drain=True).

SharedTile.subtile

SharedTile.subtile(self, rows: int, cols: int, row: Scalar = 0, col: Scalar = 0) -> SharedTile

A rows x cols window, indexed in units of itself; a view, so the swizzle still applies and loads still vectorise.

SharedTile.load

SharedTile.load(self, tile: RegTileType, *, wait: bool = True, into=None) -> Tile

LDS -> register tile. wait=False leaves the reads in flight; the tile must then be named in hk.lds.wait_for before it is read.

SharedTile.store

SharedTile.store(self, value: Tile) -> None

Register tile -> LDS.

SharedTile.granules

SharedTile.granules(self, name: str = 'gr') -> Granules

Surface: an escape hatch, used only within its boundary: the same as hk.Granules'.

Factor this tile's addressing into swizzle_bytes/16 registers, so a loop reading many fragments holds those and not one address each.

SharedTile.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.SharedVec

A stack of LDS vectors: the only way across the warps of a workgroup.

SharedVec.store

SharedVec.store(self, vec: Vec, index: Scalar = 0) -> None

Write a register vector into slot index of the stack (no barrier: put one before another warp reads it).

SharedVec.load

SharedVec.load(self, vt: RegVecType, index: Scalar = 0) -> Vec

Read slot index of the stack as a register vector of type vt.

SharedVec.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.Granules

Surface: an escape hatch, used only within its boundary: gfx11 kernels whose LDS address registers are the measured limiter; not on CDNA.

One shared tile's per-lane LDS addresses.

Granules.load_frag

Granules.load_frag(self, row: int, col: int, tile: RegTileType, *, into=None) -> Tile

Surface: an escape hatch, used only within its boundary: the same as hk.Granules'.

One 16x16 fragment at (row, col), in units of 16. Never waits.

Granules.store_frag

Granules.store_frag(self, value: Tile, row: Scalar, col: int) -> None

Surface: an escape hatch, used only within its boundary: the same as hk.Granules'.

One 16x16 fragment into the tile; row may be a runtime value.

Granules.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.MxScales

E8M0 block scales of an fp8 operand tile, in the lanes the scaled MFMA reads them from (load_mx_scales). An operand takes them with Tile.scaled.

MxScales.copy

MxScales.copy(self, *, into: MxScales) -> MxScales

into = these scales, register to register -- how a one-stage loop body hands the next K-tile's prefetched scales to the current set. Returns into.

MxScales.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.Scaled

An MX operand: an fp8 e4m3 row tile (FP4 in its container with fmt="fp4") and its E8M0 scales, made by Tile.scaled. hk.mma("mma_ABt", a.scaled(sa), b.scaled(sb), acc) is gfx950's block-scaled MFMA; nothing else takes one.

hk.RowIndex

Which rows a gather, a scatter or a gathered LDS copy moves: row r of the tile is named by ids[at + r], an int32 global, for positions below count (default: all of ids) -- and how such an index names a row:

  • plain: it is the row;
  • div=k: the row is ids[at + r] // k (a MoE's top-k, its sorted list counting (token, choice) pairs); for a gather;
  • sort_topk=k: AITER's MoE sort ids, token | choice << 24, padding token >= M. A gather or a gathered copy reads the token's row; a scatter writes row choice * M + token of a [k * M, ...] tensor, and with add=True adds into the token's row.

Positions at or past count, padding and indices outside the tensor read zero and write nothing. g.stage_rows(ix, rows) copies [at, at + rows) into LDS and returns the staged index the copies then read there (no vmcnt wait for an index). Made in the kernel body; no instruction of its own.

RowIndex.offset

RowIndex.offset(self, n) -> RowIndex

The same index from position at + n (a later tile of the same block). A staged index stays staged: [at, at + n + the tile's rows) must lie inside what was staged.

RowIndex.staged

RowIndex.staged(self, rows: int, *, keep_choice: bool = False) -> RowIndex

This index as g.stage_rows(self, rows, keep_choice=...) stages it, without the copy: for code written before the place that stages it (a loop body's copies, defined above the loop). A consumer still refuses it until a stage_rows has made that copy.

hk.Int

A wave-uniform 32-bit integer: an index, an extent, a loop counter.

Python's operators build device arithmetic; // and % are C++'s truncating division and remainder, which agree with Python's on the non-negative values an index takes.

Int.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.Bool

A comparison's answer: steers an if, or combines with & | ~.

Bool.to_int

Bool.to_int(self) -> Int

1 where true, else 0, as an Int.

Bool.type (property)

The value's hk type (RegTileType, RegVecType, ...).

hk.Coord

A (b, d, r, c) index, in tiles or in elements.

Coord.unit (property)

"tile" or "element".

Coord.type (property)

The value's hk type (RegTileType, RegVecType, ...).

Namespaces

Runtime, errors and the rest

hk.VerifyError

The kernel is wrong or unbuildable. Never downgrade one of these.

hk.CompileError

Common base class for all non-exit exceptions.

hk.ResourceError

A kernel that must not be used. Raised, never warned about.

hk.Build

class hk.Build(key: str, module_name: str, so_path: Path, source_path: Path, log_path: Path, kernels: List[KernelResources], cached: bool) -> None

One compiled artifact and everything used to judge it.

Build.report

Build.report(self) -> str

One line per instantiation: vgpr, occupancy, LDS, scratch, spills (KernelResources.line). python -m hk.check reports the same with the occupancy LDS allows.

hk.get_target

hk.get_target(arch: str)

Look up a target by gfx name or by the GPU_TARGET name common.mk uses.

hk.TARGETS

The known targets by gfx name, hk.target.Target records: see hk.target.

hk.detect_arch

hk.detect_arch() -> Optional[str]

The local GPU's gfx name, or None. Cached: probing costs a subprocess and the answer cannot change within a process.

hk.torch_op

hk.torch_op(kernel, *, ns: str = 'hk', name: str = '', **const_overrides)

Build, load and return torch.ops.<ns>.<name>.

Memoised on (ns, name): the second call in a process returns the same op rather than re-registering it, which torch refuses with "Tried to register an operator with the same name twice".

By default it is registered over a device-only code object (hk.runtime.codeobj): the same schema and checks, without compiling libtorch's headers -- 1.1-1.5 s a kernel on the pod where this registration takes 15 (tools/hk-bench/compile_time.py), and the same time a layer inside vLLM's decode graphs. HK_TORCH_OP=library builds the libtorch registration below instead.

hk.attention

hk.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

Tools

  • hk.check(fn, reference, inputs), python -m hk.check: correctness, resources and timing in one call: hk.check, docs/check.md.
  • hk.profile(fn, inputs), python -m hk.profile: why it runs at that speed -- counters, the thread trace, the main loop's instructions and a verdict: hk.profile, docs/profile.md.

Also exported

hk.fp4_operand, hk.fp8_operand, hk.gemv_w4, hk.lane_coords, hk.mx, hk.mx_scales_loose, hk.specialize, hk.templates