Skip to content

Latest commit

 

History

History
806 lines (634 loc) · 38.3 KB

tutorial.md

File metadata and controls

806 lines (634 loc) · 38.3 KB

Getting started

English | 简体中文

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. 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. Words in links are explained in the glossary. To move a model you already have, read migrate.md after this page.

Before you start

  • Python 3.10 or newer. macOS's own python3 is 3.9, and pip then finds no tilefish ("No matching distribution"): install a newer Python first.
  • Steps 2 to 7 need no GPU (macOS is fine; step 1 says what to install there). Steps 8 to 13 need Linux with an NVIDIA GPU and a driver recent enough for CUDA 12.8 (torch 2.9.1's); you need no CUDA toolkit for them, torch's pip wheels bring the libraries.
  • Step 10 (Rust): Rust from rustup. The crate's default CUDA bindings want a CUDA 12.8 driver or newer; step 10 says how to pick another feature if needed.
  • Step 11 (C++): git, CMake 3.19 or newer, a C++17 compiler, and either a CUDA toolkit or the CUDA runtime of torch's pip wheels (step 11 shows both).

The idea

There is no importer from torch: you write the model's forward again, by hand, following the original op by op. You declare operators with typed signatures (steps 3 to 6) and call them from a graph (step 7), which tilefish checks as it traces it. You run the graph from Python (step 8). An export (step 9) builds every binary once and writes it next to a manifest and a plan, the list of launches for each bucket. Python, Rust and C++ load those files, check them against a digest you pin, and run the same machine code (steps 9 to 11). A lock lets a machine without a GPU write the same files (step 12). Step 13 is a bigger block, an attention layer.

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: at run time T must be exactly one of them (there is no padding), and the plan that step 7 makes has one list of launches per bucket. 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; each bucket gets its own launches and GEMM pins
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

Each line of the IR is one op with its result type. # rounding point marks the one op that rounds, the cast of the f32 result to bf16 (a rounding point); the widening casts are exact. template: row is how the body was lowered: one program per row, because the body reduces along the row (a body without a reduction gets the elementwise template). 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: a function whose body is ... and whose parameters are the kernel's, 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; Out[...] is a tensor the kernel writes, which a call returns (Out). 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']

The signature is what Triton compiles for: two bf16 pointers, an i32 and a constant. The preconditions are what every launch checks first: static_size (axis 1 of x and y is 512), pointer_alignment (both pointers are 16-byte aligned, which the compile assumed), max_elements (fewer than 2**31 elements, since the kernel computes 32-bit offsets) and divisible (n = 512 * T is a multiple of 16, a hint the compile used). 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 (posture). cuBLASLt may compute a GEMM by split-K, cutting K into pieces and adding their partial sums at the end; allow_bf16_reduction=True lets it add them in bf16, as torch does by default. 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

How to read it:

  • 05bcc33b507f is the start of this plan's digest. Once exported (step 9), the plan also names its manifest and its GPU architecture, so its digest changes.
  • The arena is the one block of device memory the plan allocates for what the caller does not give. The line says three things: this plan's arena is 1835008 bytes, because it was made without reuse (the default); then the size of each variant, 1835008 bytes without reuse and 1572864 with it (reuse=True lets buffers whose lifetimes do not overlap share bytes).
  • Each buffer has a role. external ones (x, the weights, out0) are the caller's tensors; t0 to t2 are intermediates at fixed offsets in the arena; workspace is scratch memory for the cuBLASLt GEMM. The returned value is named out0 (@tilefish.graph(outputs=("y",)) would name it y).
  • Each step is one launch: the operators, then fused_8fc7ca452d82, the residual add of the body as one kernel tilefish generated (a fused region, named by a hash of its content). proj.T256 is the GEMM pinned for the bucket T = 256.

Fusion is in fusion.md, plans in plans.md.

Which declaration for which op

One rule per kind of operator:

  • Arithmetic between calls (elementwise ops, casts, a bias, an activation, a residual add, and a norm or softmax whose sums have a fixed order, order=): write it in the graph body. Fusion makes it kernels, and joins neighbouring ops into one.
  • @tilefish.kernel: the same kind of array code, when you want it as one named operator with a binary of its own, called from several graphs or launched alone by a host. A call is a boundary: fusion never joins a kernel with the ops around it.
  • @tilefish.extern: a kernel you already have, or one that needs tiles, tensor cores or shared memory (attention, a custom GEMM).
  • @tilefish.library: a GEMM or a convolution.

This tutorial's RMSNorm is a @tilefish.kernel to show that declaration; in a model, write a norm in the graph body, as GPT-2's LayerNorm is in migrate.md: there it becomes one kernel with the residual add before it, where a kernel call would cost a launch and a round trip through memory. To predict what fuses: a fused region never crosses a call of an operator and holds at most 64 ops; elementwise ops, sums and means with order=, max, argmax and gather_rows join one; a sum or mean without order= is a kernel of its own. tilefish.plan(graph).describe() and tilefish.fusion_report(graph) show the result without a GPU.

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 inputs from a fixed seed, so every run sees the same data; 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 gives torch's bytes because it runs the algorithm torch's addmm runs (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

Replay runs the files of build/ after checking them against the pin. 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. In build/: a cubin per generated or Triton kernel (one each: T is a runtime argument for them, so one binary serves every bucket), manifest.json, plan.json, and two files no host reads: block.fusion.json, the fusion report, and selection.json, what chose each implementation (selections). 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(())
}

instantiate_all loads the binaries of every bucket and allocates the arena; the launch takes the inputs and outputs by name, and its last argument, &[], gives the values of the plan's device scalars (this plan has none). The crate's default bindings are for a CUDA 12.8 driver or newer; to pick another driver version, add it as cargo add tilefish --no-default-features --features cuda-12040 (or cuda-13000, cuda-13020). 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). A tilefish::Region is device memory the program vouches for: its address, its length in bytes and its device index.

#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";
}

instantiate(ctx, stream) is Rust's instantiate_all: without a list of buckets it loads every bucket. Build the C library:

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

The program also needs the CUDA runtime's headers and library. With a CUDA toolkit (CUDA_HOME, usually /usr/local/cuda):

CUDA_FLAGS="-I$CUDA_HOME/include -L$CUDA_HOME/lib64 -lcudart"

Without one, take them from the pip wheels: torch's CUDA runtime (which has no lib64 and no libcudart.so, only libcudart.so.12) and the headers of the nvidia-cuda-nvcc-cu12 wheel of step 1 (crt/host_defines.h):

NV=$(python -c "import nvidia; print(nvidia.__path__[0])")
CUDA_FLAGS="-I$NV/cuda_runtime/include -I$NV/cuda_nvcc/include -L$NV/cuda_runtime/lib -l:libcudart.so.12 -Wl,-rpath,$NV/cuda_runtime/lib"

Then compile and run, with cuBLASLt on the library path as in step 10:

g++ -std=c++17 -O2 cpp/main.cpp -o cpp/host -I../tilefish-capi/include -L../tilefish-capi/lib -ltilefish_capi $CUDA_FLAGS \
    -Wl,-rpath,$PWD/../tilefish-capi/lib
export LD_LIBRARY_PATH=$(python -c "import nvidia.cublas as m; print(m.__path__[0])")/lib:$LD_LIBRARY_PATH
./cpp/host $(cat plan.pin) && cmp data/y.bin data/y_cpp.bin && echo identical
wrote data/y_cpp.bin
identical

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 check 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. Run cpu_export.py on a Linux machine without a GPU that has tilefish, the same Triton and the same ptxas as the GPU machine: a locked export still compiles every cubin with Triton (it needs no torch, but step 1's install is the simple way to get the same Triton, the one torch 2.9.1 installs). macOS cannot: Triton does not install there, and the export stops with TilefishLockError: ... Triton is not installed here. To try it on the GPU machine, hide the GPU 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): for proj, cuBLASLt's heuristic asked the way torch asks it (heuristic:torch); for the generated kernels, a rule of tilefish's (rule:row.warps: how many warps a row kernel gets). Its format, what is checked where and when to re-lock are in locked-export.md.

13. One attention block: views, a fused norm and taps

What for: a step between this page's block and a whole model. An attention layer as in a transformer: one GEMM for q, k and v, causal attention as a Triton kernel that reads them as views, the output projection, then the residual add and a layer norm, which fusion makes one kernel. It also shows how to look inside a run with taps. The attention kernel is a short flash attention:

import triton
import triton.language as tl


@triton.jit
def causal_attention(q, k, v, o, s_head, s_tok, n, H: tl.constexpr, HD: tl.constexpr, BLOCK: tl.constexpr, SCALE: tl.constexpr):
    # one program per BLOCK queries of one head: an online softmax over the keys up to the diagonal
    m = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
    h = tl.program_id(1)
    d = tl.arange(0, HD)
    qv = tl.load(q + h * s_head + m[:, None] * s_tok + d[None, :], mask=m[:, None] < n, other=0.0)
    best = tl.full([BLOCK], float("-inf"), tl.float32)
    total = tl.zeros([BLOCK], tl.float32)
    acc = tl.zeros([BLOCK, HD], tl.float32)
    for start in range(0, tl.minimum((tl.program_id(0) + 1) * BLOCK, n), BLOCK):
        j = start + tl.arange(0, BLOCK)
        kt = tl.load(k + h * s_head + j[None, :] * s_tok + d[:, None], mask=j[None, :] < n, other=0.0)
        s = tl.where((j[None, :] < n) & (m[:, None] >= j[None, :]), tl.dot(qv, kt) * SCALE, float("-inf"))
        new = tl.maximum(best, tl.max(s, 1))
        p = tl.exp(s - new[:, None])
        alpha = tl.exp(best - new)
        total = total * alpha + tl.sum(p, 1)
        vv = tl.load(v + h * s_head + j[:, None] * s_tok + d[None, :], mask=j[:, None] < n, other=0.0)
        acc = acc * alpha[:, None] + tl.dot(p.to(vv.dtype), vv)
        best = new
    tl.store(o + m[:, None] * (H * HD) + h * HD + d[None, :], (acc / total[:, None]).to(tl.bfloat16), mask=m[:, None] < n)

The block. qkv(...).reshape(T, 3, H, HD) and select/permute are views: q, k and v are windows on the GEMM's result, and nothing is copied. The extern takes them because its parameters say Strided[...], with the strides they share passed as StrideOf scalars (s_head, s_tok). The layer norm is graph-body code with ordered sums (order=), so fusion puts it and the residual add before it in one kernel:

import tilefish
from tilefish import Dim, Out, StrideOf, Strided, Tensor, bf16, const, f32

T = Dim("T", buckets=[16, 64, 256])  # the same T as model.py
D, H, HD = 256, 4, 64                # width, heads, size of a head


@tilefish.library("qkv", acc=f32, impl="cublaslt.gemm_bias", heuristic="torch", allow_bf16_reduction=True)
def qkv(a: Tensor[T, D, bf16], w: Tensor[3 * D, D, bf16], bias: Tensor[3 * D, bf16]) -> Tensor[T, 3 * D, bf16]: ...


@tilefish.library("out_proj", acc=f32, impl="cublaslt.gemm_bias", heuristic="torch", allow_bf16_reduction=True)
def out_proj(a: Tensor[T, D, bf16], w: Tensor[D, D, bf16], bias: Tensor[D, bf16]) -> Tensor[T, D, bf16]: ...


head = Strided[Tensor[H, T, HD, bf16], 16]  # a view: the [H, T, HD] heads of q, k or v inside the qkv result, read where they are


@tilefish.extern(triton="attention_kernel:causal_attention", num_warps=4, grid=lambda T, BLOCK, H: (tilefish.cdiv(T, BLOCK), H))
def attention(
    q: head, k: head, v: head, o: Out[Tensor[T, D, bf16]],
    s_head: StrideOf(("q", "k", "v"), 0), s_tok: StrideOf(("q", "k", "v"), 1), n: T,
    H: const = H, HD: const = HD, BLOCK: const = 64, SCALE: const[f32] = HD**-0.5,
): ...


def layer_norm(x, w, b):
    v = x.to(f32)
    mu = tilefish.mean(v, -1, keepdims=True, order=tilefish.tree(256))  # order=: a fixed order of adds, so it can fuse
    xc = v - mu
    var = tilefish.mean(xc * xc, -1, keepdims=True, order=tilefish.tree(256))
    return (xc * tilefish.rsqrt(var + 1e-5) * w.to(f32) + b.to(f32)).to(bf16)


@tilefish.graph(inputs=("x",))
def attn_block(x: Tensor[T, D, bf16], w_qkv: Tensor[3 * D, D, bf16], b_qkv: Tensor[3 * D, bf16],
               w_o: Tensor[D, D, bf16], b_o: Tensor[D, bf16], ln_w: Tensor[D, bf16], ln_b: Tensor[D, bf16]):
    heads = qkv(x, w_qkv, b_qkv).reshape(T, 3, H, HD)                  # views: nothing is copied
    q, k, v = (heads.select(1, i).permute(1, 0, 2) for i in range(3))  # each [H, T, HD]
    h = x + out_proj(attention(q, k, v), w_o, b_o)                     # the residual add...
    return layer_norm(h, ln_w, ln_b)                                    # ...and the norm: one fused kernel

run_attention.py runs it against the same block in torch and compares every op's output. No name of a plan buffer is chosen by you: the intermediates are t0, t1, ... in the order they are made. Read which buffer an op writes off plan.steps(T=64) (the step of an operator binds its output parameter, out for a library GEMM, o for this extern), then ask for those buffers as taps, which copies them during the run, with the plan unchanged:

import torch
import torch.nn.functional as F

import tilefish
from attention_block import attn_block, out_proj

g = torch.Generator(device="cuda").manual_seed(0)


def randn(*shape, scale=1.0):
    return scale * torch.randn(*shape, generator=g, device="cuda", dtype=torch.bfloat16)


x = randn(64, 256)
w = {"w_qkv": randn(768, 256, scale=256**-0.5), "b_qkv": randn(768, scale=0.1), "w_o": randn(256, 256, scale=256**-0.5),
     "b_o": randn(256, scale=0.1), "ln_w": 1 + randn(256, scale=0.1), "ln_b": randn(256, scale=0.1)}

# the block in torch, keeping the output of each op
ref = {"qkv": F.linear(x, w["w_qkv"], w["b_qkv"])}
q, k, v = ref["qkv"].view(64, 3, 4, 64).permute(1, 2, 0, 3)  # each [H, T, HD]
ref["attention"] = F.scaled_dot_product_attention(q, k, v, is_causal=True).permute(1, 0, 2).reshape(64, 256)
ref["out_proj"] = F.linear(ref["attention"], w["w_o"], w["b_o"])
ref["block"] = F.layer_norm(x + ref["out_proj"], (256,), w["ln_w"], w["ln_b"], eps=1e-5)

# which buffer of the plan each op writes, read off the plan's steps at T = 64
plan = tilefish.plan(attn_block)
steps = {s["entry"].split(".")[0]: {a["name"]: a["binding"] for a in s["args"]} for s in plan.steps(T=64)}
for op, args in steps.items():
    print(f"{op:<18} {args}")
buffer = {"qkv": steps["qkv"]["out"], "attention": steps["attention"]["o"], "out_proj": steps["out_proj"]["out"]}
taps = {b: torch.empty(plan.shape_of(b, T=64), dtype=torch.bfloat16, device="cuda") for b in buffer.values()}

y = tilefish.run(attn_block, x, **w, taps=taps)  # taps: copies of those buffers, made during the run
got = {name: taps[b] for name, b in buffer.items()} | {"block": y}
for name in ("qkv", "attention", "out_proj", "block"):
    diff = (got[name].float() - ref[name].float()).abs().max().item()
    print(f"{name:<9} {buffer.get(name, 'out0'):<4} elements equal {(got[name] == ref[name]).float().mean().item():.4f}, max |diff| {diff:.4f}")
print("out_proj alone on torch's input, equal to F.linear:",
      torch.equal(tilefish.run(out_proj, ref["attention"], w["w_o"], w["b_o"]), ref["out_proj"]))
python run_attention.py
qkv                {'a': 'x', 'w': 'w_qkv', 'bias': 'b_qkv', 'out': 't0'}
attention          {'q': 't0', 'k': 't0', 'v': 't0', 'o': 't1'}
out_proj           {'a': 't1', 'w': 'w_o', 'bias': 'b_o', 'out': 't2'}
fused_902c5cf0efad {'a0': 'x', 'a1': 't2', 'a2': 'ln_w', 'a3': 'ln_b', 'out': 'out0'}
qkv       t0   elements equal 1.0000, max |diff| 0.0000
attention t1   elements equal 0.6939, max |diff| 0.0078
out_proj  t2   elements equal 0.5626, max |diff| 0.0078
block     out0 elements equal 0.8036, max |diff| 0.0156
out_proj alone on torch's input, equal to F.linear: True

Four steps: the q, k and v GEMM writes t0; the attention reads three views of t0 and writes t1; the output projection writes t2; the residual add and the layer norm are one fused kernel that writes the result. Reading the comparison from the top: the GEMM is torch's to the bit; the attention is not torch's kernel, so about a third of its elements differ, by at most one bf16 step (0.0078 at values near 1); the output projection differs too, but run alone on torch's input it is torch's to the bit, so its difference came from its input. That walk back, from the first output that differs to the op that made it, is how migrate.md verifies a whole model.

Where to go next

  • migrate.md: moving a model you already have to tilefish, with GPT-2 as the worked example.
  • glossary.md: every term of these pages.
  • 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.kernel body 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.md and cpp.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.