Graph & operators¶
The lazy Tensor graph and the operators it is built from. These are exposed at the top
level, so aneforge.graph.conv is reached as af.conv.
graph ¶
The aneforge compute graph: a lazy Tensor whose methods/operators record
structure (op + sources + attrs), plus the op constructors and the higher-level
neural-net helpers (conv, multi-head / cross attention, GEGLU). Nothing here
touches the device - compile (_compile.py) lowers the graph to one program.
Tensor ¶
A node in the compute graph.
Source code in aneforge/graph.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
inverse ¶
1 / x (elementwise reciprocal). eps is the MIL inverse epsilon
floor under the divide (0.0 = plain reciprocal).
scaled_tanh ¶
threshold ¶
thresholded_relu ¶
clamped_relu ¶
min(beta, x) for x >= 0 else min(beta, alpha * x) (a leaky relu6).
sigmoid_hard ¶
Hard sigmoid: min(max(alpha * x + beta, 0), 1).
linear_activation ¶
alpha * x + beta (scalar affine, fused as one op).
greater ¶
Elementwise x > o -> a BOOL tensor (use as the cond of af.select).
Comparison ops output bool, not a numeric value on their own.
Source code in aneforge/graph.py
prelu ¶
Per-channel PReLU: x if x>0 else alpha[c]*x. alpha: [C]; input rank>=3 [N,C,...].
Source code in aneforge/graph.py
reverse ¶
Reverse along axes (native reverse).
Source code in aneforge/graph.py
tile ¶
Repeat reps[i] times along each axis (native tile; factors of {2,3,4,8}).
Source code in aneforge/graph.py
reduce_log_sum_exp ¶
adds ¶
x + scalar as a fused scalar-add (additive sibling of x * scalar).
The only fused way to inject a scalar offset (e.g. a normalization eps);
+ requires two graph Tensors.
Source code in aneforge/graph.py
linear ¶
x @ W.T (+ bias). W is [out, in] (PyTorch convention).
Source code in aneforge/graph.py
squeeze ¶
Remove size-1 dims at axes (native squeeze). Each named axis must
have size 1.
Source code in aneforge/graph.py
expand_dims ¶
Insert size-1 dims at axes (native expand_dims), the inverse of
squeeze. Axes index into the OUTPUT rank.
Source code in aneforge/graph.py
flatten2d ¶
Collapse to 2-D about axis: dims [:axis] -> rows, [axis:] ->
cols (native flatten2d).
Source code in aneforge/graph.py
slice_by_size ¶
Static slice x[begin[i] : begin[i]+size[i]] per axis (native
slice_by_size). begin/size are per-axis lists matching the rank.
Source code in aneforge/graph.py
cumsum ¶
Cumulative sum along axis (last axis only). The ANE has no native
cumsum, but a last-axis cumsum is exactly x @ triu_ones -- a matmul with
a baked upper-triangular-ones weight, made exact by the wide accumulator.
A composition, not a native op (native cumsum is arch-gated). For other
axes, transpose the target axis to last first.
Source code in aneforge/graph.py
l1_norm ¶
log_sum ¶
sum_square ¶
l2_norm ¶
L2-normalize over axis: x / sqrt(sum(x**2, axis) + eps).
Runs as fused e5rt MIL (reduce_l2_norm over the axis, then real_div)
- no graph cut. The MIL l2_norm op normalises over all non-batch dims,
so we build the per-axis form explicitly.
Source code in aneforge/graph.py
argmax ¶
Index of the maximum along axis (keepdims). Runs as a native-ANE
GlobalArgMinMax sub-program (netplist bridge, like af.sdpa) - a graph cut.
2D inputs [C, W] only, over the last axis (axis=-1/1, Width) or axis 0 (Channel); indices are returned fp16-encoded (exact for index<2048).
Source code in aneforge/graph.py
rms_norm ¶
RMSNorm over the last dim. gamma: a [D] array for a fixed (baked)
scale, or a broadcastable parameter Tensor ([1, D]) for a TRAINABLE
scale (normalized with a unit-scale op, then scaled by the Tensor so its
gradient flows via the mul VJP).
Source code in aneforge/graph.py
layer_norm ¶
LayerNorm over the last dim (2D inputs [M, D]). gamma/beta: [D]
arrays for a fixed (baked) affine, or broadcastable parameter Tensors
([1, D]) for a TRAINABLE affine (normalized with a unit affine, then scaled
and shifted by the Tensors so their gradients flow via the mul/add VJPs).
Pass both as Tensors for the trainable form.
Source code in aneforge/graph.py
group_norm ¶
GroupNorm over [1,C,H,W]. gamma/beta: [C] arrays for a fixed
(baked) affine, or broadcastable parameter Tensors ([1, C, 1, 1]) for a
TRAINABLE affine (normalized with a unit affine, then scaled and shifted by
the Tensors). Pass both as Tensors for the trainable form.
Source code in aneforge/graph.py
upsample ¶
Nearest-neighbour upsample [N,C,H,W] -> [N,C,scaleH,scaleW].
input ¶
A graph input placeholder. Inputs are fed to the compiled Model in the order they were created.
dtype is the wire dtype of the input port: "fp16" (default, the ANE compute
type) or "uint8" (raw camera/decoded-video bytes, dequantised in-graph - see
af.image_input). A uint8 input only feeds an in-graph cast; not a compute
tensor on its own.
Source code in aneforge/graph.py
image_input ¶
A uint8 image input that is dequantised to fp16 ON the engine.
Feed raw 8-bit pixels (camera / decoded-video bytes) straight to the compiled
model - the uint8->fp16 conversion and the scale*x + bias normalisation run
as in-graph ANE ops, so the host skips the float-convert + repack. Returns a
normal fp16 Tensor for the rest of the graph.
scale/bias are scalars by default (the usual x/255 ImageNet-style
normalisation is scale=1/255). For per-channel normalisation on an NCHW image
pass length-C sequences; they broadcast as [1,C,1,1] constants. The dequant is
cast(uint8->fp16) -> mul(scale) -> add(bias); identity add/mul are dropped, so
the common scale=1/255, bias=0 case is a cast + one mul.
Source code in aneforge/graph.py
conv ¶
conv(x: Tensor, weight, stride: int = 1, pad: int = 0, dilation: int = 1, groups: int = 1, bias=None) -> Tensor
2D conv. x: [N,Cin,H,W]; weight: [Cout, Cin/groups, kH, kW]; bias: [Cout].
Source code in aneforge/graph.py
dynamic_conv ¶
dynamic_conv(x: Tensor, weight: Tensor, stride: int = 1, pad: int = 0, dilation: int = 1, groups: int = 1) -> Tensor
2D conv with a DYNAMIC (runtime-tensor) weight - the kernel is a graph value, not a
baked constant. Lowers to the ANE's native dynamic-kernel path (CreateDynamicKernel /
DynamicGOC), so the weight can be produced at runtime by an earlier op or fed as an input.
Enables hypernetworks / per-sample (per-image) kernels - a capability no other ANE frontend
exposes, since Apple's MIL/CoreML conv bakes the weight.
x: [1, Cin, H, W]; weight: a Tensor [Cout, Cin/groups, kH, kW]. Returns
[1, Cout, Hout, Wout].
BATCH MUST BE 1. The ANE dynamic-kernel path does not support a dynamic-weight conv
with batch >= 2, so it is rejected at build time. For batched convolution use af.conv
(constant weight) or the im2col-based trainable conv2d.
Source code in aneforge/graph.py
conv_transpose ¶
conv_transpose(x: Tensor, weight, stride: int = 1, pad: int = 0, dilation: int = 1, groups: int = 1, bias=None) -> Tensor
2D transposed conv (deconv) - upsampling conv for VAE/segmentation decoders.
x: [N,Cin,H,W]; weight: [Cin, Cout, kH, kW] (PyTorch ConvTranspose2d layout);
bias: [Cout].
Source code in aneforge/graph.py
batch_norm ¶
BatchNorm in inference mode over [1,C,H,W] (or [1,C,...]); per-channel
affine from precomputed running mean/var. gamma/beta/mean/var: [C].
Source code in aneforge/graph.py
maximum ¶
minimum ¶
concat ¶
Concatenate tensors along axis (e.g. UNet skip connections).
Source code in aneforge/graph.py
gather ¶
Gather slices along axis by STATIC (build-time) integer indices. The
ANE has no native gather, but for constant indices a gather is exact via
slice_by_size + concat (a composition, not a native op -- native gather
is arch-gated). Dynamic (data-dependent) indices are not reachable on the ANE.
Source code in aneforge/graph.py
stack ¶
Stack equal-shaped tensors along a NEW axis (native stack):
N x [shape] -> [..., N, ...] with N inserted at axis.
Source code in aneforge/graph.py
split ¶
Split x into num_splits equal parts along axis (native split).
Returns the list of output Tensors; the axis size must divide evenly.
Source code in aneforge/graph.py
select ¶
Elementwise cond ? a : b (native select). cond is a BOOL tensor
(e.g. from x.greater(y)); a/b are fp16 tensors.
Source code in aneforge/graph.py
instance_norm ¶
InstanceNorm over [N,C,H,W]: normalize each (N,C) slice over its spatial dims,
then a per-channel affine. gamma/beta: [C]. Native instance_norm op.
Source code in aneforge/graph.py
local_response_norm ¶
local_response_norm(x: Tensor, size: int = 5, alpha: float = 0.0001, beta: float = 0.75, k: float = 1.0) -> Tensor
Cross-channel LRN over [N,C,H,W] via the native MIL local_response_norm op
(fused, no graph cut - distinct from the netplist af.lrn bridge): each output
is x / (k + alpha/size * sum_{window} x**2) ** beta over a window of size
neighbouring channels. gamma-free; alpha/beta/k in natural units.
Source code in aneforge/graph.py
einsum_native ¶
Restricted batched contraction via the native MIL einsum op (distinct from
the general af.einsum decomposer: this is the single hardware einsum layer).
The only on-ANE-verified equation is 'nchw,nwhu->nchu' (a batched matmul over
the W/U dims sharing N,H): a=[N,C,H,W], b=[N,W,H,U] (streamed weight) ->
[N,C,H,U]. b is a weight array (streamed), not a graph Tensor.
Source code in aneforge/graph.py
space_to_depth ¶
Space-to-depth (TensorFlow space_to_depth / native MIL space_to_depth):
[N,C,H,W] -> [N, C*bs*bs, H/bs, W/bs]. Fused e5rt MIL (no cut).
Source code in aneforge/graph.py
depth_to_space ¶
Depth-to-space (TensorFlow depth_to_space / native MIL depth_to_space):
[N, C*bs*bs, H, W] -> [N, C, H*bs, W*bs] (inverse of space_to_depth).
Fused e5rt MIL (no cut).
Source code in aneforge/graph.py
crop ¶
Spatial crop of [N,C,H,W]: drop top/bottom rows and left/right
columns (native MIL crop). Fused e5rt MIL (no cut).
Source code in aneforge/graph.py
resize_nearest_neighbor ¶
Nearest-neighbour resize of [N,C,H,W] to (target_h, target_w) (native MIL
resize_nearest_neighbor, arbitrary target size). Fused e5rt MIL (no cut).
Source code in aneforge/graph.py
resize_bilinear ¶
Bilinear resize of [N,C,H,W] to an explicit (target_h, target_w) (native
MIL resize_bilinear). Half-pixel sampling by default (align_corners=False).
Fused e5rt MIL (no cut).
Source code in aneforge/graph.py
upsample_bilinear ¶
Bilinear upsample of [N,C,H,W] by an integer scale (native MIL
upsample_bilinear, scale-factor form). Half-pixel sampling by default.
Fused e5rt MIL (no cut).
Source code in aneforge/graph.py
affine ¶
2-D affine warp of [N,C,H,W] to (output_h, output_w) via the native MIL
affine op (AffineTransform hardware layer). transform is the [N,6]
(or [1,6], broadcast) affine matrix [a0,a1,a2, b0,b1,b2] in
normalized [-1,1] coordinates; bilinear sampling with zero padding. Fused MIL.
Source code in aneforge/graph.py
pixel_shuffle ¶
Depth-to-space upscale (PyTorch nn.PixelShuffle):
[N, C*r*r, H, W] -> [N, C, H*r, W*r]. Runs as fused e5rt MIL (no cut).
Source code in aneforge/graph.py
pixel_unshuffle ¶
Space-to-depth (PyTorch nn.PixelUnshuffle):
[N, C, H*r, W*r] -> [N, C*r*r, H, W]. Runs as fused e5rt MIL (no cut).
Source code in aneforge/graph.py
space_to_channel ¶
Space-to-depth on the ANE's native SpaceToChannel layer (TensorFlow
space_to_depth, block-major channels): [N,C,H*r,W*r] -> [N,C*r*r,H,W].
Same shape law as PixelUnshuffle but the TF channel ordering. Graph cut.
Source code in aneforge/graph.py
channel_to_space ¶
Depth-to-space on the ANE's native ChannelToSpace layer (TensorFlow
depth_to_space, block-major channels): [N,C*r*r,H,W] -> [N,C,H*r,W*r].
Same shape law as PixelShuffle but the TF channel ordering. Graph cut.
Source code in aneforge/graph.py
space_to_batch ¶
Move spatial blocks into the batch dim on the ANE's native SpaceToBatch
layer: [N,C,H,W] -> [N*bh*bw, C, H/bh, W/bw]. Output batch slice
(n*bh+i)*bw+j == x[n, :, i::bh, j::bw]. Graph cut.
The batch dim grows, so this can only be a leaf/output of the segmented plan or feed another netplist cut (segment outputs are threaded as host arrays); feeding it into a fused e5rt region changes the batch the region expects, which is fine since each region is compiled from its own input shapes.
Source code in aneforge/graph.py
batch_to_space ¶
Move batch blocks back into space on the ANE's native BatchToSpace layer
(inverse of space_to_batch): [N*bh*bw, C, H, W] -> [N, C, H*bh, W*bw].
Graph cut.
ARCH-GATED: the validator requires the input batch divisible by bh*bw
(string: "Input batch n is not divisible by factor x * factor y"); a
non-divisible batch fails compilation, so it is rejected here.
Source code in aneforge/graph.py
flatten ¶
Flatten on the ANE's native Flatten layer (NCHW): collapse to a 1-D
vector of prod(shape) elements. The bridge takes a [C,H,W] input, so this
requires a 3D graph tensor. Graph cut.
Source code in aneforge/graph.py
input_view ¶
Contiguous view x[offset:offset+size] along Width on the ANE's native
InputView layer. x is flattened to 1-D (length W); returns [size].
Graph cut.
Source code in aneforge/graph.py
dynamic_slice ¶
Runtime-parametric slice x[start:start+size] on the ANE's native
DynamicSlice layer (start bound through a netplist constant). Graph cut.
ARCH-NOTE: the only verified/accepted netplist variant of this layer on this
host fixes Width=4 and SliceSize=2, so this op requires a length-4 input and
size==2. The static-start API is general in spirit; only the hardware variant
is verified.
Source code in aneforge/graph.py
scaled_elementwise ¶
scale * (x OP z) on the ANE's native ScaledElementWise layer (a fused
binary-op + scalar-scale). op in {Add, Mult, Min, Max}; inputs are flattened
to equal-length 1-D Width vectors. Graph cut.
Two arch quirks of the native layer are guarded here (found by tests/gen_random):
Sub is rejected by ANECCompile, and Mult ignores scale on-silicon - reject
those configs rather than emit a wrong/uncompilable program.
Source code in aneforge/graph.py
topk ¶
Top-k values along the last axis of a 2D input [C, W], keyed per row.
Runs as a native-ANE TopK sub-program (netplist bridge, like af.sdpa) - a cut.
k in {3, 4} is ARCH-GATED on this hardware (ANECCompile fails) and rejected
here; the rest of k in [1, W] is supported.
Source code in aneforge/graph.py
sort ¶
Sort each row of a 2D input [C, W] along the last axis (Width). Runs as a native-ANE Sort sub-program (netplist bridge, like af.sdpa) - a cut.
With return_indices=True the argsort indices are returned instead of the
sorted values (fp16-encoded, exact for index < 2048). Output shape is [C, W].
Like the native TopK, the hardware Sort keys the order on one channel lane and permutes all channels by it; for a numpy-like per-row independent sort the bridge dispatches each row as its own 1-channel tile.
Source code in aneforge/graph.py
cross_product ¶
3-vector cross product cross(a, b) on the ANE's native CrossProduct
layer - a path Apple's MIL frontend rejects. Both inputs are length-3
(shape (3,) or any shape with 3 elements); returns shape (3,). Graph cut.
Source code in aneforge/graph.py
cross_correlation ¶
Valid (no-flip) cross-correlation of a single-channel map x [H, W] with
a template [Th, Tw] on the ANE's native CrossCorrelation layer:
y[i,j] = sum_{u,v} x[i+u, j+v] * template[u,v] over [(H-Th+1), (W-Tw+1)].
Graph cut. (True correlation - the template is not flipped.)
Source code in aneforge/graph.py
cost_volume ¶
L1 stereo/optical-flow matching cost on the ANE's native CostVolume layer.
aux is a length-Wa row, ref a length-Wr row with Wr >= Wa + R;
returns (R+1, Wa) where cost[d,x] = |aux[x] - ref[x+d]|. Graph cut.
Source code in aneforge/graph.py
fps ¶
Furthest-point sampling: greedily pick k maximally-far-apart points
(seeded at index 0) on the ANE's native FurthestPointSampling layer.
points is [N, 3]; returns the [k, 3] selected centroids. Graph cut.
NOTE: the DistanceMetric param is L2-only on this arch (the bridge always uses Euclidean distance regardless of the param), so this is L2 FPS.
Source code in aneforge/graph.py
radius_search ¶
L2 ball-query membership on the ANE's native RadiusSearch layer: for each
(point, centroid) pair, 1 iff the point is within radius of the centroid.
points is [N, 3], centroids is [Nc, 3]; returns an [N, Nc] 0/1
membership matrix (fp16-encoded). Graph cut.
Source code in aneforge/graph.py
minmax_norm ¶
Min-max normalize y = (x - min) / (max - min + eps) over dimension
on the ANE's native MinMaxNormalization layer. x is [1, C, H, W]; reduces
over "Width" or "Height" ("Channel" is arch-gated and rejected). Graph cut.
Source code in aneforge/graph.py
lrn ¶
Cross-channel local response normalization (classic AlexNet LRN) on the ANE's
native LocalResponseNormalization layer (Channel mode). x is [1, C, H, W];
graph cut.
Per-channel, per-pixel:
y[c] = x[c] / (k + alpha * sum_{j in window(c)} x[j]^2) ** beta
The window is a LOCAL channel window of size N = C (the bridge fixes the layer's
KernelChannel to the channel count), asymmetric-centered on c and CLIPPED at
the channel boundaries:
window(c) = [max(0, c-(N-1)//2) : min(C, c + N//2 + 1)].
So only the center channel sees all C channels; edge channels see a partial sum.
This is NOT a full-channel sum (the old docstring's sum_j x[j]^2 over all j
was wrong - see the corrected reference in tests/test_numerical.py and the RE in
the reverse-engineering corpus).
alpha/beta/k are the standard LRN coefficients in their natural units;
alpha is the TRUE effective alpha. The bridge encodes alpha as an fp16
bit-pattern and pre-multiplies by KernelChannel to cancel the layer's internal
divide-by-KernelChannel; callers do not see that.
ARCH-GATED: the layer compiles only for C <= 15 (KernelChannel = C; C >= 16 fails ANECCompile on this hardware), so larger channel counts are rejected here.
Source code in aneforge/graph.py
mha ¶
Multi-head self-attention on x [S, D]. Weights [out,in]; biases [D] or None.
Builds split-heads -> per-head SDPA -> concat -> output-proj from graph ops.
Source code in aneforge/graph.py
cross_attention ¶
cross_attention(x: Tensor, context: Tensor, Wq, Wk, Wv, Wo, n_heads: int, bq=None, bk=None, bv=None, bo=None) -> Tensor
Cross-attention: queries from x [S, D], keys/values from context
[T, Dctx]. Wq:[D,D]; Wk,Wv:[D,Dctx]; Wo:[D,D]. (SD UNet text conditioning.)
Source code in aneforge/graph.py
sdpa ¶
sdpa(q: Tensor, k: Tensor, v: Tensor, scale: float | None = None, is_causal: bool = False, attn_mask: 'Tensor | None' = None) -> Tensor
Scaled-dot-product attention. Uses the ANE's native fused-attention hardware
layer (ANECSDPALayerDesc) - a path Apple's user-space MIL compiler never emits
(it always decomposes SDPA) - for sequence lengths where it is numerically
reliable (S <= SDPA_NATIVE_MAX_SEQ); above that it emits the accurate fused
decomposition instead (the native layer returns garbage at large S). q/k/v:
[1, heads, seq, d_head], fp16. Returns the same shape. scale defaults to
1/sqrt(d_head).
Where the native layer is used this is a graph-cut boundary: the surrounding graph
runs as e5rt program(s) and this node runs as a separate native-SDPA ANE
sub-program (see _compile.compile). is_causal=True is NATIVE: the causal additive
mask rides the SDPA layer's optional 5th bottom (kept on the native bridge route -
the route optimizer does not decompose it, since the decomposition is unmasked).
Validated on M1: cos 1.0 vs softmax(QK^Tscale + causal)V, single + multi-head.
Requires S <= SDPA_NATIVE_MAX_SEQ (above that the op decomposes, which has no mask).
Source code in aneforge/graph.py
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 | |
geglu ¶
GEGLU FFN gate: split the [2*Dff, D] projection into value/gate halves (weight-split at build, no slice op), out = value * gelu(gate).