Control flow
Python builds the graph. RDL control-flow operations decide which graph computations execute during inference.
A Python loop over a fixed layer count is appropriate for constructing a stack. A loop whose stopping condition depends on tokens must use While.
If
If(condition, *, then_branch, else_branch)
condition is a scalar boolean tensor. Each callback takes no arguments and returns a tuple of tensors. Both callbacks build their graph once during tracing; only the selected branch executes during inference.
from redwood.rdl import *
with Graph() as graph:
x = Input(name="x", shape=(4,), dtype="fp32")
enabled = Input(name="enabled", shape=(), dtype="bool")
result = If(
enabled,
then_branch=lambda: (Relu(x),),
else_branch=lambda: (x,),
)[0]
Output(result, name="y")
Branches must return the same number of outputs with compiler-compatible types and shapes. Captured outer tensors are available inside callbacks.
Use Select for elementwise selection when evaluating both alternatives is acceptable.
While
While(initial, *, condition, body)
initial is a tuple of loop-carried tensors. Both callbacks receive that tuple. condition returns a scalar boolean; body returns the next tuple.
from redwood.rdl import *
with Graph() as graph:
limit = Input(
name="limit", shape=(), dtype="int32", minimum=0, maximum=16,
)
result = While(
(Constant(0, dtype="int32"), Constant(0.0)),
condition=lambda state: Compare(state[0], limit, predicate="lt"),
body=lambda state: (
Add(state[0], 1),
Add(state[1], Cast(state[0], "fp32")),
),
)
Output(result[1], name="sum")
The example sums the integers before limit into a floating-point result. A zero limit performs no body iterations.
The condition executes before each iteration, including the final check. It may read caches but cannot write them. The body can update caches explicitly.
Preserve the number and rank of carried tensors. Dtypes must settle to compatible inferred types, and changing dimensions must stay within compiler-supported bounds. Bounds permit memory planning; the model author must still provide a stopping condition that terminates.
Reduce
Reduce(values, *, initial, axes, reducer, keepdims=False)
Use Sum, Mean or Max for ordinary reductions. Reduce handles a custom associative scalar computation, including several accumulator values.
valuesis a tuple of tensors with corresponding reduction domainsinitialsupplies one scalar per accumulatorreducer(accumulators, elements)returns the next accumulator tupleaxesidentifies reduced dimensions
The reducer must be pure and associative. It cannot access caches. Initial values are returned for empty domains, in the inferred accumulator dtypes.
from redwood.rdl import *
with Graph() as graph:
x = Input(name="x", shape=(8,), dtype="fp32")
total = Reduce(
(x,), initial=(Constant(0.0),), axes=(0,),
reducer=lambda acc, item: (Add(acc[0], item[0]),),
)[0]
Output(total, name="total")
Floating-point results can vary with the reduction order chosen by the backend.
Randomness and token selection
Random(shape, seed=..., offset=0, distribution="uniform", dtype="fp32") records seeded draws without a shared global generator. Uniform values are in [0,1); normal values have mean zero and variance one.
Seed fits uint64. Offset is nonnegative and counts logical samples. Advance it between repeated draws when fresh values are needed. The logical sample offset determines sample order independently of thread scheduling. Sequences can vary between backends or dtypes.
Greedy(logits) selects one token from a rank-one logit vector and returns int32. Sample(logits, seed=..., offset=0, temperature=1.0, top_k=None, top_p=1.0) adds temperature, top-k and nucleus sampling. Temperature must be positive and 0 < top_p <= 1.
In a generation loop, advance the sampling offset with progress. Selecting tokens is only one part of the full procedure; include prefill, cache updates, stopping and output collection in RDL too.