interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / docs / autodiff / M21_OMEGA_AUTODIFF.md

240 lines · 14899 bytes Raw Blame History Rendered
1# M21 OMEGA_AUTODIFF: reverse-mode tape, CPU tier
2
3Status 2026-10-01: **M21 NOT QUALIFIED.** The tape, its tests and its
4mutation sweep are written. Forge host run on commit c098a74 (before the
5rebase onto omega#178/#179 and before the gate fixes): `test-autodiff` PASS
6182 pass / 0 fail (log HIVE-M21-181152.log), mutation sweep 10/10 caught (log
7HIVE-M21-181157.log). Forge host run on commit 0f0938f (rebased, bit-exact layer, pure 1e-3 relative FD, 12 mutants): `test-autodiff` PASS 262 pass / 0 fail, plain and ASan/UBSan (log HIVE-M21-light-185710.log); mutation sweep PASS 12/12 caught (log HIVE-M21-light-185715.log). This doc-only commit changes no code, so the 0f0938f host receipt applies to its code. GB10 NOT_RUN. M20, which this layer sits on, is itself not
8qualified (GB10 parity NOT_RUN).
9
10Plan source: `aien-architecture/CURRENT_EXECUTION_PLAN.md`, section
11"E3. M21 OMEGA_AUTODIFF": "Omega forward graph -> differentiate -> Omega
12backward graph. The backward pass is ordinary Omega and uses the same
13Forge/AEGIS path." ROADMAP row M21: "Sovereign automatic differentiation
14generating gradient semantic graphs", PLANNED. Neither document states an
15M21 exit gate or a gradient tolerance. The owner approved the M21 gate
16(queen, 2026-10-01):
17
18> **M21 gate: gradients bit-exact against the same M20 operations, plus a
19> finite-difference check within 1e-3 relative error.**
20
21See "Gate conformance" below for how the current tests map onto it.
22
23## Scope
24
25A reverse-mode tape over the M20 OMEGA_TENSOR CPU tier
26(`src/tensor/omega_tensor.h`). Forward: each recorded op is one M20 call.
27Backward: walks the tape from the root down and builds every gradient with
28M20 calls (ADD, SUB, MUL, DIV, matmul, transpose, reshape, broadcast_to,
29reduce SUM), so the backward pass runs on the same E1 realization as the
30forward pass. One exception: MAX routing is a host-side data move (compare
31and copy, no arithmetic) in the caller's scratch buffer, because M20 has no
32mask-producing op (CR-3 below).
33
34Out of scope here: GB10 realization, gradients for the M20 transcendental
35unary ops (EXP2, LOG2, SIGMOID, TANH, added by omega#178; a later cut,
36pending LT-M20), slicing/concat/gather gradients, second derivatives, dispatch
37provenance records for forward/backward ops (open question for E5), and
38any edit of `src/tensor` or `src/train`.
39
40## Files
41
42| File | Role |
43|---|---|
44| `src/autodiff/omega_autodiff.h` | The meaning: ops, ownership, determinism rules, per-op error contract |
45| `src/autodiff/omega_autodiff.c` | Tape recording, reverse walk, tensor ownership and M22 flatten |
46| `src/autodiff/gradient_shape.om` | Unbroadcast reduction order, shape equality and restoration of a reduced axis on the caller’s stack |
47| `tests/test_omega_autodiff.c` | Contract, bit-exact replay, finite-difference, determinism, error-path and leak checks |
48| `tools/autodiff_mutations.sh` | Source mutation sweep (12 mutants) |
49| `mk/autodiff.mk` | `make test-autodiff`, `make test-autodiff-mutations` (alias `autodiff-mutants`) |
50
51## Determinism and resources
52
53- No global state, no heap allocation in `src/autodiff`. The caller passes
54 the node array (explicit capacity), an optional float scratch buffer
55 (needed only by MAX: `3 * elements(y)` floats, see
56 `omega_ad_scratch_need`) and the M20 context, whose slot capacity bounds
57 every tensor made.
58- Tape full: `OMEGA_AD_ERR_TAPE_FULL`, nothing recorded, nothing leaked.
59- Fixed order: nodes are walked in strictly decreasing index; per node, the
60 contribution to the first input is accumulated before the second; several
61 contributions to one node are added in that order with M20 ADD.
62- Every gradient is a dense row-major F32 tensor with exactly its node's
63 shape; a contribution of any other shape is refused (`OMEGA_AD_ERR_SHAPE`)
64 instead of being silently broadcast.
65
66## Ops, backward rules and error bounds
67
68g = incoming gradient, y = stored forward value, unb = sum back to the
69input's shape (extra leading axes by reduce SUM over axis 0, then every axis
70where the input has size 1 by reduce SUM with keepdims). u = 2^-24,
71gamma(k) = k u / (1 - k u). L(m) = max(1, ceil(log32 m)) E1 reduction levels,
725 tree steps each, so a declared-order sum of m terms has error at most
73gamma(5 L(m)) times the sum of absolute terms (E1 reduction contract; padding
74with -0.0 is exact). D(x) = sum of 5 L(m) over every reduction unb makes for
75input x (0 when x was not broadcast).
76
77Bounds are local: each gradient against exact real arithmetic on the float32
78values that are on the tape (stored forward values and the incoming g), in
79the normal range (no overflow, no subnormal intermediates).
80
81| Op | M20 forward | Backward (M20 calls) | Bound per gradient element |
82|---|---|---|---|
83| ADD | binary ADD | ga = unb(g), gb = unb(g) | gamma(D(x)) sum abs(g); exact when not broadcast |
84| SUB | binary SUB | ga = unb(g), gb = unb(g * -1) | same as ADD (negation is exact) |
85| MUL | binary MUL | ga = unb(g * b), gb = unb(g * a) | gamma(D(x)+1) sum abs(g * other) |
86| DIV | binary DIV | ga = unb(g / b); gb = unb(-(g * (y / b))) | a: gamma(D(a)+1) sum abs(g/b); b: gamma(D(b)+3) sum abs(g a / b^2) |
87| MAX | binary MAX | g routed: to a if b is NaN and a is not, or a > b; else to b | gamma(D(x)) sum abs(routed g); routing exact |
88| SQRT | unary SQRT | ga = g / (y + y) | gamma(2) abs(g / (2 sqrt a)); inf at a = 0 |
89| MATMUL [..,M,K]x[..,K,N] | matmul | gA = unb(g @ B^T), gB = unb(A^T @ g) | A: gamma(1 + 5 L(N) + D(A)) sum abs(g) abs(B); B: gamma(1 + 5 L(M) + D(B)) sum abs(A) abs(g) |
90| TRANSPOSE | transpose + contiguous | ga = g^T | exact |
91| BROADCAST | broadcast_to + contiguous | ga = unb(g) | gamma(D(a)) sum abs(g) |
92| SUM(axis) | reduce SUM | ga = broadcast_to(reshape(g)) | exact |
93| MEAN(axis) | reduce MEAN | ga = broadcast_to(reshape(g)) / n | gamma(1) abs(g / n), n <= 2^24 |
94| fan-out | | k contributions added in tape order | extra gamma(k-1) sum abs(contribution) |
95
96MAX tie rule: ties (including -0 vs +0) and a NaN `a` send g to `b`, so
97`relu(x) = MAX(x, 0)` has gradient 0 at x = 0.
98
99## M22 bridge (tg_sgd compatibility)
100
101`tg_sgd_step(st, sh, const float *grad, size_t n, lr, momentum, grad_ref)`
102takes one flat float32 gradient whose length equals the shadow's parameter
103count. `omega_ad_grads_flatten(tape, ids, n, out, count)` writes the
104gradients of the given parameter nodes back to back, each in logical
105row-major order, and refuses (writing nothing) unless the total equals
106`count`. Compatible as long as the caller lays the shadow's parameters out
107in the same node order. `src/train` is unchanged and still includes no
108tensor header (its purity rule). `grad_ref` is the caller's: a natural
109choice is a prefix of `omega_tensor_value_id` of the gradient tensors
110(`omega_ad_grad` gives the handle). NaN/Inf gradients are not refused by the
111tape or by `tg_sgd_step`; where to refuse them (tape end or the `tg_commit`
112validate callback) is an open decision.
113
114## Test design (M21 gate, approved 2026-10-01)
115
116Approved M21 gate (owner, via the queen, 2026-10-01): **"gradients bit-exact
117against the same M20 operations, plus a finite-difference check within 1e-3
118relative error"**. Layers 2 and 3 below are that gate; layers 1, 4 and 5 are
119extra.
120
121`tests/test_omega_autodiff.c`, 21 op cases (every op, with and without
122broadcasting, batched matmul) plus a composite graph:
123
1241. **Contract layer.** Each tape gradient against an exact reference written
125 in the test from the calculus (double precision, index arithmetic on
126 shapes only), within the bound in the table above.
1272. **Bit-exact layer (gate).** For every op case the test replays the
128 backward rule itself with direct M20 calls in the tape's order (for
129 example MUL: `binary MUL (g, b)`, then reduce SUM over the extra leading
130 axes and the size-1 axes of a, keepdims) and compares the tape's gradient
131 with it bit for bit (`memcmp`), for a and for b. MAX routing, a host data
132 move, is replayed with the routing rule written independently in the
133 test. In-process counterexample: a one-bit flip of the replay must make
134 `memcmp` differ.
1353. **Finite-difference layer (gate).** Central differences of the M20 CPU
136 forward pass, step h = 2^-6 (actual step taken from the rounded floats),
137 loss L = sum(y * R) in double. Pass if `|tape - fd| <= 1e-3 |fd|`
138 (`FD_RTOL`, `fd_ok`): pure relative, **no absolute term**. Near-zero
139 gradients are handled by choosing the test points, not by loosening:
140 the FD layer runs on its own data set (`gen_fd_data`, seed R in
141 [0.5, 1]; MUL and MATMUL operands in [0.5, 1], DIV numerator in [1, 2],
142 SQRT input in [1, 4]) where every gradient element is a sum of same-sign
143 terms of magnitude about 0.1 or more, or exactly zero (MAX routing, where
144 the perturbed forward is unchanged and fd is exactly 0 too). Every
145 element, near zero or not, is still covered by layers 1 and 2 on the
146 mixed-sign data. Inputs are kept away from kinks (MAX) and singular
147 points (DIV, SQRT). In-process counterexamples: the FD comparator accepts
148 the exact gradient on all 12 elements of a MUL case, rejects a sign flip,
149 and rejects a gradient 2e-3 too large on all 12.
1504. **Composite.** Linear layer + squared error, `mean_i sum_j (XW + b - Y)^2`,
151 with a reused node (fan-out): closed form `(2/N) X^T E` within 1e-5 on
152 mixed-sign data; FD (pure 1e-3 relative) on every parameter on a second
153 data set (`lin_data_fd`: X, W, b in [0.5, 1], Y in [-0.5, 0], so every
154 gradient is >= 1.25), with the FD loss computed in double from the tape's
155 float `d` values. X and Y have no gradient.
1565. **Determinism.** Two full runs in two M20 contexts: flat gradients
157 bit-identical (memcmp) and the loss value id identical.
1586. **Error paths.** Tape full (no state change, no leak), shape mismatch
159 (`[3,4]+[5]`, `[3,5]x[4,2]`, `[3,5]x[3,5]`, broadcast `[5]->[4]`, bad axis),
160 wrong seed shape, scalar seed on a non-scalar root, too little scratch,
161 second backward, recording after backward, unreached leaf, no-grad root,
162 F16 leaf, flatten count mismatch (buffer untouched), bad node ids, leak
163 check of the M20 context.
164
165Counterexamples in process: the contract comparator must reject a gradient
166off by 2^-20 relative and accept the exact one; the FD comparator as above;
167the bit-exact and determinism comparators must see a one-bit flip.
168
169Mutation sweep (`tools/autodiff_mutations.sh`), each must make the test
170fail (12 mutants): TAPE_WALK (skip the root), ACCUMULATE (replace instead of
171add), UNBROADCAST (skip size-1 axis sums), SUB_NEGATE, MUL_OPERAND,
172MATMUL_TRANSPOSE, SQRT_TWICE, MEAN_DIVISOR (n+1), MAX_ROUTE (reverse
173comparison), MAX_TIE (ties to a), DIV_B_SIGN (drop the minus on the DIV
174b-gradient) and DIV_FORMULA. DIV_FORMULA computes the DIV b-gradient as
175`-((g * y) / b)` instead of `-(g * (y / b))`: the same real number with the
176same number of roundings, so by construction it stays inside the contract
177bound gamma(D(b)+3) and the 1e-3 FD bound, and only the bit-exact layer is
178expected to catch it (UNVERIFIED until the forge runs the sweep).
179
180## Qualification checklist
181
182Two commits matter here. **c098a74** (before the rebase, before the fixes
183below) has a forge receipt. **The current commit** (rebased onto omega#178
184and #179, with the bit-exact layer, the pure relative FD check and 12
185mutants) has a forge host PASS receipt (0f0938f).
186
187| Item | c098a74 (forge receipt) | Current commit | Evidence |
188|---|---|---|---|
189| Reverse-mode tape over M20 CPU ops | WRITTEN | WRITTEN | `src/autodiff/` |
190| Contract layer | PASS | PASS (0f0938f) | `make test-autodiff` |
191| Bit-exact layer (gate) | not present | PASS (0f0938f) | `make test-autodiff` |
192| Finite differences, pure 1e-3 relative (gate) | not present (c098a74 used 5e-4 + 1e-3 \|fd\|) | PASS (0f0938f) | `make test-autodiff` |
193| Composite graph end to end | PASS | PASS (0f0938f) | `make test-autodiff` |
194| Determinism (bit-identical rerun) | PASS | PASS (0f0938f) | `make test-autodiff` |
195| Error paths and leak check | PASS | PASS (0f0938f) | `make test-autodiff` (plain and ASan/UBSan) |
196| Host test totals | PASS, 182 pass / 0 fail (log HIVE-M21-181152.log) | PASS, 262 pass / 0 fail (log HIVE-M21-light-185710.log) | forge |
197| Mutation sweep | PASS, 10/10 caught (log HIVE-M21-181157.log) | PASS, 12/12 caught (log HIVE-M21-light-185715.log) | `sh tools/autodiff_mutations.sh` |
198| CI wiring | MISSING | MISSING | no `autodiff` job in `host-suites-2.yml` yet |
199| GB10 | NOT_RUN | NOT_RUN | no GB10 realization of M20 yet |
200| Owner approval of the gate | | APPROVED | queen, 2026-10-01 (wording above) |
201| Reproducible receipt | MISSING_IMPLEMENTATION | MISSING_IMPLEMENTATION | no receipt writer for this gate yet; the forge receipt lines do not name the commit hash |
202
203**M21 verdict: NOT QUALIFIED.** Host PASS on 0f0938f; a GB10 chip receipt does not exist yet.
204
205## Gate conformance (approved wording vs current tests)
206
207- **FD within 1e-3 relative.** Met by construction in the current commit:
208 `fd_ok` is `|tape - fd| <= 1e-3 |fd|` with no absolute term (the 5e-4
209 floor of c098a74 is removed), on FD data sets chosen so no gradient
210 element is near zero. Host PASS on 0f0938f.
211- **Bit-exact against the same M20 operations.** Met by construction in the
212 current commit: layer 2 replays every op case's backward rule with direct
213 M20 calls and `memcmp`s it against the tape, for both inputs. The
214 composite graph is covered by the per-op replays plus the bit-identical
215 determinism check, not by its own whole-graph replay. Host PASS on 0f0938f.
216- Owed (inspector, recommended, not blocking): separate mutants for
217 TRANSPOSE backward, SUM expand axis, the unbroadcast leading-axis loop
218 and the capacity check; a forge receipt that records the commit hash.
219
220## Tensor API change requests (not made here; owner LT-M20)
221
222- **CR-1** PARTLY RESOLVED by omega#178 (1a470c2): `OmegaTensorUnaryOp` now
223 has `OMEGA_TU_EXP2`, `OMEGA_TU_LOG2`, `OMEGA_TU_SIGMOID`, `OMEGA_TU_TANH`
224 (E1 bounded contract, via the optional `transc` realization hook).
225 Still open: EXP, LOG, RSQRT, ERF, SIN, COS, GELU. Autodiff for the four
226 new ops is not in this cut (later cut, pending LT-M20).
227- **CR-2** Constant helpers (full / zeros / ones / neg). Convenience; the
228 tape builds constants with `omega_tensor_from_f32`.
229- **CR-3** A mask-producing op (compare returning 1.0 / 0.0, or
230 where(pred, x, y) with a separate predicate). Lets MAX/MIN/relu/abs and
231 reduce MAX/MIN backward stay inside M20 instead of the host routing step.
232- **CR-4** Scatter / pad / zero-embed, for slice, concat and gather
233 backward.
234- **CR-5** Multi-axis reduce or sum-to-shape, so unbroadcast is one call.
235
236## Open questions
237
2381. Whether forward/backward ops should write E5 tier (a) dispatch records.
2392. Where NaN/Inf gradients are refused before an optimizer commit.
2403. What "the same Forge/AEGIS path" (CEP E3) requires of a CPU-tier tape.