Higher-level compositions
Compositions describe familiar operations using core RDL. They can map to a fused kernel or compile into smaller operations. Prefer them when their mathematical behavior matches the model.
Examples on this page are graph-building fragments. x, weights and caches must be declared in the surrounding model.
Linear and MLP
Linear(x, weight, *, bias=None)
FFN(x, *, up, down, gate=None, up_bias=None, down_bias=None,
gate_bias=None, activation=Silu)
Linear accepts a Tensor or Weight for its weights/bias. Weights have logical shape [out,in]; input is [...,in], output is [...,out]. A fused kernel can consume the original weight layout directly.
FFN projects up, applies an activation, then projects down. With a gate, the hidden value is up(x) * activation(gate(x)). Match the activation and bias choices to the checkpoint.
hidden = RMSNorm(x, weight=W["norm.weight"])
y = FFN(
hidden, up=W["mlp.up.weight"], gate=W["mlp.gate.weight"],
down=W["mlp.down.weight"], activation=Silu,
)
x = Add(x, y)
BitLinear, QuantizeInt8 and QuantizedLinear provide explicit activation-quantization compositions. See dtypes.
Attention
Attention(q, k, v, *, causal=True, scale=None, mask=None,
query_positions=None, key_positions=None, window=None,
softcap=None, sinks=None, softmax=True, dtype="fp32")
Use token-major tensors: Q [queries,query_heads,key_dim], K [keys,kv_heads,key_dim], V [keys,kv_heads,value_dim]. Query heads must group compatibly with KV heads. The result is [queries,query_heads,value_dim].
| Option | Meaning |
|---|---|
causal | Hide keys after each query’s position |
scale | Score multiplier; default is 1/sqrt(key_dim) |
mask | Values added to scores; use 0 to keep a score and -inf to mask it |
query_positions, key_positions | Absolute one-dimensional positions |
window | Restrict visible score distances |
softcap | Apply tanh score capping before softmax |
sinks | Extra softmax denominator terms |
softmax | Whether to normalize scores |
dtype | Returned tensor’s logical dtype |
Default positions align the queries with the right end of the keys, which fits cached decode. Supply explicit positions when the algorithm uses another alignment.
SplitHeads(x, heads=..., head_dim=None) views [T,H*D] as [T,H,D]; MergeHeads reverses it. RelativeAttention implements Transformer-XL-style relative scores with relative keys [2T-1,H,D] and content/position biases.
Normalization and activations
| Composition | Use |
|---|---|
LayerNorm | Center and normalize selected axes, with optional weight/bias |
RMSNorm | Normalize RMS on the last axis; optional weight offset/output dtype |
L2Norm | Normalize vector length on an axis |
BatchNorm | Inference using saved mean and variance on channel-first input |
GroupNorm | Normalize channel groups |
AdaptiveLayerNorm | Apply a supplied shift/scale after layer normalization |
VarianceNorm | Scale by variance without subtracting the mean from the output |
The activation functions are Relu, ReluSquared, Sigmoid, Silu, SiluMul, SwiGLU, Tanh, Gelu, Elu and Softplus. Choose the exact activation from the architecture, including approximation options where provided.
Normalization epsilon and affine parameters affect the model. Batch normalization uses saved statistics during inference.
Embeddings and positions
Embedding(tokens, weight, token_rank=1, padding_idx=None) selects learned rows, optionally zeroing a padding token. InterpolatedEmbedding(positions, weight, grid_size=...) bilinearly interpolates a learned square grid using [N,2] coordinates.
Sinusoidal generates positional features. Rotary rotates Q/K features using positions. Other variants include RotaryFromAngles, YaRN, AxialRotary and Qwen’s MRope.
Match position conventions, rotary sections and scaling to the model’s architecture.
Spatial operations
Conv accepts one channel-first input [C,spatial...], with weights [out,in/groups,spatial...]. Give kernel explicitly and set stride, padding, dilation and groups as required.
ConvTranspose uses checkpoint weights [in,out/groups,spatial...] and supports output_padding. Pool selects max or average windows; AdaptivePool targets an output size. Resize supports nearest, linear and cubic spatial interpolation.
Follow the model’s channel order and interpolation rules in processing and RDL.
Recurrent and expert operations
| Composition | Main state/layout |
|---|---|
GatedDelta | Q/K [T,H,K], V [T,H,V], state [H,K,V] |
CausalConv | Input [T,C], history [C,K-1] |
Mamba | Input/delta [T,D], state [D,N] |
Mamba2 | Input [T,H,P], state [H,P,N] |
LSTMCell | One step with input/forget/candidate/output gate order |
MoE | Route to supplied pure tensor functions |
GptOssMoE | GPT-oss expert-bank projection and gating conventions |
Persistent state uses explicit caches. Specialized routing kernels can reduce the expert work performed by a generic MoE composition.
Keep model-specific stacks and orchestration in the RDL file. Add a new reusable composition when it simplifies repeated mathematical computation, with @Construct preserving its core body.