Resident pipelines on XDNA¶
A resident pipeline keeps data moving between independently progressing strands inside one device invocation. DMA can fill an input while a compute worker processes another record. Channels govern when each record becomes readable and when its storage can be reused; the host does not dispatch every stage.
This walkthrough follows a BF16 gate/up projection from authored C++ through Loom High IR to a native XDNA executable. The same source is a maintained compiler workload. It exercises ordinary functions, owned channels, adjacent tile memory, DMA, and specialization. It computes one projection pair and a quadratic gate, not a complete FFN or an optimized matrix multiplication.
The current native realization requires explicit singleton worker selections, specialized storage sizes, and channel protocols supported by the target. Each worker's resident instructions must fit its tile's instruction budget. GPU and CPU strands need execution and progress mechanisms specific to those targets.
Compile a complete program¶
Save gated-projection.cxx.
It includes all helper functions and the public
ffn_gate_up_quadratic_bf16 pipeline. With an installed Loom toolchain that
includes the C++ importer and XDNA, import and compile it for Strix Halo NPU5:
loom-import-cxx --root=ffn_gate_up_quadratic_bf16 \
gated-projection.cxx --output=gated-projection.loom
loom-format --check gated-projection.loom
loom-compile gated-projection.loom \
--root=@ffn_gate_up_quadratic_bf16 \
--target=amd.xdna.aie2p:amd.xdna.strix_halo.17f0_11 \
--config=ffn_gate_up.input_size=512 \
--format=xdna --output=projection.xdna
For Strix NPU4, use amd.xdna.aie2p:amd.xdna.strix.17f0_10.
Compilation needs no attached NPU. Execution requires a device matching the
exact profile; these images are not interchangeable.
The caller supplies three buffers in source argument order:
| Argument | Contents at width K | Access |
|---|---|---|
| Input | One row of K BF16 values. | Read. |
| Weights | Two rows of K BF16 values, gate then up. | Read. |
| Output | One F32 value carrying the rounded BF16 result. | Write. |
All three bindings satisfy the source's 64-byte base-alignment contract. K is
a compile-time configuration from 512 through 4096, divisible by 32. Dot
products accumulate in F32. The epilogue computes
gate * (0.5 + 0.25 * gate) * up, rounding each step to BF16. This explicitly
chosen quadratic gate is different from SiLU or SwiGLU.
Construct storage and independently progressing strands¶
Here is the complete pipeline body in the imported High IR. Its helper definitions are in the downloadable generated module; the authored C++ transfer helpers appear below.
pipeline.def<kernel> public target(@npu) @ffn_gate_up_quadratic_bf16() run(%input: buffer, %weights: buffer, %output: buffer) {
%input_aligned = buffer.assume.alignment %input {minimum_alignment = 64} : buffer
%weights_aligned = buffer.assume.alignment %weights {minimum_alignment = 64} : buffer
%output_aligned = buffer.assume.alignment %output {minimum_alignment = 64} : buffer
%tile_memory = pipeline.memory<workgroup>[0, 3] : pool
%input_size$11 = config.get @ffn_gate_up.input_size : index
%241 = index.constant 1 : index
%242 = index.shli %input_size$11, %241 : index
%13 = index.constant 2 : offset
%14 = index.scale %242, %13 : index, offset -> offset
%input_storage = buffer.alloca<workgroup> pool(%tile_memory) align(64) %14 : buffer
%input_storage_byte_offset = index.constant 0 : index
%input_slots = buffer.view %input_storage[%input_storage_byte_offset] : buffer -> view<2x[%input_size$11]xbf16>
%237 = index.constant 2 : index
%inputs = channel.bind<fifo> %input_slots, %237 : view<2x[%input_size$11]xbf16>, index -> channel<tile<[%input_size$11]xbf16>>
%weight_storage = buffer.alloca<workgroup> pool(%tile_memory) align(64) %14 : buffer
%weight_slots = buffer.view %weight_storage[%input_storage_byte_offset] : buffer -> view<1x2x[%input_size$11]xbf16>
%resident_weights = channel.bind<fifo> %weight_slots, %241 : view<1x2x[%input_size$11]xbf16>, index -> channel<tile<2x[%input_size$11]xbf16>>
%234 = index.constant 8 : offset
%output_storage = buffer.alloca<workgroup> pool(%tile_memory) align(64) %234 : buffer
%output_slots = buffer.view %output_storage[%input_storage_byte_offset] : buffer -> view<2x1xf32>
%outputs = channel.bind<fifo> %output_slots, %237 : view<2x1xf32>, index -> channel<tile<1xf32>>
pipeline.strand workers([0, 2], [1, 1], [1, 1]) {
%input_size = config.get @ffn_gate_up.input_size : index
%51 = index.constant 0 : index
%source_weights = buffer.view %weights_aligned[%51] : buffer -> view<2x[%input_size]xbf16>
%reservation_write, %reservation_payload = channel.reserve %resident_weights : channel<tile<2x[%input_size$11]xbf16>> -> (write<tile<2x[%input_size$11]xbf16>>, view<2x[%input_size$11]xbf16>)
%copy = kernel.async.copy %source_weights to %reservation_payload {cache_scope = workgroup, cache_temporal = regular, direction = global_to_workgroup} : view<2x[%input_size]xbf16> to view<2x[%input_size$11]xbf16> -> kernel.async.token
%56 = kernel.async.group %copy : kernel.async.token -> kernel.async.group
kernel.async.wait %56 {newer_groups = 0} : kernel.async.group
channel.publish %reservation_write : write<tile<2x[%input_size$11]xbf16>>
func.call @fill_input(%51, %input_aligned, %input_size$11, %inputs) : (index, buffer, index, channel<tile<[%input_size$11]xbf16>>)
func.call @drain_output(%51, %outputs, %output_aligned) : (index, channel<tile<1xf32>>, buffer)
}
pipeline.strand workers([0, 3], [1, 1], [1, 1]) {
%weights_record_read, %weights_record_payload = channel.acquire %resident_weights : channel<tile<2x[%input_size$11]xbf16>> -> (read<tile<2x[%input_size$11]xbf16>>, view<2x[%input_size$11]xbf16>)
%input_record_read, %input_record_payload = channel.acquire %inputs : channel<tile<[%input_size$11]xbf16>> -> (read<tile<[%input_size$11]xbf16>>, view<[%input_size$11]xbf16>)
%output_record_write, %output_record_payload = channel.reserve %outputs : channel<tile<1xf32>> -> (write<tile<1xf32>>, view<1xf32>)
func.call @gate_up_tile(%input_size$11, %input_record_payload, %input_size$11, %weights_record_payload, %output_record_payload) : (index, view<[%input_size$11]xbf16>, index, view<2x[%input_size$11]xbf16>, view<1xf32>)
channel.publish %output_record_write : write<tile<1xf32>>
channel.release %input_record_read : read<tile<[%input_size$11]xbf16>>
channel.release %weights_record_read : read<tile<2x[%input_size$11]xbf16>>
}
}
func.def inline @fill_input(%record: index, %input: buffer, %inputs_dim0: index, %inputs: channel<tile<[%inputs_dim0]xbf16>>) {
%input_size = config.get @ffn_gate_up.input_size : index
%101 = index.mul %record, %input_size : index
%243 = index.constant 2 : index
%105 = index.mul %101, %243 : index
%byte_offset = index.cast %105 : index to offset
%source = buffer.view %input[%byte_offset] : buffer -> view<[%input_size]xbf16>
%reservation_write, %reservation_payload = channel.reserve %inputs : channel<tile<[%inputs_dim0]xbf16>> -> (write<tile<[%inputs_dim0]xbf16>>, view<[%inputs_dim0]xbf16>)
%copy = kernel.async.copy %source to %reservation_payload {cache_scope = workgroup, cache_temporal = regular, direction = global_to_workgroup} : view<[%input_size]xbf16> to view<[%inputs_dim0]xbf16> -> kernel.async.token
%112 = kernel.async.group %copy : kernel.async.token -> kernel.async.group
kernel.async.wait %112 {newer_groups = 0} : kernel.async.group
channel.publish %reservation_write : write<tile<[%inputs_dim0]xbf16>>
func.return
}
func.def inline @drain_output(%record: index, %outputs: channel<tile<1xf32>>, %output: buffer) {
%244 = index.constant 4 : index
%119 = index.mul %record, %244 : index
%byte_offset = index.cast %119 : index to offset
%destination = buffer.view %output[%byte_offset] : buffer -> view<1xf32>
%acquisition_read, %acquisition_payload = channel.acquire %outputs : channel<tile<1xf32>> -> (read<tile<1xf32>>, view<1xf32>)
%copy = kernel.async.copy %acquisition_payload to %destination {cache_scope = workgroup, cache_temporal = regular, direction = workgroup_to_global} : view<1xf32> to view<1xf32> -> kernel.async.token
%125 = kernel.async.group %copy : kernel.async.token -> kernel.async.group
kernel.async.wait %125 {newer_groups = 0} : kernel.async.group
channel.release %acquisition_read : read<tile<1xf32>>
func.return
}
func.def inline @gate_up_tile(%input_dim0: index, %input: view<[%input_dim0]xbf16>, %weights_dim1: index, %weights: view<2x[%weights_dim1]xbf16>, %output: view<1xf32>) {
%256 = index.constant 64 : offset
%scratch = buffer.alloca<private> align(64) %256 : buffer
%scratch_byte_offset = index.constant 0 : index
%scratch_view = buffer.view %scratch[%scratch_byte_offset] : buffer -> view<16xf32>
%gate_sum$139 = scalar.constant 0.0 : f32
%254 = index.constant 2 : index
%147 = index.constant 1 : index
%gate_sum$151, %up_sum = scf.for %row = [%scratch_byte_offset to %254 step %147](%gate_sum$149 = %gate_sum$139 : f32, %up_sum$150 = %gate_sum$139 : f32) -> (f32, f32) {
%parts$259 = vector.splatf 0.0 : vector<16xf32>
%parts$161, %position = scf.while(%parts = %parts$259 : vector<16xf32>, %position = %scratch_byte_offset : index) -> (vector<16xf32>, index) {
%input_size = config.get @ffn_gate_up.input_size : index
%164 = index.cmp slt, %position, %input_size : index
scf.condition %164, %parts, %position : i1, vector<16xf32>, index
} do(%parts$159: vector<16xf32>, %position$160: index) {
%input_values = vector.load<type_disjoint> %input[%position$160] : view<[%input_dim0]xbf16> -> vector<32xbf16>
%weight_values = vector.load<type_disjoint> %weights[%row, %position$160] : view<2x[%weights_dim1]xbf16> -> vector<32xbf16>
%parts$167 = vector.dot2f %input_values, %weight_values, %parts$159 : vector<32xbf16>, vector<32xbf16>, vector<16xf32>
%252 = index.constant 32 : index
%position$171 = index.add %position$160, %252 : index
scf.yield %parts$167, %position$171 : vector<16xf32>, index
}
vector.store<type_disjoint> %parts$161, %scratch_view[%scratch_byte_offset] : vector<16xf32>, view<16xf32>
%249 = index.constant 16 : index
%sum = scf.for %lane = [%scratch_byte_offset to %249 step %147](%sum$184 = %gate_sum$139 : f32) -> (f32) {
%186 = view.load<type_disjoint> %scratch_view[%lane] : view<16xf32> -> f32
%sum$187 = scalar.addf %sum$184, %186 : f32
scf.yield %sum$187 : f32
}
%191 = index.cmp eq, %row, %scratch_byte_offset : index
%gate_sum$257 = scf.select %191, %sum, %gate_sum$149 : f32
%up_sum$258 = scf.select %191, %up_sum$150, %sum : f32
scf.yield %gate_sum$257, %up_sum$258 : f32, f32
}
%264 = scalar.fptrunc %gate_sum$151 : f32 to bf16
%gate = vector.splat %264 : vector<16xbf16>
%262 = scalar.fptrunc %up_sum : f32 to bf16
%up = vector.splat %262 : vector<16xbf16>
%quarters = vector.splatf 0.25 : vector<16xbf16>
%halves = vector.splatf 0.5 : vector<16xf32>
%linear = func.call pure @bf16_product(%gate, %quarters) : (vector<16xbf16>, vector<16xbf16>) -> (vector<16xbf16>)
%204 = vector.extf %linear : vector<16xbf16> to vector<16xf32>
%205 = vector.addf %halves, %204 : vector<16xf32>
%scale = vector.fptrunc %205 : vector<16xf32> to vector<16xbf16>
%activated = func.call pure @bf16_product(%gate, %scale) : (vector<16xbf16>, vector<16xbf16>) -> (vector<16xbf16>)
%result = func.call pure @bf16_product(%activated, %up) : (vector<16xbf16>, vector<16xbf16>) -> (vector<16xbf16>)
%245 = vector.extract %result[0] : vector<16xbf16> -> bf16
%212 = scalar.extf %245 : bf16 to f32
view.store<type_disjoint> %212, %output[%scratch_byte_offset] : f32, view<1xf32>
func.return
}
func.def inline @bf16_product(%lhs: vector<16xbf16>, %rhs: vector<16xbf16>) -> (vector<16xbf16>) {
%zeros = vector.splatf 0.0 : vector<16xbf16>
%initial = vector.splatf 0.0 : vector<16xf32>
%left = vector.interleave<0> %lhs, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%right = vector.interleave<0> %rhs, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%223 = vector.dot2f %left, %right, %initial : vector<32xbf16>, vector<32xbf16>, vector<16xf32>
%224 = vector.fptrunc %223 : vector<16xf32> to vector<16xbf16>
func.return %224 : vector<16xbf16>
}
pipeline.def<kernel> requires one directly loadable artifact. Its leading
parentheses contain specialization arguments, empty here; run declares the
values supplied for each invocation. The selected target provides hardware
facts. The target symbol is not a live device or a shared mutable execution
instance.
A pipeline.strand declares work rather than executing inline at its position
in the construction region. Each selected worker enters its strand once.
Ordinary scf.for loops express repetition. Reaching the closing brace completes
that strand instance; it does not implicitly restart it whenever input arrives.
Strands capture lexical SSA values, including buffers and channel identities.
The three coordinate lists are origins, counts, and strides. On this target,
workers([0, 2], [1, 1], [1, 1]) selects column 0, row 2, and
workers([0, 3], [1, 1], [1, 1]) selects its adjacent compute tile. Coordinate
i within a dimension maps to origin + i * stride.
A strand need not consume a compute core. After specialization, this example's transfer strand consists entirely of fixed DMA transfers and channel actions. The device invocation command stream issues its copies and preserves its waits and publications. Only the arithmetic strand needs tile instructions. A transfer strand and a compute strand can also select the same tile when communication has this realization.
The command stream is one sequential engine, so the compiler assigns at most one strand to it. This realization requires an acyclic unconditional sequence, fixed transfer endpoints, and at most one admission at each channel endpoint. Bounded ingress loops have a separate realization: the DMA engine itself can reserve a free channel slot, copy the next record, and publish it. Independent DMA streams keep separate engines and routes rather than sharing the command sequencer's execution order. Communication that needs instruction execution still runs on its selected core.
pipeline.memory<workgroup>[0, 3] selects the invocation's tile-local pool.
Generic child pipelines and nested groups borrow that same coordinate space;
the selected pool must exist in their materializing invocation. The query
allocates nothing and introduces no synchronization. The three buffer.alloca
operations create distinct allocation roots in that pool. Their buffer.view
operations describe how slots and payload elements occupy those allocations.
Compute accesses and DMA routes must have legal mappings to that memory.
Adjacency permits direct shared-memory access between these selected tiles.
The leading view dimension is the number of storage slots. For example,
view<2x[%input_size]xbf16> supplies two K-element records to
channel<tile<[%input_size]xbf16>>. The channel type describes one record, while the bound
view and capacity describe its storage. Binding creates a fresh protocol
identity: equal addresses do not imply equal channels or control dependencies.
At K=512, the authored channel storage totals 4104 bytes: 2048 for input slots, 2048 for retained weights, and 8 for output slots. The projection also uses a 64-byte private reduction buffer. Alignment and transport/control storage are additional physical requirements accounted for during lowering. The compiler checks the complete placement against the device's available memory.
Order phases and overlap independent branches¶
pipeline.serial completes each child before advancing. A
pipeline.concurrent group inside it runs independent branches together, then
joins the whole group before the next serial child. Both scopes nest, so a
branch can have its own ordered phases without making its siblings wait at
those intermediate boundaries.
Given composable project_gate, activate_gate, project_up, and combine
pipelines, an FFN schedule can express that relationship directly:
pipeline.serial {
pipeline.concurrent {
pipeline.serial {
pipeline.compose @project_gate(%input, %gate) : (buffer, buffer)
pipeline.compose @activate_gate(%gate) : (buffer)
}
pipeline.compose @project_up(%input, %up) : (buffer, buffer)
}
pipeline.compose @combine(%gate, %up, %output) : (buffer, buffer, buffer)
}
The two projections use disjoint progress engines and write separate buffers.
activate_gate may reuse project_gate's engines after it completes, while the
up branch progresses independently. combine starts after both branches
finish and can reuse their engines. Buffers declared outside the groups survive
these boundaries. This is one device invocation; the host submits no intermediate
phases. In C++, the matching scopes are [[loom::serial]] and
[[loom::concurrent]], with loom::pipeline::compose<callee>(...) for each child.
Runtime loops and conditions belong in serial schedules. Repeating a concurrent group calls the same resident phase bodies; it does not stamp out more workers per iteration. Group-owned channels start a fresh protocol lifetime on each visit, while outer channels keep their published records and cursor state. Direct strands belong in a concurrent graph or a composed child definition.
A serial completion boundary waits for the child's strands and transfers. Its children must be able to finish without work from a later phase: for example, a producer that fills a bounded channel and needs its consumer to release slots belongs in the same concurrent group as that consumer. Completion neither empties an outer channel nor supplies missing credits. The compiler rejects overlapping concurrent engine assignments and unsupported completion graphs.
Publication and reuse surround the actual transfer¶
The ingress helper reserves writable storage, launches a copy into it, waits for that copy, then publishes the initialized record:
static LOOM_INLINE void fill_input(loomt::index record, Bytes input,
InputChannel inputs) {
auto byte_offset = loom::offset::cast(record * input_size * loomt::index{2});
auto source = loom::buffer::view<loomt::dynamic>(
loom::buffer::cast<std::bfloat16_t>(input), byte_offset,
loomt::indices{input_size});
auto reservation = loom::channel::reserve(inputs);
auto copy = loom::kernel::async::copy<
loom::kernel::async::direction::global_to_workgroup,
loom::cache::scope::workgroup, loom::cache::temporal::regular>(
source, reservation.payload);
loom::kernel::async::wait<0>(loom::kernel::async::group(copy));
loom::channel::publish(reservation.write);
}
write<tile<[%input_size]xbf16>> owns the reservation. The view is a borrowed way to access
its payload, so ordinary vector operations and functions can use it.
Publishing consumes the write obligation. Publishing before the DMA completes
would let the consumer read incomplete data.
The output helper follows the other side of the lifetime:
static LOOM_INLINE void drain_output(loomt::index record, OutputChannel outputs,
Bytes output) {
auto byte_offset = loom::offset::cast(record * loomt::index{4});
auto destination =
loom::buffer::view<1>(loom::buffer::cast<float>(output), byte_offset, {});
auto acquisition = loom::channel::acquire(outputs);
auto copy = loom::kernel::async::copy<
loom::kernel::async::direction::workgroup_to_global,
loom::cache::scope::workgroup, loom::cache::temporal::regular>(
acquisition.payload, destination);
loom::kernel::async::wait<0>(loom::kernel::async::group(copy));
loom::channel::release(acquisition.read);
}
channel.acquire returns an owned read plus a ready payload view. The read
stays owned through the outgoing DMA; only channel.release permits recycling
that record's storage. Waiting for the DMA is a storage-lifetime edge, not a
global barrier across the pipeline.
The compute strand holds its weight read across its entire loop. Each input and output record has a shorter lifetime inside that loop. More records can reuse the same weights and slots without a new host submission. This maintained workload sets the record count to one; its two-slot storage and prefill/drain loops express the streaming schedule even when specialization removes that repetition. A larger stream also needs input and output bindings sized for its record count.
This schedule preloads at most two inputs and then drains an output before refilling an input. That order matters: a service worker that blocks filling an input while the compute worker blocks on a full output can deadlock. Buffer capacity and control flow are part of the author's schedule in this native cut; channel ownership alone is not a proof that every authored network makes progress.
Repeating ingress without a feeder core¶
A regular input stream can move its entire reserve/copy/wait/publish loop into
DMA descriptors. For example, eight external records can cycle through two
tile-local slots while the compute strand retains its weights. Each DMA
iteration acquires a free credit and publishes a ready credit only after the
local write completes. The consumer returns free credit through its ordinary
channel.release. A full input channel stalls that DMA stream without making a
compute core poll for space.
This realization preserves supported strided record layouts. Descriptor iteration advances the external record address and rotates the local slot; it does not gather each record into another transient buffer. On the current profiles, one task supports up to 256 executions, with up to 64 distinct external record offsets and 64 local slots. A repeatedly read fixed external record can use all 256 executions. Memory, descriptor, route, and lock limits still apply.
Read-ahead needs an ownership proof. An external DMA can fetch bytes before the
corresponding local slot becomes free. The compiler therefore requires disjoint
caller-buffer facts and verifies that the complete pipeline cannot write the
source while those reads are in flight. Distinct buffer arguments alone do not
establish disjointness; an author's buffer.assume.noalias is a caller contract.
Imported channels or opaque effects that prevent this proof keep instruction
execution. The compiler also requires the consumer to drain the complete
produced prefix before invocation completion, so no task still owns its backing
storage when the caller reuses it.
Output lifetime remains separate. A compute strand can drain each result with the output helper above, holding its read until the external write completes. Ingress offload does not authorize releasing that output after only a local source read. Configuration starts autonomous input streams before potentially blocking command-stream work, and resets the local iteration cursor between invocations when the record count ends partway around the slot ring.
The resulting compile report counts instruction images and channel storage separately, so eliminating a feeder image cannot hide its storage cost. Successful lowering proves that the program fits this realization; device execution and timing remain separate qualification steps.
Inspect the real compilation boundaries¶
Add IR tracing to the same successful compile when investigating placement or generated worker code:
loom-compile gated-projection.loom \
--root=@ffn_gate_up_quadratic_bf16 \
--target=amd.xdna.aie2p:amd.xdna.strix_halo.17f0_11 \
--config=ffn_gate_up.input_size=512 --format=xdna \
--dump-ir-after=outline-pipeline-strands \
--dump-ir-after=aie2p-lower-pipeline \
--dump-ir-output=trajectory/ \
--compile-report=summary --compile-report-output=projection.report.json \
--output=projection.xdna
The trace directory contains complete modules, with a trace index identifying their boundaries. The generated examples below come from those compiler outputs, with trace comments removed from the downloadable modules.
Explicit callable boundaries¶
The outlined module still contains the pipeline's storage and placement. Each strand calls an ordinary function with explicit captured arguments. The public three-buffer invocation ABI has not acquired those internal channel arguments.
Complete compiler-produced outlined module
aie2p.target<array> @npu
pipeline.def<kernel> public retain target(@__loom_target_context_0_0) @ffn_gate_up_quadratic_bf16() run(%input: buffer, %weights: buffer, %output: buffer) {
%input_aligned = buffer.assume.alignment %input {minimum_alignment = 64} : buffer
%weights_aligned = buffer.assume.alignment %weights {minimum_alignment = 64} : buffer
%output_aligned = buffer.assume.alignment %output {minimum_alignment = 64} : buffer
%tile_memory = pipeline.memory<workgroup>[0, 3] : pool
%input_size$11 = index.constant 512 : index
%241 = index.constant 1 : index
%14 = index.constant 2048 : offset
%input_storage = buffer.alloca<workgroup> pool(%tile_memory) align(64) %14 : buffer
%input_storage_byte_offset = index.constant 0 : index
%input_slots = buffer.view %input_storage[%input_storage_byte_offset] : buffer -> view<2x[%input_size$11]xbf16>
%237 = index.constant 2 : index
%inputs = channel.bind<fifo> %input_slots, %237 : view<2x[%input_size$11]xbf16>, index -> channel<tile<[%input_size$11]xbf16>>
%weight_storage = buffer.alloca<workgroup> pool(%tile_memory) align(64) %14 : buffer
%weight_slots = buffer.view %weight_storage[%input_storage_byte_offset] : buffer -> view<1x2x[%input_size$11]xbf16>
%resident_weights = channel.bind<fifo> %weight_slots, %241 : view<1x2x[%input_size$11]xbf16>, index -> channel<tile<2x[%input_size$11]xbf16>>
%234 = index.constant 8 : offset
%output_storage = buffer.alloca<workgroup> pool(%tile_memory) align(64) %234 : buffer
%output_slots = buffer.view %output_storage[%input_storage_byte_offset] : buffer -> view<2x1xf32>
%outputs = channel.bind<fifo> %output_slots, %237 : view<2x1xf32>, index -> channel<tile<1xf32>>
pipeline.strand workers([0, 2], [1, 1], [1, 1]) {
func.call @__pipeline_strand_1(%output_aligned, %inputs, %outputs, %weights_aligned, %resident_weights, %input_aligned, %input_size$11) : (buffer, channel<tile<[%input_size$11]xbf16>>, channel<tile<1xf32>>, buffer, channel<tile<2x[%input_size$11]xbf16>>, buffer, index)
}
pipeline.strand workers([0, 3], [1, 1], [1, 1]) {
func.call @__pipeline_strand_0(%resident_weights, %input_size$11, %outputs, %inputs) : (channel<tile<2x[%input_size$11]xbf16>>, index, channel<tile<1xf32>>, channel<tile<[%input_size$11]xbf16>>)
}
}
aie2p.target<array> @__loom_target_context_0_0 {device_profile = "amd.xdna.strix_halo.17f0_11"}
func.def inline target(@__loom_target_context_1_0) @__pipeline_strand_0(%resident_weights: channel<tile<2x[%input_size$11]xbf16>>, %input_size$11: index, %outputs: channel<tile<1xf32>>, %inputs: channel<tile<[%input_size$11]xbf16>>) {
cfg.br ^_bb1
^_bb1:
%weights_record_read, %weights_record_payload = channel.acquire %resident_weights : channel<tile<2x[%input_size$11]xbf16>> -> (read<tile<2x[%input_size$11]xbf16>>, view<2x[%input_size$11]xbf16>)
%input_record_read, %input_record_payload = channel.acquire %inputs : channel<tile<[%input_size$11]xbf16>> -> (read<tile<[%input_size$11]xbf16>>, view<[%input_size$11]xbf16>)
%output_record_write, %output_record_payload = channel.reserve %outputs : channel<tile<1xf32>> -> (write<tile<1xf32>>, view<1xf32>)
%256 = index.constant 64 : offset
%scratch = buffer.alloca<private> align(64) %256 : buffer
%scratch_byte_offset = index.constant 0 : index
%scratch_view = buffer.view %scratch[%scratch_byte_offset] : buffer -> view<16xf32>
%gate_sum$139 = scalar.constant 0.0 : f32
%254 = index.constant 2 : index
%147 = index.constant 1 : index
%parts$259 = vector.splatf 0.0 : vector<16xf32>
%252 = index.constant 32 : index
%249 = index.constant 16 : index
%input_size = index.constant 512 : index
cfg.br ^_bb2(%scratch_byte_offset: index, %gate_sum$139: f32, %gate_sum$139: f32)
^_bb2(%43: index, %gate_sum$149: f32, %up_sum$150: f32):
%46 = index.cmp slt, %43, %254 : index
cfg.cond_br %46, ^_bb3, ^_bb10
^_bb3:
%row = index.assume %43 [range(%43, 0, 1)] : index
cfg.br ^_bb4(%parts$259: vector<16xf32>, %scratch_byte_offset: index)
^_bb4(%parts: vector<16xf32>, %49: index):
%position = index.assume %49 [range(%49, 0, 512), multiple_of(%49, 32)] : index
%164 = index.cmp slt, %position, %input_size : index
cfg.cond_br %164, ^_bb5, ^_bb6
^_bb5:
%position$160 = index.assume %position [range(%position, 0, 480), multiple_of(%position, 32)] : index
%input_values = vector.load<type_disjoint> %input_record_payload[%position$160] : view<[%input_size$11]xbf16> -> vector<32xbf16>
%weight_values = vector.load<type_disjoint> %weights_record_payload[%row, %position$160] : view<2x[%input_size$11]xbf16> -> vector<32xbf16>
%parts$167 = vector.dot2f %input_values, %weight_values, %parts : vector<32xbf16>, vector<32xbf16>, vector<16xf32>
%position$171 = index.add %position$160, %252 : index
cfg.br ^_bb4(%parts$167: vector<16xf32>, %position$171: index)
^_bb6:
vector.store<type_disjoint> %parts, %scratch_view[%scratch_byte_offset] : vector<16xf32>, view<16xf32>
cfg.br ^_bb7(%scratch_byte_offset: index, %gate_sum$139: f32)
^_bb7(%57: index, %sum$184: f32):
%59 = index.cmp slt, %57, %249 : index
cfg.cond_br %59, ^_bb8, ^_bb9
^_bb8:
%lane = index.assume %57 [range(%57, 0, 15)] : index
%186 = view.load<type_disjoint> %scratch_view[%lane] : view<16xf32> -> f32
%sum$187 = scalar.addf %sum$184, %186 : f32
%63 = index.add %lane, %147 : index
cfg.br ^_bb7(%63: index, %sum$187: f32)
^_bb9:
%191 = index.cmp eq, %row, %scratch_byte_offset : index
%gate_sum$257 = scf.select %191, %sum$184, %gate_sum$149 : f32
%up_sum$258 = scf.select %191, %up_sum$150, %sum$184 : f32
%67 = index.add %row, %147 : index
cfg.br ^_bb2(%67: index, %gate_sum$257: f32, %up_sum$258: f32)
^_bb10:
%264 = scalar.fptrunc %gate_sum$149 : f32 to bf16
%gate = vector.splat %264 : vector<16xbf16>
%262 = scalar.fptrunc %up_sum$150 : f32 to bf16
%up = vector.splat %262 : vector<16xbf16>
%quarters = vector.splatf 0.25 : vector<16xbf16>
%halves = vector.splatf 0.5 : vector<16xf32>
%zeros = vector.splatf 0.0 : vector<16xbf16>
%left$75 = vector.interleave<0> %gate, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%right$76 = vector.interleave<0> %quarters, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%223$77 = vector.dot2f %left$75, %right$76, %parts$259 : vector<32xbf16>, vector<32xbf16>, vector<16xf32>
%224$78 = vector.fptrunc %223$77 : vector<16xf32> to vector<16xbf16>
%204 = vector.extf %224$78 : vector<16xbf16> to vector<16xf32>
%205 = vector.addf %halves, %204 : vector<16xf32>
%scale = vector.fptrunc %205 : vector<16xf32> to vector<16xbf16>
%right$82 = vector.interleave<0> %scale, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%223$83 = vector.dot2f %left$75, %right$82, %parts$259 : vector<32xbf16>, vector<32xbf16>, vector<16xf32>
%224$84 = vector.fptrunc %223$83 : vector<16xf32> to vector<16xbf16>
%left$85 = vector.interleave<0> %224$84, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%right$86 = vector.interleave<0> %up, %zeros : vector<16xbf16>, vector<16xbf16> -> vector<32xbf16>
%223$87 = vector.dot2f %left$85, %right$86, %parts$259 : vector<32xbf16>, vector<32xbf16>, vector<16xf32>
%224$88 = vector.fptrunc %223$87 : vector<16xf32> to vector<16xbf16>
%245 = vector.extract %224$88[0] : vector<16xbf16> -> bf16
%212 = scalar.extf %245 : bf16 to f32
view.store<type_disjoint> %212, %output_record_payload[%scratch_byte_offset] : f32, view<1xf32>
channel.publish %output_record_write : write<tile<1xf32>>
channel.release %input_record_read : read<tile<[%input_size$11]xbf16>>
channel.release %weights_record_read : read<tile<2x[%input_size$11]xbf16>>
func.return
}
func.def inline target(@__loom_target_context_1_1) @__pipeline_strand_1(%output_aligned: buffer, %inputs: channel<tile<[%input_size$11]xbf16>>, %outputs: channel<tile<1xf32>>, %weights_aligned: buffer, %resident_weights: channel<tile<2x[%input_size$11]xbf16>>, %input_aligned: buffer, %input_size$11: index) {
%input_size = index.constant 512 : index
%51 = index.constant 0 : index
%source_weights = buffer.view %weights_aligned[%51] : buffer -> view<2x[%input_size]xbf16>
%reservation_write$101, %reservation_payload$102 = channel.reserve %resident_weights : channel<tile<2x[%input_size$11]xbf16>> -> (write<tile<2x[%input_size$11]xbf16>>, view<2x[%input_size$11]xbf16>)
%copy$103 = kernel.async.copy %source_weights to %reservation_payload$102 {cache_scope = workgroup, cache_temporal = regular, direction = global_to_workgroup} : view<2x[%input_size]xbf16> to view<2x[%input_size$11]xbf16> -> kernel.async.token
%56 = kernel.async.group %copy$103 : kernel.async.token -> kernel.async.group
kernel.async.wait %56 {newer_groups = 0} : kernel.async.group
channel.publish %reservation_write$101 : write<tile<2x[%input_size$11]xbf16>>
%byte_offset = index.constant 0 : offset
%source = buffer.view %input_aligned[%byte_offset] : buffer -> view<512xbf16>
%reservation_write$107, %reservation_payload$108 = channel.reserve %inputs : channel<tile<[%input_size$11]xbf16>> -> (write<tile<[%input_size$11]xbf16>>, view<[%input_size$11]xbf16>)
%copy$109 = kernel.async.copy %source to %reservation_payload$108 {cache_scope = workgroup, cache_temporal = regular, direction = global_to_workgroup} : view<512xbf16> to view<[%input_size$11]xbf16> -> kernel.async.token
%112 = kernel.async.group %copy$109 : kernel.async.token -> kernel.async.group
kernel.async.wait %112 {newer_groups = 0} : kernel.async.group
channel.publish %reservation_write$107 : write<tile<[%input_size$11]xbf16>>
%destination = buffer.view %output_aligned[%byte_offset] : buffer -> view<1xf32>
%acquisition_read, %acquisition_payload = channel.acquire %outputs : channel<tile<1xf32>> -> (read<tile<1xf32>>, view<1xf32>)
%copy$114 = kernel.async.copy %acquisition_payload to %destination {cache_scope = workgroup, cache_temporal = regular, direction = workgroup_to_global} : view<1xf32> to view<1xf32> -> kernel.async.token
%125 = kernel.async.group %copy$114 : kernel.async.token -> kernel.async.group
kernel.async.wait %125 {newer_groups = 0} : kernel.async.group
channel.release %acquisition_read : read<tile<1xf32>>
func.return
}
aie2p.target<core> @__loom_target_context_1_0 {device_profile = "amd.xdna.strix_halo.17f0_11"}
aie2p.target<core> @__loom_target_context_1_1 {device_profile = "amd.xdna.strix_halo.17f0_11"}
Shapes and target environments are visible in this IR. The normal compiler has also simplified the single-record loop and lowered remaining structured loops to CFG. A helper that accepts only borrowed views still performs ordinary memory computation. Channel-aware helpers expose ownership effects through their definitions before worker realization.
Tile code and configuration code¶
The native realization module contains the arithmetic worker and configuration functions. The worker implements its channel credits and arithmetic. Configuration code establishes routes, storage and bindings, loads the worker image, and starts execution. It also implements the finite transfer strand's ordered DMA and channel actions before joining the final completion obligations. No transfer image is loaded.
An input publication still follows its DMA completion. An output acquisition can become a descriptor's credit acquire when its copy and wait immediately follow it; otherwise it remains an explicit ordered wait. The final command waits for the external output write before returning. Channel storage remains allocated even when communication requires no tile instructions, and the compile report accounts for storage and worker images separately.
Both are ordinary target IR. In particular, program.load is an AIE2P
configuration instruction, inside a Low function targeting
amd.xdna.aie2p.configuration. It selects
the column, row, and tile-code symbol to load. It is not a generic pipeline
operation, a host callback between records, or a separate executable category.
| Term | Meaning in this example |
|---|---|
| Role | The logical transfer or projection computation authored by functions and control flow. |
| Strand | One independently progressing source body, entered once per selected worker instance. |
| Worker program | Tile instructions for the computation and communication assigned to a core. A DMA-realized strand needs no worker program. |
| Tile image | Linked instructions and data admitted against one tile's physical budgets. |
| Exported entry | The named invocation ABI in the containing ELF. |
The .xdna ELF can contain multiple exports and tile programs. The 16 KiB
instruction limit applies to the code live on one compute tile at one time.
The projection above fits in one load. For a larger worker the compiler can
pack code from mutually exclusive pipeline scopes into the same instruction
addresses. The instructions that issue the loads stay resident. When a scope
needs a new group, the worker requests it from the adjacent SRAM tile and
waits for completion before entering it. Live channel records keep their
storage throughout the exchange.
The establishing command fills the SRAM code catalogs before activation.
For large contiguous catalogs it can upload one range per column in
parallel while the compute cores are held in reset. The application then
takes over the same DMA engines and switches. The executable carries the
source ranges in an immutable .xdna.data section. Its size in
readelf -SW model.xdna includes the alignment padding between DMA sources.
On NPU2, columns with less than 4 KiB of catalog data use direct firmware
writes because establishing and retiring a DMA circuit also takes time.
Resume compilation from text or bytecode¶
Save either complete generated module, for example the native realization as
native.loom, and compile it without the original source or analysis process:
loom-format native.loom --to=bc --output=native.loombc
loom-compile native.loombc --root=@ffn_gate_up_quadratic_bf16 \
--format=xdna --output=resumed.xdna
The IR already contains its specialized target and program semantics. Analysis is reconstructed from that module; no saved compiler-side planning object is required. The walkthrough exercises both boundaries on both profiles and compares the native artifacts produced by their text and bytecode forms.
Use the compile-report workflow to inspect the native artifact's code, allocation and scheduling evidence. Successful compilation establishes target admission; it does not establish numerical correctness or measured device throughput.
Account for a completed request¶
The unit of comparison is one completed request of a specified shape. Start with a full, heavily loaded request. For a port, run the working reference on the same NPU and follow the same inputs through both programs to the caller's final output. Keep a row for each unexplained difference. That row determines the next measurement whenever it could change the choice of schedule.
For a novel operation, take the transfer and compute baselines from
matched primitives
on the intended NPU partition. The first suggest output names the number
of programmed workers. A single-tile correctness example on a larger
partition makes the placement decision visible immediately. A larger worker
count still needs per-tile measurements on the completed request.
- Match the work. Record the executable and weight identities, input lengths before padding, batch composition, numerical acceptance, active device partition, and power policy. Interleave uninstrumented runs and record latency distributions and useful input tokens per second. Exercise a second shape that holds one cost constant. For example, one 4,096-token sequence and eight independent 512-token sequences have 4,096 dense rows each. At a 32-token tile width, their causal prefixes have 8,256 and 1,088 contributing score tiles per head, respectively. Padded slots, entirely skipped blocks, and finalization belong in the account.
- Find the phase that owns the excess elapsed time. Span tokenization, submission, device work, and final output. Use device-clock intervals for device phases. Count the union of overlapping intervals once. Keep mixed submissions as mixed until markers separate them. Record uncovered time. Compare an instrumented run with the ordinary invocation cadence and quantify any perturbation. Summed tile cycles answer a separate question about how the array spends its time.
- Follow one operand through that phase. For both programs record the
loop order, rows served per weight arrival, multicast destinations, buffer
depth, and where each accumulator lives until its last use. Count bytes per
transfer times actual executions at each boundary. For example, saving and
restoring a 1,024-byte partial result on each of seven window boundaries
contributes 14,336 external bytes. Count the input rereads required by the
alternative traversal too. Keep external payload, on-array deliveries, and
peak live storage in separate columns. To establish overlap, locate the
enqueue for panel i+1, the first use of its buffer, and the completion
that permits reuse. Two allocated slots alone establish only capacity.
On the first compile, run
loom-compile-report suggest model.report.json. Its source-phase copy rows name the external binding and give records and bytes per call. Exercise inputs on both sides of the first panel boundary. A save and restore on the same binding warrants checking whether the byte ranges coincide, how often each phase runs, and what must be reread to keep those partial results on chip. The complete group inventory is available withshow --format=jsonunder.pipeline_phase_copies[].groups. With--include-experimental, a repeated read into one freshly reserved slot names the producer phase, input binding, copy width, and refill count per worker. Measure the wait for that slot's credit and check available local storage before comparing a two-slot schedule. For a strided external copy, the report also gives the number of consecutive bytes in its inner dimensions. A 128 KiB copy with a 64-byte run visits 2,048 address groups. The same payload with a 2 KiB run visits - Check the selected DMA order at both ends and time the complete phase to see whether moving the reorder into SRAM pays. The device can combine or split those source-level groups into bus transactions.
- Count what every participating core executes. Disassemble the native
loops in the measured images, including their callers. Count loop trips,
full and partial tiles, issue packets, empty packets, MACs with operand
loads, independent accumulators, conversions, masks, and spills per useful
output. Use the actual branch mix. A cheap fast path that the full request
never enters contributes zero. Compare the result against core events on
every participating tile. Preserve the collection window and event mask
for each counter.
The default
aie2p.empty_loop_packetsfinding gives the function, byte offset, and number of all-NOP packets executed each time a repeated loop is entered. Multiply by visits on the worker that determines completion. For a callable shared across workers, query its final native placements in the summary report. Quote the glob to include specialized copies.
A body with 145 stored packets and a 110-packet region executed four
times issues 145 + (4 - 1) × 110 = 475 packets per call. If a fully
visible score block takes that path four times, charge it 1,900 packets.
The report gives the tile, loaded group, and address for checking the native
image. A request-dependent call count appears as unknown. Obtain its
visits from the request geometry or a matched device capture.
If two loops perform the same matrix operations and move the same bytes, count packets before the first MAC, from the first through the last MAC, and after the last MAC. In one eight-trip projection, moving packed reads between load ports cut the first interval from 35 to 30 packets per trip and the middle interval from 83 to 79. The last nine packets stayed the same. That accounts for all 72 packets saved per call. In the disassembly, distinguish loads tied to a port, such as accumulator loads on A, from packed loads that can issue on either A or B. Two ports that are free on the current cycle can have very different demand over the whole loop. 5. Trace a wait to its owner. A core stalled acquiring a record identifies the consumer. Locate the matching publication, the producer or DMA that performs it, and the event preventing that producer from progressing. A full output ring can delay an input publication several stages away. Pair the wait with a timestamp, a counted native site, or a controlled change to that edge. Count overlapping stall reasons with a hardware union when available. Keep unknown owners and unavailable events visible.
With AIE2P event counters, count LOCK_STALL directly and in combination
with a program-counter range on the same tile. A range covering the whole
program should reproduce the direct count. Disabled comparators should
give zero. Start with a range around one acquire and narrow it until the
stalled packet is identified. On Strix Halo, a straight-line capture of
query and key/value acquires counted zero through the third packet after
each acquire. The stall appeared at the fifth packet after it. Repeat
this calibration for the measured program. Check every code group that
can occupy the address and count a shared physical site once.
For a record relayed between tiles, follow the consumer's ready lock back to the neighbor's publish. Count that wait separately from the neighbor's wait for an empty slot and the ingress tile's wait for DMA completion. To measure elapsed cost, time the enclosing call and return on one tile, check their visit counts, and repeat with an input that skips the phase. Summing simultaneous waits across tiles measures lost compute capacity.
The static inventory for the gated-projection program is available in both views.
loom-compile-report show projection.report.json
loom-compile-report suggest projection.report.json --format=json \
| jq '.pipelines.rows[] | {root, external_dma_byte_count, routed_dma_byte_count}'
These byte counts describe one planned activation. A zero is a reported zero.
A null means the compiler lacks that transfer total. In particular, the
resident configuration inventory can establish placement and SRAM occupancy
while leaving transfer totals unknown. Account for those bytes from the
executed transfer schedule and its repetition counts. Even an exact payload
count requires a device observation to establish its cost on the critical
path.
With a HAL profile captured around the request and counters enabled, these commands identify the counter names, submission IDs, and sample values.
iree-profile summary --format=jsonl request.ireeprof
iree-profile counter --format=jsonl --counter_samples request.ireeprof \
| jq 'select(.type == "counter_sample") | {submission_id, key, block, counter, flags, values}'
Check the summary for dropped records and match each sample to the submitted
entry and request interval. The XDNA HAL exposes
partition_shim.invocation_cycles, which counts cycles inside the
compiler-declared measurement interval. Generated pipelines bracket worker
activation through completion waits. Setup before activation needs a separate
interval to account for its cost.
Attribution to core issue or stalls additionally needs per-tile event windows
from a collector that exposes those events on the target. A shim timer alone
leaves both quantities unknown.
Count each establishment in the complete request. For example, a 28-layer chain that re-establishes its attention entry at each layer pays for its initial tile instructions and SRAM code catalog 28 times. Measure setup before activation separately from the worker loop and compare with a continuation of the same entry.
For a phase dominated by vector work, the following accounting also exposes
three distinct costs. For each implementation measure elapsed cycles
summed over its participating tiles (T), cycles in the union of selected
stall events (S), and issued vector-instruction events (V). Count the same
semantic unit of useful work (U) on both sides. When the denominators are
nonzero the factors multiply to the measured cost.
The factors show how many vector events each output takes, how many remaining tile cycles accompany each vector event, and how much the selected waits inflate elapsed tile cycles. The middle term includes scalar issue, bubbles, and idle time inside the window. A vector event can be a mask, a conversion, or a MAC. Disassembly and the executed dataflow determine which one. Record a missing counter as unavailable. Summing individual stall reasons can count the same cycle twice.
A visibility mask illustrates why the caller matters. Suppose its native
helper contains 146 packets, including a 110-packet hardware loop that runs
four times. Each call issues 146 + 3 × 110 = 476 packets. A caller invoking
it twice per query half across two halves spends 1,904 packets per score tile
on masking alone. Count fully visible, boundary, and wholly masked tiles in
the actual request. Multiply by the call count in each class and compare the
fully visible case to the reference's unmasked complete tile. This exposes
a traversal or dispatch choice that improving register allocation inside the
mask cannot eliminate.
Admission to tuning requires a falsifiable prediction. Name the source loop or channel, the difference from the reference, the phase and counter or byte count that should change, and the maximum recoverable request time consistent with measured overlap. Test that prediction at the original request boundary with the same output-quality gate. If the investigation leaves a material residual large enough to explain the loss, the next experiment measures that residual. A shorter leaf, a cleaner report, or a win on prepared inputs cannot close it.
The caller owns the invocation lifetime¶
The normal loom-test path can compile and execute buffer-bound XDNA
pipelines through the
XDNA HAL:
The HAL selects the exact compiler profile from immutable device facts, loads the emitted ELF, stages the scenario buffers, submits the entry, and preserves their lifetimes through completion and readback. The current image ABI accepts buffer launch bindings. Leading specialization values must already be bound into compiler SSA before image emission; runtime scalar bindings and invocation results require a future image ABI.
The HAL queries each entry's backing and binding requirements and prepares its establishing command. libamdf submits the prepared instruction range. It does not interpret channels, invent a work schedule, or patch each pipeline record.
The establishing command loads/configures the workers once for that invocation. All record processing and input/output handoffs occur inside it. The emitted completion path waits for the program's worker and transfer obligations before the caller can reclaim their resources. A separate device consumer of the output still needs its own synchronization and lifetime edge.
The current time-sliced native context does not guarantee tile state survives between independent submissions. Reusing the same context or immutable command allocation does not establish that guarantee. Each independent invocation uses the establishing command; retaining state within one invocation is a different contract from retaining it between submissions.
This is the boundary a complete pipeline launcher must own: materialize transient allocations, bind the caller's I/O, submit work, and track completion. The XDNA HAL implements those steps for finite buffer-bound pipelines.