hk.templates¶
Stability: stable, except where an entry says otherwise (stability).
hk.templates: complete, tuned kernels with hooks for the part that is yours.
A template owns the tiling, the layout, the per-architecture plan and the
schedule; the hook is a traced function (like an @hk.func body) for the
math that makes the kernel yours -- an elementwise function, a row
reduction's epilogue, a GEMM's epilogue, an attention score modifier.
docs/archive/design/dx-goal.md says what they are for and how they are judged.
Each template lives in its own module and is imported on first use, so the modules are independent of one another.
hk.templates.elementwisehk.templates.gemmhk.templates.metahk.templates.per_colhk.templates.per_rowhk.templates.pickhk.templates.row_lengthhk.templates.row_logsumexphk.templates.row_maxhk.templates.row_meanhk.templates.row_minhk.templates.row_sumhk.templates.rowwisehk.templates.scalar
Each template has a guide in docs/templates.
hk.templates.elementwise¶
hk.templates.elementwise(fn: Optional[Callable] = None, inputs: Optional[Sequence] = None, outputs: Any = None, *, name: Optional[str] = None, arch: Optional[str] = None, plan: Optional[Dict[str, int]] = None)
A pointwise kernel from fn, the math of one element.
gelu_and_mul = hk.templates.elementwise(lambda g, u: hk.math.gelu(g) * u)
y = gelu_and_mul(gate_up[:, :d], gate_up[:, d:])
fn takes one tile per operand -- fp32 register strips; a load widens
and a store rounds -- and returns a tile, or a tuple of them for several
outputs. Its parameters with defaults are constexprs, overridable per
call: fn = lambda x, b, *, ALPHA=1.0: ..., k(x, b, ALPHA=0.5).
inputs: the operands' kinds and dtypes, if you want them checked --
a dtype is a full operand, per_col(d) one value per column (a bias),
per_row(d) one per row, scalar(d) one value. Left out, they follow
from the tensors by torch's broadcasting. outputs: the output dtype
(the first full operand's by default), or a tuple of them. Operands may
be any (rows, cols) view whose last axis is contiguous -- a slice of the
last axis is read in place -- with any leading axes.
The plan (layout, warps, the stretch a warp covers, the grid) is picked
per architecture; k.plan(*args) shows it and plan={"warps": ...,
"chunks": ..., "run": ..., "flat": ...} (or k.with_plan(...))
overrides it. Usable as a decorator: @hk.templates.elementwise.
hk.templates.gemm¶
hk.templates.gemm(a=None, b=None, *, epilogue=None, out=None, out_dtype=None, schedule=None, **operands)
hk.templates.gemm: a tuned GEMM whose store is yours.
import hk
def bias_gelu(acc, ctx): # acc: the fp32 accumulator tile
return (acc + ctx.bias).gelu() # ctx.bias: one value per column of C
y = hk.templates.gemm(x, w, epilogue=bias_gelu, bias=b) # gelu(x @ w.T + b)
C = epilogue(A @ Báµ€ accumulated in fp32, ctx), A (M, K) and B (N, K) bf16 as
in hk.ops.matmul, C (M, N) in out_dtype (bf16 by default; fp16, fp32, int8).
The GEMM is hk.ops.matmul's, shape for shape: on gfx1100 the WMMA kernel at
hk.ops.gemm.schedule_for's schedule (the tuned records included), on
gfx950 whichever of hk's kernels hk.ops.gemm_cdna.route picks -- the
256x256 pingpong, the four-warp blocks, the weight-streaming ones, the decode
GEMV, split-K. The epilogue is traced into the kernel where it stores C.
The epilogue is a traced function, like an @hk.func body: acc is a
register tile of C (its shape and lane layout are the kernel's, and are not
the epilogue's business), ctx what it can read:
ctx.<name> an operand passed to gemm() by that name, loaded for this
tile in its layout and converted to fp32. What it is follows
torch's broadcasting against C (M, N):
(N,) or (1, N) a row vector: one value per column of C
-- a bias, a per-channel scale
(M, 1) a column vector: one value per row -- a
per-token scale
(M, N) a tile of C's shape -- a residual
a Python number baked into the kernel (a constexpr): a
value that changes per call is a tensor
ctx.row, ctx.col C's element coordinates of the tile's first element
ctx.m C's rows
It returns the tile to store (or None, having written acc in place). The
math is the language's: + - * / with tiles, vectors and numbers,
.gelu() (tanh), .silu(), .relu(), .exp(), .maximum(), ...
Where it runs: once per element of C, after the whole sum over K. A split-K
plan stores fp32 shares and runs the epilogue in the reduction that adds
them, never on a share, so an epilogue that is not linear (a GELU, a bias)
is right whatever the route; a linear one (a scale) would gain nothing from
running earlier, since the reduction is there anyway. plan() says, for a
shape, which kernels run and which of them carries the epilogue.
Ready-made epilogues are attributes of this function: gemm.bias,
gemm.gelu, gemm.bias_gelu, gemm.silu, gemm.bias_silu, gemm.relu,
gemm.bias_relu, gemm.residual, gemm.bias_residual, gemm.scale (its
operand a number, a row or a column vector), and gemm.chain(f, g, ...).
docs/templates/gemm.md has the plans and the measurements.
hk.templates.meta¶
hk.templates.meta(shape, dtype, stride=None) -> Meta
A stand-in for a tensor of this shape, dtype and strides (contiguous if not given), for planning and building without a GPU.
hk.templates.per_col¶
hk.templates.per_col(dtype: Optional[DType] = None) -> Operand
One value per column, a (cols,) tensor: a weight or a bias, the same for every row (torch's broadcasting of a 1-D tensor).
hk.templates.per_row¶
hk.templates.per_row(dtype: Optional[DType] = None, width: int = 1) -> Operand
One value per row, a (rows,) or (rows, 1) tensor: a token's scale, a
row's label. In a rowwise output, a per-row result (a scale, a loss);
width k makes it (rows, k), the hook returning k row values for it
(a top-k's ids and weights).
hk.templates.pick¶
hk.templates.pick(t, col) -> Vec
The element of operand t (a full operand as the hook received it)
at column col of this row -- a gather, as cross-entropy's target
logit: pick(logits, label). col is a device int (a per-row int32 or
int64 operand) or an int, clamped into the row, so an ignored label
(-100) reads column 0 instead of memory before the row.
hk.templates.row_length¶
hk.templates.row_length()
The row's length (a device int): what row_mean divides by.
hk.templates.row_logsumexp¶
hk.templates.row_logsumexp(t) -> Vec
log(sum(exp(t))) of each row of t, the whole row, max-shifted so it
does not overflow. Online: a row too wide to hold is read once for it,
where row_max then row_sum(exp(t - max)) read it twice. Softmax is
(x - row_logsumexp(x)).exp().
hk.templates.row_max¶
hk.templates.row_max(t) -> Vec
The max of each row of t, the whole row.
hk.templates.row_mean¶
hk.templates.row_mean(t) -> Vec
The mean of each row of t: row_sum(t) over the row's length.
hk.templates.row_min¶
hk.templates.row_min(t) -> Vec
The min of each row of t, the whole row.
hk.templates.row_sum¶
hk.templates.row_sum(t) -> Vec
The sum of each row of t -- the whole row, across every lane and
warp that holds a part of it: one value per row, broadcast against the
row's strips (x - row_sum(x) / n).
hk.templates.rowwise¶
hk.templates.rowwise(fn: Optional[Callable] = None, inputs: Optional[Sequence] = None, outputs: Any = None, *, like: Optional[str] = None, name: Optional[str] = None, arch: Optional[str] = None, plan: Optional[Dict[str, int]] = None)
A kernel that reduces each row and maps it, from fn, the math of
one row.
@hk.templates.rowwise
def rms_norm(x, w, *, EPS=1e-6):
return x * (hk.templates.row_mean(x * x) + EPS).rsqrt() * w
fn takes one value per operand: a full or per-column operand as an
fp32 strip of the row, a per-row float as a column vector, a per-row
int32 as a scalar. hk.templates.row_sum / row_max / row_min /
row_mean reduce the whole row. It returns a tile (a full output) or a
column vector (a per-row output), or a tuple. Its parameters with
defaults are constexprs, overridable per call (k(x, w, EPS=1e-5)).
inputs / outputs as hk.templates.elementwise's, plus per-row
outputs: outputs=(hk.i8, hk.templates.per_row(hk.fp32)). like
names the hk.ops kernel whose measured plan to take ("rms", "rmsw",
"addrmsw", "layer", "softmax", "quantize"); left out it follows from
the operands. plan={...} / k.with_plan(...) overrides warps,
chunks, run, steps (a multi-pass stream) and reserve; k.plan(*args)
shows what a call runs.
hk.templates.scalar¶
hk.templates.scalar(dtype: Optional[DType] = None) -> Operand
One value for the whole tensor, a () or (1,) tensor on the device.