class
SushiAI::Graph::GraphBuilder
Emits shape-checked IR nodes into a Graph.
- Declared in
include/SushiAI/graph/builder.hpp
Public member functions
explicit GraphBuilder(Graph &graph) noexceptWraps graph for emission.
Parameters
graphThe graph to append to; must outlive this builder.
Graph & graph() const noexceptThe graph being built.
ValueId input(Shape shape, std::string_view debug_name, DType dtype=DType::FLOAT32) constDeclares a minibatch input: a leaf rewritten every step.
Parameters
shapeThe value's extents.
debug_nameA label for diagnostics; must outlive the graph.
dtypeThe element type.
Returns
The new value's id.
ValueId parameter(Shape shape, std::string_view debug_name, DType dtype=DType::FLOAT32) constDeclares a learnable parameter: a leaf that needs a gradient.
Parameters
shapeThe value's extents.
debug_nameA label for diagnostics; must outlive the graph.
dtypeThe element type.
Returns
The new value's id.
ValueId matmul(ValueId a, ValueId b, bool transpose_a=false, bool transpose_b=false) constEmits MATMUL: C = op(A) * op(B).
Parameters
aLeft operand matrix.
bRight operand matrix.
transpose_aWhether to transpose
a.transpose_bWhether to transpose
b.
Returns
The product value id.
ValueId bias_add(ValueId x, ValueId bias) constEmits BIAS_ADD: Y = X + 1 * bias^T, over an [N, C] X.
Parameters
xThe [N, C] matrix.
biasThe [C] row added to every row of
x.
Returns
The sum's id.
Exceptions
ErrorIf the ranks or extents do not line up.
ValueId sum_rows(ValueId x) constEmits SUM_ROWS: the column sums of an [N, C] matrix.
Parameters
xThe [N, C] matrix.
Returns
The [C] result's id.
Exceptions
ErrorIf
xis not rank 2.
ValueId add(ValueId a, ValueId b) constEmits ADD: elementwise A + B.
Exceptions
Erroron mismatch.
ValueId sub(ValueId a, ValueId b) constEmits SUB: elementwise A - B.
Exceptions
Erroron mismatch.
ValueId mul(ValueId a, ValueId b) constEmits MUL: elementwise A * B.
Exceptions
Erroron mismatch.
ValueId div(ValueId a, ValueId b) constEmits DIV: elementwise a / b.
Parameters
aThe dividend.
bThe divisor; must share the shape and dtype of
a.
Returns
The quotient, shaped and laid out like a.
ValueId minimum(ValueId a, ValueId b) constEmits MINIMUM: the elementwise smaller of a and b.
Parameters
bMust share the shape and dtype of
a.
Returns
The minimum, shaped and laid out like a.
ValueId maximum(ValueId a, ValueId b) constEmits MAXIMUM: the elementwise larger of a and b.
Parameters
bMust share the shape and dtype of
a.
Returns
The maximum, shaped and laid out like a.
ValueId less_equal(ValueId a, ValueId b) constEmits LESS_EQUAL: 1 where a <= b and 0 elsewhere.
Parameters
bMust share the shape and dtype of
a.
Returns
The mask, in the shape, dtype and layout of a.
ValueId select(ValueId condition, ValueId a, ValueId b) constEmits SELECT: a where the condition is non-zero, b elsewhere.
Parameters
conditionA mask holding 0 or 1, in the shape and dtype of
a.bMust share the shape and dtype of
a.
Returns
The selection, shaped and laid out like a.
ValueId scale(ValueId x, double alpha) constEmits SCALE: Y = alpha * X.
Parameters
xThe operand.
alphaThe host-side constant factor.
Returns
The scaled value's id.
ValueId dynamic_scale(ValueId x, ValueId factor, std::string_view debug_name="dynamic_scale") constEmits DYNAMIC_SCALE: Y = X * S[0] with S in device memory.
Parameters
xThe tensor to scale.
factorA 1-element value holding the factor.
debug_nameDiagnostic label for the operation.
Returns
The scaled value id.
Exceptions
ErrorIf factor is not 1 element or dtypes mismatch.
ValueId exp(ValueId x) constEmits EXP: elementwise exp(X), out of place.
ValueId abs(ValueId x) constEmits ABS: elementwise |x|, out of place.
ValueId atan(ValueId x) constEmits ATAN: elementwise arctangent of x, out of place.
ValueId softplus(ValueId x) constEmits SOFTPLUS: elementwise log(1 + exp(x)), out of place.
ValueId zeros(Shape shape, DType dtype=DType::FLOAT32) constEmits ZERO: a fresh all-zero tensor with no operands.
Parameters
shapeThe tensor extents.
dtypeThe element data type.
Returns
The new value id.
ValueId zeros_like(ValueId like, Shape shape, DType dtype=DType::FLOAT32) constEmits ZERO adopting the layout of like.
Parameters
likeValue whose layout the zeros adopt.
shapeThe tensor extents.
dtypeThe element data type.
Returns
The new value id.
ValueId relu(ValueId x) constEmits RELU.
ValueId gelu(ValueId x) constEmits GELU (tanh approximation).
ValueId sigmoid(ValueId x) constEmits SIGMOID.
ValueId tanh(ValueId x) constEmits TANH.
ValueId silu(ValueId x) constEmits SILU: elementwise x * sigmoid(x).
ValueId leaky_relu(ValueId x, double slope) constEmits LEAKY_RELU with the given negative slope.
Parameters
xThe input tensor.
slopeThe negative-side slope; must lie in (0, 1).
Returns
The activated value id.
Exceptions
ErrorIf
slopeis outside (0, 1).
ValueId activation_backward(OpID op, ValueId dy, ValueId primal, const Attributes &attributes={}) constEmits an activation gradient operation.
Parameters
opThe activation backward OpID.
dyThe incoming gradient tensor.
primalThe forward input or forward output tensor.
attributesOptional attributes such as leaky ReLU slope.
Returns
The gradient value id.
ValueId log_softmax(ValueId x) constEmits LOG_SOFTMAX over the rows of an [N, C] matrix.
Parameters
xThe logits.
Returns
The [N, C] log-probabilities' id.
Exceptions
ErrorIf
xis not rank 2.
ValueId nll_loss(ValueId log_probs, ValueId one_hot) constEmits NLL_LOSS: the mean negative log-likelihood.
Parameters
log_probsAn [N, C] value, normally a
LOG_SOFTMAXresult.one_hotAn [N, C] one-hot target matrix.
Returns
A 1-element loss value's id.
Exceptions
ErrorIf the two operands disagree in shape or dtype.
ValueId accumulate(ValueId acc, ValueId delta) constEmits ACCUMULATE: acc_out = acc + delta into buffer of acc.
Parameters
accThe buffer accumulated into.
deltaThe contribution added.
Returns
The accumulated value id.
Exceptions
ErrorIf operands disagree in shape or dtype.
ValueId layout_convert(ValueId x, TensorLayout layout) constEmits LAYOUT_CONVERT to permute between NHWC and NCHW layouts.
Parameters
xThe rank-4 value to convert.
layoutThe target tensor layout.
Returns
The converted value id.
Exceptions
ErrorIf
xis not rank 4.
ValueId cast(ValueId x, DType dtype, std::string_view debug_name="cast") constEmits CAST: a copy of x converted to dtype.
Parameters
xThe value to convert.
dtypeThe target element type.
debug_nameDiagnostic label for the operation.
Returns
The converted value id.
Exceptions
ErrorIf either element type is not a real float.
void cast_into(ValueId source, ValueId destination) constEmits CAST writing directly into an existing value buffer.
Parameters
sourceThe value to read.
destinationThe value to write; must have no producer yet.
Exceptions
ErrorIf shapes disagree, non-float dtype, or destination exists.
ValueId like(ValueId like, std::string_view debug_name={}) constDeclares a value with the same shape, dtype and lifetime as like.
Parameters
likeThe value to copy the description from.
debug_nameA label for diagnostics; must outlive the graph.
Returns
The new value's id.
ValueId declare_like(ValueId like, Shape shape, DType dtype, Lifetime lifetime, std::string_view debug_name) constDeclares a value inheriting the layout of like.
Parameters
likeValue whose layout the result adopts.
shapeResult extents.
dtypeResult element type.
lifetimeStorage arena lifetime.
Returns
The new value id.
ValueId im2col(ValueId x, const ConvGeometry &g) constEmits IM2COL: expands convolution windows into matrix rows.
Parameters
xThe [N,H,W,C] input tensor.
gThe window geometry.
Returns
The column matrix value id.
Exceptions
ErrorIf
xis not rank 4 NHWC or window does not fit.
ValueId im2col_with_extents(ValueId x, const ConvGeometry &g, int64_t out_h, int64_t out_w) constEmits IM2COL with explicit output extents.
Parameters
xThe [N,H,W,C] input tensor.
gThe window geometry.
out_hNumber of window rows;
out_wNumber of window columns.
Returns
The column matrix value id.
ValueId col2im(ValueId cols, Shape image_shape, const ConvGeometry &g) constEmits COL2IM: the adjoint operation of IM2COL.
Parameters
colsThe column matrix.
image_shapeThe [N,H,W,C] image shape to reconstruct.
gThe window geometry used during production.
Returns
The image value id.
Exceptions
ErrorIf shapes, ranks, or implied dimensions mismatch.
ValueId col2im_with_extents(ValueId cols, Shape image_shape, const ConvGeometry &g, int64_t out_h, int64_t out_w) constEmits COL2IM with explicit window counts.
Parameters
colsThe column matrix.
image_shapeReconstructed [N,H,W,C] image shape.
gWindow geometry.
out_hWindow rows;
out_wWindow columns.
Returns
The reconstructed image value id.
ValueId conv2d(ValueId x, ValueId weight, ValueId bias, const ConvGeometry &g) constEmits a convolution as IM2COL and MATMUL, with symmetric padding assumed.
Parameters
xThe [N,H,W,C_in] input; must be NHWC.
weightThe [C_out,kernel_h,kernel_w,C_in] filters, matching
gandx.biasThe [C_out] bias, or NO_VALUE to add none.
gThe window geometry; a 1x1 unit-stride unpadded one emits no IM2COL.
Returns
The [N,out_h,out_w,C_out] value id.
PoolResult maxpool2d(ValueId x, const ConvGeometry &g) constEmits MAXPOOL2D, with symmetric padding assumed.
Parameters
xThe
[N,H,W,C] input.gThe window geometry.
Returns
The pooled value and its argmax indices.
Exceptions
ErrorIf
xis not rank 4, not NHWC, or the window does not fit.
PoolResult maxpool2d_with_extents(ValueId x, const ConvGeometry &g, int64_t out_h, int64_t out_w) constEmits MAXPOOL2D with explicit output extents.
Parameters
xThe [N,H,W,C] input tensor.
gThe window geometry.
out_hPooled height;
out_wPooled width.
Returns
The pooled value and argmax indices.
ValueId avgpool2d(ValueId x, const ConvGeometry &g) constEmits AVGPOOL2D.
Divides by the full window area.
Parameters
xThe
[N,H,W,C] input.gThe window geometry.
Returns
The pooled value's id.
Exceptions
ErrorIf
xis not rank 4, not NHWC, or the window does not fit.
ValueId upsample2d(ValueId x, int64_t scale_h, int64_t scale_w) constEmits UPSAMPLE2D using nearest-neighbour integer scaling.
Parameters
xThe [N,H,W,C] input tensor.
scale_hVertical replication factor; must be positive.
scale_wHorizontal replication factor; must be positive.
Returns
The upsampled value id.
Exceptions
ErrorIf
xis not rank 4 NHWC or scales are below 1.
ValueId spatial_mean(ValueId x) constEmits SPATIAL_MEAN: the mean of every [H,W] plane.
Parameters
xThe
[N,H,W,C] input.
Returns
The [N,C] result's id.
Exceptions
ErrorIf
xis not rank 4 or not NHWC.
ValueId maxpool2d_backward(ValueId dy, ValueId indices, Shape input_shape, const ConvGeometry &g) constEmits MAXPOOL2D_BACKWARD routing gradients through argmax indices.
Parameters
dyThe [N,H_o,W_o,C] output gradient.
indicesThe INT64 argmax indices tensor.
input_shapeThe [N,H,W,C] shape of the pooled input.
gThe window geometry.
Returns
The input gradient value id.
ValueId avgpool2d_backward(ValueId dy, Shape input_shape, const ConvGeometry &g) constEmits AVGPOOL2D_BACKWARD: spreads each gradient over its window.
Parameters
dyThe
[N,H_o,W_o,C] output gradient.input_shapeThe
[N,H,W,C] shape of the pooled input.gThe window geometry the forward used.
Returns
The [N,H,W,C] input gradient's id.
Exceptions
ErrorIf
dyis not rank 4 or not NHWC.
ValueId upsample2d_backward(ValueId dy, Shape input_shape, int64_t scale_h, int64_t scale_w) constEmits UPSAMPLE2D_BACKWARD summing replicas into source pixels.
Parameters
dyThe output gradient tensor.
input_shapeThe input tensor shape.
scale_hVertical factor;
scale_wHorizontal factor.
Returns
The input gradient value id.
ValueId spatial_mean_backward(ValueId dy, Shape input_shape) constEmits SPATIAL_MEAN_BACKWARD broadcasting by 1/(H*W).
Parameters
dyThe [N,C] output gradient.
input_shapeThe [N,H,W,C] shape averaged over.
Returns
The [N,H,W,C] input gradient value id.
Exceptions
ErrorIf
dyis not rank 2 or input_shape is not rank 4.
ValueId concat_channels(SushiRuntime::span< const ValueId > parts) constEmits CONCAT_CHANNELS: joins operands along the channel axis.
Parameters
partsThe
[N,H,W,C_i] operands, at least one, sharing N, H, W and dtype.
Returns
The [N,H,W,sum(C_i)] result's id.
Exceptions
ErrorIf
partsis empty, any operand is not rank 4 or not NHWC, or the operands disagree on N, H, W or dtype.
ValueId slice_channels(ValueId x, int64_t offset, int64_t count) constEmits SLICE_CHANNELS extracting a contiguous channel slice.
Parameters
xThe [N,H,W,C] input tensor.
offsetThe starting channel index.
countThe number of channels to extract.
Returns
The [N,H,W,count] sliced tensor id.
Exceptions
ErrorIf range exceeds channels or
xis not rank 4 NHWC.
ValueId channel_affine(ValueId x, ValueId gamma, ValueId beta) constEmits CHANNEL_AFFINE: per-channel Y = gamma * X + beta.
Parameters
xThe [N,H,W,C] input tensor.
gammaThe [C] per-channel scale parameter.
betaThe [C] per-channel shift parameter.
Returns
The [N,H,W,C] affine result id.
Exceptions
ErrorIf shapes or parameter dimensions mismatch.
ValueId sum_channels(ValueId x) constSums an [N,H,W,C] tensor down to [C] per-channel sums.
Parameters
xThe [N,H,W,C] input tensor.
Returns
The [C] per-channel sum value id.
Exceptions
ErrorIf
xis not rank 4 or not NHWC.
BatchNormResult batchnorm2d(ValueId x, ValueId gamma, ValueId beta, double epsilon) constEmits BATCHNORM2D normalising across N, H, and W dimensions.
Parameters
xThe [N,H,W,C] input tensor.
gammaThe [C] scale;
betaThe [C] shift.epsilonSmall constant added to variance; must be positive.
Returns
The normalised value and saved batch statistics.
BatchNormGrads batchnorm2d_backward(ValueId dy, ValueId x, ValueId gamma, ValueId saved_mean, ValueId saved_inv_std) constEmits BATCHNORM2D_BACKWARD producing dx, dgamma, and dbeta.
Parameters
dyOutput gradient;
xForward input tensor.gammaThe [C] scale parameter.
saved_meanThe [C] batch mean computed during forward.
saved_inv_stdThe [C] inverse standard deviation.
Returns
The input, scale, and shift gradient value ids.
ValueId reshape(ValueId x, Shape shape) constEmits RESHAPE: a view of x with different extents.
Parameters
xThe value reshaped.
shapeThe result's extents.
Returns
The reshaped value's id.
Exceptions
ErrorIf
shape'selement count differs fromx's.

