Getting started¶
This page takes you from nothing to a small model running from Python, Rust and C++, in small steps. Each step says what it is for, gives the code and the
command, and shows what you should see. Steps 1 to 7 need no GPU (macOS is fine); steps 8 to 12 need Linux with an NVIDIA GPU. Every file
of this page is in the repository, in python/examples/tutorial/,
and a test checks that they are the files shown here. The outputs were recorded on a B300 MIG slice (sm_103) with tilefish 0.0.15, torch
2.9.1 and Triton 3.5.1.
To move a model you already have, read migrate.md after this page.
The idea¶
You declare typed operators: a kernel tilefish generates from a few lines of array code (@tilefish.kernel), a kernel you already have,
given a type (@tilefish.extern), or a pinned cuBLASLt or cuDNN call (@tilefish.library). You compose them in a graph
(@tilefish.graph), ordinary Python over typed values, which tilefish traces and checks: shapes, dtypes and layouts are part of every type,
so a mistake is an error at the line that makes it. You run the graph in Python (tilefish.run) and compare it with what you had. Then you
export it once: the cubins, a manifest.json that describes each binary and a plan.json that lists every launch of the graph over one
block of device memory, one plan per bucket of each runtime size. Python, Rust and C++ load those same files, check them against a digest
you pin, and launch the same machine code. Optionally you lock the export, so that CI or an image build can write the same files on a
machine without a GPU.
1. Install¶
What for: the Python package, with torch and Triton for the GPU steps. On Linux with an NVIDIA GPU:
python -m venv .venv && . .venv/bin/activate
pip install "tilefish[gpu]" "torch==2.9.1" # torch 2.9.1 brings Triton 3.5.1: the versions tilefish 0.0.15 is tested with
mkdir tutorial && cd tutorial # every file of this page goes here
python -c "import tilefish, torch, triton; print(tilefish.__version__, torch.__version__, triton.__version__)"
0.0.15 2.9.1+cu128 3.5.1
Pin torch: a newer one brings a Triton that tilefish is not tested with. On a machine without a GPU (macOS included), pip install tilefish
(pure Python, no dependencies) is enough for steps 2 to 7; Triton has no macOS build, so the [gpu] extra does not install there.
On an sm_103 GPU (a B300), Triton 3.5.1's own ptxas (CUDA 12.8's) cannot build; give it the ptxas of CUDA 12.9 or newer:
pip install "nvidia-cuda-nvcc-cu12==12.9.86"
export TRITON_PTXAS_PATH=$(python -c "import nvidia.cuda_nvcc as m; print(m.__path__[0])")/bin/ptxas
2. Dimensions and tensor types¶
What for: every tensor's shape and dtype is part of its type, so tilefish can check calls, compile sizes into the binaries and plan memory.
A Dim is a named size. Dim("D", 512) is static: its value is compiled into the binaries. Dim("T", buckets=[16, 64, 256]) is a runtime
size with buckets: a plan is made for each bucket, and a run must be exactly one of them (there is no padding). Tensor[T, D, bf16] is a
dense, row-major T x 512 tensor of bf16. Start model.py:
import tilefish
from tilefish import Dim, Out, Tensor, bf16, const, f32
T = Dim("T", buckets=[16, 64, 256]) # tokens: a runtime size, one binary per bucket
D = Dim("D", 512) # model width: static, compiled into the binaries
3. A kernel tilefish generates: @tilefish.kernel¶
What for: simple elementwise code and reductions, written as array code; tilefish lowers it to Triton for you.
@tilefish.kernel
def rmsnorm(x: Tensor[T, D, bf16], w: Tensor[D, bf16]) -> Tensor[T, D, bf16]:
v = x.to(f32)
ms = tilefish.mean(v * v, axis=-1, keepdims=True)
return (v * tilefish.rsqrt(ms + 1e-6) * w.to(f32)).to(bf16)
Nothing is promoted implicitly: the body says where it widens to f32 and where it rounds back to bf16. Look at the typed IR and at the Triton source tilefish writes from it:
python -c "import model; print(model.rmsnorm.graph); print(model.rmsnorm.lower().source)"
kernel rmsnorm(%x: Tensor[T, D, bf16], %w: Tensor[D, bf16]) -> (Tensor[T, D, bf16]):
%0: Tensor[T, D, f32] = cast(%x) {to=f32, rounding=false}
%1: Tensor[T, D, f32] = mul(%0, %0)
%2: Tensor[T, 1, f32] = mean(%1) {axes=(1,), keepdims=true}
%3: Tensor[T, 1, f32] = add(%2, 1e-06:f32)
%4: Tensor[T, 1, f32] = rsqrt(%3)
%5: Tensor[T, D, f32] = mul(%0, %4)
%6: Tensor[D, f32] = cast(%w) {to=f32, rounding=false}
%7: Tensor[T, D, f32] = mul(%5, %6)
%8: Tensor[T, D, bf16] = cast(%7) {to=bf16, rounding=true} # rounding point
return %8
# Generated by tilefish.lower from the kernel 'rmsnorm'. Do not edit.
# template: row; one program per row, grid (T,)
# D = 512 (static), BLOCK_D = next_pow2(D)
# num_warps: 2
# Numerics contract: see the docstring of tilefish.lower.
import triton
import triton.language as tl
@triton.jit
def tf_rmsnorm(
x,
w,
out,
D: tl.constexpr,
BLOCK_D: tl.constexpr,
):
row = tl.program_id(0)
cols = tl.arange(0, BLOCK_D)
mask = cols < D
offs = row * D + cols
v0 = tl.load(x + offs, mask=mask, other=0) # x
v1 = tl.load(w + cols, mask=mask, other=0) # w
v2 = v0.to(tl.float32)
v3 = v2 * v2
v4 = tl.sum(tl.where(mask, v3, 0.0), axis=0) / D
v5 = v4 + 1e-06
v6 = tl.rsqrt(v5)
v7 = v2 * v6
v8 = v1.to(tl.float32)
v9 = v7 * v8
v10 = v9.to(tl.bfloat16) # rounding point
tl.store(out + offs, v10, mask=mask) # return value 0
What a body may use (masks, gathers, ordered sums, IEEE math) is in lowering.md.
4. What a type error looks like¶
What for: a wrong shape or dtype is refused where the call is made, before anything is compiled or launched. errors.py declares three
graphs that are wrong:
import tilefish
from tilefish import Tensor, bf16, f32
from model import D, T, rmsnorm
try:
@tilefish.graph
def wrong_width(x: Tensor[T, 256, bf16], w: Tensor[D, bf16]):
return rmsnorm(x, w)
except tilefish.TilefishTypeError as e:
print(e)
try:
@tilefish.graph
def wrong_dtype(x: Tensor[T, D, f32], w: Tensor[D, bf16]):
return rmsnorm(x, w)
except tilefish.TilefishTypeError as e:
print(e)
try:
@tilefish.graph
def no_promotion(x: Tensor[T, D, bf16], w: Tensor[D, f32]):
return x + w
except tilefish.TilefishTypeError as e:
print(e)
python errors.py
in graph 'wrong_width': rmsnorm: argument 'x' (Tensor[T, 256, bf16]): dimension 1 is 256, but the signature requires D = 512
in graph 'wrong_dtype': rmsnorm: argument 'x': expected dtype bf16, got f32 (parameter is Tensor[T, D, bf16], argument is Tensor[T, D, f32])
in graph 'no_promotion': add (+): no implicit promotion between tensor dtypes: left operand is Tensor[T, D, bf16], right operand is Tensor[D, f32]; cast one side explicitly with .to(dtype)
A launch checks the same at run time: a torch tensor of another dtype, shape or bucket, a pointer that is not 16-byte aligned, a tensor that is not contiguous are all refused before the kernel runs.
5. A kernel you already have: @tilefish.extern¶
What for: a Triton (or Gluon, CuTe DSL, PTX, cubin) kernel you wrote or took from elsewhere, used as it is. Here is a tiny Triton kernel, in its own file:
import triton
import triton.language as tl
@triton.jit
def silu(x, y, n, BLOCK: tl.constexpr):
offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
mask = offs < n
v = tl.load(x + offs, mask=mask).to(tl.float32)
tl.store(y + offs, (v / (1.0 + tl.exp(-v))).to(tl.bfloat16), mask=mask)
The declaration is a stub that lists the kernel's parameters in order, each with a type: a tensor is a pointer, n: T * D is an i32
that tilefish computes from the shapes, BLOCK: const = 1024 is a constexpr compiled in, and Out[...] is a tensor the kernel writes, which
a call returns. grid= is computed at each launch. The kernel is named by "module:function", so declaring it imports no Triton:
@tilefish.extern(triton="kernels:silu", num_warps=4, grid=lambda n, BLOCK: (tilefish.cdiv(n, BLOCK),))
def silu(x: Tensor[T, D, bf16], y: Out[Tensor[T, D, bf16]], n: T * D, BLOCK: const = 1024): ...
The types become the binary's compile inputs and the checks every host makes before a launch:
python -c "import tilefish, model; (s,) = tilefish.aot.compile_specs(model.silu); print(s.signature); print(s.grid); print(sorted({p.kind for p in s.preconditions}))"
{'x': '*bf16', 'y': '*bf16', 'n': 'i32', 'BLOCK': 'constexpr'}
(cdiv(512*T, 1024),)
['divisible', 'max_elements', 'pointer_alignment', 'static_size']
Strided views, device scalars, one kernel per architecture and the other forms of an extern are in operators.md.
6. A pinned cuBLASLt GEMM: @tilefish.library¶
What for: GEMMs (and convolutions, with cuDNN) are best left to NVIDIA's libraries. A library operator has a typed signature and no body; tilefish asks cuBLASLt for an algorithm once per bucket and pins it, so every host runs that algorithm.
@tilefish.library("proj", acc=f32, impl="cublaslt.gemm_bias", heuristic="torch", allow_bf16_reduction=True)
def proj(a: Tensor[T, D, bf16], w: Tensor[D, D, bf16], bias: Tensor[D, bf16]) -> Tensor[T, D, bf16]: ...
impl="cublaslt.gemm_bias" computes a @ w.T + bias with an f32 accumulator and one rounding. heuristic="torch" asks cuBLASLt the way
torch's addmm does, and allow_bf16_reduction=True is torch's default for split-K partial sums: together they give F.linear(a, w, bias)
byte for byte (step 8 checks it). Layouts, f16 and f32, imported algorithm tables and cuDNN are in operators.md.
7. A graph that composes them: @tilefish.graph¶
What for: the model itself. A graph body is ordinary Python over typed values: calls of operators, and arithmetic, which tilefish fuses into generated kernels.
@tilefish.graph(inputs=("x",))
def block(x: Tensor[T, D, bf16], w_norm: Tensor[D, bf16], w: Tensor[D, D, bf16], b: Tensor[D, bf16]):
h = silu(proj(rmsnorm(x, w_norm), w, b))
return (x.to(f32) + h.to(f32)).to(bf16)
inputs=("x",) says that x changes at every call and the other parameters are weights, which a host binds once. Make the plan; this needs no
GPU and no torch:
python -c "import tilefish, model; print(tilefish.plan(model.block).describe())"
plan of graph 'block' (05bcc33b507f): dims {'T': (16, 64, 256)}, 3 bucket(s), 4 step(s)
arena: 1835008 bytes (without reuse); without reuse 1835008, with reuse 1572864
buffers:
x input bf16 ['T', 512] 262144 bytes, external
w_norm weight bf16 [512] 1024 bytes, external
w weight bf16 [512, 512] 524288 bytes, external
b weight bf16 [512] 1024 bytes, external
t0 intermediate bf16 ['T', 512] 262144 bytes, arena +0
t1 intermediate bf16 ['T', 512] 262144 bytes, arena +262144
t2 intermediate bf16 ['T', 512] 262144 bytes, arena +524288
out0 output bf16 ['T', 512] 262144 bytes, external
workspace workspace u8 [1048576] 1048576 bytes, arena +786432
steps at {'T': 256}:
#0 rmsnorm (kernel): x, w_norm, t0
#1 proj.T256 (library): t0, w, b, t1
#2 silu (kernel): t1, t2
#3 fused_8fc7ca452d82 (kernel): x, t2, out0
Each step is one launch. The residual add of the body became fused_8fc7ca452d82, a kernel tilefish generated; the intermediates t0 to t2
and the cuBLASLt workspace live in the arena, one block of device memory at fixed offsets, the same for every bucket (so a plan can be
captured in a CUDA graph). The returned value is out0. Fusion is in fusion.md, plans in plans.md.
8. Run it on the GPU and compare with torch¶
What for: check the port against what you had before going further. data.py makes seeded inputs; run.py runs the graph (jit: every
binary built in memory) and the same block written in torch.
import torch
def make(tokens=64, seed=0):
"""Seeded test data on the GPU: an input x and the block's three weights."""
g = torch.Generator(device="cuda").manual_seed(seed)
def randn(*shape):
return torch.randn(*shape, generator=g, device="cuda", dtype=torch.bfloat16)
x = randn(tokens, 512)
weights = {"w_norm": 1 + 0.1 * randn(512), "w": randn(512, 512) / 512**0.5, "b": 0.1 * randn(512)}
return x, weights
import torch
import torch.nn.functional as F
import tilefish
from data import make
from model import block, proj
x, wts = make(tokens=64)
y = tilefish.run(block, x, **wts) # jit: every binary built in memory, the plan run on the GPU
# the same block written in torch
h = F.rms_norm(x, (512,), wts["w_norm"], eps=1e-6)
ref = x + F.silu(F.linear(h, wts["w"], wts["b"]))
print("block, max |tilefish - torch|:", (y.float() - ref.float()).abs().max().item())
print("block, elements equal:", (y == ref).float().mean().item())
print("proj alone, bytes equal to F.linear:", torch.equal(tilefish.run(proj, h, wts["w"], wts["b"]), F.linear(h, wts["w"], wts["b"])))
python run.py
block, max |tilefish - torch|: 0.0
block, elements equal: 1.0
proj alone, bytes equal to F.linear: True
The GEMM is torch's to the bit, by construction (heuristic="torch"). The generated RMSNorm and the Triton SiLU are not torch's kernels: they
add in another order and use another exp, so in general a few elements differ by one bf16 step; at this size and on this data every element
is equal. migrate.md shows how to compare a real model op by op.
9. Export once, and replay the files in Python¶
What for: build every binary once, write them with the manifest and the plan, and run those files, which is what every host runs.
import pathlib
import torch
import tilefish
from data import make
from model import block
p = tilefish.runtime.export(block, "build/") # cubins, manifest.json, plan.json: every bucket of T
pathlib.Path("plan.pin").write_text(p.digest + "\n") # the pin: keep it outside build/, where you trust it
print("exported", p)
print("plan digest", p.digest)
x, wts = make(tokens=64)
y = tilefish.run(block, x, **wts, mode="replay", plan="build/", pin=p.digest) # the files on disk, verified first
print("replay equals jit:", torch.equal(y, tilefish.run(block, x, **wts)))
bound = tilefish.runtime.bind_weights(block, wts, mode="replay", plan="build/", pin=p.digest) # the weights, once
print("weights bound once, same bytes:", torch.equal(bound.run(x), y))
data = pathlib.Path("data") # raw bytes for the Rust and C++ hosts
data.mkdir(exist_ok=True)
for name, t in {"x": x, **wts, "y": y}.items():
(data / f"{name}.bin").write_bytes(t.cpu().view(torch.uint8).numpy().tobytes())
python export.py && ls build
exported <Plan 'block': 3 buckets, 4 steps, arena 1835008 bytes, digest dcbb684e0a22>
plan digest dcbb684e0a227e421114ed8c35d231366095f90eb02d6abaec3cd3409a32bcd7
replay equals jit: True
weights bound once, same bytes: True
block.fusion.json
fused_8fc7ca452d82.sm_103.cubin
manifest.json
plan.json
rmsnorm.sm_103.cubin
selection.json
silu.sm_103.cubin
The plan digest covers the plan, the manifest, every cubin and every pinned GEMM algorithm: a host given it refuses a directory in which
anything changed. An export is reproducible, so the same files on another machine with the same toolchain and GPU give the same digest; yours
differs if your GPU or toolchain does. The three GEMM pins (proj.T16, proj.T64, proj.T256) are entries of manifest.json, not files.
What a build does and what replay refuses are in build.md.
10. Run the same plan from Rust¶
What for: the production host, with no Python. The tilefish crate loads build/, checks it against the pin, binds the weights once and
launches the plan, checking every step's preconditions first.
cargo new host && (cd host && cargo add tilefish@0.0.11) # then replace host/src/main.rs with the file below
use std::fs;
use tilefish::{Bf16, CudaContext, LaunchPlan, Pin, TensorMut, TensorRef};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let pin = std::env::args().nth(1).ok_or("usage: host <plan digest>")?;
let ctx = CudaContext::new(0)?;
let stream = ctx.new_stream()?;
// verify build/ against the pin, load its binaries, allocate its arena
let plan = LaunchPlan::load("build/", Pin::Digest(&pin))?;
let run = plan.instantiate_all(&stream)?;
// the weights, bound once
let w_norm = stream.clone_htod(&fs::read("data/w_norm.bin")?)?;
let w = stream.clone_htod(&fs::read("data/w.bin")?)?;
let b = stream.clone_htod(&fs::read("data/b.bin")?)?;
let model = run.bind_weights(vec![
("w_norm", TensorRef::<Bf16>::from_cuda(&w_norm, &[512])?.into_arg()),
("w", TensorRef::<Bf16>::from_cuda(&w, &[512, 512])?.into_arg()),
("b", TensorRef::<Bf16>::from_cuda(&b, &[512])?.into_arg()),
])?;
// one forward step: 64 tokens, the bucket T = 64
let x = stream.clone_htod(&fs::read("data/x.bin")?)?;
let mut y = stream.alloc_zeros::<u8>(64 * 512 * 2)?;
model.launch(
&stream,
&mut [
("x", TensorRef::<Bf16>::from_cuda(&x, &[64, 512])?.into_arg()),
("out0", TensorMut::<Bf16>::from_cuda(&mut y, &[64, 512])?.into_arg()),
],
&[],
)?;
fs::write("data/y_rust.bin", stream.clone_dtoh(&y)?)?;
println!("wrote data/y_rust.bin");
Ok(())
}
The crate's default bindings are for a CUDA 13.2 driver or newer; with an older driver, add it as
cargo add tilefish@0.0.11 --no-default-features --features cuda-12080 (or cuda-12040, cuda-13000). It opens cuBLASLt at run time by name:
if yours came with torch (a pip wheel) rather than a CUDA toolkit, put it on the library path first:
export LD_LIBRARY_PATH=$(python -c "import nvidia.cublas as m; print(m.__path__[0])")/lib:$LD_LIBRARY_PATH
cargo run --release -q --manifest-path host/Cargo.toml -- $(cat plan.pin)
cmp data/y.bin data/y_rust.bin && echo identical
wrote data/y_rust.bin
identical
The bytes are Python's: the same cubins, the same pinned algorithm, the same launches. A CUDA graph, plan sets, shared arenas and typed
launchers generated from the plan (tilefish.hosts.rust.emit_plan) are in rust.md.
11. ... and from C++¶
What for: the same, for a C++ program. The C library is built from the repository (it needs CMake and cargo), and the program owns its device memory (here with the CUDA runtime):
#include <cuda_runtime_api.h>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include "tilefish.hpp"
// device memory holding the bytes of a file (error checks of the CUDA runtime left out)
static tilefish::Region upload(const char* path) {
std::ifstream f(path, std::ios::binary);
std::vector<char> bytes{std::istreambuf_iterator<char>(f), {}};
void* p = nullptr;
cudaMalloc(&p, bytes.size());
cudaMemcpy(p, bytes.data(), bytes.size(), cudaMemcpyHostToDevice);
return {reinterpret_cast<uint64_t>(p), bytes.size(), 0};
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "usage: host_cpp <plan digest>\n";
return 2;
}
using tilefish::Bf16;
auto ctx = tilefish::Context::primary(0); // the CUDA runtime's context of device 0
cudaStream_t stream;
cudaStreamCreate(&stream);
auto run = tilefish::LaunchPlan::load("build/", argv[1]).instantiate(ctx, stream);
auto model = run.bind_weights({
{"w_norm", tilefish::TensorRef<Bf16>(upload("data/w_norm.bin"), {512})},
{"w", tilefish::TensorRef<Bf16>(upload("data/w.bin"), {512, 512})},
{"b", tilefish::TensorRef<Bf16>(upload("data/b.bin"), {512})},
});
tilefish::Region x = upload("data/x.bin"), y{0, 64 * 512 * 2, 0};
cudaMalloc(reinterpret_cast<void**>(&y.address), y.bytes);
model.launch(stream, {{"x", tilefish::TensorRef<Bf16>(x, {64, 512})}, {"out0", tilefish::TensorMut<Bf16>(y, {64, 512})}});
cudaStreamSynchronize(stream);
std::vector<char> out(y.bytes);
cudaMemcpy(out.data(), reinterpret_cast<void*>(y.address), y.bytes, cudaMemcpyDeviceToHost);
std::ofstream("data/y_cpp.bin", std::ios::binary).write(out.data(), out.size());
std::cout << "wrote data/y_cpp.bin\n";
}
git clone https://github.com/Kilerd/tilefish ../tilefish-src
cmake -S ../tilefish-src/crates/tilefish-capi -B ../capi-build -DCMAKE_BUILD_TYPE=Release
cmake --build ../capi-build && cmake --install ../capi-build --prefix ../tilefish-capi
g++ -std=c++17 -O2 cpp/main.cpp -o cpp/host -I../tilefish-capi/include -I$CUDA_HOME/include \
-L../tilefish-capi/lib -ltilefish_capi -L$CUDA_HOME/lib64 -lcudart -Wl,-rpath,$PWD/../tilefish-capi/lib
./cpp/host $(cat plan.pin) && cmp data/y.bin data/y_cpp.bin && echo identical
wrote data/y_cpp.bin
identical
CUDA_HOME is your CUDA toolkit (/usr/local/cuda). A CMake project uses find_package(tilefish) instead; typed launchers, CUDA graphs and
errors are in cpp.md.
12. Lock it, and export without a GPU¶
What for: CI and image builds rarely have a GPU. A lock records what the export learnt from the device (the pinned GEMM algorithms, the verification of the fused regions) and the hash of every file; an export from the lock then writes the same files on a machine with no GPU, and fails if a file differs.
import tilefish
tilefish.runtime.write_lock("build/", "block.lock.json") # on the GPU, after export.py: commit this file
print("wrote block.lock.json")
import pathlib
import tilefish
from model import block
p = tilefish.runtime.export(block, "build-cpu/", lock="block.lock.json") # no GPU needed: the device's facts come from the lock
print("same plan digest as the GPU export:", p.digest == pathlib.Path("plan.pin").read_text().strip())
Run lock.py on the GPU, then cpu_export.py on a machine without one, with the same tilefish, Triton and ptxas (here the GPU is only
hidden, with CUDA_VISIBLE_DEVICES=):
python lock.py
CUDA_VISIBLE_DEVICES= python cpu_export.py
diff -r build build-cpu && echo "no differences"
wrote block.lock.json
same plan digest as the GPU export: True
no differences
The lock also says what chose each operator's implementation (selections: here the cuBLASLt heuristic under torch's posture for proj, a
rule of tilefish's for the generated kernels). Its format, what is checked where and when to re-lock are in
locked-export.md.
Where to go next¶
migrate.md: moving a model you already have to tilefish, with GPT-2 as the worked example.build.md: the build, the three modes (jit,replay,reference), pins and reproducible exports.operators.md: strided views, device scalars, prebuilt PTX and cubin, one kernel per architecture, cuBLASLt and cuDNN.lowering.md: what a@tilefish.kernelbody can do, and its numerics.plans.md: plans, CUDA graphs, weights bound once, plan sets, carried buffers, debug taps.fusion.md: how the arithmetic of a graph body becomes kernels, and epilogues.rust.mdandcpp.md: the hosts.../advise.md,../explain.md,../instrument.md: where the time goes, the SASS of every line, probes inside a kernel.../scope.md: what tilefish is and is not.