Agents
For a more token-efficient view of this page, read the raw documentation source. Follow its includes and API references for code examples and docstrings.
Advanced topics#
This page is for kernels that run native CuTe code next to the primitives. It covers three places where the two meet: a tile that native code stages in shared memory, shared memory that both use in turn, and registers that another object loads.
A walkthrough follows one complete kernel, in which a Tensor Core accumulator moves from tensor memory into registers, through a top-k selection and back, with the synchronization that dependent matrix multiply-accumulate (MMA) iterations need:
Typed workspaces#
TempStorage.reserve returns
a one-dimensional CuTe shared tensor inside a TempStorage region, so
native CuTe code and primitives can take turns with the same bytes:
@cute.jit
def prepare(values: cute.Tensor):
thread, _, _ = cute.arch.thread_idx()
values[thread] = cutlass.Float32(2 * thread + 1)
@cute.kernel
def kernel(destination: cute.Pointer):
block = coop.this_block()
thread = block.rank()
storage = coop.TempStorage(sharing="shared", auto_sync=False)
workspace = storage.reserve(64, cutlass.Float32, alignment=64)
persistent = SmemAllocator().allocate_tensor(
cutlass.Float32, cute.make_layout(64), byte_alignment=64
)
persistent[thread] = cutlass.Float32(3 * thread + 7)
# reserve() returns an ordinary tensor consumed by native CuTe code.
prepare(workspace)
storage.sync()
value = workspace[63 - thread]
# Every thread must finish reading before the sum overwrites these
# bytes with its scratch. The input now lives in registers.
storage.sync()
total = coop.sum(block, value, temp_storage=storage)
storage.sync()
# Fill the reserved tensor again for the next native step. The tensor
# from SmemAllocator kept its values across the sum.
workspace[thread] = cutlass.Float32(thread + 101)
storage.sync()
output = cute.make_tensor(destination, cute.make_layout(129))
if thread == 0:
output[0] = total
output[1 + thread] = persistent[63 - thread]
output[65 + thread] = workspace[63 - thread]
@cute.jit
def launch(destination: cute.Pointer):
kernel(destination).launch(grid=1, block=64)
The block has 64 threads. workspace is 64 Float32 elements in the
region of storage, and prepare is native CuTe code that writes one
of them in each thread. Each thread then reads into a register the element
that thread 63 - thread wrote. coop.sum takes its scratch from the
same storage, which has sharing="shared", so the sum overwrites the
workspace. After the sum the kernel fills the workspace again.
persistent comes from CuTe’s SmemAllocator and keeps its values
across the sum, which the host checks.
Each storage.sync() is a block barrier between one use of the bytes and
the next:
After
prepare, so that every element is written before another thread reads it.After the read, so that every thread holds its value in a register before the sum overwrites the workspace.
After the sum, so that the sum is finished with its scratch before the kernel writes the workspace again.
After the second filling, so that every element is written before another thread reads it.
The entry for
TempStorage.reserve has the
rules for element types, sharing and barriers.
A reserved tensor can also be the source of load or the destination of
store, like the shared tensor of the previous section. The exceptions
are Float16 and BFloat16 tensors, which load and store
reject when the kernel is compiled. The algorithms "direct",
"striped" and "vectorize" use no scratch. A transpose algorithm uses
scratch while it reads or writes the tensor. With sharing="shared", a
transpose load or store that takes the tensor’s own TempStorage
puts that scratch where the tensor starts, and nothing checks for the
overlap. Give that call scratch elsewhere: leave temp_storage out, or
pass another TempStorage.
Producer-owned register loads#
A producer is an object that owns a register load: its
__cuda_coop_thread_data_load__ method, the hook, copies the producer’s
data into each thread’s registers and returns them. This producer owns a
CuTe register tensor, and calls counts how often its hook runs:
Full example and test on GitHub
class _RegisterProducer:
def __init__(self, registers):
self.registers = registers
self.calls = 0
@property
def shape(self):
return self.registers.shape
@property
def dtype(self):
return self.registers.element_type
def __cuda_coop_thread_data_load__(self):
self.calls += 1
return self.registers.load()
ThreadData.load calls the hook
and makes a payload of what it returns. Here the kernel loads the producer’s
registers, and the check on calls runs while the kernel is compiled. The
payload is a copy, so the write to registers[0] leaves values as it
was. The runtime loop adds 1 to item 0 on each trip, and
to_tensor_ssa(like=source) returns the payload’s items as a
TensorSSA with the producer’s shape and dtype:
source = _RegisterProducer(registers)
values = coop.ThreadData.load(source)
if cutlass.const_expr(source.calls != 1):
raise AssertionError("producer hook called more than once")
registers[0] = cutlass.Int32(-100)
for iteration in range(iterations):
values[0] += cutlass.Int32(1)
snapshot = values.to_tensor_ssa(like=source)
The producer:
Chooses the copy: its copy atom, and the elements each thread takes.
Makes sure its source is ready to be read, with whatever barrier or wait that takes.
Owns its source for as long as the kernel reads it.
Rejects a second call itself if its source can be read only once.
ThreadData.load:
Looks for the hook on the object and its class. A hook that only
__getattr__would supply is ignored, and an object without a hook is rejected when the kernel is compiled.Calls the hook once for each
ThreadData.loadin the kernel, while the kernel is compiled. The CuTe operations the hook performs become part of the kernel, so it can run a native copy there, such as one from tensor memory (TMEM) into registers.Passes on an error that the hook raises, unchanged.
Converts the hook’s result with
from_payload().
The hook returns a ThreadData, or register values that from_payload
takes, such as a CuTe register tensor or a TensorSSA. The item count
must be known when the kernel is compiled, from the result’s shape or from
items_per_thread. The optional items_per_thread and dtype of
ThreadData.load work as they do for from_payload, and an
items_per_thread that is not a positive Python integer is rejected
before the hook runs. A result of another kind, such as a tensor in global,
shared or tensor memory, is rejected with an error that names the producer’s
class and the class of the result.
A tensor in tensor memory that is passed to ThreadData.load by itself
is rejected as well. The tensor names no copy atom and does not say which
elements each thread takes, when it is ready or how long it lives. Write a
producer that supplies those, and test its copy and its synchronization on
a GPU that has tensor memory.
values.to_tensor_ssa(like=source) reads source.shape and
source.dtype for the shape and the element type of its result. A
shape or dtype argument takes precedence over like. The shape is
made of positive Python integers and holds exactly the payload’s item count.
With neither shape nor like the result has the shape
(items_per_thread,). The items keep their flat order. A payload keeps no
record of the shape of the tensor it came from. The kernel keeps track of
which thread owns which element of an MMA fragment.
Each conversion between a payload and a CuTe register tensor or
TensorSSA copies, and the compiler can keep register values in local
memory. To see what a kernel does with them, read its linked cubin, as
Checking and tuning a kernel describes.
Three protocol classes describe a producer to a type checker. A producer
works without them, because ThreadData.load finds the hook by its name.
- class cuda.coop.cutlass.ThreadDataLoadSource#
An object with the
__cuda_coop_thread_data_load__hook.ThreadData.loadcalls the hook while the kernel is compiled.
- class cuda.coop.cutlass.ThreadDataTensorMetadata#
An object with the
shapeanddtypethatto_tensor_ssareads.Pass it as
like.
- class cuda.coop.cutlass.ThreadDataSource#
An object with the hook and with
shapeanddtype.