Skip to content

Plan schema 1 (plan.json, "tilefish.plan.v1")

A launch plan is a @tilefish.graph compiled into, for every combination of the bucket values of its dimensions, an ordered list of steps (each one launch of a manifest entry: a Triton kernel, a prebuilt PTX or cubin, or a pinned cuBLASLt GEMM) with every pointer argument bound to a buffer or a view of one, and one memory plan: every buffer that is not provided by the caller lives in a single arena at a fixed byte offset, the same in every bucket. A host that holds a verified plan and its manifest launches the steps in order on one stream and allocates nothing while it does, so the whole execution can be captured in a CUDA graph once per bucket at fixed addresses.

The Python package writes and reads this document (tilefish.plan, tilefish.runtime.export, tilefish.run(graph, ..., mode="replay", plan=...)). The Rust crate implements this specification, and the C++ host (crates/tilefish-capi, docs/en/rfcs/0002-cpp-host.md) runs plans through that Rust implementation, so what this document says of the Rust host holds for it too. Everything is checked by tests in python/tests/ (named in section 14) and the Python code that writes or checks each part is named where the part is described (python/src/tilefish/_plan.py, _planrun.py).

A reader of this document is assumed to know manifest schema 3 (docs/en/manifest-schema-3.md): the entries of kernels and library, the abi, the dimension expression grammar, the preconditions, canonical JSON and the launch checks a host makes for one launch. A plan adds nothing to those: a step is a launch of a manifest entry, checked and made exactly as a single launch is; the plan says which entry, with which memory.

Contents: 1 what a plan is made of; 2 the top level; 3 the digest and the pin; 4 strict reading; 5 dimensions, buckets and shape expressions; 6 buffers and the arena; 7 steps (7.5 copy steps, 7.6 memset steps); 8 order, liveness and reuse; 9 what a host does; 10 CUDA graphs; 11 the Python API; 12 what a plan does not do (version 1); 13 an example; 14 where it is tested; 15 plan sets (several plans over one manifest), 15.1 an arena shared by the plans of a set, 15.2 carried buffers.

1. What a plan is made of

  • dims: the dimensions of the graph (the free dimensions of its parameters' shapes), each with the list of sizes planned for it (its buckets). A bucket combination is one size for every dimension. There is one list of steps per combination, and a call selects one by the sizes of its tensors, which must equal a bucket exactly (there is no padding).
  • buffers: every tensor the plan names, in one table. A buffer is external (the caller provides it: a parameter or a returned value), lives in the arena (an intermediate, the slot of a device scalar, the workspace of the GEMMs), or is carried (a parameter whose tensor the arena holds between executions, in a region the host places after the plans' own: section 15.2). Its dtype and shape are fixed by the graph; the shape is an expression over dims.
  • buckets[i].steps: the launches of one bucket combination, in order. A step names a manifest entry (entry, whose stem includes the entry's own buckets, such as gemm_up.M64) and binds each pointer parameter of that entry, in the order of the entry's ABI, to a buffer and, optionally, to a view of it.
  • the memory plan: arena_bytes and the offset of every arena buffer, in bytes from the start of the arena, aligned to 256, the same in every bucket.

Views copy nothing. A step that reads the q, k and v of a fused [M, 3, H, D] tensor passes three views of one buffer (offsets 0, H*D and 2*H*D elements, strides 3*H*D, D, 1), and the kernel is handed three pointers and the strides as scalars, as for any Strided[...] pointer (manifest schema 3, section 5.1); a kernel that takes one stride pair for the three (a stride that several views share, StrideOf(("q", "k", "v"), axis)) is handed it once, and the step binds it from the first view and holds the others to it, as a single launch does.

2. The top level

{"schema": "tilefish.plan.v1", "tilefish": "0.0.3", "graph": "block", "arch": "sm_103", "manifest_digest": "<64 hex>", "dims": {"M": [32, 64, 128]},
 "reuse": false, "arena_alignment": 256, "arena_bytes": 9634048, "buffers": [ ... ], "outputs": ["out0"], "buckets": [ ... ], "plan_digest": "<64 hex>"}

Exactly these keys, no others and none missing (a reader refuses the file otherwise), and optionally roles:

key type and rule
schema the JSON string "tilefish.plan.v1". Any other value is refused ("not a tilefish plan of schema ...").
tilefish string, the version of the package that wrote the file. Informative: it is not digested.
graph string, the name of the graph: an ASCII identifier ([A-Za-z_][A-Za-z0-9_]*).
arch string sm_<2 or 3 digits>, no suffix: the architecture the entries of the manifest are taken for. A host refuses to run the plan on a device of another architecture.
manifest_digest 64 lowercase hex digits: the digest (manifest schema 3, section 3) of the manifest in the same directory. The plan is refused if the manifest has another digest.
dims object: dimension name (identifier) -> non-empty, strictly increasing list of integers >= 1 (the buckets). May be {} (a graph with no dimension has one bucket combination, the empty one).
reuse boolean: whether the memory plan lets buffers share bytes (section 8).
arena_alignment the integer 256.
arena_bytes integer >= 0, equal to the end of the last arena region rounded up to 256: align_up(max over arena buffers of offset + align_up(bytes), 256), 0 if there is none.
buffers non-empty list of buffer objects (section 6).
outputs list of buffer names: the buffers of role output, each once, in the order the graph returns them.
buckets list with one entry per bucket combination (section 5), each {"values": {...}, "steps": [...]} (section 7).
plan_digest 64 lowercase hex digits (section 3).
roles (optional) the string "declared", present exactly when the graph declares which parameters are inputs and which weights (@tilefish.graph(inputs=..., weights=...), section 6). Any other value is refused. A plan of a graph that declares nothing has no roles and is, with its digest, what it always was; a reader that predates the key (the published crate 0.0.2, tilefish 0.0.4) refuses a plan that has it.

Integers are JSON integers: a reader refuses 2.0, 1e3 and true where an integer is wanted (Python: type(v) is int).

3. The digest and the pin

plan_digest(doc) (python/src/tilefish/_plan.py) is

sha256( b"tilefish.plan-digest.v1\0" + canonical_json(body) ),   body = doc without the keys "plan_digest" and "tilefish"
  • canonical_json is exactly the manifest's: object keys sorted (code point order), separators "," and ":", no whitespace, non-ASCII escaped (ensure_ascii), no NaN/Infinity. A plan has only strings, integers, booleans and null (a plan that was only made in memory has null for arch and manifest_digest; a file never does). Lists keep their order (the order of buffers, buckets, steps and arguments is part of the plan).
  • The digest includes manifest_digest, so pinning the plan digest pins the manifest, and with it every binary and every pinned GEMM algorithm the plan launches.
  • Test vectors (test_plan_schema.py): the digest of {} is 345611870fcf5832cd7533b55c9bcb061b78c17c4f53635c9bcf8f7cffca6893; the digest of {"schema": "tilefish.plan.v1", "tilefish": "x", "graph": "g", "plan_digest": "ignored"} is f59e1096fcfb737bcb745fc0a11258a25a1e2eb2fd3039b8958c777d4dadc71e (it is the sha256 of the tag and {"graph":"g","schema":"tilefish.plan.v1"}).

A plan needs a trust anchor, as a manifest does. The digests in a directory sit next to the files they describe, so whoever can write the directory can rewrite all of them. The anchor is the pin (the plan_digest the exporter returned, kept somewhere trusted) or an explicit statement that whatever the directory holds is fine (trust_directory=True in Python); a replay with neither, or with both, is refused. The checks, in this order (_plan.read_plan, _plan.load_plan):

  1. the file is read as strict JSON (section 4) and has schema "tilefish.plan.v1";
  2. its digest is computed; with a pin it must equal the pin (else refused: "has digest X, but the pin is Y"); and it must equal the file's own plan_digest (else refused: "was edited: its plan_digest says ...", which also catches an edit when only the directory is trusted);
  3. every rule of sections 2 and 5 to 8 (validate_doc);
  4. the manifest next to it is loaded and verified as manifest schema 3 says (every cubin's digests), and its digest must equal manifest_digest (else refused: "built against the manifest with digest ...");
  5. every step is what the manifest's entries say (section 7.3, check_against_manifest);
  6. a host that has the graph (Python does) requires the document to be exactly the plan it derives from the graph for the same dims and reuse, ignoring arch, manifest_digest, tilefish and plan_digest: a graph that changed since the export is refused as stale. (A host that has no graph, such as the Rust one, has steps 1 to 5 and the pin.)

4. Strict reading

The file is read as strict JSON, as the manifest is: no duplicate keys in an object, no NaN/Infinity, no number that does not fit a double (an integer must be at most 2**53 in magnitude, so that every language reads the same number); a file larger than 256 MiB, nested too deeply, or that is not UTF-8 is refused. An object has exactly the fields listed for it: a missing or an unknown field is a refusal.

Limits, so that a document cannot make a reader do work out of proportion to its size (a reader counts before it lists): at most 4096 bucket combinations (the product of the lengths of the dims lists), 32768 buffers, 1 048 576 steps in a bucket and 256 arguments in a step. A refusal that quotes the document quotes at most the first 1000 characters of what it refuses.

5. Dimensions, buckets and shape expressions

  • dims names every dimension that appears in any shape. The bucket combinations are the Cartesian product of the lists, with the names sorted (code point order), the first name varying slowest, each list ascending: for {"B": [1, 2], "M": [32, 64]} they are B1 M32, B1 M64, B2 M32, B2 M64. buckets has exactly one entry per combination, in this order, and buckets[i].values is the object {name: size} of the i-th.
  • A shape entry (of a buffer) is a JSON integer >= 1 or a string: a dimension expression, the grammar of the manifest's shapes: integers, names, +, -, *, // (exact), unary -, parentheses and cdiv(a, b), at most 512 characters. Python writes only affine forms ("M", "3*M", "2*M + 3"). It must mention only names in dims and evaluate to an integer >= 1 for every combination; an expression that is not an affine form that folds to an integer under the combination's values is refused.
  • Selecting a bucket at a call. The host binds the dimensions from the sizes of the external tensors it is given (each external's shape expressions are equations; 3*M against 192 gives M = 64, and a size that is not a whole multiple is a refusal), exactly as it binds the dimensions of one launch. Every name in dims must be bound, and its value must be in its list; else the call is refused with the kind bucket and nothing runs. Two externals that bind a name differently are refused.
  • A dimension only an operator's Out parameters mention. An extern may write a tensor whose dimension no argument of the call has (a [B] mask made from a device scalar: manifest schema 3, section 7). In a graph such a call binds it to the graph's dimension that is the same Dim (its name, divisible_by and buckets): the plan is made per bucket of the graph's dimensions, so the step's Out buffer has the bucket's size, and the step binds the entry's dimension from that buffer as any launch given its Out tensor does (section 7.2). A graph that has no such dimension cannot make the call (TilefishTypeError at the call).

6. Buffers and the arena

buffers is a list of objects with exactly the fields name role dtype shape offset bytes:

field type and rule
name string, an identifier, unique in the plan. The graph's parameters keep their own names; the returned values have the names the graph gives them (@tilefish.graph(outputs=("y", "residual")), in the order it returns them) or, when it gives none, out0, out1, ...; an intermediate is t0, t1, ... in the order the steps make them, the workspace workspace. A name that would collide with a parameter's or a returned value's gets underscores. A host takes a returned value by its name, or by out<i> for the i-th returned value whatever its name (the name every returned value had before a graph could name them), when no buffer of the plan is called out<i> (Python _plan.output_buffer, Rust LaunchPlan::output_buffer).
role one of the eight below.
dtype one of bf16 f16 f32 i32 i64 u8 e4m3 e5m2 (the dtypes that have a storage type).
shape list of integers >= 1 and dimension expressions (section 5); [] for a device scalar.
offset null for an external role and for carried (the host places it: section 15.2); for an arena role an integer >= 0 that is a multiple of 256.
bytes integer >= 1, exactly the largest of product(shape) * itemsize(dtype) over the bucket combinations.
role what it is who provides it a step may
input a graph parameter that a call gives every time (an activation) the caller, at every call read
weight a graph parameter that a host binds once (a model weight) the caller, once (or at every call) read
inout an InOut parameter: updated in place the caller read and write
output a returned value (a result of a call) the caller (allocated by the Python run unless outputs= gives it) write (first), then read and write
intermediate a result that is not returned the arena write (first), then read and write
devscalar a DevScalar parameter: one element in device memory (DevScalar[i32]: a token count) the host writes the value into its slot before the first launch read
workspace the cuBLASLt workspace, and the global scratch of the kernels that have one: dtype u8, shape [N] with a static N the arena (only as the workspace of a step)
carried a parameter the graph declares carried (@tilefish.graph(carried=("h",))): a tensor the arena holds between executions (section 15.2) the arena, in its carried region (an earlier execution on the arena wrote it) read and write
  • The buffers listed first are the graph's parameters, in the order of its signature; they have the roles input, weight, inout, devscalar and carried. The rest are made by the steps, then the workspace. Neither input nor weight is written, and a reader checks nothing else about the two. Who chose them: with "roles": "declared" the graph did (@tilefish.graph(inputs=("x",)), weights=(...) or both: every read-only tensor parameter is one or the other, an InOut is inout and a DevScalar is devscalar), and a host may bind the weights once per instantiation and only the inputs at every call (section 9). Without roles the writer labelled a parameter by its shape (weight when it mentions no dimension), which is not a contract: every parameter of a fully static graph is a weight, its per-call inputs included, so a host does not bind the weights of such a plan once (both hosts refuse to).
  • A devscalar has shape [] (one element). There is at most one workspace, and it exists exactly when some step has a workspace: a step of kind library, or (tilefish 0.0.7, crate 0.0.5) a step of kind kernel whose entry has a global scratch (manifest schema 3, section 4.6). Its bytes is the largest of the workspace_bytes of the library entries the plan uses (a reader requires it to be at least each one's: section 7.3) and of the global scratch of every such kernel step at every bucket: global_scratch bytes per CTA (the declaration's: a plan is made without building anything) times the CTAs of the step's grid at the bucket (the tiles of a persistent grid, which the programs a device runs are at most, times num_ctas). The steps run one after the other, so one scratch serves them all, as one workspace serves the GEMMs. A plan whose kernels have no global scratch is what it always was.
  • The arena is arena_bytes bytes of device memory, allocated once by the host and aligned to 256 bytes. The region of an arena buffer is [offset, offset + align_up(bytes, 256)), which must lie inside the arena. A buffer's region is large enough for every bucket: a smaller bucket uses a prefix of it, so a buffer is at the same address in every bucket. Without reuse (section 8) no two regions overlap. A carried buffer has no region in this layout: the host allocates the arena with a carried region after the arena_bytes of its plans, and places it there (section 15.2), so it overlaps no buffer of any plan.
  • An external's bytes is informative for the host's own allocation (the largest bucket); at a call its size is the bucket's product(shape) * itemsize, which the host checks.

7. Steps

7.1 The fields

buckets[i].steps is a list (the same length in every bucket) of objects with the fields entry kind args and, for kind library and for a kernel step whose entry has a global scratch, workspace, and for a kernel step whose entry has fixed arguments given per call, given; a step of kind copy has exactly the fields kind args (section 7.5), and so does a step of kind memset (section 7.6):

field type and rule
entry string: the stem of a manifest entry (rmsnorm, attention, gemm_qkv.M64: an identifier, then .<Dim><value> per bucketed dimension of the operator). It is the entry's own bucket, which differs between buckets of the plan for an operator whose binaries are bucketed.
kind "kernel": an entry of the manifest's kernels (Triton or prebuilt binary). "library": an entry of its library (a pinned GEMM). The manifest must have the entry for arch in that section. "copy": a device-to-device copy (section 7.5), which names no entry. "memset": bytes set to zero (section 7.6), which names no entry.
args non-empty list, one object per pointer parameter of the entry's abi.params, in order (a kernel's scalar and fixed parameters are not arguments: the host derives them). A tensordesc parameter (a TMA descriptor of a tensor, manifest schema 3, section 5.5) is a pointer parameter here: the step binds its tensor. Names in one step are distinct.
workspace present when kind is "library", and on a step of kind "kernel" exactly when its entry has a global scratch (launch.global_scratch_size above 0, manifest schema 3, section 4.6; tilefish 0.0.7, crate 0.0.5): the name of the buffer of role workspace. A reader that predates the kernel step's refuses it.
given present exactly when the entry has fixed arguments given per call (manifest schema 3, section 5.3: a prebuilt binary's kind: "given" parameters), on a step of kind "kernel": a non-empty object, the name of every one of them (an identifier) to the JSON integer the call gave, in range of its type (i32, i64; a plan number is at most 2**53 in magnitude). The value may differ between buckets (a call may give an expression of the graph's dimensions, c=Rg, evaluated at each bucket); the names may not. It is part of the digest.

An argument is {"name": <string>, "binding": <buffer name>} and optionally "view": exactly the keys name, binding and view.

  • name is the name of the ABI pointer parameter (it must equal it; it is there so that a reader can check the order). For a library entry the pointers are the operands of the operation as its abi.params name them (a, b, bias for a bias GEMM, as declared, and c for a cublaslt.matmul with beta 1, manifest schema 3 section 9.5) and then out; for a lowered kernel they include the generated names of its results (out, out0, out1).
  • binding names a buffer of the plan. It must not be the workspace.
  • view is {"shape": [...], "strides": [...], "offset": n}: shape a list of integers >= 1, strides a list of integers >= 0 of the same length, offset an integer >= 0, in elements of the buffer's dtype. Without a view the argument is the whole buffer: the buffer's shape at the bucket, the row-major strides, offset 0. A view must lie inside its buffer: offset + 1 + sum((shape[a] - 1) * strides[a]) <= product(buffer shape at the bucket). The writer of a plan (Python) omits view exactly when the argument is the whole buffer; a reader accepts a view that equals the whole buffer too. A device scalar is bound whole, with no view. The numbers are the view's at the bucket, whatever the expressions they come from: a buffer of shape [4, "L", "L"] (each entry an affine form, section 5) has the stride L*L along its first axis, a product of two sizes that no shape entry writes, and its transpose is "strides": [576, 1, 24] at L = 24 (Python 0.0.5 refused to plan such a buffer; nothing changes for a reader).

The pointer of an argument is address(buffer) + view.offset * itemsize(buffer dtype), where address(buffer) is the address of the external tensor, or arena + buffer.offset.

7.2 What a host does with a step

The step is a launch of the manifest entry entry with the tensors of its arguments: pointer = as above, shape = view.shape (or the buffer's), element strides = view.strides (or the row-major ones). Everything else is as for a single launch in manifest schema 3: the host binds the entry's dimensions from those shapes and strides (section 5.1 there, with its canonical strides for axes of size 1; a dimension the arguments the entry reads leave unbound is bound from the shape of its out arguments, section 7 there), derives the runtime scalars (dimensions, element counts, strides, fixed values) and passes the step's given values at their slots, evaluates the grid expression, and checks every precondition of the entry (pointer_alignment of the passed pointer, static_size, divisible, bucket, max_elements, max_extent), that a pointer without strides in its ABI entry gets a dense tensor (the strides of its axes of size > 1 are the row-major ones), that the ranks and dtypes are the ABI's, that a written pointer (access out or inout) overlaps no other argument of the step (but an out pointer with alias and the in pointer it names, which may be exactly one tensor: manifest schema 3, section 5.4), and the grid against the device's limits. A kernel is launched with cuLaunchKernel (a Triton kernel with its two zero scratch slots, a prebuilt one with exactly its parameters), the entry's block (of a warp-specialised kernel: the warps of all its partitions, manifest schema 3, section 4.2) and its shared memory; the launch shapes of manifest schema 3 are those of a single launch: a persistent grid is cut to the programs the SMs the host loaded it for run (section 4.3: the device's, or the partition's, so a plan prepared on a partition runs its programs), a kernel of clusters is launched with cuLaunchKernelEx and its cluster (section 4.5), and a kernel with a global scratch (section 4.6) is given the buffer named by the step's workspace as its scratch, at its address in the arena, which a host checks holds the scratch of the launch at the bucket when it prepares the bucket; a library entry with cublasLtMatmul and its pinned algorithm (manifest schema 3, section 9), whose workspace is the buffer named by workspace, at its address in the arena (workspace_bytes of the entry are always there; the matmul is given the size the algorithm needs, at most that), so the call allocates nothing.

A TMA descriptor argument (a tensordesc parameter of the entry: manifest schema 3, section 5.5) is checked as that section says (its address 16-byte aligned, its strides multiples of 16 bytes, its dimensions within i32: kind tensor_map) and its CUtensorMap is encoded from the tensor of the argument, at every execution, with every check of section 9 step 3: the address address(buffer) + view.offset * itemsize (an arena buffer at arena + offset, an external at the caller's tensor), the view's shape and canonical strides, and the map of the entry. So an encode the driver refuses launches nothing, and a step launches with the maps of the memory it binds at this execution; no map is computed when the plan is made or loaded (the document has no addresses). Python keeps the last 4096 encodings by their arguments, which makes a repeated execution of one binding encode nothing new, and any other binding another key.

An operator with an implementation per architecture (manifest schema 3, section 4.1) is one entry name, its stem, whichever implementation runs, and its step's args name the operator's tensors, which every implementation takes in the same order; the manifest of the plan's arch has the entry of the implementation that architecture runs, with its own ABI (a tensor passed as a pointer or as a tensordesc, its own scalars and fixed arguments, its own preconditions), which the host follows as for any entry. Nothing in the plan says which implementation it is, so the plan of a graph is one document for every architecture. Python's planner resolves every step with every implementation, their preconditions included (a TMA descriptor's 16-byte strides, say), so a plan is made only when every implementation can run it.

The one binary an entry names serves every size of its unbucketed dimensions: a plan for M in {32, 64, 128} of a row kernel names the entry rmsnorm in all three buckets, with M bound from the shapes of the views; and every value of its fixed arguments given per call: two steps of one prebuilt binary with other given values name one entry.

7.3 What a plan is checked against in the manifest

check_against_manifest (and Python's export, which refuses to write a plan that fails it). For every step of every bucket:

  • the entry exists in the section kind says, for arch; for a library step the workspace buffer's bytes is at least the entry's workspace_bytes; a kernel step has a workspace exactly when its entry has a global scratch (launch.global_scratch_size above 0; how many bytes a launch of it needs depends on its grid at the bucket, which a host checks when it prepares the bucket);
  • the entry has as many pointer parameters (pointer and tensordesc) as the step has arguments, and argument i has the name of pointer i;
  • the step's given names exactly the entry's parameters of kind given (none: no given), and each value fits the parameter's type;
  • the dtype of the buffer is the pointer's dtype; the rank of the view (or buffer) is len(shape) of the ABI pointer;
  • a pointer with shape [] (a device scalar) is bound to a buffer of role devscalar, and only such a pointer is;
  • a pointer with access out or inout is bound to a buffer whose role is intermediate, output, inout or carried (a step never writes an input, a weight, a devscalar);
  • a buffer is written before it is read: a pointer with access in or inout is bound to a buffer that is input, weight, inout, devscalar or carried (an earlier execution on the arena wrote it: a host checks that when it runs the plan, section 15.2), or that an earlier step of the same bucket wrote (a pointer with access out; an inout pointer on a buffer not yet written is refused);
  • every output is written by some step of every bucket (a returned value no step writes would come back as whatever its tensor held).

A copy step (section 7.5) has no entry: of the rules above it has the last two, its src read (written before) and its dst written. A memset step (section 7.6) has no entry either: its dst is written.

7.4 What the rules of validate_doc say about steps and buckets (no manifest needed)

  • every bucket has the same number of steps, and in step k the kind, the workspace, the names of given and, for every argument, the name and the binding are the same in every bucket; only entry, the views' numbers and the given values may differ between buckets;
  • a given is a non-empty object of identifiers to JSON integers, on a kernel step;
  • every binding is a buffer; a workspace is the buffer of role workspace, and a step of kind library has one; a view is well formed and inside its buffer at that bucket;
  • a copy step is what section 7.5 says, and a memset step what section 7.6 says, at every bucket.

7.5 Copy steps

A step of kind "copy" is {"kind": "copy", "args": [{"name": "src", ...}, {"name": "dst", ...}]}: exactly those two fields (no entry: it launches no binary; no workspace), and exactly two arguments, named src and then dst, each a buffer and optionally a view of it, as any argument. At every bucket:

  • each of src and dst is dense: the whole buffer, or a view whose axes of a size other than 1 have the row-major strides (one run of elements, from the view's offset);
  • the two have the same dtype (their buffers') and the same number of elements (their shapes may differ: a copy is of bytes);
  • dst is a buffer a step may write (intermediate, output, inout, carried), and in one buffer the two runs of elements do not overlap.

What a host does. The copy is cuMemcpyDtoDAsync(address(dst) + dst.offset * itemsize, address(src) + src.offset * itemsize, count * itemsize) on the plan's stream, in its place among the steps; with the real addresses the two runs of bytes must not overlap (two externals that overlap are refused before, section 9). A stream that is being captured records it as a memcpy node, so a plan with copy steps captures in a CUDA graph as before.

Where they come from. tilefish.copy(x) in a graph body (a new tensor of its own: a copy step from x, a tensor or a dense view of one, into a fresh intermediate, which an in-place call may then update, where x, a parameter, is the caller's and never written), and param[...] = value into an InOut parameter of the graph (a copy step into the caller's tensor; param[...] = param is no step). A copy of a view that is not dense at some bucket (a permutation, a column block) is not a copy step: the writer makes it a step of kind kernel that launches the generated op tilefish.contiguous (a strided view of rank 1 to 4, read through its strides, into the dense destination; python/src/tilefish/_copyops.py) at every bucket, so the document has nothing new (a view of rank 5 or more is refused). That holds of a store too: param[...] = view of a view that is not dense (a transpose, a column block) into an InOut parameter of its shape and dtype is a launch of tilefish.contiguous into the caller's tensor (the tracer of tilefish 0.0.6 and earlier refused such a store; a kernel body still does). A view of the parameter itself is refused (the source and the destination overlap). A reader that predates copy steps (the published crate 0.0.2, tilefish 0.0.4) refuses a plan that has one (kind must be kernel or library); a plan without one is what it always was.

7.6 Memset steps (tilefish 0.0.7, crate 0.0.5)

A step of kind "memset" is {"kind": "memset", "args": [{"name": "dst", ...}]}: exactly those two fields (no entry: it launches no binary; no workspace), and exactly one argument, named dst, a buffer and optionally a view of it, as any argument. At every bucket dst is dense (the whole buffer, or a view whose axes of a size other than 1 have the row-major strides: one run of elements from the view's offset) and is a buffer a step may write (intermediate, output, inout, carried). It writes dst (section 7.3), and counts in the live range of its buffer like any argument (section 8).

What a host does. The memset is cuMemsetD8Async(address(dst) + dst.offset * itemsize, 0, count * itemsize) on the plan's stream, in its place among the steps: every byte of the run is zero (+0.0 for a float, 0 for an integer). A stream that is being captured records it as a memset node, so a plan with memset steps captures in a CUDA graph as before, and every replay zeroes again.

Where they come from. tilefish.zeros_like(x, dtype=None) in a graph body: a new tensor of the shape of x (nothing of x is read) and its dtype or dtype, all zero, which an in-place call may then update (an accumulator) or the graph may return (the memset then writes the caller's output buffer). param[...] = tilefish.zeros_like(param) into an InOut (or carried) parameter is one memset of that buffer: the memset writes it directly, with no intermediate and no copy, when nothing reads the zeroed value again. A kernel body has no memset (zeros_like is refused there). The step is additive: a plan without one is what it always was, digest included, and a reader that predates memset steps (the published crate 0.0.4, tilefish 0.0.6) refuses a plan that has one.

8. Order, liveness and reuse

  • Order. The steps of a bucket run in list order, all on one stream, with no synchronization between them and none implied: a step that writes a buffer comes before every step that reads that version of it, in the order of the graph's IR (an in-place call keeps the storage of the version it consumes, so its readers come after it, and a view that is read after its buffer was updated in place is refused by the writer of a plan, because the IR gives a view the contents it had when it was made and a view shares the storage). A host does not reorder, overlap or parallelize steps, and does not insert events between them (the order event of section 9 is between executions).
  • Liveness. The live range of a buffer is [first, last]: the index of the first step, and of the last, that has the buffer as an argument (a library step's workspace is live for the whole plan; a devscalar slot is written before step 0 and lives for the whole plan). Both ends are inclusive: a step that reads one buffer and writes another has both live.
  • Reuse. "reuse": false means no two arena regions overlap. "reuse": true allows two regions to overlap only if both buffers are intermediate and their live ranges are disjoint (last of one < first of the other). A device scalar's slot and the workspace never share bytes. validate_doc checks this from the steps of the first bucket (the bindings are the same in every bucket). Python lays out a reusing plan first-fit by first step; the layout is part of the document, and a host uses it as it is.
  • A buffer with no step (a parameter that no operator reads) is allowed; it has no live range. A carried buffer has a live range like any buffer, but no region in the plan's layout: it is never part of the reuse.
  • A result written over its input. A call to an operator whose Out may be written over an input (Out[..., MayAlias("r")], an alias in the manifest) has its result bound to the buffer of r, the same view, when that changes no value the graph computes: r is a whole intermediate at its current version (made by a call of the graph: not a parameter, which is the caller's, and not a view), no later node of the graph reads its storage (a view of it, a version of it, or the graph's return), and no other argument of the call is in that storage. The step then binds r and r_out to one buffer (python/src/tilefish/_plan.py, _in_place); the buffer is written by the step that made r and again by this one, and its live range covers both. Otherwise the result has a buffer of its own. The document needs nothing new: two arguments of a step bound to one buffer are checked by the launch (section 7.2) as any two arguments are.

9. What a host does

  1. Load (section 3): the file, the pin or the trust statement, the manifest, the rules, the entries. Allocate the arena once per device: arena_bytes bytes, 256-aligned (nothing if it is 0), and the regions of the plan's carried buffers after them when it has some (section 15.2). Keep it for as long as the plan is in use, and for as long as any CUDA graph captured from the plan can be replayed (the graph holds its address: a host-owned graph, section 10, keeps its arena alive; nothing keeps it alive for a graph the caller captured with torch.cuda.graph: Python keeps an arena per plan layout and device until tilefish.runtime.clear_caches(), however many runners and plan objects come and go; a host that frees an arena must drop the graphs, and must first wait for the work of the last execution on it, whatever its stream). Two executions that use one arena must not overlap on the device, whatever streams they are enqueued on: they share the intermediates, the device scalars and the workspace. A host orders them. Python does it with one order event per arena (_planrun._Arena): an execution, under the arena's lock, makes its stream wait for the event's most recent record (cuStreamWaitEvent) before its first write (step 4), and records the event on its stream (cuEventRecord) after its last launch (step 5), also when a launch fails after others were enqueued, and when an interrupt lands after the wait (a record that fails is tried again, and if it fails again the host waits for the stream before the error is raised; a wait that failed enqueued nothing and is followed by no record). The wait is skipped when the event's most recent record was made on the execution's own stream, outside a capture: stream order already puts the execution after the work that record stands for, so executions that stay on one stream cost one cuEventRecord each, and one on another stream one cuStreamWaitEvent more. The record is always made; since every execution records after it waited (or after the record before it, on its own stream), the most recent record stands for every execution before it, whatever their streams. Python never skips inside a capture, on the per-thread default stream, or on an arena a torch.cuda.graph captured (that graph's replays record the event where the host does not see them); the event is recorded once when the arena is allocated, on the stream it was allocated on, so a first execution on another stream waits for what used the memory before. So executions of one plan on different streams, from one thread or several, are correct and run on the device one after the other, in the order the host issued them (a lock that orders only the enqueueing is not enough: the race it leaves corrupted the outputs of two runs on two streams in 5 of 5 tries). Executions on one stream are ordered by the stream. clear_caches frees nothing under an execution: it waits for every execution in progress on any thread to have recorded the event (executions, captures and replays hold a gate shared, clear_caches takes it exclusive, and the executions that start meanwhile wait for it, then allocate and load again), takes each arena's lock, waits for the event (cuEventSynchronize) before it frees the arena, and synchronizes every context before it unloads the modules. Plans of different layouts have different arenas and are not ordered with each other. The order is the arena's, not the plan's: an arena shared by several plans (section 15.1) orders the executions of all of them, with the same lock and the same event. So executions that must run concurrently need an arena each. Runs of one plan, or of one shared arena, are serialised on the device whatever their streams; a host that runs the same plans on several streams at once (one stream per request lane, say) gives each lane an arena of its own, with its own lock, order and carried buffers. Python: tilefish.runtime.share_arena([g, ...], name="lane0"), share_arena([g, ...], name="lane1") (every arena of the same plans and the same name is one; a plan alone is a shared arena of one plan); Rust: every LaunchPlan::instantiate and every SharedArena::new allocates an arena of its own (an instantiation, or a SharedArena, per lane). An execution on one arena never waits for one on another (behind a stream that sleeps 600 ms before a run on arena lane0, a run on lane1 on another stream finishes in about a millisecond; on lane0 it waits for the sleep: test_gpu_arena_lanes.py). The Rust host (PlanRun, one arena per instantiation) gives the same order with an order event of its own (plan_run::Order): an execution, under the arena's lock, makes its stream wait for the event (skipped when its most recent record is on that stream) and records it after its last launch, so executions of one instantiation on any streams, from any threads, run one after the other in the order they are issued; nothing is enqueued on any other stream than the execution's own and the streams its externals are freed on; dropping the last handle of an instantiation waits on the host for the event before its modules are unloaded and its arena freed. (Up to crate 0.0.4 the Rust host ordered the arena through the stream it was allocated on, as a slice owned by that stream.) A capture (PlanRun::capture) begins under the arena's lock, so an execution of the arena on the stream being captured is refused rather than captured; the capture does not hold the lock after that, since no execution touches the captured stream (when executions did make the arena's own stream wait, a capture of that stream had to hold the lock to its end: 3 to 18 of 200 captures failed with CUDA_ERROR_STREAM_CAPTURE_ISOLATION or ..._INVALIDATED against a loop of launches on another thread).
  2. Bind the externals. The caller gives a tensor (address, shape, strides, dtype) for every buffer of role input, weight and inout, and for every output (or the host allocates it), and a value for every devscalar (and nothing for a carried buffer: the arena holds it). Check each external against its buffer: dtype, rank, contiguous row-major (a parameter is a dense tensor), and bind the dimensions (section 5; a carried buffer the plan reads before it writes it binds them too, with the shape it was written with: section 15.2). Select the bucket. The external tensors of one call must not overlap each other where one of them is written (output, inout), and none may overlap the arena (its carried region included).
  3. Check, before anything is launched: for every step of the selected bucket, resolve it (section 7.2) with the real addresses and run every check of a single launch, and, under the arena's lock, that every carried buffer the plan reads before it writes it holds the shape it reads (section 15.2). If any check fails, nothing is launched and nothing is written, not even a device scalar: the checks are all done first, then the writes and the launches.
  4. Write the device scalars, after the stream waits for the previous execution on the arena (step 1). Each devscalar slot (at arena + offset) gets the value the caller gave, as the little-endian bytes of its dtype, ordered on the stream before the first launch: a copy from device memory (stream-ordered), or an asynchronous copy from pinned host memory. (Python: _planrun.TorchBackend.write_devscalar; Rust: a pinned staging buffer per instantiation, ffi::plan::Staging. A copy from pageable memory may synchronize with the stream, as CUDA documents cuMemcpyHtoDAsync from pageable memory.)
  5. Launch the steps in order on the stream (section 7.2), then record the arena's order event on it (step 1), and note what each carried buffer the plan writes holds now (its shape at the bucket; unknown when a launch failed). Nothing else: no allocation, no synchronization of the host.

A host may cache everything of steps 1 to 3 that does not depend on an address (the dimension bindings, scalars, grids, the entries' loaded functions and pinned algorithms) per bucket, as Python's runner does; the address-dependent checks are repeated at every execution.

Weights bound once (not part of the document). For a plan with "roles": "declared" a host may take the tensors of the buffers of role weight once and every other external at each call: what it checks and launches is exactly steps 2 to 5 with all of them. The weights are checked when they are bound as an external is (dtype, rank, density, the static sizes; a weight is only read), and again with the rest at every call (a dimension a weight's shape mentions, the overlaps). A weight given again at a call is refused. Python: tilefish.runtime.bind_weights(graph, {"w": t, ...}, mode=, plan=, pin=), a WeightedRun whose run(*inputs) and capture(*inputs, devscalars=...) take the parameters that are not weights; Rust: PlanRun::bind_weights(vec![("w", t), ...]), a WeightedRun<'w> (it borrows the weights) whose launch, launch_tapped, check and capture take the other externals. Both refuse a plan without roles.

Debug taps (not part of the document). A host may copy a buffer of the plan out during an execution, to observe the intermediates of the very plan a product runs: the plan and its digest are unchanged. A tap names a buffer (any but the workspace; a returned value by its name or out<i>) and a step of the bucket (by default the last step that writes the buffer: an out or inout pointer of a kernel, the out of a GEMM, the dst of a copy), and gives a dense tensor of the buffer's dtype and its shape at the bucket that overlaps no external, no other tap and not the arena. It is checked with everything else in step 3, and in step 5 the whole buffer is copied into it (cuMemcpyDtoDAsync, on the stream) right after its step, before the next step may write over the buffer's bytes (with reuse, an intermediate's bytes are reused). Python: tilefish.run(graph, ..., taps={"t3": tensor, ("t5", 4): tensor}) and tilefish.capture(..., taps=...) (the copies are memcpy nodes of the graph); Rust: PlanRun::launch_tapped(stream, externals, devscalars, &mut [Tap { buffer, after, into }]), and PlanRun::capture_tapped(stream, externals, devscalars, taps), whose graph holds the copies as memcpy nodes (every replay copies again; the CapturedPlan borrows the tap tensors, CapturedPlan::tap(buffer) is the memory of one).

One step alone (not part of the document). A host may launch one step of a bucket on the caller's tensors: the binary of the step's entry in the verified manifest (the one the plan's pin pins) and the binding of the step (each argument the buffer and the view the step names, made of the tensor given for that buffer), with every check of a launch of the step (section 7.2) made with those addresses first. The caller gives a tensor for every buffer the step binds and for nothing else (a returned value by its name or out<i>; not the workspace, which is the arena's), of the buffer's dtype and its shape at the bucket (a device scalar: one element), dense, and overlapping neither the arena nor, where the step writes one, each other. The launch is ordered with the executions of the plan (section 9, step 1). It is how one op of an exported plan is replayed on a reference's inputs under the pin a product uses. Python: tilefish.runtime.run_step(graph, step, buffers, mode=, plan=, pin=, bucket=None) (the bucket is found from the shapes when one fits them); Rust: PlanRun::launch_step(stream, bucket, step, buffers). It is not captured (both hosts refuse a capturing stream): it is a check of one op under the product's pin on a reference's inputs, done once, where a graph buys nothing, and a step reads the plan's arena (a GEMM's workspace) under the arena's order; a host that wants one binary of the plan in a graph of its own launches it from the manifest the plan pins (LaunchPlan::manifest().kernel(...), Kernel::launch_raw), or captures the plan.

10. CUDA graphs

A plan does nothing during execution that a stream capture forbids: no allocation (the workspace of a GEMM, the intermediates and the device scalars are in the arena), no synchronization of the host (the order event of the arena is waited for and recorded on the stream, as event nodes: item 7), no host write to device memory but the copy of a device scalar, no module loading, no handle creation, every launch on one stream (a copy step is a memcpy node, a memset step a memset node). So a plan can be captured once per bucket, at fixed addresses, and the graph replays byte-identically (Python gate: test_gpu_plan.py, byte-identical to the uncaptured replay and to per-op eager execution, with 0 allocations inside the capture).

A plan is captured in one of two kinds of graph. A graph the host owns (Python: tilefish.capture, which returns a CapturedPlan; Rust: PlanRun::capture, a CapturedPlan) holds the launches of the steps and nothing else, and is replayed only through the host's replay, which orders it exactly as an execution (section 9, step 1: under the arena's lock, the stream waits for the order, the device scalars are written from the values set, the graph is launched, the order is recorded after it), so its replays are ordered with every execution and every other replay of the plan, from any thread and on any stream. A graph the caller owns (Python: tilefish.run inside the caller's torch.cuda.graph(...)) is replayed by whoever holds it, with no lock of the host: item 7 says what its event nodes order, and what they do not. What has to be so:

  1. Everything that allocates or waits is done before the capture: the arena, the loading of every function of the bucket (cuModuleLoadData, and cuFuncLoad where the driver has it, so that lazy loading does not happen inside the capture), the cuBLASLt handle (cublasLtCreate), and the checks that depend on the bucket only (the grids against the device's limits, cublasLtMatmulAlgoCheck of every pinned algorithm: Python does them when it prepares a bucket, so a refusal comes before the first launch of any run). Python: run the plan once, or tilefish.runtime.prepare(graph, ...). Python refuses a capture that would do one of these ("has not been prepared").
  2. The outputs are best tensors the caller gives (outputs= in Python) and that stay alive as long as the graph: memory allocated inside a capture belongs to the graph (torch allows it, from the capture's private pool, and Python does not refuse it; it is an allocation inside the capture all the same, so a test that proves there is none passes outputs=).
  3. A device scalar must be written by a captured, device-side copy from a CUDA tensor of one element: the graph re-reads that tensor at every replay, so changing the value between replays is writing that tensor. An int or a CPU tensor is a host write (an asynchronous copy from pinned memory is not capturable as a value that changes), and Python refuses it under capture. (A host-owned graph keeps the write out of the graph. Python's CapturedPlan.replay writes every slot before it launches the graph, after the wait for the order, by an asynchronous copy from pinned host memory of the value CapturedPlan.set_devscalar set (or a stream-ordered copy of a CUDA tensor given there): the host is not synchronized, and an execution in between, which writes the slots too, does not change what the graph reads. The Rust host's CapturedPlan::replay writes the slots with an asynchronous copy from pinned host memory before it launches the graph, whenever they do not hold that graph's values; CapturedPlan::set_devscalar changes them.)
  4. A graph holds addresses, not values: the externals are the same tensors at every replay (write into them in place), and the arena of a captured graph is the plan's arena, the one the uncaptured executions use, at the address the graph holds (the shared arena, for a plan that runs on one: section 15.1). A TMA descriptor is held by value: the kernel node of a step with a tensordesc argument (section 7.2) holds the 128 bytes of the CUtensorMap encoded for the capture, which say the address, the shape and the strides the capture bound: an arena buffer at its offset in this arena, an external at the tensor the capture was given, the view and the bucket of the step. So a graph's descriptors are fixed by its bucket, its arena (its address and the layout of the plan) and its externals, exactly as its pointers are, and they are right for every replay for as long as those are (which item 4 already requires: nothing else is). There is nothing to patch in a graph: binding another tensor, or another arena, is another execution or another capture, which encodes the maps of what it binds (Python's tilefish.capture and a torch.cuda.graph of tilefish.run, Rust's PlanRun::capture, all encode in the checks before the capture begins). Writing new values into the same tensors between replays (item 4) changes no descriptor.
  5. One stream: the capture is of the stream the steps are launched on; all steps go there. Every execution of one plan in one capture is on one stream: Python refuses a second execution of a plan's arena in the same capture (the same cuStreamGetCaptureInfo id) on another stream, such as a stream forked from the capturing one, before it enqueues anything (its wait node would not depend on the first execution's record node inside the graph, so one replay could run the two at once on the arena; CUDA does not say it orders them, though the B300 driver ran them one after the other in 2 800 replays of such a graph).
  6. One bucket per graph: a graph is made for one bucket combination's steps, from the first launch to the last, and replayed for that combination's tensors.
  7. The order of the replays. The wait for the arena's order event and its record (section 9, step 1) are captured as external event nodes (CU_EVENT_WAIT_EXTERNAL, CU_EVENT_RECORD_EXTERNAL; a plain wait on an event recorded outside the capture is not allowed in it, and a plain record would only join the capture). So every replay of the graph waits for the most recent record of the event made before it is launched, and records the event when its work is done. That orders a replay only against the executions whose record it sees. The replay of a caller-owned graph takes no lock of the host: an execution on another thread that is between its wait and its record when the replay is launched has waited for the record before it and has not recorded yet, so the replay waits for the same record as that execution, and the two overlap on the arena, with wrong bytes and no error (Python, on a B300: 3 of 4 000 executions on one thread came out wrong against a loop of replays of a torch.cuda.graph on another; 0 of 8 000 with tilefish.capture in the same test). So a caller who replays its own graph while another thread may use the same plan (an execution, the replay of a host-owned graph, whose wait and record are two calls too, or the replay of another caller-owned graph) must order them itself (one thread, or a lock of its own around all of them), or capture the plan in a host-owned graph. Issued from one thread, replays and uncaptured executions of one plan, on any streams, are ordered with each other in the order the host issues them, exactly as executions are. The caller orders nothing but its own tensors (an input written on another stream, an output read on one), as for any launch. The hazard is loud, and the cure is one call. A replay of a caller-owned graph is a call into torch, which tilefish does not see, so it cannot be made safe behind the caller's back (a replay would have to take the arena's lock, and only a call of the host can; the wait and the record cannot be made one driver call; a lock-free order on the device would need a ticket a graph cannot take at replay). Python therefore (a) warns: an arena that a caller-owned graph holds, used by a second thread (a run, a replay of a host-owned graph, a step alone, another capture), gives one TilefishOrderWarning (with warnings.simplefilter("error", tilefish.TilefishOrderWarning) it is an error that refuses every such use before anything is enqueued; one thread never warns, and the warning is not given once the caller replays through (b)); and (b) offers tilefish.runtime.replay_graph(g, stream=None), which replays g under the lock of every arena a caller-owned graph was captured on, so no execution of another thread is between its wait and its record while g is launched, and the event nodes do the rest: 0 of 3 000 runs wrong against a loop of replay_graph on another thread (test_gpu_arena_lanes.py). The warning cannot see a replay made with g.replay() itself on a thread that never calls tilefish; it sees the second thread that does. The Rust host has no caller-owned graph: a launch on a capturing stream is refused, and PlanRun::capture is how a plan is captured. (A host-owned graph has no event node: Python's CapturedPlan.replay and Rust's CapturedPlan::replay order a replay exactly as an execution, step 1 of section 9, so replays and executions of one plan, or of one Rust instantiation, are ordered the same way, whatever thread issues them.)
  8. Not a plan's doing, but a reason a capture can fail: a binary that is not capturable by itself (both hosts refuse cooperative launches, PDL and profile scratch, so none of those is in a plan; a kernel of clusters is captured with its cluster, and a global scratch is the arena's workspace, at the address the graph holds), and the capture mode of the framework (torch's global mode refuses an unsafe call from another thread while it captures).

11. The Python API

plan = tilefish.plan(graph, buckets={"M": [32, 64, 128]}, reuse=False)      # a Plan: no GPU, no torch, nothing built
plan.doc, plan.digest, plan.arena_bytes, plan.arena_bytes_without_reuse, plan.arena_bytes_with_reuse, plan.steps(M=64), plan.buffers, plan.describe()
p = tilefish.runtime.export(graph, "build/", buckets=..., reuse=...)        # builds the binaries, writes manifest.json and plan.json; returns the Plan loaded back (p.digest to pin)
y = tilefish.run(graph, *inputs)                                            # jit: the plan in memory (tilefish.plan(graph), or plan=<a Plan>), binaries built in memory
y = tilefish.run(graph, *inputs, mode="replay", plan="build/", pin=p.digest)  # replay: the exported plan, verified; or trust_directory=True
y = tilefish.run(graph, *inputs, mode="reference")                          # the ops' references composed in torch (an extern's reference= is its oracle)
tilefish.run(graph, *inputs, outputs=out)                                   # write the returned values into these tensors instead of allocating
tilefish.run(graph, *inputs, outputs={"y": y, "residual": r})              # the same by name (the graph's names, or out0, out1, ...)
tilefish.run(graph, *inputs, taps={"t3": t, ("t5", 4): u})                 # copy buffers out after a step (section 9: debug taps; the plan is unchanged)
plan.shape_of("t3", M=64)                                                   # the shape of a buffer at a bucket (what a tap is given)
w = tilefish.runtime.bind_weights(graph, {"w_o": w_o, ...}, mode="replay", plan="build/", pin=p.digest)  # a plan with declared roles (section 6)
w.run(x, n); w.capture(x, devscalars={"n": 5})                              # the inputs only: the weights are bound (section 9)
tilefish.runtime.prepare(graph, mode="replay", plan="build/", pin=p.digest) # arena, binaries, handle: before a CUDA graph capture
tilefish.runtime.run_step(graph, 3, {"t2": a, "w_o": w, "t3": o}, mode="replay", plan="build/", pin=p.digest)  # one step alone (section 9)
cap = tilefish.capture(graph, *externals, devscalars={"n": 5}, outputs=out) # a CapturedPlan: the plan in a CUDA graph of its own (mode=, plan=, pin= as for run)
cap.replay(stream=None)                                                     # ordered with every run and replay of the plan, from any thread
cap.set_devscalar("n", 7)                                                   # the value the next replays write (nothing is enqueued now)
s = tilefish.runtime.share_arena([g1, g2], mode="replay", plan="build/", pin=planset.digest)  # plans of a set on one arena they share (section 15.1)
a = s.run(g1, x); y = s.run(g2, a); s.capture(g2, a)                        # one at a time: every run and replay on the arena is ordered with the others
lane1 = tilefish.runtime.share_arena([g1, g2], name="lane1", ...)          # another arena of the same plans: its executions run concurrently with s's
s.run(stage_a, x); z = s.run(stage_b)                                       # carried buffers (section 15.2): stage_a leaves h in the arena, stage_b reads it
tilefish.runtime.replay_graph(g)                                            # replay a torch.cuda.graph holding plans, ordered with every thread (section 10)

In a graph body, tilefish.copy(x) is a copy step (section 7.5), tilefish.zeros_like(x, dtype=None) a memset step (section 7.6), param[...] = x into an InOut parameter a copy step or a launch of tilefish.contiguous, and @tilefish.graph(carried=("h",)) declares carried parameters (section 15.2).

  • buckets maps a dimension name to the sizes to plan; it defaults to the dimension's own buckets= and is required for a dimension that has none. reuse defaults to False.
  • A DevScalar parameter takes an int (a number that is not an integer of its dtype, such as 3.7 for an i32, is refused in jit, replay and reference alike: it is never truncated), a CPU tensor or a CUDA tensor of one element at a call.
  • A compile-time argument (const) that a call in the graph gives another value than the declared default is refused when the plan is made, as it is at a single launch (the binary has the declared value compiled in); the same in reference mode.
  • tilefish.capture(graph, *externals, mode=..., plan=..., pin=..., trust_directory=..., devscalars=..., outputs=..., stream=None) prepares the plan, then captures the launches of the bucket the externals select in a torch.cuda.CUDAGraph of its own, on stream (default: a new one), in the thread-local capture mode, with nothing allocated inside. externals are the graph's arguments in the order of its signature without its DevScalar parameters, whose values devscalars= gives (every one: a number, or a tensor of one element on the host or the device); outputs= defaults to tensors allocated before the capture (cap.outputs). The CapturedPlan keeps the externals and the arena alive. replay is refused inside a capture and after clear_caches.
  • tilefish.runtime.clear_caches() waits for the executions in progress on every thread, resets every runner and frees every arena (after the last execution on it is done), so call it only when no graph captured with torch.cuda.graph will be replayed again (a CapturedPlan keeps its arena alive, but refuses to replay: capture again).
  • jit builds the binaries of the plan in memory from the same compile specs and pins the same GEMM algorithms in memory, and runs the same runner as replay, which differs in where a binary comes from (a manifest verified against the specs); so the two are identical by construction (a test holds them to byte equality). The plan jit runs is held to every rule a reader holds a file to (sections 2 and 5 to 8, validate_doc(doc, made=True), the overlap sweep of the arena among them; only its arch and manifest_digest are null): tilefish.plan checks every plan it makes.

12. What a plan does not do (version 1)

A graph body that a plan cannot make is refused by tilefish.plan with the rule that says so (TilefishPlanError):

  • a scatter into an InOut parameter in the graph body, and a value read by tilefish.load that is returned, stored or passed to a call. (Other arithmetic traced in the graph body, x + y, a cast, a comparison, a reduction, is planned: the writer groups it into fused regions, each a step of kind kernel that launches a kernel tilefish generates, named fused_<hash> by its content, byte for byte the composition of one kernel per op; docs/en/rfcs/0001-plan-fusion.md. The document has nothing new: a reader sees kernel steps of manifest entries, as for any @tilefish.kernel.)
  • an Out parameter of the graph (and so a store into one) and a runtime Dim parameter: a graph's results are its returned values (a store into an InOut parameter is a copy step, or a launch of tilefish.contiguous for a view that is not dense, section 7.5);
  • a call to another graph (it is not inlined yet).
  • an in-place call on a view of another tensor (the IR says updating a view does not change its parent; a plan has no copy to make that true), and a view read after its tensor was updated in place.
  • a returned value that is a DevScalar, or a view of a tensor updated in place after the view was made (a view that is not dense is a launch of tilefish.contiguous into the caller's output, section 7.5). (Any other returned value is planned: a tensor a call made is the caller's output buffer itself; all of it in another shape (a reshape: offset 0, the row-major strides, as many elements) too, the output buffer then having the returned shape and the steps that write and read it a view of their own shape; any other dense view, a parameter and a value returned twice are copied into the caller's buffer by a copy step after the last call, section 7.5.)
  • a dimension without buckets, an operator without an implementation (a library op with no impl), two different operators with one name, a block-scaled tensor.

13. An example

The plan of a small graph with an in-place tensor (accumulate of python/tests/plan_model.py, buckets={"Q": [16, 32]}, reuse=True; the tilefish key and the two digests are not the ones of a real export, which has a manifest; test_plan_docs.py checks that this text is what the code makes and that the digest is right):

{"schema": "tilefish.plan.v1", "tilefish": "0.0.3", "graph": "accumulate", "arch": "sm_103", "manifest_digest": "abababababababababababababababababababababababababababababababab", "dims": {"Q": [16, 32]}, "reuse": true, "arena_alignment": 256, "arena_bytes": 16384, "buffers": [{"name": "a", "role": "input", "dtype": "f32", "shape": ["Q", 128], "offset": null, "bytes": 16384}, {"name": "state", "role": "inout", "dtype": "f32", "shape": ["Q", 128], "offset": null, "bytes": 16384}, {"name": "t0", "role": "intermediate", "dtype": "f32", "shape": ["Q", 128], "offset": 0, "bytes": 16384}, {"name": "out0", "role": "output", "dtype": "f32", "shape": ["Q", 128], "offset": null, "bytes": 16384}], "outputs": ["out0"], "buckets": [{"values": {"Q": 16}, "steps": [{"entry": "bump", "kind": "kernel", "args": [{"name": "state", "binding": "state"}, {"name": "y", "binding": "a"}]}, {"entry": "bump", "kind": "kernel", "args": [{"name": "state", "binding": "state"}, {"name": "y", "binding": "a"}]}, {"entry": "twice", "kind": "kernel", "args": [{"name": "x", "binding": "a"}, {"name": "out", "binding": "t0"}]}, {"entry": "bump", "kind": "kernel", "args": [{"name": "state", "binding": "t0"}, {"name": "y", "binding": "a"}]}, {"entry": "plus", "kind": "kernel", "args": [{"name": "x", "binding": "t0"}, {"name": "y", "binding": "state"}, {"name": "out", "binding": "out0"}]}]}, {"values": {"Q": 32}, "steps": [{"entry": "bump", "kind": "kernel", "args": [{"name": "state", "binding": "state"}, {"name": "y", "binding": "a"}]}, {"entry": "bump", "kind": "kernel", "args": [{"name": "state", "binding": "state"}, {"name": "y", "binding": "a"}]}, {"entry": "twice", "kind": "kernel", "args": [{"name": "x", "binding": "a"}, {"name": "out", "binding": "t0"}]}, {"entry": "bump", "kind": "kernel", "args": [{"name": "state", "binding": "t0"}, {"name": "y", "binding": "a"}]}, {"entry": "plus", "kind": "kernel", "args": [{"name": "x", "binding": "t0"}, {"name": "y", "binding": "state"}, {"name": "out", "binding": "out0"}]}]}], "plan_digest": "e4dc0d05d73b157aa1860171601687ce7d40aba3b8dba1f2f41c1dd2c6112bcf"}

Read it: state is updated in place twice (steps 0 and 1), twice makes t0 in the arena at offset 0 from a, bump updates t0 in place (step 3: no second buffer), and plus reads the newest versions of both and writes the returned value into out0. The two buckets differ in nothing but the sizes the buffers have there (and each step's stem, which here has no bucket of its own).

The steps of a plan with views, the attention of the transformer block of the gate (python/tests/plan_model.py) at M = 64: q, k and v are views of the fused output t1, and the result is bound whole:

{"entry": "attention", "kind": "kernel", "args": [
  {"name": "q", "binding": "t1", "view": {"shape": [64, 4, 64], "strides": [768, 64, 1], "offset": 0}},
  {"name": "k", "binding": "t1", "view": {"shape": [64, 4, 64], "strides": [768, 64, 1], "offset": 256}},
  {"name": "v", "binding": "t1", "view": {"shape": [64, 4, 64], "strides": [768, 64, 1], "offset": 512}},
  {"name": "o", "binding": "t2"},
  {"name": "n_valid", "binding": "n"}]}

The block's plan has 9 steps (5 kernels and 4 GEMMs) in each of 3 buckets and an arena of 9 634 048 bytes without reuse (8 519 680 of them the cuBLASLt workspace, 1 114 112 the intermediates) and 9 240 832 with it (720 896 for the intermediates).

14. Where it is tested

what tests (python/tests/)
the walk, the steps and views, the buffers, roles, buckets, the refusals of section 12 test_plan.py
a step that reads three views with one stride pair; a step whose dimension only its Out buffer has (section 5) test_shared_strides.py, test_output_dims.py; on a GPU test_gpu_shared_strides.py, test_gpu_output_dims.py
a result written over its input (MayAlias, section 8) test_alias.py; on a GPU test_gpu_alias.py
buffers whose strides are products of sizes ([4, Lb, Lb]: views at a stride and an offset of Lb*Lb, section 7.1) test_product_strides.py; on a GPU test_gpu_product_strides.py; the Rust gate's plan product_strides (gpu_plan_gate.rs)
copy steps (tilefish.copy, a store into an InOut parameter; section 7.5) test_plan_copy.py; on a GPU test_gpu_plan_copy.py; the Rust reader: python_plans.json (copy ... documents)
a view that is not dense stored into an InOut parameter: a launch of tilefish.contiguous (section 7.5) test_plan_strided_store.py, test_trace.py; on a GPU test_gpu_plan_strided_store.py (jit, replay, reference, tilefish.capture, torch.cuda.graph) and the gate plan strided_store
memset steps (tilefish.zeros_like; section 7.6) test_plan_memset.py; the Rust reader: python_plans.json (memset ... documents); on a GPU test_gpu_plan_memset.py (the caller's tensors filled with NaN first; captured as memset nodes) and the gate plan memset_steps
carried buffers (section 15.2): the role, the store written by the step that makes the value, the layout of the carried region, the order of what each holds, the dimensions bound from it, the refusals test_plan_carried.py; test_plan_fixtures.py and launch_plans.rs (the golden set carried: the_golden_set_of_carried_buffers_...); the Rust reader: python_plans.json (carried ... documents); on a GPU test_gpu_plan_carried.py (jit and replay against torch, tilefish.capture between runs on other streams, a torch.cuda.graph of two stages, two arenas from two threads) and gpu_plan_gate.rs (carried_buffers_handed_from_plan_to_plan_...: the calls of rust_gate.py's CARRIED_CALLS on one SharedArena, launched and replayed)
an arena per stream (share_arena(..., name=), section 9) and the warning and replay_graph for a graph of the caller's (section 10, item 7) test_arena_lanes.py; on a GPU test_gpu_arena_lanes.py (a run on another arena does not wait for a sleeping stream; two threads; 0 of 3 000 runs wrong against replay_graph on another thread)
returned views and parameters (section 12) test_plan_returns.py; on a GPU test_gpu_plan_returns.py
one step alone (section 9) test_plan_step.py; on a GPU test_gpu_plan_step.py and gpu_plan_gate.rs (the_steps_launched_one_by_one_give_the_bytes_of_the_plan)
steps with TMA descriptors (sections 7.2 and 10): encoded from the buffers they bind before the first launch, held by value in a graph test_tensordesc.py (a fake backend); on a GPU test_gpu_tma.py (jit, replay, tilefish.capture, torch.cuda.graph, a step alone) and the gate plans tma_chain, tma_chain-reuse, tma_view (gpu_plan_gate.rs: launched and replayed from a graph)
debug taps (section 9) test_plan_taps.py; on a GPU test_gpu_plan_taps.py and gpu_plan_gate.rs (taps_are_pythons_bytes: Rust taps against Python's)
the roles of the parameters, declared or chosen from the shapes (sections 2, 6), and weights bound once (section 9) test_plan_roles.py; the golden plan steps (launch_plans.rs); on a GPU test_gpu_plan_roles.py and gpu_plan_gate.rs (weights_bound_once_give_pythons_bytes)
the fixed arguments given per call of a prebuilt binary: a step's given (section 7) test_given_args.py; the golden plan given (launch_plans.rs, and the given ... documents of python_plans.json); on a GPU test_gpu_given_args.py, gpu_gate.rs (one_binary_serves_the_values_each_call_gives) and the gate plan given_steps
views that are not dense, returned or copied: launches of tilefish.contiguous (section 7.5) test_plan_materialise.py; on a GPU test_gpu_plan_materialise.py and the gate plan strided_returns
the names of the returned values (section 6) test_plan_names.py; the golden plan steps (launch_plans.rs); on a GPU gpu_plan_gate.rs (a_named_output_is_given_by_its_name_or_by_out_i)
the memory plan: alignment, no overlap, liveness reuse against a simulated arena test_plan_arena.py
the digest, the pin, every rule of the format, the manifest checks, tampering test_plan_schema.py
the document of section 13 test_plan_docs.py
the runner: order, addresses, scalars, preconditions before the first launch, captures, the order event of the arena (fake backend) test_planrun.py
on a GPU: replay == jit == per-op eager, replay vs reference, CUDA graph capture, tampering, the arena test_gpu_plan.py
on a GPU: runs of one plan on two streams (the race of the review, 0 of 20 rounds corrupted), from two threads, and replays of a captured graph between runs on other streams test_gpu_plan_streams.py
plan sets: one manifest, <graph>.plan.json per graph, the index plans.json, either pin (section 15) test_plan_sets.py; the golden set golden/plans/set (launch_plans.rs); on a GPU test_gpu_plan_sets.py and gpu_plan_gate.rs (a_plan_set_is_loaded_with_one_pin_and_its_plans_give_pythons_bytes)
an arena shared by the plans of a set: its size and layout, the one order, the refusals, the pin (section 15.1) test_shared_arena.py; test_plan_fixtures.py and launch_plans.rs (shared_arena_bytes of the golden set); on a GPU test_gpu_shared_arena.py (the stages of the block on one arena: the bytes of separate arenas and of the block, captured, in a torch graph; two plans racing on two streams, 0 of 10 rounds wrong, 10 of 10 without the order event) and gpu_plan_gate.rs (the_plans_of_a_set_on_one_shared_arena_..., launches_and_replays_of_different_plans_of_a_shared_arena_..., a_shared_arena_refuses_...)
golden fixtures for a second implementation: three plan directories (manifest.json, cubins and plan.json; the cubins are fakes, which no driver loads: the fixtures are for a reader, on any machine): the transformer block, without and with reuse, and steps (a result written over its input, two copy steps, a returned reshape, named outputs); expected.json with the plan digest, the manifest digest, the arena size, every arena offset and the outputs that a reader must reproduce from the files alone golden/plans/ (written by export_plan_fixtures.py, no GPU needed), test_plan_fixtures.py

The cubins of the golden fixtures are fake (a tiny ELF file per kernel entry, a made-up algorithm per GEMM): the format, the digests and the plan are real, so a reader can be checked against them; they cannot be launched.

15. Plan sets: several plans over one manifest

A stage whose launch count depends on a key (a prologue that processes ceil(T / tile) tiles, each a fixed chain of launches) is one plan per key: a plan's steps are the same in every bucket. Exported one by one, every plan directory has its own manifest and its own copy of the same binaries. A plan set exports them together: tilefish.runtime.export([g1, g2, ...], directory) (an item may be (graph, buckets)) builds the binaries of all of them once and writes

  • one manifest.json (schema 3, sections there): an entry per binary, whichever plans launch it;
  • <graph>.plan.json per graph: a plan of this schema, exactly as plan.json is, whose manifest_digest is the one manifest's;
  • plans.json, the index: {"schema": "tilefish.plan-set.v1", "tilefish": <version>, "arch": "sm_103", "manifest_digest": <64 hex>, "plans": {"<graph>": "<plan digest>", ...}, "set_digest": <64 hex>}, exactly these keys; plans a non-empty object (at most 65 536) of graph names (identifiers) to plan digests. set_digest is sha256(b"tilefish.plan-set-digest.v1\0" + canonical_json(index without "set_digest" and "tilefish")) (_plan.set_digest; Rust plan_set_digest).

The pin. The set's digest covers the digest of every plan it lists, and each plan's digest covers the manifest's (section 3), so one pin, the set's, covers every plan, their manifest and every binary they launch. A host reads the index strictly (as a plan, section 4), checks its digest against the pin and against its own set_digest, then every rule above, loads the manifest once with the index's manifest_digest as its pin, and loads a plan from <graph>.plan.json with the digest the index lists as its pin (so a plan file that is not the listed plan is refused) and with that manifest. Each plan file is also an ordinary plan: it loads alone with its own digest as the pin (the manifest next to it).

Hosts: Python tilefish.run(graph, ..., mode="replay", plan=directory, pin=<the set's digest or the plan's>) (the directory's <graph>.plan.json; tilefish.capture, prepare, run_step and bind_weights alike), and export returns a PlanSet (.digest, .manifest_digest, .plans). Rust: PlanSet::load(directory, Pin::Digest(set_digest)), set.plan("tiles2") (a LaunchPlan that shares the set's manifest, so the modules of its binaries are loaded once per context for all the plans), set.names(), set.manifest(); LaunchPlan::load_with_manifest(file, &manifest, pin) for a plan file with a manifest already loaded. A directory holds one plan (plan.json) or one plan set, not both: an export of one into a directory of the other is refused (without overwrite=True). An export of a set with another graph builds another manifest, so every plan of the set gets a new digest, and so does the set. A locked export (export(..., lock=path), docs/en/guide/locked-export.md) writes a plan, a set and its fusion reports byte for byte on a machine without a GPU; the documents are the ones specified here (a lock adds no field), and the lock records the digests to pin.

Why sets and not a plan whose steps repeat: a repeated step range would need loop-carried rules both readers agree on (liveness, the order of reads and writes, the views of each iteration, the step a tap or run_step names), and a stage whose tiles are not all alike (a last partial tile has other shapes) is not a repetition of one range; one plan per key keeps every plan a straight list whose every launch is checked before the first, and the set removes what was duplicated, the binaries and the pins.

15.1 An arena shared by the plans of a set

A host that runs several plans one at a time (a request's stage A, then B, then C; a variable number of tile plans) needs no arena per plan: the plans can share one. It is a choice of the host, not part of any document: every plan, its digest, the index and its digest are what they were.

  • The layout. The shared arena has max(arena_bytes) bytes over the plans that share it (the plans the host names: all of a set's, or some of them), allocated once and aligned to 256 as any arena. Each plan keeps its own memory plan in it, from the first byte: buffer b of plan P is at arena + offset(P, b), exactly as on an arena of its own, so every rule of section 6 holds of each plan, and each plan is captured in CUDA graphs at fixed addresses (section 10). The regions of different plans overlap: their intermediates, device-scalar slots and cuBLASLt workspaces share bytes. So the arena holds each plan's workspace (at that plan's offset, with at least what every library step of the plan declares, section 7.3): in effect one workspace, the largest of the plans', and the device-scalar slots the same way. The gate's three stages of the transformer block (plan_model.STAGES) have arenas of 8 782 080, 8 585 216 and 9 109 504 bytes, and share one of 9 109 504 (three arenas: 26 476 800).
  • Why that is sound: the order. Two executions that use one arena must not overlap on the device (section 9, step 1), and that is said of the arena, whatever plans run on it: a host orders every execution on the shared arena, of any of its plans (a run, a capture, the replay of a host-owned graph, a step alone) with every other, under one lock and one order event (both hosts), so the executions of two plans of the arena cannot run concurrently, from any threads and on any streams. A replay of plan A's graph is ordered with every run and replay of plan B. Then an execution finds in the arena whatever the one before it left, and needs nothing of it but its carried buffers (section 15.2, which the order hands on): it writes every arena buffer of its own region it reads before it reads it (an intermediate, section 7.3; a device scalar's slot, before the first launch, section 9 step 4; the workspace is a GEMM's scratch). A graph the caller owns (torch.cuda.graph) takes its place in the arena's order as section 10, item 7 says, with the same caveats; two executions on the arena in one capture on two streams are refused (item 5). (The Rust host writes the device scalars of a host-owned graph's replay again whenever another execution on the arena, of any plan, may have written over them.)
  • What outlives an execution: nothing in the plans' regions; the carried buffers. A value one plan makes and a later plan reads is a returned value of the first, an external in the caller's memory (role output: Python allocates it or takes outputs=, Rust takes the caller's), given as a parameter of the second; or a carried buffer (section 15.2), which the arena holds in a region of its own after the plans' regions, so no buffer of any plan writes it but a step bound to it. What would be overwritten is refused, never corrupted: a tensor of the caller that overlaps the shared arena anywhere (not only the part of the plan that runs: the next plan writes the rest; the carried region too) is refused with the kind alias before anything is launched, whether it is an external, a tap's tensor or a tensor of a step alone (section 9).
  • The pin. The layout of a shared arena is a function of the plans' documents (their arena_bytes and offsets), which their digests cover, which the set's digest covers: the set's pin covers the shared arena, and plans.json has nothing new. A plan file edited to say another layout is refused by the pin before an arena is sized from it. expected.json of the golden fixtures has each plan's arena_bytes and the shared_arena_bytes of the golden set, which a reader reproduces from the files.

Hosts. Python: s = tilefish.runtime.share_arena([g1, g2, g3], mode="replay", plan="build/", pin=planset.digest) (in jit the items are graphs or the Plans tilefish.plan made), then s.run(g1, *args, outputs=, taps=), s.capture(g2, *externals, devscalars=, outputs=), s.bind_weights(g3, {...}), s.run_step(g1, step, buffers), s.prepare(); s.arena_bytes, s.sizes (each plan's arena_bytes), s.carried (section 15.2). Python keeps arenas per layout, as for one plan: every SharedArena of the same plans and the same name= (or none) on one device is one arena, kept until clear_caches, another name is another arena (share_arena([...], name="lane1"): one per stream), and a plan run alone (tilefish.run) has its own. Rust: let runs = set.instantiate(&stream, &["g1", "g2", "g3"])? (a SetRun: runs.run("g1")? is a PlanRun on the shared arena, runs.arena() the SharedArena), or SharedArena::new(&stream, &[&p1, &p2]) and p1.instantiate_in(&arena, values) / instantiate_all_in(&arena), which refuse a plan the arena was not made for (by digest); every Rust SharedArena (and every SetRun) is an arena of its own (a host with several lanes makes one per lane). PlanSet::shared_arena_bytes(names) and SharedArena::bytes_for(plans) give the size with no GPU.

15.2 Carried buffers (tilefish 0.0.7, crate 0.0.5)

A stage that hands an intermediate to the next stage need not make it a returned value that the caller allocates: the graphs declare it carried, and the arena holds it.

  • The declaration. @tilefish.graph(carried=("h",)) names tensor parameters of the graph, In (the plan reads h) or InOut (it writes h, or updates it in place), not a DevScalar, and neither an input nor a weight of inputs=/weights=. The name is the buffer's identity across plans: every plan of an arena that has a carried parameter h uses the one tensor h of that arena. In the document such a parameter is a buffer of role carried, with offset null, like an external, and the bytes of its largest bucket (section 6). It is listed in the order of the signature with the other parameters; a step may read it (it counts as provided, section 7.3) and write it. Nothing else of the document is new: a plan without one is what it always was, digest included, and a reader that predates the role (the published crate 0.0.4, tilefish 0.0.6) refuses a plan that has one.
  • The writer. h[...] = value into a carried parameter is written by the step that makes the value (its result is bound to h: no intermediate and no copy) when the value is a whole intermediate the step just before made and nothing reads it again; otherwise it is a copy step (or a launch of tilefish.contiguous). h[...] = tilefish.zeros_like(h) is a memset of h (section 7.6). An in-place call (accumulate(h, y), an InOut operand) updates it where it is.
  • The layout (_plan.carried_layout; Rust CarriedLayout::of). The arena of a set of plans (one plan for an arena of its own) is their regions (from the arena's first byte, each plan's own offsets, base = max(arena_bytes)), then one region per carried name of any of the plans, in code point order of the names, each align_up(max bytes over the plans that name it, 256) long, at a multiple of 256. Two plans that give a name two dtypes are refused. The layout is a function of the documents alone, so a plan's or a set's pin covers it as it covers the rest of the arena (15.1), and plans.json has nothing new. The golden set carried (expected.json: carried_base, carried, shared_arena_bytes) has two names after a plan with a region of its own; a reader reproduces it from the files.
  • The lifetime. A carried buffer lives as long as its arena (Python: until clear_caches; Rust: the last handle of the arena), and holds what the last execution on the arena that wrote it left there. Nothing else writes its bytes (it is in no plan's region; the caller's tensors may not overlap the arena). An arena of its own (tilefish.run of one plan, a Rust instantiate) has its own carried regions, so two plans that are not on one shared arena do not share a carried buffer, and a plan that reads a carried buffer first is refused alone (nothing but itself could have written its arena's): it runs on a shared arena with a plan that writes the buffer.
  • What each holds, and the checks. A host keeps, under the arena's lock and so in the order the executions run in, the shape (at its bucket) of the execution that wrote each carried buffer last, or nothing (no execution wrote it, or one that did failed after it was enqueued). A plan that reads a carried buffer before it writes it (its first use in the steps is a pointer that is in or inout, an operand of a library step, the source of a copy) binds its dimensions from that shape, as from an external's (so stage_b(h) is called with nothing: its T is the size h was written with), and is refused before anything is enqueued unless the buffer holds exactly the shape it reads (kind shape; "no execution on this arena has written it", or "left the shape ..."). After an execution, every carried buffer it writes holds its shape. A run, the replay of a host-owned graph (CapturedPlan.replay, Rust CapturedPlan::replay) and a Rust check do this; a capture (tilefish.capture, PlanRun::capture) runs nothing and checks nothing of what they hold, but binds its dimensions as a run does (so a plan whose dimensions only a carried buffer binds is captured after that buffer was written); a caller-owned graph (torch.cuda.graph) is checked and noted when it is captured, not at its replays, which tilefish does not see: a replay of such a graph that writes h in another shape than the last execution the arena noted leaves the note wrong, and a later run that reads h binds the noted shape (capture the stages that hand a buffer on in one graph, in their order, or use tilefish.capture, whose replays are checked and noted). The dimensions are bound from the carried buffers a plan reads first, not from those it only writes: a stage that only writes h (a reset by a memset) takes a tensor that has its dimensions. A step alone (run_step, launch_step) takes the caller's tensor for a carried buffer, as for any buffer, and touches no carried region.
  • The calls. A run gives every parameter but the carried ones (Python: positionally in the order of the signature without them, or by name; giving one is refused: "held by the plan's arena"); tilefish.capture and bind_weights alike. The reference mode, which has no arena, takes a carried parameter as an argument like any other. A plan whose parameters are all carried runs on torch's current device.

Hosts. Python: @tilefish.graph(carried=...), Plan.carried, SharedArena.carried ({name: (offset, bytes, dtype)}), share_arena as in 15.1, tilefish.run, capture, bind_weights, taps of a carried buffer (taps={"h": t}). Rust: BufferRole::Carried, LaunchPlan::carried(), CarriedLayout, SharedArena::carried(); PlanRun::launch and CapturedPlan::replay check and note what the carried buffers hold. Tests: section 14.