Skip to main content

hk-dsl

PyPI CI License: MIT

Fast AMD GPU kernels in a few lines of Python. Write the math of an element, a row or a GEMM epilogue; hk-dsl turns it into a tuned kernel for the Radeon (gfx1100) or Instinct (gfx950) GPU you are on. For full control, write the kernel in HipKittens' tiles. Either way it is traced into an MLIR dialect whose passes refuse silent failures, translated to HipKittens C++, compiled by hipcc and called from torch. python -m hk.check says whether it is right and whether it beats torch.compile.

Quick start

pip install hk-dsl (ROCm's hipcc and a ROCm torch besides), then save a file:

# my_kernels.py
import hk
from hk import templates as T

gelu_and_mul = T.elementwise(lambda g, u: hk.math.gelu(g) * u)  # the math of one element

@T.rowwise                                                       # the math of one row
def rms_norm(x, w, *, EPS=1e-6):
    return x * (T.row_mean(x * x) + EPS).rsqrt() * w

def bias_gelu(acc, ctx):                                         # traced into a tuned GEMM's store
    acc += ctx.bias
    return hk.templates.gemm.gelu_tanh(acc)

def linear_bias_gelu(x, w, b):
    return hk.templates.gemm(x, w, epilogue=bias_gelu, bias=b)

call it with torch tensors:

import torch
from my_kernels import gelu_and_mul, rms_norm, linear_bias_gelu

x = torch.randn(4096, 2 * 14336, device="cuda", dtype=torch.bfloat16)  # a gate/up output
h = torch.randn(4096, 4096, device="cuda", dtype=torch.bfloat16)
w = torch.randn(4096, device="cuda", dtype=torch.bfloat16)
W = torch.randn(12288, 4096, device="cuda", dtype=torch.bfloat16) / 64
b = torch.randn(12288, device="cuda", dtype=torch.bfloat16)

y = gelu_and_mul(x[:, :14336], x[:, 14336:])  # the two halves, read in place
n = rms_norm(h, w)
z = linear_bias_gelu(h, W, b)                  # F.gelu(F.linear(h, W, b), approximate="tanh")

and check a kernel against torch:

python -m hk.check my_kernels.py:rms_norm \
    --ref "lambda x, w: x * torch.rsqrt((x * x).mean(-1, keepdim=True) + 1e-6) * w" \
    --inputs "bf16[4096,4096], bf16[4096]"

hk.check reports registers, occupancy and spills, the error against the reference, and the time against torch eager and torch.compile; it exits 0 (pass), 1 (wrong) or 2 (error). Each block runs as shown on a W7900D and an MI355X. Guides: elementwise/rowwise, GEMM epilogues, hk.check.

Results at a glance

Speedup of hk.templates over torch.compile, W7900D then MI355X: GELU-and-mul 1.03x, 1.11x; the same op on 16x64 tiles 0.83x, 0.78x; add+RMSNorm+int8 1.17x, 1.45x; cross-entropy 1.58x, 2.50x; MoE router 7.37x, 9.06x; linear+bias+GELU 1.68x, 1.20x; linear+residual 1.71x, 1.20x.

Hollow: the same op by hand on 16x64 tiles, the slow way. The chart's script reads the committed tables.

Radeon PRO W7900D (gfx1100) Instinct MI355X (gfx950)
templates against hk's tuned kernel for the same job 0.92-1.02x 0.98-1.03x
GEMM + epilogue against torch.compile faster at 48 of 48 layer shapes, geomean 1.69x faster at 46 of 48, level at 2
vLLM, Qwen3-8B, per request against stock (A1, B1) 1.22-1.85x at 1-32 requests (vLLM 0.31.0, torch 2.13.0+rocm7.2, triton-rocm 3.7.1) 1.13x at 16, 1.21x at 64
bf16 GEMM against the field (A2, B2) ties FlyDSL, 1.28-1.39x hipBLASLt 0.9x or better of the best at all 122 LLM shapes
where it loses (A4, B4) paged decode 0.86-1.12x Triton's GEMMs 0.79-1.21x aiter's, norms 0.74-1.05x, MoE 0.66-0.94x CK's

One GPU of each; every comparison interleaved in one process. Performance has the method, the software stack of every table and every loss.

The language, when you need control

import hk

@hk.kernel(grid=lambda p: (p.o.rows * hk.cdiv(p.o.cols, p.CW), 1, 1))
def gelu_mul(a: hk.Tensor[hk.bf16], b: hk.Tensor[hk.bf16], o: hk.Tensor[hk.bf16], *, CW=512):
    S = hk.RS(hk.fp32, 1, CW, 8)                  # a register strip: one row, 8 bf16 (16 B) a lane
    per_row = hk.cdiv(o.cols, CW)
    row = hk.arch.block_idx.x // per_row
    c0 = (hk.arch.block_idx.x - row * per_row) * CW
    x = a.at[row, c0].load(S, bounded=True)       # bf16 -> fp32 on the load; past the end reads 0
    x.gelu(into=x)                                # hk.math.gelu: the tanh form, fp32 only
    x *= b.at[row, c0].load(S, bounded=True)
    o.at[row, c0].store(x, bounded=True)          # fp32 -> bf16 on the store

print(gelu_mul.trace().dump())      # the hk MLIR module -- needs nothing
print(gelu_mul.source())            # the HipKittens C++ -- needs nothing
print(gelu_mul.build().report())    # hipcc and the resource gate -- no GPU

It ties torch.compile on an MI355X (check). More: the language, examples.

On gfx950 a kernel can also hand work between workgroups, XCDs and GPUs: hk.comm has scoped tensors, signal / wait with a timeout instead of a hang, work queues, grid barriers, tagged mailboxes and symmetric memory across GPUs, each lowered to what a memory-model litmus suite found correct (hk.comm, design, a task graph). Which XCD runs which workgroup is a compiler pass: hk.kernel(placement="auto") keeps a sharing cluster on one XCD where that measured faster, with outputs bitwise the unplaced kernel's (placement, an example). For kernels that must match another implementation bit for bit, strips take a C++ expression per element (hk.map_cpp), i32 elements, stated reduction orders and element-wise exchange (strips).

flowchart LR
    A["kernel body<br/>or template hook"] -->|trace| B["hk MLIR dialect"]
    B -->|"passes: waits, LDS,<br/>layouts, races"| C["HipKittens C++"]
    C -->|"hipcc + resource gate"| D["code object"]
    D -->|launch| E["torch, vLLM, SGLang"]

The passes refuse what fails silently: an MMA above its wait, a spill, a slow operand layout, a copy racing a barrier (the traps).

Where it runs

GPU arch status
Radeon PRO W7900 / W7900D, RX 7900 gfx1100, RDNA3 primary: every kernel, template and engine patch
Instinct MI355X gfx950, CDNA4 every kernel and template; vLLM end to end (CDNA)
Radeon AI PRO R9700, RX 9070 gfx1201, RDNA4 the GPU tier runs (chapter 47); no engine route validated, nothing tuned yet
Instinct MI300X gfx942, CDNA3 compile-only, no templates

Install

pip install hk-dsl, for CPython 3.10 or 3.12 on Linux x86_64 with glibc 2.35 or newer (Ubuntu 22.04 and later). The release is 0.8.0: one manylinux_2_35 wheel for cp310 and one for cp312, both built on glibc 2.35. A wheel carries the HipKittens headers, so at run time it needs ROCm's hipcc (on PATH, or HK_HIPCC; tested with ROCm 7.2 and the ROCm 10 of vLLM's image) and, to launch, a ROCm build of torch (not a dependency). From source, with the HipKittens submodule:

git clone --recursive https://github.com/vivienfanghuagood/hk-dsl.git && cd hk-dsl
scripts/build_mlir.sh && scripts/build_hk_mlir.sh   # MLIR 23.1.3 (~20 min on 64 cores), then hk (~1 min)
export PYTHONPATH=$PWD/python

Details: getting started, building.

In vLLM and SGLang

hk is on by default. Installed, hk's vLLM and SGLang plugins apply every route that was validated with real weights on your GPU: its outputs were bit-identical to the engine's, or its error was within the engine's own noise. On an MI355X that is K1 and K2 for DeepSeek-V4.1. On a W7900D it is linear, MoE, AWQ and attention. Each route sends a shape to hk's kernel only where hk measured faster (integration). Turning it off is for comparisons:

vllm serve Qwen/Qwen3-8B                         # hk on: the routes validated on this GPU
HK_DISABLE=1 vllm serve Qwen/Qwen3-8B            # stock vLLM: nothing patched
HK_VLLM_GEMM=0 vllm serve Qwen/Qwen3-8B          # one route off (HK_<ROUTE>=0)
python3 -m hk.integration --status               # which routes are on, and why

If the installed engine does not match the contract the routes were measured against, hk patches nothing and prints one warning line. ConvRot INT8 is lossy, so it stays opt-in (HK_SGLD=attn,linear,convrot).

For coding agents

llms.txt (or llms-full.txt, every doc in one file), the hk-kernel skill, the generated API reference, and python -m hk.check FILE.py:NAME --json - as the loop's one command (--arch gfx1100,gfx950 builds for the GPU that is not in the machine).

Documentation

Getting started · templates · hk.check · the language · workgroup placement · API · performance · everything, and why hk-dsl exists · changelog

Contributing, license, acknowledgements

Issues and pull requests welcome: testing, how numbers are taken. MIT (LICENSE). hk-dsl began in a fork of HipKittens (HazyResearch), whose headers stay under its MIT License (NOTICE) and which brings ThunderKittens' tiles to AMD GPUs. The control-flow rewrite follows CUTLASS's CuTe DSL.

Metadata

Release files for hk-dsl 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for hk-dsl 0.8.0
File Interpreter ABI Platform Actions
hk_dsl-0.8.0-cp312-cp312-manylinux_2_35_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.35+ x86-64 Details for hk_dsl-0.8.0-cp312-cp312-manylinux_2_35_x86_64.whl
hk_dsl-0.8.0-cp310-cp310-manylinux_2_35_x86_64.whl CPython 3.10 CPython 3.10 Linux glibc 2.35+ x86-64 Details for hk_dsl-0.8.0-cp310-cp310-manylinux_2_35_x86_64.whl

Total release size: 24.6 MB

Release files / hk_dsl-0.8.0-cp312-cp312-manylinux_2_35_x86_64.whl

Download URL hk_dsl-0.8.0-cp312-cp312-manylinux_2_35_x86_64.whl
Size 12.3 MB
Tags CPython 3.12 Linux glibc 2.35+ x86-64
SHA-256 checksum
How to use checksums
c0530440a450b0bbebbd0a827e32b7d2778de0fb8e0b261bc168d20d5ec6ef4c
BLAKE2b-256 checksum
How to use checksums
15ab6c71524073f5177d829126ac7803e3360a109546d34cb5e2bdc0524ca0ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.12

Release files / hk_dsl-0.8.0-cp310-cp310-manylinux_2_35_x86_64.whl

Download URL hk_dsl-0.8.0-cp310-cp310-manylinux_2_35_x86_64.whl
Size 12.3 MB
Tags CPython 3.10 Linux glibc 2.35+ x86-64
SHA-256 checksum
How to use checksums
b7f89059593fc0272b083a8d8936e7a667c16f78a6246e3904fe14d15f55b27a
BLAKE2b-256 checksum
How to use checksums
6cc2228fcdd2aa064680d2a06599157f12ccd2407eae4271da89ed9beedf0bef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.12

Security for hk-dsl 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page