跳转至

入门教程

本页从零开始,一小步一小步地走到一个在 Python、Rust 和 C++ 中运行的小模型。每一步都说明它的用途,给出代码和命令,并展示你应当看到的输出。第 1 到 7 步不需要 GPU(macOS 也可以);第 8 到 12 步需要带 NVIDIA GPU 的 Linux。本页的每个文件都在仓库的 python/examples/tutorial/ 中,有一个测试检查它们就是这里展示的文件。输出是在一块 B300 MIG 切片(sm_103)上用 tilefish 0.0.15、torch 2.9.1 和 Triton 3.5.1 记录的。

要迁移你已有的模型,读完本页之后再读 migrate.md。

基本思路

你 声明类型化的算子:tilefish 根据几行数组代码生成的 kernel(核函数;@tilefish.kernel),一个你已有的、被赋予了类型的 kernel(@tilefish.extern),或者一个已 pin(固定)的 cuBLASLt 或 cuDNN 调用(@tilefish.library)。你 在 graph(计算图)中组合它们(@tilefish.graph):graph 是在类型化的值上写的普通 Python,由 tilefish 追踪并检查:形状、dtype 和布局都是每个类型的一部分,所以一个错误会在写出它的那一行报错。你 在 Python 中运行 graph(tilefish.run),并与你原有的实现比较。然后你 只导出一次:cubin,一个描述每个二进制文件的 manifest(清单)manifest.json,以及一个 plan.json,它列出 graph 在一块设备内存上的每一次启动,每个运行时尺寸的每个 bucket(分桶)各一个 plan(计划)。Python、Rust 和 C++ 加载的是同样的这些文件,对照你 pin 住的 digest(摘要)检查它们,并启动同样的机器码。你还可以选择 锁定(lock) 这次导出,这样 CI 或镜像构建就能在一台没有 GPU 的机器上写出同样的文件。

1. 安装

用途:Python 包,以及 GPU 步骤要用的 torch 和 Triton。在带 NVIDIA GPU 的 Linux 上:

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

要固定 torch 的版本:更新的 torch 会带来 tilefish 没有测试过的 Triton。在没有 GPU 的机器上(包括 macOS),pip install tilefish(纯 Python,没有依赖)就足以完成第 2 到 7 步;Triton 没有 macOS 版本,所以 [gpu] extra 在那里装不上。

在 sm_103 GPU(B300)上,Triton 3.5.1 自带的 ptxas(CUDA 12.8 的)无法构建;给它 CUDA 12.9 或更新版本的 ptxas:

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. 维度与张量类型

用途:每个张量的形状和 dtype 都是它类型的一部分,所以 tilefish 可以检查调用、把尺寸编译进二进制文件,并规划内存。

Dim 是一个具名的尺寸。Dim("D", 512) 是静态的:它的值被编译进二进制文件。Dim("T", buckets=[16, 64, 256]) 是一个带 bucket 的运行时尺寸:每个 bucket 生成一个 plan,一次运行必须恰好是其中之一(没有填充)。Tensor[T, D, bf16] 是一个稠密、行主序的 T x 512 bf16 张量。开始写 model.py:

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. tilefish 生成的 kernel:@tilefish.kernel

用途:简单的逐元素代码和归约,写成数组代码;tilefish 替你把它下沉(lowering)到 Triton。

model.py
@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)

没有任何隐式类型提升:函数体写明在哪里加宽到 f32,又在哪里舍入回 bf16。看看类型化的 IR,以及 tilefish 由它写出的 Triton 源码:

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

函数体可以使用什么(掩码、gather、有序求和、IEEE 数学函数)见 lowering.md。

4. 类型错误是什么样子

用途:错误的形状或 dtype 会在调用处被拒绝,早于任何编译或启动。errors.py 声明了三个错误的 graph:

errors.py
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)

启动时也会在运行期做同样的检查:dtype、形状或 bucket 不对的 torch 张量,不是 16 字节对齐的指针,不连续的张量,都会在 kernel 运行之前被拒绝。

5. 你已有的 kernel:@tilefish.extern

用途:一个你自己写的或从别处拿来的 Triton(或 Gluon、CuTe DSL、PTX、cubin)kernel,原样使用。下面是一个很小的 Triton kernel,放在它自己的文件里:

kernels.py
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)

声明是一个 stub(存根),按顺序 列出 kernel 的参数,每个参数带一个类型:张量是一个指针,n: T * D 是一个由 tilefish 根据形状计算的 i32,BLOCK: const = 1024 是编译进去的 constexpr,Out[...] 是 kernel 写出的张量,调用会返回它。grid= 在每次启动时计算。kernel 用 "module:function" 指名,所以声明它不会导入 Triton:

model.py
@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): ...

这些类型会成为二进制文件的编译输入,也成为每个 host(宿主)在启动前所做的检查:

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']

带步长的视图、设备标量、每个架构一个 kernel,以及 extern(外部 kernel)的其他形式,见 operators.md。

6. 已 pin 的 cuBLASLt GEMM:@tilefish.library

用途:GEMM(通用矩阵乘)以及卷积(用 cuDNN)最好交给 NVIDIA 的库。library operator(库算子)有类型化的签名,没有函数体;tilefish 每个 bucket 向 cuBLASLt 询问一次算法,并 pin 住它,这样每个 host 运行的都是那个算法。

model.py
@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" 用 f32 累加器和一次舍入计算 a @ w.T + bias。heuristic="torch" 按 torch 的 addmm 的方式询问 cuBLASLt,allow_bf16_reduction=True 是 torch 对 split-K(K 维切分)部分和的默认设置:两者合起来,结果与 F.linear(a, w, bias) 逐字节一致(第 8 步会检查)。布局、f16 和 f32、导入的算法表以及 cuDNN 见 operators.md。

7. 组合它们的 graph:@tilefish.graph

用途:模型本身。graph 的函数体是在类型化的值上写的普通 Python:对算子的调用,以及算术,tilefish 会把算术融合进生成的 kernel。

model.py
@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",) 说明 x 每次调用都会变,其他参数是权重,由 host 绑定一次。生成 plan;这一步既不需要 GPU,也不需要 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

每个步骤是一次启动。函数体中的残差加变成了 fused_8fc7ca452d82,一个由 tilefish 生成的 kernel;中间值 t0 到 t2 和 cuBLASLt 的 workspace(工作区)都放在 arena(内存池) 中:一块设备内存,其中的偏移是固定的,每个 bucket 都相同(所以 plan 可以被 capture(捕获)进 CUDA graph(CUDA 图))。返回值是 out0。融合见 fusion.md,plan 见 plans.md。

8. 在 GPU 上运行,并与 torch 比较

用途:在继续之前,先对照你原有的实现检查这次移植。data.py 生成带种子的输入;run.py 运行 graph(jit:每个二进制文件都在内存中构建),以及用 torch 写的同一个 block。

data.py
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
run.py
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

GEMM 按构造就与 torch 的逐位相同(heuristic="torch")。生成的 RMSNorm 和 Triton 的 SiLU 不是 torch 的 kernel:它们按另一种顺序做加法,用的是另一个 exp,所以一般会有少数元素相差一个 bf16 步长;在这个尺寸和这些数据上,每个元素都相等。migrate.md 展示了如何逐个算子地比较一个真实的模型。

9. 导出一次,并在 Python 中 replay(回放)这些文件

用途:把每个二进制文件构建一次,连同 manifest 和 plan 一起写出,然后运行这些文件,它们就是每个 host 运行的东西。

export.py
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

plan 的 digest 覆盖 plan、manifest、每个 cubin 和每个已 pin 的 GEMM 算法:拿到它的 host 会拒绝其中任何东西有改动的目录。导出是可复现的,所以在另一台工具链和 GPU 都相同的机器上,同样的文件会得到同样的 digest;如果你的 GPU 或工具链不同,你得到的 digest 也会不同。三个 GEMM pin(proj.T16、proj.T64、proj.T256)是 manifest.json 中的条目,而不是文件。构建做了什么、replay 会拒绝什么,见 build.md。

10. 在 Rust 中运行同一个 plan

用途:生产环境的 host,不需要 Python。tilefish crate 加载 build/,对照 pin 检查它,绑定一次权重,然后启动 plan,并事先检查每个步骤的前置条件。

cargo new host && (cd host && cargo add tilefish@0.0.11)    # then replace host/src/main.rs with the file below
host/src/main.rs
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(())
}

crate 默认的绑定针对 CUDA 13.2 或更新版本的驱动;驱动更旧时,用 cargo add tilefish@0.0.11 --no-default-features --features cuda-12080(或 cuda-12040、cuda-13000)添加它。它在运行时按名字打开 cuBLASLt:如果你的 cuBLASLt 来自 torch(一个 pip wheel)而不是 CUDA toolkit,先把它放进库路径:

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

字节与 Python 的相同:同样的 cubin、同样的已 pin 算法、同样的启动。CUDA graph、plan set(plan 集)、shared arena(共享内存池),以及由 plan 生成的类型化启动器(tilefish.hosts.rust.emit_plan)见 rust.md。

11. ……以及在 C++ 中

用途:同样的事,换成一个 C++ 程序。C 库从仓库构建(需要 CMake 和 cargo),程序自己持有它的设备内存(这里用的是 CUDA runtime):

cpp/main.cpp
#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 是你的 CUDA toolkit(/usr/local/cuda)。CMake 项目改用 find_package(tilefish);类型化的启动器、CUDA graph 和错误见 cpp.md。

12. 锁定它,然后不用 GPU 导出

用途:CI 和镜像构建很少有 GPU。lock(锁定表) 记录导出从设备得知的东西(已 pin 的 GEMM 算法、融合区域的验证结果)以及每个文件的哈希;之后按 lock 进行的导出就能在一台没有 GPU 的机器上写出同样的文件,某个文件不同时则失败。

lock.py
import tilefish

tilefish.runtime.write_lock("build/", "block.lock.json")  # on the GPU, after export.py: commit this file
print("wrote block.lock.json")
cpu_export.py
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())

在 GPU 上运行 lock.py,然后在一台没有 GPU 的机器上、用同样的 tilefish、Triton 和 ptxas 运行 cpu_export.py(这里只是用 CUDA_VISIBLE_DEVICES= 把 GPU 隐藏起来):

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

lock 还说明了是什么选择了每个算子的实现(selections:这里对 proj 是 torch 姿态(posture)下的 cuBLASLt 启发式,对生成的 kernel 是 tilefish 的一条规则)。它的格式、什么在哪里检查,以及何时重新锁定,见 locked-export.md。

接下来读什么

  • migrate.md:把你已有的模型迁移到 tilefish,以 GPT-2 为完整示例。
  • build.md:构建,三种模式(jit、replay、reference),pin 与可复现的导出。
  • operators.md:带步长的视图、设备标量、预构建的 PTX 和 cubin、每个架构一个 kernel、cuBLASLt 和 cuDNN。
  • lowering.md:@tilefish.kernel 的函数体能做什么,以及它的数值语义。
  • plans.md:plan、CUDA graph、只绑定一次的权重、plan set、carried buffer(携带缓冲区)、调试 tap(观测点)。
  • fusion.md:graph 函数体中的算术如何变成 kernel,以及 epilogue(尾部)。
  • rust.md 和 cpp.md:各个 host。
  • ../advise.md、../explain.md、../instrument.md:时间花在哪里、每一行的 SASS、kernel 内部的 probe(探针)。
  • ../scope.md:tilefish 是什么、不是什么。