Skip to content

Migrating an existing model

You have a model that works: a PyTorch module, or an engine written by hand in CUDA, C++ or Rust. This page is the method for moving it to tilefish without losing what it computes. It is a checklist of six steps, then the pitfalls that catch most ports, then the two usual starting points: a torch model, with GPT-2 as a worked example whose code is in python/examples/gpt2/, and a hand-written engine. Read tutorial.md first: it shows every piece used here on a small block.

The method

1. Start from the original model

  • Port what runs, from its source. Take the code that runs today, not a paper or a re-implementation. If the model was already ported once (from Python to C++, say), go back to the original and to the change that ported it: the order of its ops and the fusions the port made are what you reproduce, or change knowingly.
  • Write down one forward step: every op in order, the shapes and dtypes of its inputs and outputs, and which sizes change at run time (tokens, batch, sequence length) and over which range.
  • Each size becomes a Dim. A size that never changes is static (Dim("D", 768)) and is compiled in. A size that changes is bucketed (Dim("T", buckets=[64, 256, 1024])): there is one plan per bucket, a run must be exactly a bucket, and a library GEMM pins one algorithm per bucket. Pick the buckets from the sizes the product sees.
  • Record a reference: a fixed input, and the output of every module for it (forward hooks in torch, a debug dump in an engine). Step 4 compares against it.

2. Choose an implementation per op

in the original in tilefish declared with bytes against the original
a linear layer, addmm, mm with a weight a pinned cuBLASLt GEMM @tilefish.library(impl="cublaslt.gemm" or "cublaslt.gemm_bias", heuristic="torch") and torch's split-K opt-in (allow_bf16_reduction=True, ...); layout= from how the weight is stored torch's, in bf16, f16 and f32 (TF32 off)
a GEMM whose cuBLASLt algorithm an engine pins that algorithm algos=[tilefish.AlgoTable(arch, sm_count, cublaslt_version, {(m, n, k, bias): config})] the engine's
a convolution a pinned cuDNN convolution @tilefish.library(impl="cudnn.conv_fwd"), torch's choice by default; an engine's with algos=tilefish.CudnnTable(...) torch's, or the engine's
a kernel you have: Triton, Gluon, CuTe DSL, or CUDA C++ built to PTX or a cubin that kernel @tilefish.extern(triton=...), gluon=, cute=, ptx= or cubin= with symbol= and block= the kernel's own (a cubin runs as it is; PTX is assembled with tilefish's fixed ptxas flags)
a fused kernel you have no source for (torch's SDPA, a vendor's attention) a Triton kernel you write or adapt @tilefish.extern(triton=...) within a tolerance
elementwise ops, casts, activations, residual adds, a bias generated, and fused into one kernel per region arithmetic in the graph body, op for op; tilefish.fusion(math="ieee", intermediates="opmath") for torch's eager arithmetic torch's, when written op for op
a norm, a softmax, a reduction generated the graph body with order= (fused into a row region), or a @tilefish.kernel the original's only with its order of adds (order=, tilefish.tree(...)); otherwise within a tolerance
an embedding, a gather, a scatter generated tilefish.gather_rows, tilefish.scatter_rows the bits, copied
reshape, transpose, split, a layer's weight in a stack a view: nothing is copied .reshape, .permute, .split, .select, x[i] none

Prefer what keeps the original's bytes: it makes step 4 a comparison of bits wherever it can be one. The details of each row are in operators.md, lowering.md and fusion.md.

3. Write the graph in the original order, and bind the weights

  • One graph per forward step (or per stage: a prefill and a decode step are two graphs of one plan set, plans.md).
  • The original's ops in the original's order, in its dtypes, with its rounding points. Every op of a torch model on a 16-bit tensor rounds its result; write that op, and the graph rounds there too. Computing a chain in f32 and rounding once is more accurate, but it is not the original's bytes (see the pitfalls).
  • Views for the layout ops: a reshape of a dense value, permute, split, select copy nothing. An extern that reads a view declares the parameter Strided[...] with its strides as StrideOf scalars.
  • Weights. @tilefish.graph(inputs=("idx",)) says which parameters change at every call; the others are weights, which every host binds once (tilefish.runtime.bind_weights; Rust PlanRun::bind_weights). Stack per-layer weights into one tensor (attn_w: Tensor[L, D, 3 * D]) and take attn_w[i], a view: the signature then does not grow with the depth. Name the outputs (outputs=("logits",)).
  • Plan it on your laptop: tilefish.plan(graph).describe() needs no GPU and lists every launch, buffer and offset of every bucket.

4. Verify layer by layer against the original

Make three comparisons, on the reference of step 1:

  1. Each op alone, on the original's inputs. Feed each op of the port the original's input of that op and compare with the original's output. tilefish.run(op, ...) runs one operator; a graph-body function (a layer norm) runs as a small graph of its own. This tells which ops give the original's bytes and which are within a tolerance, without any drift from the ops before.
  2. Each layer inside the plan. tilefish.run(graph, ..., taps={"t12": tensor}) copies buffers of the plan into your tensors after the step that writes them: the intermediates of the very plan you will ship, with the plan unchanged. plan.steps(T=...) says which buffer each step reads and writes. Compare each with the original's output of that op: this is the drift of a whole forward.
  3. The outputs, with the measure the product cares about (here: the logits, and how often the greedy next token agrees).

Byte identity, or a tolerance. Expect the original's bytes where the port runs the same arithmetic in the same order: GEMMs under heuristic="torch" or imported pins, elementwise code written op for op with torch's math, gathers, and an extern of the original's own kernel. Expect a tolerance where the order of adds differs (a layer norm, a softmax, an attention kernel of your own) or another exp is used. Set the tolerance from the original against itself: run it twice in two of its own configurations (torch's eager attention against its SDPA, an engine built with two compilers) and use that distance; a port within it is as close as the original is to itself.

Bisecting a mismatch. The taps give the first op where the drift jumps. Run that op alone on the original's input: if it differs alone, the op is not the original's (a rounding point, an order of adds, a constant rounded to bf16, a * b + c contracted on one side, math="fast"); if it agrees alone, its input drifted earlier, so move up one op. Inside a fused region, tilefish.fusion(grouping="none") makes every op a kernel of its own and tilefish.barrier(x) gives one value a buffer (fusion never changes a byte, so either shows the same values). tilefish.runtime.run_step(graph, i, buffers, mode="replay", plan=..., pin=...) replays one step of the exported plan on your tensors under the production pin.

5. Deploy

  • Export once per target GPU, p = tilefish.runtime.export(graph, "build/") (a list of graphs exports a plan set), and pin p.digest in the host (in its code or its configuration): a host refuses a directory whose files are not the ones the digest covers. Ship the directory, or commit a lock and export in CI or the image build without a GPU (locked-export.md).
  • Integrate the host: Python bind_weights(...).run(x) and capture(...) for a CUDA graph; Rust LaunchPlan::load, instantiate_all, bind_weights, launch, capture (rust.md); C++ the same calls (cpp.md).
  • Roll out behind a switch, with a shadow run:
    1. Add the tilefish path next to the old one, behind a switch that is off by default; one switch per stage when the model has several (an encoder and a decoder), so each is rolled out alone.
    2. In dual mode the old path still answers. The tilefish path runs the same input on the side; the two outputs are compared (bytes, or the tolerance of step 4) and counted, and a mismatch is logged with its input, so it can be replayed offline. A failure of the tilefish path never fails the request.
    3. Run dual mode on every target GPU, on real traffic, until the counters are clean. Then make tilefish the default with the old path as the fallback, and remove the old path last.

6. Only then, performance

Measure before changing anything, then change one thing, and verify again (step 4).

  • Where the time goes: tilefish.profile_plan(graph, "build/", pin=..., bucket={...}, out="timing.json") times every step of the plan, and tilefish-explain build/ --graph G --advise --timing timing.json ranks the steps by time and lists what could become one kernel, why it is not one today and what to do (../advise.md).
  • Fusion is on by default (tilefish.fusion(), version 2): the arithmetic between calls becomes generated kernels, a layer norm with the add before it one kernel, exactly. A cuBLASLt GEMM's bias, ReLU or residual can run in the library (epilogues="library"), and an extern can take its epilogue in its own kernel (tilefish.hook): fusion.md.
  • Hand-written kernels for the ops that dominate, as externs; probes time the phases inside one (../instrument.md).
  • Memory and launches: export(..., reuse=True) lets intermediates share bytes; capture puts a plan in a CUDA graph.

Every change of numerics is a declaration (a mode of tilefish.fusion, an imported table, a kernel), so it is in the digest, and the bytes do not change without one.

Common pitfalls

Buckets are exact, and padding can change reductions. A plan runs a bucket exactly; another size is refused, not padded. A request of 100 tokens runs in the 256 bucket only after you pad it, and padding is harmless only where no op mixes the padded rows into the real ones. Per-row ops (GEMMs, a norm over the features, elementwise code) and a causal attention (a query never reads a later key) are safe for right padding: the GPT-2 example checks that the logits of the real positions do not depend on what pads them. A mean over the tokens, a non-causal attention, a softmax over the padded axis or batch statistics are not: mask them with the real count, a device scalar (n: DevScalar[i32], tilefish.iota(x, axis) < tilefish.load(n); operators.md, lowering.md). The padded rows' results are garbage; do not read them. A bucket also picks the GEMM algorithm: the rows a 256-row GEMM computes are not always the bytes torch computes for 100 rows.

Views are not every operator's tensors. A reshape, permute, split or select is a view. Generated code reads a view where it is; a declared operator takes one only where its parameter says so (Strided[...] on an extern); a library GEMM takes a contiguous tensor (a layer's weight in a stack is one). Passing a strided view anywhere else is refused at the call, with what to do:

p: argument 'a' is a strided view (View[T, 64, bf16]); this parameter takes a contiguous tensor: pass the unsplit tensor, compute from the view
(x + 0 is a contiguous copy), or have an extern declare the parameter Strided[...] (a chunk that does not start on a 16-byte boundary is a view too)

tilefish.contiguous(view) materialises it (a copy, one step of the plan); an extern that declares the parameter Strided reads it in place, as the GPT-2 attention reads q, k and v.

Rounding points and casts. Every torch op on a bf16 or f16 tensor rounds its result, so five ops round five times; tilefish rounds where the IR says, and each op rounds to its own dtype. Write the original's ops one for one in its dtypes and the bytes follow. Three details decide them:

  • a Python scalar: torch applies 0.044715 * x of a bf16 x in f32 and rounds once; tilefish's default rounds the scalar to bf16 first, and tilefish.fusion(intermediates="opmath") does it torch's way;
  • f32 math: torch's kernels are built without fast math; math="ieee" (per graph, kernel or op) gives CUDA's expf, tanhf, rsqrtf, IEEE division;
  • contraction: a graph body contracts nothing (a * b + c rounds twice) unless tilefish.fma or fp_contract="mul-add" says so, while a fused kernel of the original (a layer norm) may contract.

Integer powers are a classic: torch.pow(x, 3.0) on CUDA computes x * x * x in the tensor's type, which rounds twice in bf16.

Autocast. Under torch.autocast each op runs in the dtype autocast's lists give it (matmuls and convolutions in 16 bits; layer norms, softmax, sums and many pointwise ops in f32; an op of mixed inputs in the widest), and nothing in the model's code says which. Either record what autocast did (run the model once under it with forward hooks that print each module's output dtype) and write those casts into the graph, or port the model in one dtype (model.to(torch.bfloat16)) and compare with that, as the GPT-2 example does.

Data-dependent control flow cannot go into a plan. A plan is a static list of launches per bucket. if x.max() > t:, a loop until a token is EOS, nonzero, routing with a variable number of tokens per expert, an early exit: none of these is a step. Keep those decisions in the host, between runs of plans (a decode loop, sampling); make a variable count a bucketed size or a device scalar with a mask; or make one graph per branch, in one plan set.

Decode and the KV cache. A decode step updates state in place and reads a position that moves every step. A cache the caller owns is an InOut[...] parameter, written by an extern or a kernel that stores the new rows into it; state only the plans use can be a carried buffer (@tilefish.graph(carried=("h",))) that the arena keeps between the plans of a set; the position and the valid length are device scalars (DevScalar[i32]), so one plan, and one CUDA graph, serves every step. Prefill and decode are two graphs of one plan set on one shared arena (plans.md: plan sets, shared arenas, carried buffers; operators.md: device scalars). The GPT-2 example ports the prefill (a whole prompt) only.

From a torch model: GPT-2, a worked example

The reference is Hugging Face transformers' GPT2LMHeadModel (openai-community/gpt2, 124M parameters) in eval mode, in bf16 (model.to(torch.bfloat16)) and in f32. The port is written by hand, module for module (nanoGPT's model was the inspiration of an earlier experiment; nothing of it is copied):

file what it is
model.py the port: build(Config(), tilefish.bf16) returns the graph and its operators; no torch, no Triton
attention.py the causal flash-attention kernel in Triton (the one op without torch's kernel)
verify.py step 4: each op alone, each layer through taps, the logits, padding
export.py step 5: the export, Python's replay, the files the Rust host reads, a timing
runner/ the Rust host: the plan, the weights bound once, each case against Python's replay

python/tests/test_example_gpt2.py plans the full model without a GPU and, on one, holds a small random GPT2LMHeadModel to the port in bf16 and f32.

The op map

transformers (module, torch op) the port bytes (bf16 and f32)
wte(input_ids) + wpe(arange(T)) tilefish.gather_rows twice and an add, in the graph body torch's
ln_1, ln_2, ln_f: nn.LayerNorm layer_norm: two ordered means (tilefish.tree(256)), rsqrt, the affine tail; fused with the residual add before it a tolerance (another order of adds)
c_attn, c_proj, c_fc, mlp.c_proj: Conv1D, torch.addmm(b, x, W) with W stored [in, out] cublaslt.gemm_bias, layout="NN", heuristic="torch" torch's
.split(D, dim=2), .view(...).transpose(1, 2) qkv.reshape(T, 3, H, HD).select(1, j).permute(1, 0, 2): three views no copy
scaled_dot_product_attention(is_causal=True) a Triton flash-attention extern that reads the three views a tolerance (another kernel)
NewGELUActivation: eight torch ops gelu_new: the same eight ops, under intermediates="opmath" and math="ieee" torch's
residual adds x + a in the graph body torch's
lm_head (tied to wte, no bias): x @ wte.T cublaslt.gemm, heuristic="torch" torch's

The graph, for one layer (the per-layer weights are views of stacked tensors):

def block(x, i, w):
    """``GPT2Block`` ``i``: ``x + attn(ln_1(x))``, then ``x + mlp(ln_2(x))``."""
    q, k, v = heads(c_attn(layer_norm(x, w["ln_1_w"][i], w["ln_1_b"][i]), w["attn_w"][i], w["attn_b"][i]))
    x = x + attn_proj(attention(q, k, v), w["attn_proj_w"][i], w["attn_proj_b"][i])
    h = c_fc(layer_norm(x, w["ln_2_w"][i], w["ln_2_b"][i]), w["fc_w"][i], w["fc_b"][i])
    return x + mlp_proj(gelu_new(h), w["mlp_proj_w"][i], w["mlp_proj_b"][i])

and the GELU, written as transformers writes it: 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0)))).

def gelu_new(x):
    x3 = x * x * x
    inner = math.sqrt(2.0 / math.pi) * (x + 0.044715 * x3)
    th = tilefish.tanh(inner.to(f32)).to(dt)
    return 0.5 * x * (1.0 + th)

The whole model plans without a GPU: per bucket 98 steps, 49 pinned cuBLASLt GEMMs (four per layer and lm_head), 12 attention launches and 37 fused regions (the embedding with the first layer norm, then per layer the GELU and the two residual adds, each with the layer norm after it).

Verify

From python/examples (with tilefish[gpu] and transformers; the weights download from Hugging Face):

python -m gpt2.verify --dtype bf16 --tokens 256
GPT-2 12 layers, bf16, T = 256, openai-community/gpt2; torch 2.9.1+cu128, NVIDIA B300 SXM6 AC MIG 1g.67gb
1. each op alone, on torch's input:
  embed        identical   max rel 0.0e+00
 layer 0:
  ln_1         100.00% equal   max rel 2.8e-07
  c_attn       identical   max rel 0.0e+00
  attention     92.28% equal   max rel 3.5e-03
  attn_proj    identical   max rel 0.0e+00
  ln_2         100.00% equal   max rel 4.2e-07
  c_fc         identical   max rel 0.0e+00
  gelu         identical   max rel 0.0e+00
  mlp_proj     identical   max rel 0.0e+00
  residual     identical   max rel 0.0e+00
 layer 11:
  ln_1         100.00% equal   max rel 9.1e-08
  c_attn       identical   max rel 0.0e+00
  attention     94.96% equal   max rel 2.3e-03
  attn_proj    identical   max rel 0.0e+00
  ln_2         100.00% equal   max rel 6.5e-04
  c_fc         identical   max rel 0.0e+00
  gelu         identical   max rel 0.0e+00
  mlp_proj     identical   max rel 0.0e+00
  residual     identical   max rel 0.0e+00
  ln_f         100.00% equal   max rel 4.3e-07
  lm_head      identical   max rel 0.0e+00
2. each layer inside the plan (taps), against torch:
  layer  0  max rel  ln_1: 2.8e-07  attention: 3.5e-03  gelu: 3.1e-03  out: 1.5e-03
  layer  1  max rel  ln_1: 5.6e-03  attention: 7.5e-03  gelu: 5.6e-03  out: 2.1e-04
  layer  2  max rel  ln_1: 5.1e-03  attention: 2.3e-02  gelu: 3.0e-03  out: 2.0e-04
  layer  3  max rel  ln_1: 7.8e-03  attention: 6.1e-02  gelu: 2.2e-02  out: 3.8e-04
  layer  4  max rel  ln_1: 1.5e-02  attention: 3.3e-02  gelu: 1.2e-02  out: 2.7e-04
  layer  5  max rel  ln_1: 8.2e-03  attention: 2.6e-02  gelu: 2.1e-02  out: 1.7e-04
  layer  6  max rel  ln_1: 8.7e-03  attention: 2.5e-02  gelu: 1.9e-02  out: 1.7e-04
  layer  7  max rel  ln_1: 9.2e-03  attention: 2.8e-02  gelu: 1.5e-02  out: 2.5e-04
  layer  8  max rel  ln_1: 1.5e-02  attention: 1.7e-02  gelu: 1.5e-02  out: 2.5e-04
  layer  9  max rel  ln_1: 1.2e-02  attention: 2.2e-02  gelu: 1.6e-02  out: 3.6e-04
  layer 10  max rel  ln_1: 1.4e-02  attention: 2.2e-02  gelu: 1.5e-02  out: 5.0e-04
  layer 11  max rel  ln_1: 1.2e-02  attention: 4.0e-02  gelu: 2.0e-02
  ln_f          15.27% equal   max rel 5.9e-02
3. logits [256, 50257], max |logit| 324:
  tilefish     67.3% of the elements equal, max |diff| 16 (rel 4.9e-02); argmax agrees at 253 of 256 positions (where not, torch's two best logits are at most 1 apart)
  torch eager  66.7% of the elements equal, max |diff| 9.81 (rel 3.0e-02); argmax agrees at 244 of 256 positions (where not, torch's two best logits are at most 1 apart)
4. padding: 219 tokens padded to the bucket T = 256 with zeros, then with random ids: the logits of the 219 real positions are identical

How to read it:

  • Check 1: the embedding, the five GEMMs, the GELU and the residual adds are torch's bytes on torch's input. The layer norms are not torch's order of adds and differ in a few elements ("100.00% equal" rounds a fraction just below one); the attention kernel is not torch's and differs in 5 to 8% of its elements, by at most 3.5e-3 of its largest value, about one bf16 step.
  • Check 2: in bf16 those differences grow through the layers (a bf16 step is 2**-8 of a value), as they would between any two implementations.
  • Check 3 puts it in proportion: torch's own eager attention is as far from torch's SDPA as the port is (67% against 67% of the logits equal), and agrees with it on the greedy token less often (244 against 253 of 256 positions); where the port and torch disagree, the two best tokens are within one bf16 step of each other.
  • Check 4: right padding to the bucket leaves the real positions' logits unchanged, so a 219-token prompt can run in the 256 bucket.

In f32 (--dtype f32, TF32 off on both sides) the same ops are torch's bytes, the layer norms and the attention differ in the last bits (a relative 1e-7 to 1e-6), and the logits agree to a relative 1e-5:

prompt dtype logits: tilefish against torch (SDPA) torch eager against torch (SDPA)
T = 64 bf16 rel 8.1e-3, argmax 64 of 64 rel 1.1e-2, argmax 62 of 64
T = 256 bf16 rel 4.9e-2, argmax 253 of 256 rel 3.0e-2, argmax 244 of 256
T = 1024 bf16 rel 2.2e-1, argmax 1016 of 1024 rel 2.4e-1, argmax 1010 of 1024
T = 64 f32 rel 1.1e-6, argmax 64 of 64 rel 9.5e-7, argmax 64 of 64
T = 256 f32 rel 1.2e-5, argmax 256 of 256 rel 6.9e-6, argmax 256 of 256
T = 1024 f32 rel 1.5e-5, argmax 1024 of 1024 rel 1.4e-5, argmax 1024 of 1024

("rel" is the largest difference over the largest logit. GPT-2's activations have a few very large channels, so in bf16 the difference of a whole 1024-token forward reaches tens on logits of a few hundred, for torch against itself as for the port.)

Export, replay, and the Rust host

gpt2.export writes the export to build/plan/ (exported with reuse=True, so intermediates share bytes), its digest to build/plan.pin, and what the Rust host reads to build/weights/, build/cases/ and build/cases.json:

python -m gpt2.export build/ --dtype bf16 --bench
cargo run --release --manifest-path gpt2/runner/Cargo.toml -- build/ $(cat build/plan.pin)
exported <Plan 'gpt2': 3 buckets, 98 steps, arena 27394048 bytes, digest b12348bf2613> in 13 s: per bucket 98 steps, 49 cuBLASLt GEMMs and 49 kernels; arena 26.1 MiB; pin b12348bf2613db65781dfa0611a0609861d56f9d812194a34080722f0be1b676
T=64: replay equals jit: True; ms per forward: tilefish (CUDA graph) 0.735, torch eager 2.317
T=256: replay equals jit: True; ms per forward: tilefish (CUDA graph) 1.511, torch eager 2.309
T=1024: replay equals jit: True; ms per forward: tilefish (CUDA graph) 5.837, torch eager 6.661
loaded, verified and bound in 0.45 s
T=64: logits identical to Python's replay (launch), identical (CUDA graph); ms per forward: launch 0.772, graph 0.737
T=256: logits identical to Python's replay (launch), identical (CUDA graph); ms per forward: launch 1.553, graph 1.513
T=1024: logits identical to Python's replay (launch), identical (CUDA graph); ms per forward: launch 5.893, graph 5.844

The export takes 13 s (the fused regions are checked against their ops on the device at every bucket), and its plan needs a 26 MiB arena for all three buckets. Python's replay of the files equals jit, and the Rust host's logits equal Python's replay byte for byte, from a launch and from a CUDA graph. In f32 the same holds; a forward takes 2.9, 7.7 and 31.0 ms (torch eager: 3.1, 7.8 and 28.5 ms).

Performance, only now

The timings above are for the port as verified: a B300 MIG slice (sm_103), batch 1, every logit of every position (as GPT2LMHeadModel returns them), against torch eager (not torch.compile). Ask where the time goes, at T = 1024:

python -c "import tilefish; from gpt2.model import Config, build; tilefish.profile_plan(build(Config(), tilefish.bf16).gpt2, 'build/plan', pin=open('build/plan.pin').read().strip(), bucket={'T': 1024}, out='timing.json')"
tilefish-explain build/plan --graph gpt2 --advise --timing timing.json
time by class (measured | roofline estimate):
  library        49 steps      4488.6 us  76.9%  |      555.2 us  66.1%  623.44 MiB
  fused          37 steps       520.1 us   8.9%  |      237.8 us  28.3%  364.70 MiB
  opaque         12 steps       831.5 us  14.2%  |       47.0 us   5.6%  72.00 MiB
  total          98 steps      5840.2 us

time by op (the ten longest):
      3769.9 us     1 steps  library      lm_head
       831.5 us    12 steps  opaque       attention
       261.5 us    23 steps  fused        fused_2e67dfcdad82
       235.2 us    12 steps  fused        fused_53cc0b95fa4f
       235.0 us    12 steps  library      c_fc
       207.3 us    12 steps  library      c_attn
       189.1 us    12 steps  library      mlp_proj
        87.3 us    12 steps  library      attn_proj
        13.1 us     1 steps  fused        fused_bf897d3263df
        10.3 us     1 steps  fused        fused_fda4509b2879

One GEMM, lm_head, takes 65% of the forward: 1024 x 50257 x 768 runs at about 21 TFLOP/s. N = 50257 is odd, and the same product with N = 50304 (a multiple of 64) takes 0.24 ms instead of 3.77 in torch (torch.mm, measured on the same slice). So pad the vocabulary: Config(pad_vocab=64) gives wte zero rows up to 50304 and returns the real 50257 columns (one copy step). That is a change of the model, so verify it again (step 4) before keeping it:

python -m gpt2.verify --dtype bf16 --tokens 256 --pad-vocab 64
python -m gpt2.export build-pad/ --dtype bf16 --bench --pad-vocab 64

The lines of check 1 and 3 that changed, and the export:

  lm_head       99.99% equal   max rel 6.2e-03
3. logits [256, 50257], max |logit| 324:
  tilefish     67.3% of the elements equal, max |diff| 16 (rel 4.9e-02); argmax agrees at 253 of 256 positions (where not, torch's two best logits are at most 1 apart)
exported <Plan 'gpt2': 3 buckets, 99 steps, arena 116260864 bytes, digest 945f50a088ef> in 14 s: per bucket 99 steps, 49 cuBLASLt GEMMs and 50 kernels; arena 110.9 MiB; pin 945f50a088efa8b668335c75509ebdd4e5bbb0aface615de4164c31c15e55c10
T=64: replay equals jit: True; ms per forward: tilefish (CUDA graph) 0.851, torch eager 2.387
T=256: replay equals jit: True; ms per forward: tilefish (CUDA graph) 1.166, torch eager 2.213
T=1024: replay equals jit: True; ms per forward: tilefish (CUDA graph) 3.028, torch eager 6.644

In milliseconds per forward, both exports and both dtypes (the Rust host's logits equal Python's replay in all four):

bf16, T = 64 T = 256 T = 1024 f32, T = 64 T = 256 T = 1024
the port as verified 0.735 1.511 5.837 2.894 7.732 31.021
pad_vocab=64 0.851 1.166 3.028 3.422 8.224 31.779
torch eager 2.317 2.309 6.661 3.052 7.804 28.525

So the change is a decision with a cost on each side. In bf16, lm_head gets another cuBLASLt algorithm and is no longer torch's bytes (99.99% of its elements equal at T = 256, 89% at T = 1024, within one bf16 step), while the logits stay as close to torch's as before (argmax 253 of 256, and 1021 of 1024 at T = 1024); it is 1.3 times faster at T = 256 and 1.9 times at T = 1024, slower at T = 64, and the padded logits need an arena of 111 MiB instead of 26. In f32 lm_head stays torch's bytes and the change makes every bucket slower. Keep it for bf16 prompts of 256 tokens or more; leave it out of f32.

The next ones are the attention kernel (14%), whose speed is the kernel's own, and the GELU after c_fc, which the advisor lists as an epilogue for a GEMM that takes one (an extern with tilefish.hook, fusion.md).

What the example does not do

It is a prefill: the whole prompt, batch 1, every position's logits. Generating text needs a decode step with a KV cache (see the pitfalls) and the sampling loop in the host. Batches would add a dimension and a padding mask for prompts of other lengths.

From a hand-written CUDA, C++ or Rust engine

An engine already chose its kernels, its library algorithms and its buffers. Keep all three, so the port computes the engine's bytes, and let tilefish take over the typing, the checks, the launch plan and the hosts.

  1. Inventory one forward step: every launch in order with its grid, block, shared memory and arguments (a profiler trace of one step lists them), every buffer with its size, which are reused, which are updated in place, and every library call with the algorithm it pins (the cuBLASLt cublasLtMatmulAlgo_t attributes, cuDNN engine configurations).
  2. Take the kernels as they are. CUDA C++: take the engine's cubin, or build its PTX with the engine's flags, and declare @tilefish.extern(cubin={"sm_103": "k.cubin"}, symbol=..., block=..., grid=...) (or ptx=), its C parameters in order: pointers, Dim scalars, const[i32] fixed arguments, DevScalar for a counter it reads from device memory, Null for a pointer it does not use (operators.md, prebuilt binaries). Triton or CuTe DSL kernels: triton=, cute=. A cubin is the same machine code, so the same bytes.
  3. Import the library pins: cuBLASLt algorithms as an AlgoTable (the nine configuration attributes, or the 64 bytes of the pin as hex), cuDNN as a CudnnTable. A device the table is not for is refused, never handed to a heuristic.
  4. Write the graph as the engine's launch list. A buffer the engine updates in place is an InOut (or an Out that MayAlias its input); state between stages is a carried buffer; scalars the kernels read from device memory are device scalars. What the engine computes between its kernels can stay an extern or become generated code (reproduce the engine's order of adds with order=, tilefish.fma and math="ieee", or accept a tolerance).
  5. Verify against dumps of the engine: a debug switch in the engine writes every buffer after each launch for a fixed input; load them into torch tensors and compare them with the plan's taps (step 4). Every op whose binary is the engine's should be identical; run_step replays one step of the exported plan on the engine's buffers under the production pin.
  6. Replace the engine's launch code by a host (Rust or C++), with the shadow run of step 5, and keep the old path until the counters are clean.

Where to go next