Training & autograd¶
Reverse-mode autograd over the graph, the Trainer loop (with the optimizer step on the
engine), and layer-streamed training for deep stacks.
autograd ¶
A tiny reverse-mode autograd over the aneforge graph: forward and backward
both run on the ANE. Trainable parameters are graph inputs (fed each step,
updated host-side, no recompile).
CEHandle ¶
A softmax-cross-entropy training objective: carries the logits and the one-hot target (a graph input). The gradient at the logits is the analytic fused form (softmax(logits) - target)/N, which is fp16-stable (no log). The loss VALUE + accuracy are computed host-side in fp32 by the Trainer.
Source code in aneforge/autograd.py
seed ¶
dL/dlogits * loss_scale = (softmax(logits) - target) * (loss_scale / n).
SGD ¶
Host fp32 SGD over the parameters' master values. Trainer applies loss
scaling (grads come in scaled; divide before the step).
Source code in aneforge/autograd.py
Adam ¶
Host fp32 Adam over the parameters' master values. Loss-scaled grads are
divided by loss_scale before the moment update; fp16 written back into the
fed param value (sibling to SGD).
Source code in aneforge/autograd.py
Trainer ¶
Compiles a forward program ONCE plus one backward program PER PARAMETER
(each emitting that param's gradient in its natural 2-D shape); step evals
the backward programs on the ANE and applies the optimizer (params update
host-side, fed back next eval - no recompile). One program per param avoids an
ANECCompile wall hit by reshaping a large weight grad into a wide row and
concatenating it with a differently-sized row (the math is unchanged).
Accepts either
- a scalar
lossTensor (regression): forward program outputs the loss scalar;loss()reads it; backward seeds from a ones-seed at the loss. - a
CEHandle(classification): forward program outputs the logits; backward seeds from the analytic on-ANE gradient(softmax(logits) - target) * (loss_scale / N)at the logits. Host-sideloss()(fp32 cross-entropy) andaccuracy(X, y_labels)(argmax) read the logits program.
optimizer="sgd"|"adam" selects the optimizer.
device_optimizer=True runs the OPTIMIZER STEP on the ANE: alongside the
per-param backward programs (-> grads), a per-param UPDATE program computes the
new state with ANE graph ops, so no training tensor-math runs on the host. The
host only computes the scalar lr_t, shuttles state/grads in-out (the deferred
host<->device round-trip), samples minibatch indices, and prints. The Adam
moments m/v are held host-side as fp16 arrays, fed each step and read back.
device_optimizer=False (default) keeps the host fp32 optimizer path
byte-for-byte unchanged (the regression guard + the 98% baseline).
Source code in aneforge/autograd.py
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 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 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 | |
set_dataset ¶
Provide the full dataset for mini-batch sampling. x_input/target_input
are the batch-B graph input placeholders the objective was built from.
Source code in aneforge/autograd.py
accuracy ¶
Argmax accuracy over X (any length) via the batch-B forward program, chunking X into B-row pieces (last padded then truncated).
Source code in aneforge/autograd.py
UnrolledTrainer ¶
Train with K Adam steps UNROLLED into ONE fused ANE program, so the whole
forward -> backward -> optimizer-update recurrence runs on the engine with NO
per-step host loop. Each step() runs K steps in a SINGLE dispatch: the host
feeds K minibatches plus the K per-step learning rates and shuttles the (params,
m, v) arrays in and out between K-step blocks. That shuttle is an array move, not
tensor math, and there's no per-step host<->device round-trip inside the block.
The bounded-K, fully-on-engine analogue of Trainer (whose step() dispatches
once per step). Enabled by the stop-gradient frontier in
backward/backward_from: threading one step's updated-weight tensors into the
next step's forward needs each step's gradient to treat the current weights as
leaves (plain SGD/Adam), not differentiate through the previous update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
list
|
trainable leaves ( |
required |
forward
|
callable
|
|
required |
kind
|
str
|
|
required |
x_inputs
|
list
|
list of K data input placeholders ( |
required |
t_inputs
|
list
|
list of K target input placeholders, one per step. |
required |
dataset
|
tuple
|
|
required |
resident
|
bool
|
if True (default) the optimizer state (params, m, v) stays
RESIDENT on-device across dispatches - each updated-state output is aliased
( |
True
|
Source code in aneforge/autograd.py
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 | |
step ¶
Run K training steps on the ANE in ONE dispatch. Resident: feed only the K minibatches + per-step lr; state stays on-device. Else: shuttle params/m/v.
Source code in aneforge/autograd.py
predict ¶
Run the trained weights forward on the ANE in B-sized chunks; returns the model output (logits for 'ce', prediction for 'mse').
Source code in aneforge/autograd.py
vjp ¶
parameter ¶
A trainable leaf: a graph input tagged trainable, holding an fp32 master value in attrs['value']. Used like any input; fed its current value each eval and updated by the optimizer.
Source code in aneforge/autograd.py
backward ¶
Reverse-mode grads of scalar loss wrt each Tensor in params. Returns
{param: grad_Tensor}. The seed dL/dloss = loss_scale (folded into the seed's
additive constant, avoiding a muls on the reduced loss output).
stop is the stop-gradient (detach) frontier: gradient reaches these tensors
but does not propagate past them. Defaults to params - a no-op when the
params are true graph leaves (the usual case), but it matters when an UNROLLED
training step threads one step's updated-weight TENSORS into the next step's
forward: there each step's gradient must treat the current weights as leaves
(plain SGD), not differentiate through the previous update (second-order).
Source code in aneforge/autograd.py
backward_from ¶
Reverse-mode from an explicit gradient grad_root at root (e.g. logits),
rather than from a scalar loss + ones-seed. stop is the stop-gradient frontier
(defaults to params); see backward - it matters for unrolled training.
Source code in aneforge/autograd.py
conv_param ¶
A trainable conv weight parameter. weight_init is [Cout, Cin, kH, kW]
(PyTorch conv layout); stored internally as the flat patch matrix
[CinkHkW, Cout] that conv2d consumes. The patch (row) order is
ci*(kH*kW) + (u*kW + v), matching the im2col built in conv2d.
Source code in aneforge/autograd.py
conv2d ¶
A trainable stride-1 2-D conv built from primitives so weight is a real
graph parameter (see conv_param). x is [N, Cin, H, W]; weight is a
conv_param (flat [CinkHkW, Cout], carrying conv_shape). Returns
[N, Cout, Hout, Wout]. stride must be 1 (strided slicing is unavailable);
pad >= 0 zero-pads H and W IN-GRAPH (a zero-border concat before the
im2col), so a 'same' conv stays inside one fused program and the padding
differentiates through the existing concat VJP. With pad=0 the behaviour is
byte-for-byte the previous implementation.
COMPILE SCALES WITH BATCH N: the im2col materialises [N, CinkHkW, HoutWout] tensors, so the compile* (tiling/partition) time grows with N - on M1/h13 a very large full batch (e.g. N~1000 over 28x28) can take minutes or hang the compiler (M5 compiles it fine). Train large datasets in MINI-BATCHES (a modest N, e.g. <=128, fed per step) rather than one full-batch graph.
Source code in aneforge/autograd.py
mse ¶
adam_step ¶
One Adam update as graph ops over lists params/m/v (grads keyed by
param), returning the new (params, m, v) TENSOR lists. Used to UNROLL K training
steps into one program: thread the returned lists into the next step's forward.
Propagates a conv_param weight's conv_shape onto the updated tensor so an
advanced conv weight still works as a conv2d weight in the next unrolled step.
Source code in aneforge/autograd.py
Layer-streamed training¶
streaming ¶
Layer-streamed (gradient-checkpointed) training for deep stacks of identical layers.
A monolithic compile fuses a model's whole forward, backward, and optimizer step into
ONE e5rt program, so compile time grows superlinearly with depth and caps how deep a
model can train. When the layers are structurally identical (a transformer stack, a deep
MLP), that cost is avoidable: the per-layer forward and backward each depend only on one
layer's shape, not the depth, so they compile ONCE and reuse for every layer.
CheckpointedStack does exactly that.
The backward is the standard gradient-checkpointing trick: store only each layer's INPUT
activation, not every intermediate, and recompute the layer's forward inside its backward
program. The reused backward program takes a layer's params, its checkpointed input, and
the upstream gradient, and returns the param gradients plus the gradient with respect to
the input (the upstream gradient for the layer below). The result is bit-identical to a
monolithic backward (verified), with total compile work independent of layer count.
This module compiles the repeated stack; the surrounding embedding and output stages are
ordinary compiled graphs the caller drives (each compiled once). The optimizer runs
host-side over the streamed gradients, like the default autograd.Trainer path.
CheckpointedStack ¶
A depth-independent compile for a stack of identical layers.
layer_fn(params, x) builds one layer: params is a list of graph Tensor
parameters and x is the input activation Tensor; it returns the output
activation Tensor (same shape as x). example_params is a list of numpy
arrays giving one layer's parameter shapes, and io_shape is the activation shape
that flows between layers.
Two programs are compiled: the per-layer forward and the per-layer backward (a multi-output program returning each param gradient and the input gradient). Both are reused for every layer, so compile cost does not grow with depth.
Source code in aneforge/streaming.py
forward ¶
Run the stack. layers_params is a list (per layer) of lists (per-layer
parameter numpy arrays). Returns (output, checkpoints) where checkpoints[i]
is the input activation to layer i (needed by backward).
Source code in aneforge/streaming.py
backward ¶
Backprop the stack. g_out is the gradient at the stack output. Returns
(param_grads, g_in): param_grads[i] is the list of gradients for layer
i's params, and g_in is the gradient at the stack input.