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
GitHub aien-dev/omega-mv#184 (code only)
Apply it
git checkout -b patch-aa8fa5934415c1df 0171bd4224d31b22333305c6f7e7bd1f9c6e327b curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/aa8fa5934415c1df.patch | git am
Provenance
github-import 1
aien-dev/omega-mv
184
e05d0a07d75869a0f897802e1bdf283094c2e534
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":184,"url":"https://github.com/aien-dev/omega-mv/pull/184","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:41Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/docs/autodiff/.crumb b/docs/autodiff/.crumb new file mode 100644 index 000000000..a982ae2a9 --- /dev/null +++ b/docs/autodiff/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "docs/autodiff", + "layer": "docs", + "purpose": "M21 OMEGA_AUTODIFF scope, op and error-contract table, status (not qualified)" +} diff --git a/docs/autodiff/M21_OMEGA_AUTODIFF.md b/docs/autodiff/M21_OMEGA_AUTODIFF.md new file mode 100644 index 000000000..79dc4383a --- /dev/null +++ b/docs/autodiff/M21_OMEGA_AUTODIFF.md @@ -0,0 +1,239 @@ +# M21 OMEGA_AUTODIFF: reverse-mode tape, CPU tier + +Status 2026-10-01: **M21 NOT QUALIFIED.** The tape, its tests and its +mutation sweep are written. Forge host run on commit c098a74 (before the +rebase onto omega#178/#179 and before the gate fixes): `test-autodiff` PASS +182 pass / 0 fail (log HIVE-M21-181152.log), mutation sweep 10/10 caught (log +HIVE-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 +qualified (GB10 parity NOT_RUN). + +Plan source: `aien-architecture/CURRENT_EXECUTION_PLAN.md`, section +"E3. M21 OMEGA_AUTODIFF": "Omega forward graph -> differentiate -> Omega +backward graph. The backward pass is ordinary Omega and uses the same +Forge/AEGIS path." ROADMAP row M21: "Sovereign automatic differentiation +generating gradient semantic graphs", PLANNED. Neither document states an +M21 exit gate or a gradient tolerance. The owner approved the M21 gate +(queen, 2026-10-01): + +> **M21 gate: gradients bit-exact against the same M20 operations, plus a +> finite-difference check within 1e-3 relative error.** + +See "Gate conformance" below for how the current tests map onto it. + +## Scope + +A reverse-mode tape over the M20 OMEGA_TENSOR CPU tier +(`src/tensor/omega_tensor.h`). Forward: each recorded op is one M20 call. +Backward: walks the tape from the root down and builds every gradient with +M20 calls (ADD, SUB, MUL, DIV, matmul, transpose, reshape, broadcast_to, +reduce SUM), so the backward pass runs on the same E1 realization as the +forward pass. One exception: MAX routing is a host-side data move (compare +and copy, no arithmetic) in the caller's scratch buffer, because M20 has no +mask-producing op (CR-3 below). + +Out of scope here: GB10 realization, gradients for the M20 transcendental +unary ops (EXP2, LOG2, SIGMOID, TANH, added by omega#178; a later cut, +pending LT-M20), slicing/concat/gather gradients, second derivatives, dispatch +provenance records for forward/backward ops (open question for E5), and +any edit of `src/tensor` or `src/train`. + +## Files + +| File | Role | +|---|---| +| `src/autodiff/omega_autodiff.h` | The meaning: ops, ownership, determinism rules, per-op error contract | +| `src/autodiff/omega_autodiff.c` | The tape: recording, backward walk, unbroadcast, M22 flatten. No heap allocation | +| `tests/test_omega_autodiff.c` | Contract, bit-exact replay, finite-difference, determinism, error-path and leak checks | +| `tools/autodiff_mutations.sh` | Source mutation sweep (12 mutants) | +| `mk/autodiff.mk` | `make test-autodiff`, `make test-autodiff-mutations` (alias `autodiff-mutants`) | + +## Determinism and resources + +- No global state, no heap allocation in `src/autodiff`. The caller passes + the node array (explicit capacity), an optional float scratch buffer + (needed only by MAX: `3 * elements(y)` floats, see + `omega_ad_scratch_need`) and the M20 context, whose slot capacity bounds + every tensor made. +- Tape full: `OMEGA_AD_ERR_TAPE_FULL`, nothing recorded, nothing leaked. +- Fixed order: nodes are walked in strictly decreasing index; per node, the + contribution to the first input is accumulated before the second; several + contributions to one node are added in that order with M20 ADD. +- Every gradient is a dense row-major F32 tensor with exactly its node's + shape; a contribution of any other shape is refused (`OMEGA_AD_ERR_SHAPE`) + instead of being silently broadcast. + +## Ops, backward rules and error bounds + +g = incoming gradient, y = stored forward value, unb = sum back to the +input's shape (extra leading axes by reduce SUM over axis 0, then every axis +where the input has size 1 by reduce SUM with keepdims). u = 2^-24, +gamma(k) = k u / (1 - k u). L(m) = max(1, ceil(log32 m)) E1 reduction levels, +5 tree steps each, so a declared-order sum of m terms has error at most +gamma(5 L(m)) times the sum of absolute terms (E1 reduction contract; padding +with -0.0 is exact). D(x) = sum of 5 L(m) over every reduction unb makes for +input x (0 when x was not broadcast). + +Bounds are local: each gradient against exact real arithmetic on the float32 +values that are on the tape (stored forward values and the incoming g), in +the normal range (no overflow, no subnormal intermediates). + +| Op | M20 forward | Backward (M20 calls) | Bound per gradient element | +|---|---|---|---| +| ADD | binary ADD | ga = unb(g), gb = unb(g) | gamma(D(x)) sum abs(g); exact when not broadcast | +| SUB | binary SUB | ga = unb(g), gb = unb(g * -1) | same as ADD (negation is exact) | +| MUL | binary MUL | ga = unb(g * b), gb = unb(g * a) | gamma(D(x)+1) sum abs(g * other) | +| 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) | +| 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 | +| SQRT | unary SQRT | ga = g / (y + y) | gamma(2) abs(g / (2 sqrt a)); inf at a = 0 | +| 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) | +| TRANSPOSE | transpose + contiguous | ga = g^T | exact | +| BROADCAST | broadcast_to + contiguous | ga = unb(g) | gamma(D(a)) sum abs(g) | +| SUM(axis) | reduce SUM | ga = broadcast_to(reshape(g)) | exact | +| MEAN(axis) | reduce MEAN | ga = broadcast_to(reshape(g)) / n | gamma(1) abs(g / n), n <= 2^24 | +| fan-out | | k contributions added in tape order | extra gamma(k-1) sum abs(contribution) | + +MAX tie rule: ties (including -0 vs +0) and a NaN `a` send g to `b`, so +`relu(x) = MAX(x, 0)` has gradient 0 at x = 0. + +## M22 bridge (tg_sgd compatibility) + +`tg_sgd_step(st, sh, const float *grad, size_t n, lr, momentum, grad_ref)` +takes one flat float32 gradient whose length equals the shadow's parameter +count. `omega_ad_grads_flatten(tape, ids, n, out, count)` writes the +gradients of the given parameter nodes back to back, each in logical +row-major order, and refuses (writing nothing) unless the total equals +`count`. Compatible as long as the caller lays the shadow's parameters out +in the same node order. `src/train` is unchanged and still includes no +tensor header (its purity rule). `grad_ref` is the caller's: a natural +choice is a prefix of `omega_tensor_value_id` of the gradient tensors +(`omega_ad_grad` gives the handle). NaN/Inf gradients are not refused by the +tape or by `tg_sgd_step`; where to refuse them (tape end or the `tg_commit` +validate callback) is an open decision. + +## Test design (M21 gate, approved 2026-10-01) + +Approved M21 gate (owner, via the queen, 2026-10-01): **"gradients bit-exact +against the same M20 operations, plus a finite-difference check within 1e-3 +relative error"**. Layers 2 and 3 below are that gate; layers 1, 4 and 5 are +extra. + +`tests/test_omega_autodiff.c`, 21 op cases (every op, with and without +broadcasting, batched matmul) plus a composite graph: + +1. **Contract layer.** Each tape gradient against an exact reference written + in the test from the calculus (double precision, index arithmetic on + shapes only), within the bound in the table above. +2. **Bit-exact layer (gate).** For every op case the test replays the + backward rule itself with direct M20 calls in the tape's order (for + example MUL: `binary MUL (g, b)`, then reduce SUM over the extra leading + axes and the size-1 axes of a, keepdims) and compares the tape's gradient + with it bit for bit (`memcmp`), for a and for b. MAX routing, a host data + move, is replayed with the routing rule written independently in the + test. In-process counterexample: a one-bit flip of the replay must make + `memcmp` differ. +3. **Finite-difference layer (gate).** Central differences of the M20 CPU + forward pass, step h = 2^-6 (actual step taken from the rounded floats), + loss L = sum(y * R) in double. Pass if `|tape - fd| <= 1e-3 |fd|` + (`FD_RTOL`, `fd_ok`): pure relative, **no absolute term**. Near-zero + gradients are handled by choosing the test points, not by loosening: + the FD layer runs on its own data set (`gen_fd_data`, seed R in + [0.5, 1]; MUL and MATMUL operands in [0.5, 1], DIV numerator in [1, 2], + SQRT input in [1, 4]) where every gradient element is a sum of same-sign + terms of magnitude about 0.1 or more, or exactly zero (MAX routing, where + the perturbed forward is unchanged and fd is exactly 0 too). Every + element, near zero or not, is still covered by layers 1 and 2 on the + mixed-sign data. Inputs are kept away from kinks (MAX) and singular + points (DIV, SQRT). In-process counterexamples: the FD comparator accepts + the exact gradient on all 12 elements of a MUL case, rejects a sign flip, + and rejects a gradient 2e-3 too large on all 12. +4. **Composite.** Linear layer + squared error, `mean_i sum_j (XW + b - Y)^2`, + with a reused node (fan-out): closed form `(2/N) X^T E` within 1e-5 on + mixed-sign data; FD (pure 1e-3 relative) on every parameter on a second + data set (`lin_data_fd`: X, W, b in [0.5, 1], Y in [-0.5, 0], so every + gradient is >= 1.25), with the FD loss computed in double from the tape's + float `d` values. X and Y have no gradient. +5. **Determinism.** Two full runs in two M20 contexts: flat gradients + bit-identical (memcmp) and the loss value id identical. +6. **Error paths.** Tape full (no state change, no leak), shape mismatch + (`[3,4]+[5]`, `[3,5]x[4,2]`, `[3,5]x[3,5]`, broadcast `[5]->[4]`, bad axis), + wrong seed shape, scalar seed on a non-scalar root, too little scratch, + second backward, recording after backward, unreached leaf, no-grad root, + F16 leaf, flatten count mismatch (buffer untouched), bad node ids, leak + check of the M20 context. + +Counterexamples in process: the contract comparator must reject a gradient +off by 2^-20 relative and accept the exact one; the FD comparator as above; +the bit-exact and determinism comparators must see a one-bit flip. + +Mutation sweep (`tools/autodiff_mutations.sh`), each must make the test +fail (12 mutants): TAPE_WALK (skip the root), ACCUMULATE (replace instead of +add), UNBROADCAST (skip size-1 axis sums), SUB_NEGATE, MUL_OPERAND, +MATMUL_TRANSPOSE, SQRT_TWICE, MEAN_DIVISOR (n+1), MAX_ROUTE (reverse +comparison), MAX_TIE (ties to a), DIV_B_SIGN (drop the minus on the DIV +b-gradient) and DIV_FORMULA. DIV_FORMULA computes the DIV b-gradient as +`-((g * y) / b)` instead of `-(g * (y / b))`: the same real number with the +same number of roundings, so by construction it stays inside the contract +bound gamma(D(b)+3) and the 1e-3 FD bound, and only the bit-exact layer is +expected to catch it (UNVERIFIED until the forge runs the sweep). + +## Qualification checklist + +Two commits matter here. **c098a74** (before the rebase, before the fixes +below) has a forge receipt. **The current commit** (rebased onto omega#178 +and #179, with the bit-exact layer, the pure relative FD check and 12 +mutants) has a forge host PASS receipt (0f0938f). + +| Item | c098a74 (forge receipt) | Current commit | Evidence | +|---|---|---|---| +| Reverse-mode tape over M20 CPU ops | WRITTEN | WRITTEN | `src/autodiff/` | +| Contract layer | PASS | PASS (0f0938f) | `make test-autodiff` | +| Bit-exact layer (gate) | not present | PASS (0f0938f) | `make test-autodiff` | +| Finite differences, pure 1e-3 relative (gate) | not present (c098a74 used 5e-4 + 1e-3 \|fd\|) | PASS (0f0938f) | `make test-autodiff` | +| Composite graph end to end | PASS | PASS (0f0938f) | `make test-autodiff` | +| Determinism (bit-identical rerun) | PASS | PASS (0f0938f) | `make test-autodiff` | +| Error paths and leak check | PASS | PASS (0f0938f) | `make test-autodiff` (plain and ASan/UBSan) | +| 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 | +| 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` | +| CI wiring | MISSING | MISSING | no `autodiff` job in `host-suites-2.yml` yet | +| GB10 | NOT_RUN | NOT_RUN | no GB10 realization of M20 yet | +| Owner approval of the gate | | APPROVED | queen, 2026-10-01 (wording above) | +| Reproducible receipt | MISSING_IMPLEMENTATION | MISSING_IMPLEMENTATION | no receipt writer for this gate yet; the forge receipt lines do not name the commit hash | + +**M21 verdict: NOT QUALIFIED.** Host PASS on 0f0938f; a GB10 chip receipt does not exist yet. + +## Gate conformance (approved wording vs current tests) + +- **FD within 1e-3 relative.** Met by construction in the current commit: + `fd_ok` is `|tape - fd| <= 1e-3 |fd|` with no absolute term (the 5e-4 + floor of c098a74 is removed), on FD data sets chosen so no gradient + element is near zero. Host PASS on 0f0938f. +- **Bit-exact against the same M20 operations.** Met by construction in the + current commit: layer 2 replays every op case's backward rule with direct + M20 calls and `memcmp`s it against the tape, for both inputs. The + composite graph is covered by the per-op replays plus the bit-identical + determinism check, not by its own whole-graph replay. Host PASS on 0f0938f. +- Owed (inspector, recommended, not blocking): separate mutants for + TRANSPOSE backward, SUM expand axis, the unbroadcast leading-axis loop + and the capacity check; a forge receipt that records the commit hash. + +## Tensor API change requests (not made here; owner LT-M20) + +- **CR-1** PARTLY RESOLVED by omega#178 (1a470c2): `OmegaTensorUnaryOp` now + has `OMEGA_TU_EXP2`, `OMEGA_TU_LOG2`, `OMEGA_TU_SIGMOID`, `OMEGA_TU_TANH` + (E1 bounded contract, via the optional `transc` realization hook). + Still open: EXP, LOG, RSQRT, ERF, SIN, COS, GELU. Autodiff for the four + new ops is not in this cut (later cut, pending LT-M20). +- **CR-2** Constant helpers (full / zeros / ones / neg). Convenience; the + tape builds constants with `omega_tensor_from_f32`. +- **CR-3** A mask-producing op (compare returning 1.0 / 0.0, or + where(pred, x, y) with a separate predicate). Lets MAX/MIN/relu/abs and + reduce MAX/MIN backward stay inside M20 instead of the host routing step. +- **CR-4** Scatter / pad / zero-embed, for slice, concat and gather + backward. +- **CR-5** Multi-axis reduce or sum-to-shape, so unbroadcast is one call. + +## Open questions + +1. Whether forward/backward ops should write E5 tier (a) dispatch records. +2. Where NaN/Inf gradients are refused before an optimizer commit. +3. What "the same Forge/AEGIS path" (CEP E3) requires of a CPU-tier tape. diff --git a/mk/autodiff.mk b/mk/autodiff.mk new file mode 100644 index 000000000..90d8c9969 --- /dev/null +++ b/mk/autodiff.mk @@ -0,0 +1,46 @@ +# M21 OMEGA_AUTODIFF (docs/autodiff/M21_OMEGA_AUTODIFF.md): reverse-mode tape +# over the M20 tensor CPU tier. Files under src/autodiff/ and +# tests/test_omega_autodiff.c. Picked up by `-include mk/*.mk`. Not part of +# `all` or `test`. CPU only: opens no device, never touches the GB10. +# +# test-autodiff CPU tests plain and with ASan/UBSan +# test-autodiff-mutations applies each MUT: source mutation of src/autodiff +# in a scratch copy and proves the test then fails +# autodiff-mutants alias of test-autodiff-mutations +# +# Own source lists (mk/tensor.mk is read after this file, so its variables +# are not set yet when these rules are parsed). +ifndef AUTODIFF_MK +AUTODIFF_MK := 1 +.PHONY: test-autodiff test-autodiff-mutations autodiff-mutants +AUTODIFF_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -Isrc/tensor \ + -Isrc/autodiff -DOMEGA_NUMERIC_CPU_ONLY +AUTODIFF_SRCS = src/autodiff/omega_autodiff.c +AUTODIFF_TENSOR_SRCS = src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c \ + src/tensor/omega_tensor_reduce_seam.c src/omega_numeric_reduce.c src/omega_numeric_transc.c +AUTODIFF_DEPS = src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ + src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/sha256.c +AUTODIFF_HDRS = src/autodiff/omega_autodiff.h src/tensor/omega_tensor.h src/tensor/omega_tensor_reduce_seam.h \ + src/omega_numeric_reduce.h src/omega_numeric.h src/sha256.h src/omega_numeric_transc.h + +$(OUT_DIR)/test_omega_autodiff: tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) \ + $(AUTODIFF_DEPS) $(AUTODIFF_HDRS) + @mkdir -p $(OUT_DIR) + gcc $(AUTODIFF_CFLAGS) -O2 -o $@ tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) \ + $(AUTODIFF_DEPS) + +$(OUT_DIR)/test_omega_autodiff_asan: tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) \ + $(AUTODIFF_DEPS) $(AUTODIFF_HDRS) + @mkdir -p $(OUT_DIR) + gcc $(AUTODIFF_CFLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ + -o $@ tests/test_omega_autodiff.c $(AUTODIFF_SRCS) $(AUTODIFF_TENSOR_SRCS) $(AUTODIFF_DEPS) + +test-autodiff: $(OUT_DIR)/test_omega_autodiff $(OUT_DIR)/test_omega_autodiff_asan + ./$(OUT_DIR)/test_omega_autodiff + ./$(OUT_DIR)/test_omega_autodiff_asan + +test-autodiff-mutations: + sh tools/autodiff_mutations.sh + +autodiff-mutants: test-autodiff-mutations +endif diff --git a/src/autodiff/.crumb b/src/autodiff/.crumb new file mode 100644 index 000000000..824046c8c --- /dev/null +++ b/src/autodiff/.crumb @@ -0,0 +1,11 @@ +{ + "schema_version": "1.0.0", + "name": "src/autodiff", + "layer": "src/autodiff", + "purpose": "M21 OMEGA_AUTODIFF: reverse-mode tape over M20 tensor CPU ops, caller-owned nodes and scratch, per-op error contract, flat float32 gradients for M22 (not qualified)", + "invariants": [ + "never edit src/tensor or src/train from here; tensor API needs are filed as change requests in docs/autodiff/M21_OMEGA_AUTODIFF.md", + "no heap allocation and no global state in src/autodiff", + "every MUT: marker must stay in tools/autodiff_mutations.sh" + ] +} diff --git a/src/autodiff/omega_autodiff.c b/src/autodiff/omega_autodiff.c new file mode 100644 index 000000000..85f90fee5 --- /dev/null +++ b/src/autodiff/omega_autodiff.c @@ -0,0 +1,582 @@ +/* + * M21 OMEGA_AUTODIFF, CPU tier: reverse-mode tape over M20 tensor ops. + * Meaning, determinism rules and the per-op error contract are stated in + * omega_autodiff.h and docs/autodiff/M21_OMEGA_AUTODIFF.md. + * + * Lines marked MUT:<NAME> are the targets of tools/autodiff_mutations.sh. + * No heap allocation here; no floating-point arithmetic except through M20 + * calls (the MAX routing step only compares and moves values). + */ +#include "omega_autodiff.h" + +#include <string.h> + +/* ---- small helpers ---------------------------------------------------------- */ + +static void rel(OmegaAdTape *t, OmegaTensor x) { + (void)omega_tensor_release(t->ctx, x); +} + +static bool node_ok(const OmegaAdTape *t, uint32_t id) { + return t && id < t->count; +} + +static int can_record(const OmegaAdTape *t) { + if (!t || !t->ctx || !t->nodes) return OMEGA_AD_ERR_BAD_ARGS; + if (t->backward_done || t->failed) return OMEGA_AD_ERR_STATE; + if (t->count >= t->capacity) return OMEGA_AD_ERR_TAPE_FULL; + return OMEGA_AD_OK; +} + +static uint32_t push(OmegaAdTape *t, OmegaAdOp op, uint32_t in0, uint32_t in1, uint32_t axis, + bool keepdims, bool requires_grad, bool owns, OmegaTensor value) { + OmegaAdNode *n = &t->nodes[t->count]; + memset(n, 0, sizeof(*n)); + n->op = op; + n->in0 = in0; + n->in1 = in1; + n->axis = axis; + n->keepdims = keepdims; + n->requires_grad = requires_grad; + n->owns_value = owns; + n->has_grad = false; + n->value = value; + return t->count++; +} + +static bool same_shape(const OmegaTensorInfo *x, const OmegaTensorInfo *y) { + if (x->rank != y->rank) return false; + for (uint32_t d = 0; d < x->rank; d++) + if (x->shape[d] != y->shape[d]) return false; + return true; +} + +/* Rank-0 F32 constant. */ +static int scalar(OmegaAdTape *t, float v, OmegaTensor *out) { + uint64_t dummy = 1; + return omega_tensor_from_f32(t->ctx, 0, &dummy, &v, out); +} + +/* out = x * k (x borrowed). With k = -1 this is an exact negation. */ +static int scale(OmegaAdTape *t, OmegaTensor x, float k, OmegaTensor *out) { + OmegaTensor c; + int rc = scalar(t, k, &c); + if (rc) return rc; + rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, x, c, out); + rel(t, c); + return rc; +} + +/* + * Sum a gradient (owned, consumed on every path) back to the shape of + * `target`: first the extra leading axes (reduce SUM over axis 0, one at a + * time), then every axis where target has size 1 and the gradient does not + * (reduce SUM with keepdims). Returns a dense owned tensor in *out. + */ +static int unbroadcast(OmegaAdTape *t, OmegaTensor full, const OmegaTensorInfo *target, OmegaTensor *out) { + OmegaTensor cur = full; + OmegaTensorInfo ci; + int rc = omega_tensor_info(t->ctx, cur, &ci); + if (rc) { rel(t, cur); return rc; } + if (ci.rank < target->rank) { rel(t, cur); return OMEGA_AD_ERR_SHAPE; } + while (ci.rank > target->rank) { + OmegaTensor nx; + rc = omega_tensor_reduce(t->ctx, OMEGA_TR_SUM, cur, 0, false, &nx); + rel(t, cur); + if (rc) return rc; + cur = nx; + rc = omega_tensor_info(t->ctx, cur, &ci); + if (rc) { rel(t, cur); return rc; } + } + for (uint32_t d = 0; d < target->rank; d++) { + if (target->shape[d] == 1 && ci.shape[d] != 1) { /* MUT:UNBROADCAST */ + OmegaTensor nx; + rc = omega_tensor_reduce(t->ctx, OMEGA_TR_SUM, cur, d, true, &nx); + rel(t, cur); + if (rc) return rc; + cur = nx; + rc = omega_tensor_info(t->ctx, cur, &ci); + if (rc) { rel(t, cur); return rc; } + } + } + *out = cur; + return OMEGA_AD_OK; +} + +/* Add an owned, already shape-matched contribution into node idx's grad. */ +static int accumulate(OmegaAdTape *t, uint32_t idx, OmegaTensor contrib) { + OmegaAdNode *n = &t->nodes[idx]; + OmegaTensorInfo vi, gi; + int rc = omega_tensor_info(t->ctx, n->value, &vi); + if (!rc) rc = omega_tensor_info(t->ctx, contrib, &gi); + if (rc) { rel(t, contrib); return rc; } + if (!same_shape(&vi, &gi)) { rel(t, contrib); return OMEGA_AD_ERR_SHAPE; } + if (!n->has_grad) { + n->grad = contrib; + n->has_grad = true; + return OMEGA_AD_OK; + } + OmegaTensor sum; + rc = omega_tensor_binary(t->ctx, OMEGA_TB_ADD, n->grad, contrib, &sum); /* MUT:ACCUMULATE */ + rel(t, contrib); + if (rc) return rc; + rel(t, n->grad); + n->grad = sum; + return OMEGA_AD_OK; +} + +/* Give node idx the contribution `full` (owned, consumed): unbroadcast to the + * node's shape, then accumulate. No-op (but still consumes) when the node + * does not require a gradient. */ +static int contribute(OmegaAdTape *t, uint32_t idx, OmegaTensor full) { + OmegaAdNode *n = &t->nodes[idx]; + if (!n->requires_grad) { rel(t, full); return OMEGA_AD_OK; } + OmegaTensorInfo vi; + int rc = omega_tensor_info(t->ctx, n->value, &vi); + if (rc) { rel(t, full); return rc; } + OmegaTensor u; + rc = unbroadcast(t, full, &vi, &u); + if (rc) return rc; + return accumulate(t, idx, u); +} + +static bool wants(const OmegaAdTape *t, uint32_t idx) { + return idx != OMEGA_AD_NONE && t->nodes[idx].requires_grad; +} + +/* MAX subgradient rule (header): true when g goes to a. */ +static bool max_routes_to_a(float a, float b) { + if (a != a) return false; + if (b != b) return true; + return a > b; /* MUT:MAX_ROUTE MUT:MAX_TIE */ +} + +/* ---- per-op backward ------------------------------------------------------------ */ + +static int backward_max(OmegaAdTape *t, const OmegaAdNode *n) { + OmegaTensorInfo yi; + int rc = omega_tensor_info(t->ctx, n->value, &yi); + if (rc) return rc; + size_t m = (size_t)yi.elements; + if (!t->scratch || t->scratch_count / 3 < m) return OMEGA_AD_ERR_SCRATCH; + float *sa = t->scratch, *sb = t->scratch + m, *sg = t->scratch + 2 * m; + const uint32_t ins[2] = { n->in0, n->in1 }; + float *dst[2] = { sa, sb }; + for (int k = 0; k < 2; k++) { + OmegaTensor v; + rc = omega_tensor_broadcast_to(t->ctx, t->nodes[ins[k]].value, yi.rank, yi.shape, &v); + if (rc) return rc; + rc = omega_tensor_read_f32(t->ctx, v, dst[k], m); + rel(t, v); + if (rc) return rc; + } + rc = omega_tensor_read_f32(t->ctx, n->grad, sg, m); + if (rc) return rc; + for (size_t i = 0; i < m; i++) { + bool to_a = max_routes_to_a(sa[i], sb[i]); + float g = sg[i]; + sa[i] = to_a ? g : 0.0f; + sb[i] = to_a ? 0.0f : g; + } + for (int k = 0; k < 2; k++) { + if (!wants(t, ins[k])) continue; + OmegaTensor full; + rc = omega_tensor_from_f32(t->ctx, yi.rank, yi.shape, dst[k], &full); + if (rc) return rc; + rc = contribute(t, ins[k], full); + if (rc) return rc; + } + return OMEGA_AD_OK; +} + +/* Gradient of a SUM/MEAN input: g put back on the reduced axis and broadcast + * to the input's shape (dense owned copy in *out). */ +static int expand_reduced(OmegaAdTape *t, const OmegaAdNode *n, OmegaTensor *out, uint64_t *axis_len) { + OmegaTensorInfo ai, gi; + int rc = omega_tensor_info(t->ctx, t->nodes[n->in0].value, &ai); + if (!rc) rc = omega_tensor_info(t->ctx, n->grad, &gi); + if (rc) return rc; + uint64_t kshape[OMEGA_TENSOR_MAX_RANK]; + for (uint32_t d = 0; d < ai.rank; d++) kshape[d] = (d == n->axis) ? 1 : ai.shape[d]; + OmegaTensor r, b; + rc = omega_tensor_reshape(t->ctx, n->grad, ai.rank, kshape, &r); + if (rc) return rc; + rc = omega_tensor_broadcast_to(t->ctx, r, ai.rank, ai.shape, &b); + if (rc) { rel(t, r); return rc; } + rc = omega_tensor_contiguous(t->ctx, b, out); + rel(t, b); + rel(t, r); + *axis_len = ai.shape[n->axis]; + return rc; +} + +static int node_backward(OmegaAdTape *t, const OmegaAdNode *n) { + const OmegaTensor g = n->grad; + OmegaTensor c = { 0, 0 }, c2 = { 0, 0 }, tmp = { 0, 0 }; + int rc = OMEGA_AD_OK; + switch (n->op) { + case OMEGA_AD_LEAF: + return OMEGA_AD_OK; + case OMEGA_AD_ADD: + case OMEGA_AD_SUB: + if (wants(t, n->in0)) { + rc = omega_tensor_contiguous(t->ctx, g, &c); + if (!rc) rc = contribute(t, n->in0, c); + if (rc) return rc; + } + if (wants(t, n->in1)) { + if (n->op == OMEGA_AD_ADD) rc = omega_tensor_contiguous(t->ctx, g, &c); + else rc = scale(t, g, -1.0f, &c); /* MUT:SUB_NEGATE */ + if (!rc) rc = contribute(t, n->in1, c); + } + return rc; + case OMEGA_AD_MUL: { + if (wants(t, n->in0)) { + rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, g, t->nodes[n->in1].value, &c); /* MUT:MUL_OPERAND */ + if (!rc) rc = contribute(t, n->in0, c); + if (rc) return rc; + } + if (wants(t, n->in1)) { + rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, g, t->nodes[n->in0].value, &c); + if (!rc) rc = contribute(t, n->in1, c); + } + return rc; + } + case OMEGA_AD_DIV: { + const OmegaAdNode *nb = &t->nodes[n->in1]; + if (wants(t, n->in0)) { + rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, g, nb->value, &c); + if (!rc) rc = contribute(t, n->in0, c); + if (rc) return rc; + } + if (wants(t, n->in1)) { + /* gb = -(g * (y / b)) */ + rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, n->value, nb->value, &tmp); /* MUT:DIV_FORMULA */ + if (rc) return rc; + rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, g, tmp, &c2); /* MUT:DIV_FORMULA */ + rel(t, tmp); + if (rc) return rc; + rc = scale(t, c2, -1.0f, &c); /* MUT:DIV_B_SIGN */ + rel(t, c2); + if (!rc) rc = contribute(t, n->in1, c); + } + return rc; + } + case OMEGA_AD_MAX: + return backward_max(t, n); + case OMEGA_AD_SQRT: + if (!wants(t, n->in0)) return OMEGA_AD_OK; + rc = omega_tensor_binary(t->ctx, OMEGA_TB_ADD, n->value, n->value, &tmp); /* MUT:SQRT_TWICE */ + if (rc) return rc; + rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, g, tmp, &c); + rel(t, tmp); + if (!rc) rc = contribute(t, n->in0, c); + return rc; + case OMEGA_AD_MATMUL: { + const OmegaAdNode *na = &t->nodes[n->in0], *nb = &t->nodes[n->in1]; + if (wants(t, n->in0)) { + /* gA = g @ B^T */ + rc = omega_tensor_transpose(t->ctx, nb->value, &tmp); + if (rc) return rc; + rc = omega_tensor_matmul(t->ctx, g, tmp, &c); /* MUT:MATMUL_TRANSPOSE */ + rel(t, tmp); + if (!rc) rc = contribute(t, n->in0, c); + if (rc) return rc; + } + if (wants(t, n->in1)) { + /* gB = A^T @ g */ + rc = omega_tensor_transpose(t->ctx, na->value, &tmp); + if (rc) return rc; + rc = omega_tensor_matmul(t->ctx, tmp, g, &c); + rel(t, tmp); + if (!rc) rc = contribute(t, n->in1, c); + } + return rc; + } + case OMEGA_AD_TRANSPOSE: + if (!wants(t, n->in0)) return OMEGA_AD_OK; + rc = omega_tensor_transpose(t->ctx, g, &tmp); + if (rc) return rc; + rc = omega_tensor_contiguous(t->ctx, tmp, &c); + rel(t, tmp); + if (!rc) rc = contribute(t, n->in0, c); + return rc; + case OMEGA_AD_BROADCAST: + if (!wants(t, n->in0)) return OMEGA_AD_OK; + rc = omega_tensor_contiguous(t->ctx, g, &c); + if (!rc) rc = contribute(t, n->in0, c); + return rc; + case OMEGA_AD_SUM: + case OMEGA_AD_MEAN: { + if (!wants(t, n->in0)) return OMEGA_AD_OK; + uint64_t len = 0; + rc = expand_reduced(t, n, &c2, &len); + if (rc) return rc; + if (n->op == OMEGA_AD_SUM) return contribute(t, n->in0, c2); + OmegaTensor nt; + rc = scalar(t, (float)len, &nt); /* MUT:MEAN_DIVISOR */ + if (rc) { rel(t, c2); return rc; } + rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, c2, nt, &c); + rel(t, nt); + rel(t, c2); + if (!rc) rc = contribute(t, n->in0, c); + return rc; + } + default: + return OMEGA_AD_ERR_BAD_ARGS; + } +} + +/* ---- public API ------------------------------------------------------------------ */ + +int omega_ad_tape_init(OmegaAdTape *t, OmegaTensorCtx *ctx, OmegaAdNode *nodes, uint32_t capacity, + float *scratch, size_t scratch_count) { + if (!t || !ctx || !nodes || capacity == 0 || capacity == OMEGA_AD_NONE || + (!scratch && scratch_count)) return OMEGA_AD_ERR_BAD_ARGS; + memset(t, 0, sizeof(*t)); + t->ctx = ctx; + t->nodes = nodes; + t->capacity = capacity; + t->scratch = scratch; + t->scratch_count = scratch_count; + return OMEGA_AD_OK; +} + +void omega_ad_tape_release(OmegaAdTape *t) { + if (!t || !t->nodes || !t->ctx) return; + for (uint32_t i = t->count; i-- > 0;) { + OmegaAdNode *n = &t->nodes[i]; + if (n->has_grad) rel(t, n->grad); + if (n->owns_value) rel(t, n->value); + n->has_grad = false; + n->owns_value = false; + } + t->count = 0; + t->backward_done = false; + t->failed = false; +} + +int omega_ad_leaf(OmegaAdTape *t, OmegaTensor value, bool requires_grad, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensorInfo vi; + rc = omega_tensor_info(t->ctx, value, &vi); + if (rc) return rc; + if (vi.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + *id = push(t, OMEGA_AD_LEAF, OMEGA_AD_NONE, OMEGA_AD_NONE, 0, false, requires_grad, false, value); + return OMEGA_AD_OK; +} + +static int record_op(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t b, uint32_t axis, + bool keepdims, OmegaTensor value, uint32_t *id) { + bool rg = t->nodes[a].requires_grad || (b != OMEGA_AD_NONE && t->nodes[b].requires_grad); + *id = push(t, op, a, b, axis, keepdims, rg, true, value); + return OMEGA_AD_OK; +} + +int omega_ad_binary(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t b, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id || !node_ok(t, a) || !node_ok(t, b)) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensorBinaryOp bop; + switch (op) { + case OMEGA_AD_ADD: bop = OMEGA_TB_ADD; break; + case OMEGA_AD_SUB: bop = OMEGA_TB_SUB; break; + case OMEGA_AD_MUL: bop = OMEGA_TB_MUL; break; + case OMEGA_AD_DIV: bop = OMEGA_TB_DIV; break; + case OMEGA_AD_MAX: bop = OMEGA_TB_MAX; break; + default: return OMEGA_AD_ERR_BAD_ARGS; + } + OmegaTensor y; + rc = omega_tensor_binary(t->ctx, bop, t->nodes[a].value, t->nodes[b].value, &y); + if (rc) return rc; + return record_op(t, op, a, b, 0, false, y, id); +} + +int omega_ad_sqrt(OmegaAdTape *t, uint32_t a, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensor y; + rc = omega_tensor_unary(t->ctx, OMEGA_TU_SQRT, t->nodes[a].value, &y); + if (rc) return rc; + return record_op(t, OMEGA_AD_SQRT, a, OMEGA_AD_NONE, 0, false, y, id); +} + +int omega_ad_matmul(OmegaAdTape *t, uint32_t a, uint32_t b, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id || !node_ok(t, a) || !node_ok(t, b)) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensor y; + rc = omega_tensor_matmul(t->ctx, t->nodes[a].value, t->nodes[b].value, &y); + if (rc) return rc; + return record_op(t, OMEGA_AD_MATMUL, a, b, 0, false, y, id); +} + +int omega_ad_transpose(OmegaAdTape *t, uint32_t a, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensor v, y; + rc = omega_tensor_transpose(t->ctx, t->nodes[a].value, &v); + if (rc) return rc; + rc = omega_tensor_contiguous(t->ctx, v, &y); + rel(t, v); + if (rc) return rc; + return record_op(t, OMEGA_AD_TRANSPOSE, a, OMEGA_AD_NONE, 0, false, y, id); +} + +int omega_ad_broadcast(OmegaAdTape *t, uint32_t a, uint32_t rank, const uint64_t *shape, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensor v, y; + rc = omega_tensor_broadcast_to(t->ctx, t->nodes[a].value, rank, shape, &v); + if (rc) return rc; + rc = omega_tensor_contiguous(t->ctx, v, &y); + rel(t, v); + if (rc) return rc; + return record_op(t, OMEGA_AD_BROADCAST, a, OMEGA_AD_NONE, 0, false, y, id); +} + +int omega_ad_reduce(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t axis, bool keepdims, uint32_t *id) { + int rc = can_record(t); + if (rc) return rc; + if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensorReduceOp rop; + if (op == OMEGA_AD_SUM) rop = OMEGA_TR_SUM; + else if (op == OMEGA_AD_MEAN) rop = OMEGA_TR_MEAN; + else return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensor y; + rc = omega_tensor_reduce(t->ctx, rop, t->nodes[a].value, axis, keepdims, &y); + if (rc) return rc; + return record_op(t, op, a, OMEGA_AD_NONE, axis, keepdims, y, id); +} + +int omega_ad_value(const OmegaAdTape *t, uint32_t id, OmegaTensor *out) { + if (!out || !node_ok(t, id)) return OMEGA_AD_ERR_BAD_ARGS; + *out = t->nodes[id].value; + return OMEGA_AD_OK; +} + +int omega_ad_scratch_need(const OmegaAdTape *t, size_t *floats) { + if (!t || !t->nodes || !floats) return OMEGA_AD_ERR_BAD_ARGS; + size_t need = 0; + for (uint32_t i = 0; i < t->count; i++) { + if (t->nodes[i].op != OMEGA_AD_MAX) continue; + OmegaTensorInfo yi; + int rc = omega_tensor_info(t->ctx, t->nodes[i].value, &yi); + if (rc) return rc; + if (yi.elements > SIZE_MAX / 3) return OMEGA_TENSOR_ERR_CAPACITY; + if ((size_t)yi.elements * 3 > need) need = (size_t)yi.elements * 3; + } + *floats = need; + return OMEGA_AD_OK; +} + +/* Runs the walk once the root's seed gradient is in place. */ +static int run_backward(OmegaAdTape *t, uint32_t root) { + for (uint32_t i = root + 1; i-- > 0;) { /* MUT:TAPE_WALK */ + const OmegaAdNode *n = &t->nodes[i]; + if (!n->has_grad || n->op == OMEGA_AD_LEAF) continue; + int rc = node_backward(t, n); + if (rc) return rc; + } + return OMEGA_AD_OK; +} + +static int begin_backward(OmegaAdTape *t, uint32_t root, OmegaTensorInfo *ri) { + if (!t || !t->ctx || !t->nodes) return OMEGA_AD_ERR_BAD_ARGS; + if (t->backward_done || t->failed) return OMEGA_AD_ERR_STATE; + if (!node_ok(t, root)) return OMEGA_AD_ERR_BAD_ARGS; + if (!t->nodes[root].requires_grad) return OMEGA_AD_ERR_NO_GRAD; + size_t need = 0; + int rc = omega_ad_scratch_need(t, &need); + if (rc) return rc; + if (need > t->scratch_count) return OMEGA_AD_ERR_SCRATCH; + return omega_tensor_info(t->ctx, t->nodes[root].value, ri); +} + +static int finish_backward(OmegaAdTape *t, uint32_t root, OmegaTensor seed_owned) { + OmegaAdNode *r = &t->nodes[root]; + r->grad = seed_owned; + r->has_grad = true; + t->backward_done = true; + int rc = run_backward(t, root); + if (rc) t->failed = true; + return rc; +} + +int omega_ad_backward(OmegaAdTape *t, uint32_t root) { + OmegaTensorInfo ri; + int rc = begin_backward(t, root, &ri); + if (rc) return rc; + if (ri.elements != 1) return OMEGA_AD_ERR_SHAPE; + const float one = 1.0f; + OmegaTensor seed; + rc = omega_tensor_from_f32(t->ctx, ri.rank, ri.shape, &one, &seed); + if (rc) return rc; + return finish_backward(t, root, seed); +} + +int omega_ad_backward_seed(OmegaAdTape *t, uint32_t root, OmegaTensor seed) { + OmegaTensorInfo ri, si; + int rc = begin_backward(t, root, &ri); + if (rc) return rc; + rc = omega_tensor_info(t->ctx, seed, &si); + if (rc) return rc; + if (si.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + if (!same_shape(&ri, &si)) return OMEGA_AD_ERR_SHAPE; + OmegaTensor s; + rc = omega_tensor_contiguous(t->ctx, seed, &s); + if (rc) return rc; + return finish_backward(t, root, s); +} + +int omega_ad_grad(const OmegaAdTape *t, uint32_t id, OmegaTensor *out) { + if (!out || !node_ok(t, id)) return OMEGA_AD_ERR_BAD_ARGS; + if (t->failed) return OMEGA_AD_ERR_STATE; + if (!t->nodes[id].has_grad) return OMEGA_AD_ERR_NO_GRAD; + *out = t->nodes[id].grad; + return OMEGA_AD_OK; +} + +int omega_ad_grad_read_f32(const OmegaAdTape *t, uint32_t id, float *out, size_t count) { + OmegaTensor g; + int rc = omega_ad_grad(t, id, &g); + if (rc) return rc; + if (!out) return OMEGA_AD_ERR_BAD_ARGS; + OmegaTensorInfo gi; + rc = omega_tensor_info(t->ctx, g, &gi); + if (rc) return rc; + if (gi.elements != count) return OMEGA_AD_ERR_COUNT; + return omega_tensor_read_f32(t->ctx, g, out, count); +} + +int omega_ad_grads_flatten(const OmegaAdTape *t, const uint32_t *ids, uint32_t n, float *out, + size_t count) { + if (!t || !ids || !out || n == 0) return OMEGA_AD_ERR_BAD_ARGS; + size_t total = 0; + for (uint32_t k = 0; k < n; k++) { + OmegaTensor g; + OmegaTensorInfo gi; + int rc = omega_ad_grad(t, ids[k], &g); + if (!rc) rc = omega_tensor_info(t->ctx, g, &gi); + if (rc) return rc; + if (gi.elements > count - total) return OMEGA_AD_ERR_COUNT; + total += (size_t)gi.elements; + } + if (total != count) return OMEGA_AD_ERR_COUNT; + size_t off = 0; + for (uint32_t k = 0; k < n; k++) { + OmegaTensor g; + OmegaTensorInfo gi; + int rc = omega_ad_grad(t, ids[k], &g); + if (!rc) rc = omega_tensor_info(t->ctx, g, &gi); + if (!rc) rc = omega_tensor_read_f32(t->ctx, g, out + off, (size_t)gi.elements); + if (rc) return rc; + off += (size_t)gi.elements; + } + return OMEGA_AD_OK; +} diff --git a/src/autodiff/omega_autodiff.h b/src/autodiff/omega_autodiff.h new file mode 100644 index 000000000..c2a686c41 --- /dev/null +++ b/src/autodiff/omega_autodiff.h @@ -0,0 +1,174 @@ +#ifndef OMEGA_AUTODIFF_H +#define OMEGA_AUTODIFF_H + +/* + * M21 OMEGA_AUTODIFF, CPU tier (docs/autodiff/M21_OMEGA_AUTODIFF.md). + * + * A reverse-mode tape over the M20 OMEGA_TENSOR ops that exist today + * (src/tensor/omega_tensor.h). Forward: every recorded op is one M20 call + * whose result is kept on the tape. Backward: walks the tape from the root + * down to node 0 and builds every gradient with M20 calls (binary ADD / SUB / + * MUL / DIV, matmul, transpose, reshape, broadcast_to, reduce SUM), so the + * backward pass runs on the same E1 realization as the forward pass. The one + * exception is the MAX routing step (see OMEGA_AD_MAX): it is a data move + * done on the host in the caller's scratch buffer, because M20 has no + * mask-producing op yet (tensor change request CR-3 in the doc). + * + * Determinism. No hidden global state, no heap allocation in this module: + * the caller provides the node array (explicit capacity), the scratch buffer + * and the M20 context (whose slot capacity bounds every tensor made here). + * Backward walks nodes in strictly decreasing index order; for each node the + * contribution to in0 is accumulated before the contribution to in1; several + * contributions to one node are added in that order with M20 ADD. Same tape, + * same inputs, same bits. + * + * Ownership. Leaf values belong to the caller and must stay live until + * omega_ad_tape_release. Every non-leaf value and every gradient is a dense + * row-major tensor owned by the tape and released by omega_ad_tape_release. + * Handles returned by omega_ad_value / omega_ad_grad are borrowed. + * + * Errors. A forward call that fails leaves the tape unchanged (no node, no + * leaked tensor). Errors of the M20 layer are passed through unchanged + * (OMEGA_TENSOR_ERR_*, -1..-11); the tape's own errors are OMEGA_AD_ERR_*. + * A backward call that fails marks the tape failed (OMEGA_AD_ERR_STATE on + * every later backward or grad call); release it and rebuild. + * + * Error contract (per op, "local"): every vector-Jacobian product below is + * compared with exact real arithmetic applied to the float32 values that are + * actually on the tape (stored forward values and the incoming gradient g). + * u = 2^-24, gamma(k) = k*u / (1 - k*u). L(m) = number of E1 reduction + * levels for m terms = max(1, ceil(log32 m)); one level is a 5-step + * pairwise lane tree, so a declared-order sum of m terms has error + * <= gamma(5*L(m)) * sum|terms| (E1 reduction contract, padding with -0.0 + * is exact). D(x) = sum of 5*L(m) over every reduction "unbroadcast" makes + * to bring a gradient back to x's shape (m > 1 only; D = 0 when x was not + * broadcast). Bounds hold when no intermediate overflows or goes subnormal. + * + * op gradient bound per element of grad x + * ADD ga = unb(g), gb = unb(g) gamma(D(x)) * sum|g| + * SUB ga = unb(g), gb = -unb(g) gamma(D(x)) * sum|g| + * MUL ga = unb(g*b), gb = unb(g*a) gamma(D(x)+1) * sum|g*other| + * DIV ga = unb(g/b) gamma(D(a)+1) * sum|g/b| + * gb = -unb(g*(y/b)), y = a/b gamma(D(b)+3) * sum|g*a/b^2| + * MAX routed g (see OMEGA_AD_MAX) gamma(D(x)) * sum|routed g| + * SQRT ga = g / (y + y), y = sqrt(a) gamma(2) * |g / (2 sqrt(a))| + * MATMUL gA = unb(g @ B^T) gamma(1 + 5*L(N) + D(A)) * sum|g||B| + * [..,M,K]x gB = unb(A^T @ g) gamma(1 + 5*L(M) + D(B)) * sum|A||g| + * [..,K,N] + * TRANSPOSE ga = g^T 0 (exact) + * BROADCAST ga = unb(g) gamma(D(a)) * sum|g| + * SUM(axis) ga = broadcast(g) 0 (exact) + * MEAN(axis) ga = broadcast(g) / n gamma(1) * |g / n| (n <= 2^24) + * fan-out k contributions added in order extra gamma(k-1) * sum|contrib| + * + * Not thread safe: one tape per thread, like the M20 context. + */ + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +#include "omega_tensor.h" + +#define OMEGA_AD_NONE UINT32_MAX + +typedef enum { + OMEGA_AD_OK = 0, + OMEGA_AD_ERR_BAD_ARGS = -101, /* NULL, unknown op, node id out of range */ + OMEGA_AD_ERR_TAPE_FULL = -102, /* count == capacity: nothing recorded */ + OMEGA_AD_ERR_SHAPE = -103, /* seed/root shape, gradient shape drift */ + OMEGA_AD_ERR_STATE = -104, /* backward already ran, or failed */ + OMEGA_AD_ERR_NO_GRAD = -105, /* node does not require / did not get one */ + OMEGA_AD_ERR_SCRATCH = -106, /* scratch smaller than omega_ad_scratch_need */ + OMEGA_AD_ERR_COUNT = -107 /* flatten: element count != buffer count */ +} OmegaAdStatus; + +typedef enum { + OMEGA_AD_LEAF = 0, + OMEGA_AD_ADD, /* M20 binary ADD, numpy broadcast */ + OMEGA_AD_SUB, /* M20 binary SUB */ + OMEGA_AD_MUL, /* M20 binary MUL */ + OMEGA_AD_DIV, /* M20 binary DIV (correctly rounded) */ + /* M20 binary MAX (FMNMX_MAX, NaN is missing data). Subgradient rule: + * g goes to a when b is NaN and a is not, or when a > b; otherwise to b + * (ties, including -0 vs +0, and a NaN go to b). relu(x) = MAX(x, 0) + * therefore has gradient 0 at x == 0. Needs 3 * elements(y) floats of + * caller scratch at backward time. */ + OMEGA_AD_MAX, + OMEGA_AD_SQRT, /* M20 unary SQRT (correctly rounded); grad at 0 = inf */ + OMEGA_AD_MATMUL, /* M20 matmul, rank >= 2, batched broadcast */ + OMEGA_AD_TRANSPOSE, /* swap last two axes; value is a dense copy */ + OMEGA_AD_BROADCAST, /* broadcast_to; value is a dense copy */ + OMEGA_AD_SUM, /* M20 reduce SUM along one axis */ + OMEGA_AD_MEAN, /* M20 reduce MEAN along one axis */ + OMEGA_AD_OP_COUNT +} OmegaAdOp; + +typedef struct { + OmegaAdOp op; + uint32_t in0, in1; /* node ids or OMEGA_AD_NONE */ + uint32_t axis; /* SUM / MEAN */ + bool keepdims; /* SUM / MEAN */ + bool requires_grad; /* leaf: caller's choice; op: any input's */ + bool owns_value; /* false only for leaves */ + bool has_grad; + OmegaTensor value; + OmegaTensor grad; /* valid when has_grad; dense, owned by tape */ +} OmegaAdNode; + +typedef struct { + OmegaTensorCtx *ctx; + OmegaAdNode *nodes; /* caller array of `capacity` nodes */ + uint32_t capacity; + uint32_t count; + float *scratch; /* caller buffer, may be NULL if no MAX node */ + size_t scratch_count; + bool backward_done; + bool failed; +} OmegaAdTape; + +/* capacity >= 1. scratch may be NULL with scratch_count 0. */ +int omega_ad_tape_init(OmegaAdTape *t, OmegaTensorCtx *ctx, OmegaAdNode *nodes, uint32_t capacity, + float *scratch, size_t scratch_count); +/* Releases every tensor the tape owns (values of op nodes, all gradients). + * Leaves' values stay with the caller. The tape is empty afterwards. */ +void omega_ad_tape_release(OmegaAdTape *t); + +/* ---- forward recording ----------------------------------------------------- */ +/* value must be a live F32 tensor; the tape borrows it. */ +int omega_ad_leaf(OmegaAdTape *t, OmegaTensor value, bool requires_grad, uint32_t *id); +/* op in OMEGA_AD_ADD .. OMEGA_AD_MAX. */ +int omega_ad_binary(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t b, uint32_t *id); +int omega_ad_sqrt(OmegaAdTape *t, uint32_t a, uint32_t *id); +int omega_ad_matmul(OmegaAdTape *t, uint32_t a, uint32_t b, uint32_t *id); +int omega_ad_transpose(OmegaAdTape *t, uint32_t a, uint32_t *id); +int omega_ad_broadcast(OmegaAdTape *t, uint32_t a, uint32_t rank, const uint64_t *shape, uint32_t *id); +/* op is OMEGA_AD_SUM or OMEGA_AD_MEAN. */ +int omega_ad_reduce(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t axis, bool keepdims, uint32_t *id); + +/* Borrowed handle of a node's forward value. */ +int omega_ad_value(const OmegaAdTape *t, uint32_t id, OmegaTensor *out); +/* Floats of scratch the backward pass of this tape needs (MAX nodes). */ +int omega_ad_scratch_need(const OmegaAdTape *t, size_t *floats); + +/* ---- backward ---------------------------------------------------------------- */ +/* Root must have exactly one element; seed gradient 1.0. Runs once per tape. */ +int omega_ad_backward(OmegaAdTape *t, uint32_t root); +/* Vector-Jacobian product: seed has exactly the root's shape (copied). */ +int omega_ad_backward_seed(OmegaAdTape *t, uint32_t root, OmegaTensor seed); + +/* Borrowed handle of a node's gradient (dense row-major, node's shape). */ +int omega_ad_grad(const OmegaAdTape *t, uint32_t id, OmegaTensor *out); +/* Copies one gradient out: count must equal the node's element count. */ +int omega_ad_grad_read_f32(const OmegaAdTape *t, uint32_t id, float *out, size_t count); +/* + * M22 bridge: writes the gradients of ids[0..n) back to back, each in + * logical row-major order, into one flat float32 buffer of exactly `count` + * elements. This is the layout tg_sgd_step (src/train/tg_sgd.h) consumes when + * the shadow's parameters are laid out in the same id order. Nothing is + * written unless the total element count equals `count`. + */ +int omega_ad_grads_flatten(const OmegaAdTape *t, const uint32_t *ids, uint32_t n, float *out, + size_t count); + +#endif /* OMEGA_AUTODIFF_H */ diff --git a/tests/test_omega_autodiff.c b/tests/test_omega_autodiff.c new file mode 100644 index 000000000..fab8a5aa4 --- /dev/null +++ b/tests/test_omega_autodiff.c @@ -0,0 +1,1030 @@ +/* + * M21 OMEGA_AUTODIFF CPU tests (docs/autodiff/M21_OMEGA_AUTODIFF.md). + * + * Four independent checks of every backward rule, all computed here: + * 1. Contract: the tape's gradient against an exact reference written in + * this file from the calculus (double precision, index arithmetic on + * shapes only), within the per-op bound of omega_autodiff.h. + * 2. Bit-exact (approved M21 gate): the backward rule replayed here by + * calling the same M20 tensor ops directly, in the tape's order; the + * tape's gradient must equal it bit for bit (memcmp). + * 3. Finite differences (approved M21 gate): central differences of the M20 + * CPU forward pass (the same tape ops, re-run on perturbed inputs), pure + * relative tolerance |tape - fd| <= FD_RTOL * |fd| with step FD_H, on a + * separate data set whose gradients are away from zero (or exactly zero). + * 4. Determinism: two full runs in two contexts give bit-identical + * gradients and the same loss value id. + * Plus the error paths (tape full, shape mismatch, seed shape, state, + * scratch, dtype, bad ids) and a leak check. Each check computes its own + * verdict; the in-process counterexamples prove the comparators can fail. + * No GPU, no device, no libm. + */ +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> + +#include "omega_numeric.h" +#include "omega_tensor.h" +#include "omega_autodiff.h" + +static int g_pass, g_fail; +#define CHECK(cond, ...) do { if (cond) g_pass++; else { g_fail++; \ + printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0) + +static OmegaTensorCtx *g; + +#define FD_H 0.015625 /* 2^-6 */ +/* Approved M21 gate (owner, 2026-10-01): "gradients bit-exact against the same + * M20 operations, plus a finite-difference check within 1e-3 relative error". + * FD_RTOL is that 1e-3 relative bound, applied with no absolute slack term + * (fd_ok below). Near-zero gradients are not compared against FD: the FD data + * sets (gen_fd_data, lin_data_fd) keep every gradient element either >= ~0.1 + * in magnitude or exactly zero, and every element, near zero or not, is + * covered by the bit-exact layer. Do not raise FD_RTOL or add an absolute term. */ +#define FD_RTOL 1e-3 +#define U32 5.9604644775390625e-08 /* 2^-24 */ +#define MAXE 128 + +/* ---- tiny helpers (no libm) ---------------------------------------------------- */ + +static double dabs(double x) { return x < 0 ? -x : x; } + +static double dsqrt(double a) { + if (a <= 0) return 0; + double y = a > 1 ? a : 1; + for (int i = 0; i < 200; i++) { + double ny = 0.5 * (y + a / y); + if (ny == y) break; + y = ny; + } + return y; +} + +/* Approved M21 FD gate: relative error <= 1e-3, no absolute term. */ +static bool fd_ok(double an, double fd) { return dabs(an - fd) <= FD_RTOL * dabs(fd); } + +static double gamma_k(int k) { return k * U32 / (1.0 - k * U32); } + +static int levels(uint64_t m) { + int L = 1; + uint64_t cap = 32; + while (cap < m) { cap *= 32; L++; } + return L; +} + +static uint32_t g_rng = 0x2545F491u; +static float urand(float lo, float hi) { + g_rng = g_rng * 1664525u + 1013904223u; + double r = (double)(g_rng >> 8) / 16777216.0; + return (float)(lo + (hi - lo) * r); +} + +static size_t numel(uint32_t rank, const uint64_t *s) { + size_t n = 1; + for (uint32_t d = 0; d < rank; d++) n *= (size_t)s[d]; + return n; +} + +static OmegaTensor mk(uint32_t rank, const uint64_t *shape, const float *data) { + OmegaTensor t = { 0, 0 }; + uint64_t dummy = 1; + int rc = omega_tensor_from_f32(g, rank, rank ? shape : &dummy, data, &t); + if (rc) printf("mk: rc %d\n", rc); + return t; +} + +static void unravel(size_t flat, uint32_t rank, const uint64_t *s, uint64_t *coord) { + for (uint32_t d = rank; d-- > 0;) { coord[d] = flat % s[d]; flat /= s[d]; } +} + +/* Flat index into an input of shape si for output coordinate (numpy rules). */ +static size_t bmap(const uint64_t *oc, uint32_t ro, uint32_t ri, const uint64_t *si) { + size_t idx = 0; + for (uint32_t d = 0; d < ri; d++) { + uint64_t c = si[d] == 1 ? 0 : oc[d + ro - ri]; + idx = idx * si[d] + c; + } + return idx; +} + +/* D(x): depth the unbroadcast reductions add (header definition). */ +static int unb_depth(uint32_t ro, const uint64_t *so, uint32_t ri, const uint64_t *si) { + int D = 0; + for (uint32_t d = 0; d < ro - ri; d++) if (so[d] > 1) D += 5 * levels(so[d]); + for (uint32_t d = 0; d < ri; d++) if (si[d] == 1 && so[d + ro - ri] > 1) D += 5 * levels(so[d + ro - ri]); + return D; +} + +/* Bound check: |an - ref| <= gamma(k) * abs + tiny slack for the double oracle. */ +static size_t bound_violations(const float *an, const double *ref, const double *abs_, const int *k, + size_t n, size_t *first) { + size_t bad = 0; + for (size_t i = 0; i < n; i++) { + double lim = gamma_k(k[i]) * abs_[i] + 1e-12 * abs_[i] + 1e-30; + if (!(dabs((double)an[i] - ref[i]) <= lim)) { if (!bad) *first = i; bad++; } + } + return bad; +} + +/* ---- op cases ---------------------------------------------------------------------- */ + +enum { DATA_UNIFORM = 0, DATA_AWAY_FROM_ZERO, DATA_OFFSET_FROM_B }; + +typedef struct { + const char *name; + OmegaAdOp op; + uint32_t ra; uint64_t sa[4]; + uint32_t rb; uint64_t sb[4]; /* rb 0 and op unary: no b */ + bool has_b; + uint32_t axis; bool keepdims; /* SUM / MEAN */ + uint32_t rt; uint64_t st[4]; /* BROADCAST target */ + float alo, ahi, blo, bhi; + int data; +} OpCase; + +static const OpCase CASES[] = { + { "add [3,4]+[4]", OMEGA_AD_ADD, 2, {3,4}, 1, {4}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "add [2,1,3]+[4,1]", OMEGA_AD_ADD, 3, {2,1,3}, 2, {4,1}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "add [3,4]+[3,4]", OMEGA_AD_ADD, 2, {3,4}, 2, {3,4}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "sub [3,4]-[3,1]", OMEGA_AD_SUB, 2, {3,4}, 2, {3,1}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "sub [3,4]-[3,4]", OMEGA_AD_SUB, 2, {3,4}, 2, {3,4}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "mul [3,4]*[1,4]", OMEGA_AD_MUL, 2, {3,4}, 2, {1,4}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "mul [2,3]*[1]", OMEGA_AD_MUL, 2, {2,3}, 1, {1}, true, 0, false, 0, {0}, -2, 2, -2, 2, DATA_UNIFORM }, + { "div [3,4]/[4]", OMEGA_AD_DIV, 2, {3,4}, 1, {4}, true, 0, false, 0, {0}, -2, 2, 1, 2, DATA_UNIFORM }, + { "div [3,4]/[3,4]", OMEGA_AD_DIV, 2, {3,4}, 2, {3,4}, true, 0, false, 0, {0}, -2, 2, 1, 2, DATA_UNIFORM }, + { "max relu [3,4] vs [1]", OMEGA_AD_MAX, 2, {3,4}, 1, {1}, true, 0, false, 0, {0}, -1, 1, 0, 0, DATA_AWAY_FROM_ZERO }, + { "max [3,4] vs [3,4]", OMEGA_AD_MAX, 2, {3,4}, 2, {3,4}, true, 0, false, 0, {0}, -1, 1, -1, 1, DATA_OFFSET_FROM_B }, + { "sqrt [3,4]", OMEGA_AD_SQRT, 2, {3,4}, 0, {0}, false, 0, false, 0, {0}, 1, 4, 0, 0, DATA_UNIFORM }, + { "matmul [3,5]x[5,4]", OMEGA_AD_MATMUL, 2, {3,5}, 2, {5,4}, true, 0, false, 0, {0}, -1, 1, -1, 1, DATA_UNIFORM }, + { "matmul [2,3,5]x[5,4]", OMEGA_AD_MATMUL, 3, {2,3,5}, 2, {5,4}, true, 0, false, 0, {0}, -1, 1, -1, 1, DATA_UNIFORM }, + { "transpose [3,4]", OMEGA_AD_TRANSPOSE, 2, {3,4}, 0, {0}, false, 0, false, 0, {0}, -2, 2, 0, 0, DATA_UNIFORM }, + { "broadcast [4]->[3,4]", OMEGA_AD_BROADCAST, 1, {4}, 0, {0}, false, 0, false, 2, {3,4}, -2, 2, 0, 0, DATA_UNIFORM }, + { "broadcast [3,1]->[2,3,4]", OMEGA_AD_BROADCAST, 2, {3,1}, 0, {0}, false, 0, false, 3, {2,3,4}, -2, 2, 0, 0, DATA_UNIFORM }, + { "sum [3,4] axis 1", OMEGA_AD_SUM, 2, {3,4}, 0, {0}, false, 1, false, 0, {0}, -2, 2, 0, 0, DATA_UNIFORM }, + { "sum [3,4] axis 0 keep", OMEGA_AD_SUM, 2, {3,4}, 0, {0}, false, 0, true, 0, {0}, -2, 2, 0, 0, DATA_UNIFORM }, + { "mean [3,4] axis 1", OMEGA_AD_MEAN, 2, {3,4}, 0, {0}, false, 1, false, 0, {0}, -2, 2, 0, 0, DATA_UNIFORM }, + { "mean [3,4] axis 0 keep", OMEGA_AD_MEAN, 2, {3,4}, 0, {0}, false, 0, true, 0, {0}, -2, 2, 0, 0, DATA_UNIFORM }, +}; +#define NCASES (sizeof(CASES) / sizeof(CASES[0])) + +/* Records the case's op on a fresh tape. Leaves a (and b) require grad. */ +static int build(const OpCase *c, OmegaAdTape *t, OmegaTensor ta, OmegaTensor tb, + uint32_t *ia, uint32_t *ib, uint32_t *iy) { + int rc = omega_ad_leaf(t, ta, true, ia); + if (rc) return rc; + *ib = OMEGA_AD_NONE; + if (c->has_b) { rc = omega_ad_leaf(t, tb, true, ib); if (rc) return rc; } + switch (c->op) { + case OMEGA_AD_ADD: case OMEGA_AD_SUB: case OMEGA_AD_MUL: case OMEGA_AD_DIV: case OMEGA_AD_MAX: + return omega_ad_binary(t, c->op, *ia, *ib, iy); + case OMEGA_AD_SQRT: return omega_ad_sqrt(t, *ia, iy); + case OMEGA_AD_MATMUL: return omega_ad_matmul(t, *ia, *ib, iy); + case OMEGA_AD_TRANSPOSE: return omega_ad_transpose(t, *ia, iy); + case OMEGA_AD_BROADCAST: return omega_ad_broadcast(t, *ia, c->rt, c->st, iy); + case OMEGA_AD_SUM: case OMEGA_AD_MEAN: return omega_ad_reduce(t, c->op, *ia, c->axis, c->keepdims, iy); + default: return OMEGA_AD_ERR_BAD_ARGS; + } +} + +/* Forward of the case on the M20 CPU tier; returns L = sum(y * R) in double. */ +static int forward_loss(const OpCase *c, const float *a, const float *b, const float *R, size_t ny, + double *L) { + OmegaAdNode nodes[4]; + OmegaAdTape t; + OmegaTensor ta = mk(c->ra, c->sa, a), tb = { 0, 0 }; + if (c->has_b) tb = mk(c->rb, c->sb, b); + int rc = omega_ad_tape_init(&t, g, nodes, 4, NULL, 0); + uint32_t ia = 0, ib = 0, iy = 0; + if (!rc) rc = build(c, &t, ta, tb, &ia, &ib, &iy); + float y[MAXE]; + OmegaTensor ty = { 0, 0 }; + if (!rc) rc = omega_ad_value(&t, iy, &ty); + if (!rc) rc = omega_tensor_read_f32(g, ty, y, ny); + if (!rc) { + double s = 0; + for (size_t i = 0; i < ny; i++) s += (double)y[i] * (double)R[i]; + *L = s; + } + omega_ad_tape_release(&t); + omega_tensor_release(g, ta); + if (c->has_b) omega_tensor_release(g, tb); + return rc; +} + +/* Exact reference gradients and bound terms for one case. */ +static void reference(const OpCase *c, const float *a, const float *b, const float *R, + uint32_t ry, const uint64_t *sy, + double *ra_, double *aa, int *ka, double *rb_, double *ab, int *kb) { + size_t na = numel(c->ra, c->sa), nb = c->has_b ? numel(c->rb, c->sb) : 0, ny = numel(ry, sy); + for (size_t i = 0; i < na; i++) { ra_[i] = 0; aa[i] = 0; ka[i] = 0; } + for (size_t i = 0; i < nb; i++) { rb_[i] = 0; ab[i] = 0; kb[i] = 0; } + uint64_t oc[8], ic[8]; + switch (c->op) { + case OMEGA_AD_ADD: case OMEGA_AD_SUB: case OMEGA_AD_MUL: case OMEGA_AD_DIV: case OMEGA_AD_MAX: + case OMEGA_AD_BROADCAST: { + int Da = unb_depth(ry, sy, c->ra, c->sa); + int Db = c->has_b ? unb_depth(ry, sy, c->rb, c->sb) : 0; + for (size_t j = 0; j < ny; j++) { + unravel(j, ry, sy, oc); + size_t xa = bmap(oc, ry, c->ra, c->sa); + size_t xb = c->has_b ? bmap(oc, ry, c->rb, c->sb) : 0; + double gv = R[j], av = a[xa], bv = c->has_b ? b[xb] : 0, ta = 0, tb = 0; + int ea = Da, eb = Db; + switch (c->op) { + case OMEGA_AD_ADD: ta = gv; tb = gv; break; + case OMEGA_AD_SUB: ta = gv; tb = -gv; break; + case OMEGA_AD_MUL: ta = gv * bv; tb = gv * av; ea += 1; eb += 1; break; + case OMEGA_AD_DIV: ta = gv / bv; tb = -gv * av / (bv * bv); ea += 1; eb += 3; break; + case OMEGA_AD_MAX: { + bool to_a = av == av && (bv != bv || av > bv); + ta = to_a ? gv : 0; tb = to_a ? 0 : gv; + break; + } + default: ta = gv; break; /* BROADCAST */ + } + ra_[xa] += ta; aa[xa] += dabs(ta); ka[xa] = ea; + if (c->has_b) { rb_[xb] += tb; ab[xb] += dabs(tb); kb[xb] = eb; } + } + break; + } + case OMEGA_AD_SQRT: + for (size_t i = 0; i < na; i++) { + ra_[i] = (double)R[i] / (2.0 * dsqrt(a[i])); + aa[i] = dabs(ra_[i]); + ka[i] = 2; + } + break; + case OMEGA_AD_MATMUL: { + /* a: [Bt,M,K] (Bt = 1 for rank 2), b: [K,N] */ + size_t Bt = c->ra == 3 ? c->sa[0] : 1, M = c->sa[c->ra - 2], K = c->sa[c->ra - 1], N = c->sb[1]; + int kA = 1 + 5 * levels(N), kB = 1 + 5 * levels(M) + (Bt > 1 ? 5 * levels(Bt) : 0); + for (size_t q = 0; q < Bt; q++) + for (size_t i = 0; i < M; i++) + for (size_t k = 0; k < K; k++) { + double s = 0, sa = 0; + for (size_t j = 0; j < N; j++) { + double p = (double)R[(q * M + i) * N + j] * b[k * N + j]; + s += p; sa += dabs(p); + } + size_t x = (q * M + i) * K + k; + ra_[x] = s; aa[x] = sa; ka[x] = kA; + } + for (size_t k = 0; k < K; k++) + for (size_t j = 0; j < N; j++) { + double s = 0, sa = 0; + for (size_t q = 0; q < Bt; q++) + for (size_t i = 0; i < M; i++) { + double p = (double)a[(q * M + i) * K + k] * R[(q * M + i) * N + j]; + s += p; sa += dabs(p); + } + rb_[k * N + j] = s; ab[k * N + j] = sa; kb[k * N + j] = kB; + } + break; + } + case OMEGA_AD_TRANSPOSE: { + size_t M = c->sa[0], N = c->sa[1]; + for (size_t i = 0; i < M; i++) + for (size_t j = 0; j < N; j++) { + ra_[i * N + j] = R[j * M + i]; + aa[i * N + j] = dabs(R[j * M + i]); + } + break; + } + case OMEGA_AD_SUM: case OMEGA_AD_MEAN: { + double n = (double)c->sa[c->axis]; + for (size_t i = 0; i < na; i++) { + unravel(i, c->ra, c->sa, ic); + size_t j = 0; + for (uint32_t d = 0; d < c->ra; d++) { + if (d == c->axis) continue; /* keepdims: size-1 axis adds nothing */ + j = j * c->sa[d] + ic[d]; + } + ra_[i] = c->op == OMEGA_AD_SUM ? (double)R[j] : (double)R[j] / n; + aa[i] = dabs(ra_[i]); + ka[i] = c->op == OMEGA_AD_SUM ? 0 : 1; + } + break; + } + default: break; + } +} + +static void gen_data(const OpCase *c, float *a, float *b) { + size_t na = numel(c->ra, c->sa), nb = c->has_b ? numel(c->rb, c->sb) : 0; + for (size_t i = 0; i < nb; i++) b[i] = urand(c->blo, c->bhi); + for (size_t i = 0; i < na; i++) { + switch (c->data) { + case DATA_AWAY_FROM_ZERO: { + float m = urand(0.1f, 1.0f); + a[i] = (urand(0, 1) < 0.5f) ? -m : m; + break; + } + case DATA_OFFSET_FROM_B: { + float m = urand(0.1f, 0.6f); + a[i] = b[i] + ((urand(0, 1) < 0.5f) ? -m : m); + break; + } + default: a[i] = urand(c->alo, c->ahi); + } + } +} + +/* + * FD data set. With the FD seed R in [0.5, 1], every gradient element is a + * sum of same-sign terms of magnitude >= ~0.1, or exactly zero (MAX routing, + * where the perturbed forward is unchanged and fd is exactly 0 too), so the + * pure relative bound compares meaningful values. ADD/SUB/BROADCAST/SUM/MEAN/ + * TRANSPOSE/MAX gradients depend only on R; SQRT keeps a in [1, 4]; MUL, + * DIV and MATMUL get positive operands here. + */ +#define FD_RLO 0.5f +#define FD_RHI 1.0f +static void gen_fd_data(const OpCase *c, float *a, float *b) { + size_t na = numel(c->ra, c->sa), nb = c->has_b ? numel(c->rb, c->sb) : 0; + gen_data(c, a, b); + switch (c->op) { + case OMEGA_AD_MUL: case OMEGA_AD_MATMUL: + for (size_t i = 0; i < na; i++) a[i] = urand(0.5f, 1.0f); + for (size_t i = 0; i < nb; i++) b[i] = urand(0.5f, 1.0f); + break; + case OMEGA_AD_DIV: /* b stays in [1, 2] */ + for (size_t i = 0; i < na; i++) a[i] = urand(1.0f, 2.0f); + break; + default: break; + } +} + +/* Records the case on a fresh tape, seeds backward with R drawn from + * [rlo, rhi] (y's shape, written to R), reads the gradients of a (and b). */ +static int tape_grads(const OpCase *c, const float *a, const float *b, float rlo, float rhi, + float *R, size_t *ny, float *ga, float *gb) { + OmegaAdNode nodes[4]; + OmegaAdTape t; + float scratch[3 * MAXE]; + size_t na = numel(c->ra, c->sa), nb = c->has_b ? numel(c->rb, c->sb) : 0; + memset(&t, 0, sizeof(t)); + OmegaTensor ta = mk(c->ra, c->sa, a), tb = { 0, 0 }, ty = { 0, 0 }, tr = { 0, 0 }; + if (c->has_b) tb = mk(c->rb, c->sb, b); + OmegaTensorInfo yi; + memset(&yi, 0, sizeof(yi)); + uint32_t ia = 0, ib = 0, iy = 0; + int rc = omega_ad_tape_init(&t, g, nodes, 4, scratch, 3 * MAXE); + if (!rc) rc = build(c, &t, ta, tb, &ia, &ib, &iy); + if (!rc) rc = omega_ad_value(&t, iy, &ty); + if (!rc) rc = omega_tensor_info(g, ty, &yi); + if (!rc) { + *ny = (size_t)yi.elements; + for (size_t i = 0; i < *ny; i++) R[i] = urand(rlo, rhi); + tr = mk(yi.rank, yi.shape, R); + rc = omega_ad_backward_seed(&t, iy, tr); + omega_tensor_release(g, tr); + } + if (!rc) rc = omega_ad_grad_read_f32(&t, ia, ga, na); + if (!rc && c->has_b) rc = omega_ad_grad_read_f32(&t, ib, gb, nb); + omega_ad_tape_release(&t); + omega_tensor_release(g, ta); + if (c->has_b) omega_tensor_release(g, tb); + return rc; +} + +/* ---- bit-exact layer: each backward rule replayed with direct M20 calls ----------- */ + +static int rp_scalar(float v, OmegaTensor *out) { + uint64_t dummy = 1; + return omega_tensor_from_f32(g, 0, &dummy, &v, out); +} + +/* Reads x into out and releases x. */ +static int rp_take(OmegaTensor x, float *out, size_t n) { + int rc = omega_tensor_read_f32(g, x, out, n); + omega_tensor_release(g, x); + return rc; +} + +/* Sums `full` (consumed) back to shape (rt, st) in the tape's order: extra + * leading axes first (reduce SUM over axis 0, one at a time), then every + * size-1 axis of the target (reduce SUM, keepdims), and reads the result. */ +static int rp_out(OmegaTensor full, uint32_t rt, const uint64_t *st, float *out) { + OmegaTensor cur = full; + OmegaTensorInfo ci; + int rc = omega_tensor_info(g, cur, &ci); + while (!rc && ci.rank > rt) { + OmegaTensor nx; + rc = omega_tensor_reduce(g, OMEGA_TR_SUM, cur, 0, false, &nx); + omega_tensor_release(g, cur); + if (rc) return rc; + cur = nx; + rc = omega_tensor_info(g, cur, &ci); + } + for (uint32_t d = 0; !rc && d < rt; d++) { + if (st[d] == 1 && ci.shape[d] != 1) { + OmegaTensor nx; + rc = omega_tensor_reduce(g, OMEGA_TR_SUM, cur, d, true, &nx); + omega_tensor_release(g, cur); + if (rc) return rc; + cur = nx; + rc = omega_tensor_info(g, cur, &ci); + } + } + if (rc) { omega_tensor_release(g, cur); return rc; } + return rp_take(cur, out, numel(rt, st)); +} + +/* + * Expected gradients ea (and eb) for seed tg: the backward formula of the + * case's op computed here with the same M20 calls the tape is documented to + * make (omega_autodiff.h), in the same order. MAX routing is the documented + * host data move, with the routing rule written here independently. + */ +static int replay(const OpCase *c, OmegaTensor ta, OmegaTensor tb, OmegaTensor tg, + const OmegaTensorInfo *yi, float *ea, float *eb) { + OmegaTensor x = { 0, 0 }, x2 = { 0, 0 }, k = { 0, 0 }; + int rc = 0; + switch (c->op) { + case OMEGA_AD_ADD: case OMEGA_AD_SUB: + rc = omega_tensor_contiguous(g, tg, &x); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + if (rc) return rc; + if (c->op == OMEGA_AD_ADD) { + rc = omega_tensor_contiguous(g, tg, &x); + } else { + rc = rp_scalar(-1.0f, &k); + if (rc) return rc; + rc = omega_tensor_binary(g, OMEGA_TB_MUL, tg, k, &x); + omega_tensor_release(g, k); + } + if (!rc) rc = rp_out(x, c->rb, c->sb, eb); + return rc; + case OMEGA_AD_MUL: + rc = omega_tensor_binary(g, OMEGA_TB_MUL, tg, tb, &x); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + if (!rc) rc = omega_tensor_binary(g, OMEGA_TB_MUL, tg, ta, &x); + if (!rc) rc = rp_out(x, c->rb, c->sb, eb); + return rc; + case OMEGA_AD_DIV: { + OmegaTensor y = { 0, 0 }; + rc = omega_tensor_binary(g, OMEGA_TB_DIV, tg, tb, &x); /* g / b */ + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + if (rc) return rc; + rc = omega_tensor_binary(g, OMEGA_TB_DIV, ta, tb, &y); /* y = a / b */ + if (rc) return rc; + rc = omega_tensor_binary(g, OMEGA_TB_DIV, y, tb, &x2); /* y / b */ + omega_tensor_release(g, y); + if (rc) return rc; + rc = omega_tensor_binary(g, OMEGA_TB_MUL, tg, x2, &x); /* g * (y / b) */ + omega_tensor_release(g, x2); + if (rc) return rc; + rc = rp_scalar(-1.0f, &k); + if (rc) { omega_tensor_release(g, x); return rc; } + rc = omega_tensor_binary(g, OMEGA_TB_MUL, x, k, &x2); /* * -1 */ + omega_tensor_release(g, k); + omega_tensor_release(g, x); + if (!rc) rc = rp_out(x2, c->rb, c->sb, eb); + return rc; + } + case OMEGA_AD_MAX: { + size_t m = (size_t)yi->elements; + float va[MAXE], vb[MAXE], vg[MAXE], da[MAXE], db[MAXE]; + rc = omega_tensor_broadcast_to(g, ta, yi->rank, yi->shape, &x); + if (!rc) rc = rp_take(x, va, m); + if (!rc) rc = omega_tensor_broadcast_to(g, tb, yi->rank, yi->shape, &x); + if (!rc) rc = rp_take(x, vb, m); + if (!rc) rc = omega_tensor_read_f32(g, tg, vg, m); + if (rc) return rc; + for (size_t i = 0; i < m; i++) { + bool to_a = va[i] == va[i] && (vb[i] != vb[i] || va[i] > vb[i]); + da[i] = to_a ? vg[i] : 0.0f; + db[i] = to_a ? 0.0f : vg[i]; + } + rc = omega_tensor_from_f32(g, yi->rank, yi->shape, da, &x); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + if (!rc) rc = omega_tensor_from_f32(g, yi->rank, yi->shape, db, &x); + if (!rc) rc = rp_out(x, c->rb, c->sb, eb); + return rc; + } + case OMEGA_AD_SQRT: { + OmegaTensor y = { 0, 0 }; + rc = omega_tensor_unary(g, OMEGA_TU_SQRT, ta, &y); + if (rc) return rc; + rc = omega_tensor_binary(g, OMEGA_TB_ADD, y, y, &x2); /* y + y */ + omega_tensor_release(g, y); + if (rc) return rc; + rc = omega_tensor_binary(g, OMEGA_TB_DIV, tg, x2, &x); /* g / (y + y) */ + omega_tensor_release(g, x2); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + return rc; + } + case OMEGA_AD_MATMUL: + rc = omega_tensor_transpose(g, tb, &x2); + if (rc) return rc; + rc = omega_tensor_matmul(g, tg, x2, &x); /* g @ B^T */ + omega_tensor_release(g, x2); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + if (rc) return rc; + rc = omega_tensor_transpose(g, ta, &x2); + if (rc) return rc; + rc = omega_tensor_matmul(g, x2, tg, &x); /* A^T @ g */ + omega_tensor_release(g, x2); + if (!rc) rc = rp_out(x, c->rb, c->sb, eb); + return rc; + case OMEGA_AD_TRANSPOSE: + rc = omega_tensor_transpose(g, tg, &x2); + if (rc) return rc; + rc = omega_tensor_contiguous(g, x2, &x); + omega_tensor_release(g, x2); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + return rc; + case OMEGA_AD_BROADCAST: + rc = omega_tensor_contiguous(g, tg, &x); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + return rc; + case OMEGA_AD_SUM: case OMEGA_AD_MEAN: { + uint64_t ks[4]; + OmegaTensor r = { 0, 0 }, bc = { 0, 0 }; + for (uint32_t d = 0; d < c->ra; d++) ks[d] = d == c->axis ? 1 : c->sa[d]; + rc = omega_tensor_reshape(g, tg, c->ra, ks, &r); + if (rc) return rc; + rc = omega_tensor_broadcast_to(g, r, c->ra, c->sa, &bc); + if (rc) { omega_tensor_release(g, r); return rc; } + rc = omega_tensor_contiguous(g, bc, &x2); + omega_tensor_release(g, bc); + omega_tensor_release(g, r); + if (rc) return rc; + if (c->op == OMEGA_AD_SUM) return rp_out(x2, c->ra, c->sa, ea); + rc = rp_scalar((float)c->sa[c->axis], &k); + if (rc) { omega_tensor_release(g, x2); return rc; } + rc = omega_tensor_binary(g, OMEGA_TB_DIV, x2, k, &x); /* / n */ + omega_tensor_release(g, k); + omega_tensor_release(g, x2); + if (!rc) rc = rp_out(x, c->ra, c->sa, ea); + return rc; + } + default: + return OMEGA_AD_ERR_BAD_ARGS; + } +} + +static void test_op_case(const OpCase *c) { + float a[MAXE], b[MAXE], R[MAXE], ga[MAXE], gb[MAXE]; + double ra_[MAXE], aa[MAXE], rb_[MAXE], ab[MAXE]; + int ka[MAXE], kb[MAXE]; + size_t na = numel(c->ra, c->sa), nb = c->has_b ? numel(c->rb, c->sb) : 0; + gen_data(c, a, b); + + OmegaAdNode nodes[4]; + OmegaAdTape t; + float scratch[3 * MAXE]; + OmegaTensor ta = mk(c->ra, c->sa, a), tb = { 0, 0 }; + if (c->has_b) tb = mk(c->rb, c->sb, b); + int rc = omega_ad_tape_init(&t, g, nodes, 4, scratch, sizeof(scratch) / sizeof(scratch[0])); + uint32_t ia = 0, ib = 0, iy = 0; + if (!rc) rc = build(c, &t, ta, tb, &ia, &ib, &iy); + CHECK(rc == 0, "%s: record rc %d", c->name, rc); + if (rc) { omega_ad_tape_release(&t); goto out; } + OmegaTensor ty = { 0, 0 }; + OmegaTensorInfo yi; + memset(&yi, 0, sizeof(yi)); + omega_ad_value(&t, iy, &ty); + omega_tensor_info(g, ty, &yi); + size_t ny = (size_t)yi.elements; + for (size_t i = 0; i < ny; i++) R[i] = urand(-1, 1); + OmegaTensor tr = mk(yi.rank, yi.shape, R); + rc = omega_ad_backward_seed(&t, iy, tr); + CHECK(rc == 0, "%s: backward rc %d", c->name, rc); + int r1 = omega_ad_grad_read_f32(&t, ia, ga, na); + int r2 = c->has_b ? omega_ad_grad_read_f32(&t, ib, gb, nb) : 0; + CHECK(r1 == 0 && r2 == 0, "%s: grad read rc %d %d (grad shape must equal input shape)", c->name, r1, r2); + omega_ad_tape_release(&t); + if (rc || r1 || r2) { omega_tensor_release(g, tr); goto out; } + + /* bit-exact (approved M21 gate): same M20 ops called directly, same bits */ + float ea[MAXE], eb[MAXE]; + int rr = replay(c, ta, tb, tr, &yi, ea, eb); + omega_tensor_release(g, tr); + CHECK(rr == 0, "%s: bit-exact replay rc %d", c->name, rr); + if (!rr) { + CHECK(memcmp(ga, ea, na * sizeof(float)) == 0, + "%s: grad a not bit-exact with the direct M20 replay", c->name); + if (c->has_b) + CHECK(memcmp(gb, eb, nb * sizeof(float)) == 0, + "%s: grad b not bit-exact with the direct M20 replay", c->name); + if (c == &CASES[0]) { /* counterexample: a one-bit change must be seen */ + uint32_t bits; + memcpy(&bits, &ea[0], 4); bits ^= 1u; memcpy(&ea[0], &bits, 4); + CHECK(memcmp(ga, ea, na * sizeof(float)) != 0, "bit-exact comparator missed a one-bit difference"); + } + } + + /* 1. contract */ + reference(c, a, b, R, yi.rank, yi.shape, ra_, aa, ka, rb_, ab, kb); + size_t first = 0, bad = bound_violations(ga, ra_, aa, ka, na, &first); + CHECK(bad == 0, "%s: grad a outside contract at %zu elements (first %zu: %.9g vs %.9g)", c->name, bad, + first, (double)ga[first], ra_[first]); + if (c->has_b) { + bad = bound_violations(gb, rb_, ab, kb, nb, &first); + CHECK(bad == 0, "%s: grad b outside contract at %zu elements (first %zu: %.9g vs %.9g)", c->name, + bad, first, (double)gb[first], rb_[first]); + } + + /* central finite differences of the CPU forward (approved M21 gate), on + * the FD data set: a fresh tape, its own inputs and a positive seed */ + float fa[MAXE], fb[MAXE], fR[MAXE], fga[MAXE], fgb[MAXE]; + size_t fny = 0; + gen_fd_data(c, fa, fb); + int rf = tape_grads(c, fa, fb, FD_RLO, FD_RHI, fR, &fny, fga, fgb); + CHECK(rf == 0, "%s: FD data set tape rc %d", c->name, rf); + if (rf) goto out; + for (int which = 0; which < (c->has_b ? 2 : 1); which++) { + float *x = which ? fb : fa; + const float *an = which ? fgb : fga; + size_t nx = which ? nb : na, fbad = 0, ffirst = 0; + double fdv = 0; + for (size_t i = 0; i < nx; i++) { + float x0 = x[i], xp = (float)(x0 + FD_H), xm = (float)(x0 - FD_H); + double Lp = 0, Lm = 0; + x[i] = xp; + int e1 = forward_loss(c, fa, fb, fR, fny, &Lp); + x[i] = xm; + int e2 = forward_loss(c, fa, fb, fR, fny, &Lm); + x[i] = x0; + double fd = (Lp - Lm) / ((double)xp - (double)xm); + if (e1 || e2 || !fd_ok((double)an[i], fd)) { + if (!fbad) { ffirst = i; fdv = fd; } + fbad++; + } + } + CHECK(fbad == 0, "%s: grad %c disagrees with central FD at %zu elements (first %zu: %.9g vs fd %.9g)", + c->name, which ? 'b' : 'a', fbad, ffirst, (double)an[ffirst], fdv); + } +out: + omega_tensor_release(g, ta); + if (c->has_b) omega_tensor_release(g, tb); +} + +/* Counterexamples: the comparators reject a wrong gradient. */ +static void test_comparators_reject(void) { + const OpCase *c = &CASES[5]; /* mul [3,4]*[1,4] */ + float a[MAXE], b[MAXE], R[MAXE], wrong[MAXE]; + double ra_[MAXE], aa[MAXE], rb_[MAXE], ab[MAXE]; + int ka[MAXE], kb[MAXE]; + gen_data(c, a, b); + uint64_t sy[2] = { 3, 4 }; + for (int i = 0; i < 12; i++) R[i] = urand(-1, 1); + reference(c, a, b, R, 2, sy, ra_, aa, ka, rb_, ab, kb); + /* off by one float ulp-ish: 1 + 2^-20 relative, far above gamma(1) */ + for (int i = 0; i < 12; i++) wrong[i] = (float)(ra_[i] * (1.0 + 1.0 / 1048576.0)); + size_t first = 0; + CHECK(bound_violations(wrong, ra_, aa, ka, 12, &first) > 0, "contract comparator accepted a perturbed gradient"); + for (int i = 0; i < 12; i++) wrong[i] = (float)ra_[i]; + CHECK(bound_violations(wrong, ra_, aa, ka, 12, &first) == 0, "contract comparator rejected the exact gradient"); + /* FD comparator (pure 1e-3 relative), on the FD data set: it accepts the + * exact gradient, and rejects a sign-flipped one and one 2e-3 too large */ + gen_fd_data(c, a, b); + for (int i = 0; i < 12; i++) R[i] = urand(FD_RLO, FD_RHI); + reference(c, a, b, R, 2, sy, ra_, aa, ka, rb_, ab, kb); + size_t fbad = 0, facc = 0, fbig = 0; + for (size_t i = 0; i < 12; i++) { + float x0 = a[i], xp = (float)(x0 + FD_H), xm = (float)(x0 - FD_H); + double Lp = 0, Lm = 0; + a[i] = xp; forward_loss(c, a, b, R, 12, &Lp); + a[i] = xm; forward_loss(c, a, b, R, 12, &Lm); + a[i] = x0; + double fd = (Lp - Lm) / ((double)xp - (double)xm); + if (fd_ok(ra_[i], fd)) facc++; + if (!fd_ok(-ra_[i], fd)) fbad++; + if (!fd_ok(ra_[i] * 1.002, fd)) fbig++; + } + CHECK(facc == 12, "FD comparator rejected the exact gradient at %zu of 12 elements", 12 - facc); + CHECK(fbad > 0, "FD comparator accepted a sign-flipped gradient"); + CHECK(fbig == 12, "FD comparator accepted a gradient 2e-3 too large at %zu of 12 elements", 12 - fbig); +} + +/* MAX ties go to b (relu gradient 0 at 0). */ +static void test_max_ties(void) { + uint64_t s[1] = { 4 }; + float a[4] = { 0.5f, -0.25f, 0.0f, -0.0f }, b[4] = { 0.5f, -0.25f, -0.0f, 0.0f }, R[4] = { 1, 2, 3, 4 }; + OmegaAdNode nodes[3]; + OmegaAdTape t; + float scratch[12], ga[4] = { 9, 9, 9, 9 }, gb[4] = { 9, 9, 9, 9 }; + OmegaTensor ta = mk(1, s, a), tb = mk(1, s, b), tr = mk(1, s, R); + uint32_t ia = 0, ib = 0, iy = 0; + int rc = omega_ad_tape_init(&t, g, nodes, 3, scratch, 12); + if (!rc) rc = omega_ad_leaf(&t, ta, true, &ia); + if (!rc) rc = omega_ad_leaf(&t, tb, true, &ib); + if (!rc) rc = omega_ad_binary(&t, OMEGA_AD_MAX, ia, ib, &iy); + if (!rc) rc = omega_ad_backward_seed(&t, iy, tr); + if (!rc) rc = omega_ad_grad_read_f32(&t, ia, ga, 4); + if (!rc) rc = omega_ad_grad_read_f32(&t, ib, gb, 4); + CHECK(rc == 0, "max ties: rc %d", rc); + bool ok = true; + for (int i = 0; i < 4; i++) ok = ok && ga[i] == 0.0f && gb[i] == R[i]; + CHECK(ok, "max ties: gradient must go to b (ga %g %g %g %g, gb %g %g %g %g)", + (double)ga[0], (double)ga[1], (double)ga[2], (double)ga[3], + (double)gb[0], (double)gb[1], (double)gb[2], (double)gb[3]); + omega_ad_tape_release(&t); + omega_tensor_release(g, ta); omega_tensor_release(g, tb); omega_tensor_release(g, tr); +} + +/* ---- composite: linear layer + squared error ------------------------------------------- */ + +#define CX_N 4 +#define CX_IN 3 +#define CX_OUT 2 + +typedef struct { + float X[CX_N * CX_IN], W[CX_IN * CX_OUT], bias[CX_OUT], Y[CX_N * CX_OUT]; +} LinData; + +/* loss = mean_i( sum_j ( (X W + bias - Y)_ij ^2 ) ). d is used twice: fan-out. */ +/* loss_d (optional): the same loss computed in double from the tape's float d + * values, mean_i sum_j d_ij^2, for the FD layer. */ +static int lin_run(OmegaTensorCtx *ctx, const LinData *D, float *loss, float *flat_grads, + uint8_t loss_id[32], double *loss_d) { + uint64_t sx[2] = { CX_N, CX_IN }, sw[2] = { CX_IN, CX_OUT }, sb[1] = { CX_OUT }, sy[2] = { CX_N, CX_OUT }; + OmegaTensor tx, tw, tb, ty; + int rc = omega_tensor_from_f32(ctx, 2, sx, D->X, &tx); + if (!rc) rc = omega_tensor_from_f32(ctx, 2, sw, D->W, &tw); + if (!rc) rc = omega_tensor_from_f32(ctx, 1, sb, D->bias, &tb); + if (!rc) rc = omega_tensor_from_f32(ctx, 2, sy, D->Y, &ty); + if (rc) return rc; + OmegaAdNode nodes[16]; + OmegaAdTape t; + uint32_t ix = 0, iw = 0, ib = 0, iy = 0, p = 0, q = 0, d = 0, s = 0, r = 0, l = 0; + rc = omega_ad_tape_init(&t, ctx, nodes, 16, NULL, 0); + if (!rc) rc = omega_ad_leaf(&t, tx, false, &ix); + if (!rc) rc = omega_ad_leaf(&t, tw, true, &iw); + if (!rc) rc = omega_ad_leaf(&t, tb, true, &ib); + if (!rc) rc = omega_ad_leaf(&t, ty, false, &iy); + if (!rc) rc = omega_ad_matmul(&t, ix, iw, &p); + if (!rc) rc = omega_ad_binary(&t, OMEGA_AD_ADD, p, ib, &q); + if (!rc) rc = omega_ad_binary(&t, OMEGA_AD_SUB, q, iy, &d); + if (!rc) rc = omega_ad_binary(&t, OMEGA_AD_MUL, d, d, &s); + if (!rc) rc = omega_ad_reduce(&t, OMEGA_AD_SUM, s, 1, false, &r); + if (!rc) rc = omega_ad_reduce(&t, OMEGA_AD_MEAN, r, 0, false, &l); + OmegaTensor tl = { 0, 0 }; + if (!rc) rc = omega_ad_value(&t, l, &tl); + if (!rc) rc = omega_tensor_read_f32(ctx, tl, loss, 1); + if (!rc && loss_id) rc = omega_tensor_value_id(ctx, tl, loss_id); + if (!rc && loss_d) { + OmegaTensor td = { 0, 0 }; + float dv[CX_N * CX_OUT]; + rc = omega_ad_value(&t, d, &td); + if (!rc) rc = omega_tensor_read_f32(ctx, td, dv, CX_N * CX_OUT); + if (!rc) { + double acc = 0; + for (int i = 0; i < CX_N * CX_OUT; i++) acc += (double)dv[i] * (double)dv[i]; + *loss_d = acc / CX_N; + } + } + if (!rc && flat_grads) { + rc = omega_ad_backward(&t, l); + uint32_t ids[2] = { iw, ib }; + if (!rc) rc = omega_ad_grads_flatten(&t, ids, 2, flat_grads, CX_IN * CX_OUT + CX_OUT); + if (!rc) { + OmegaTensor gx; + int e1 = omega_ad_grad(&t, ix, &gx), e2 = omega_ad_grad(&t, iy, &gx), e3 = omega_ad_grad(&t, iw, &gx); + if (e1 != OMEGA_AD_ERR_NO_GRAD || e2 != OMEGA_AD_ERR_NO_GRAD || e3 != 0) rc = 1000; + } + } + omega_ad_tape_release(&t); + omega_tensor_release(ctx, tx); omega_tensor_release(ctx, tw); + omega_tensor_release(ctx, tb); omega_tensor_release(ctx, ty); + return rc; +} + +static void lin_data(LinData *D) { + for (int i = 0; i < CX_N * CX_IN; i++) D->X[i] = urand(-1, 1); + for (int i = 0; i < CX_IN * CX_OUT; i++) D->W[i] = urand(-1, 1); + for (int i = 0; i < CX_OUT; i++) D->bias[i] = urand(-1, 1); + for (int i = 0; i < CX_N * CX_OUT; i++) D->Y[i] = urand(-1, 1); +} + +/* FD data set: X, W, bias in [0.5, 1], Y in [-0.5, 0], so E = XW + b - Y lies + * in [1.25, 4.5] and every gradient, (2/N) X^T E and (2/N) sum_i E, is >= 1.25: + * no near-zero gradient element for the pure relative FD bound. */ +static void lin_data_fd(LinData *D) { + for (int i = 0; i < CX_N * CX_IN; i++) D->X[i] = urand(0.5f, 1.0f); + for (int i = 0; i < CX_IN * CX_OUT; i++) D->W[i] = urand(0.5f, 1.0f); + for (int i = 0; i < CX_OUT; i++) D->bias[i] = urand(0.5f, 1.0f); + for (int i = 0; i < CX_N * CX_OUT; i++) D->Y[i] = urand(-0.5f, 0.0f); +} + +static void test_composite(void) { + LinData D; + lin_data(&D); + float loss, grads[CX_IN * CX_OUT + CX_OUT]; + int rc = lin_run(g, &D, &loss, grads, NULL, NULL); + CHECK(rc == 0, "composite: rc %d (incl. no grad for X, Y; grad for W)", rc); + if (rc) return; + /* exact reference in double: dL/dW = (2/N) X^T E, dL/db = (2/N) sum_i E, E = XW + b - Y */ + double E[CX_N * CX_OUT]; + for (int i = 0; i < CX_N; i++) + for (int j = 0; j < CX_OUT; j++) { + double s = D.bias[j]; + for (int k = 0; k < CX_IN; k++) s += (double)D.X[i * CX_IN + k] * D.W[k * CX_OUT + j]; + E[i * CX_OUT + j] = s - D.Y[i * CX_OUT + j]; + } + size_t bad_ref = 0; + for (int k = 0; k < CX_IN; k++) + for (int j = 0; j < CX_OUT; j++) { + double s = 0; + for (int i = 0; i < CX_N; i++) s += D.X[i * CX_IN + k] * E[i * CX_OUT + j]; + s *= 2.0 / CX_N; + if (!(dabs(grads[k * CX_OUT + j] - s) <= 1e-5 + 1e-5 * dabs(s))) bad_ref++; + } + for (int j = 0; j < CX_OUT; j++) { + double s = 0; + for (int i = 0; i < CX_N; i++) s += E[i * CX_OUT + j]; + s *= 2.0 / CX_N; + if (!(dabs(grads[CX_IN * CX_OUT + j] - s) <= 1e-5 + 1e-5 * dabs(s))) bad_ref++; + } + CHECK(bad_ref == 0, "composite: %zu gradients differ from the closed form (2/N) X^T E", bad_ref); + /* central FD on every parameter (W then bias, the flatten order), pure + * 1e-3 relative (approved M21 gate), on the FD data set lin_data_fd */ + LinData F; + lin_data_fd(&F); + float floss, fgrads[CX_IN * CX_OUT + CX_OUT]; + rc = lin_run(g, &F, &floss, fgrads, NULL, NULL); + CHECK(rc == 0, "composite FD data set: rc %d", rc); + if (rc) return; + size_t fbad = 0; + float *params[2] = { F.W, F.bias }; + int counts[2] = { CX_IN * CX_OUT, CX_OUT }; + for (int pnum = 0, off = 0; pnum < 2; off += counts[pnum], pnum++) + for (int i = 0; i < counts[pnum]; i++) { + float *x = ¶ms[pnum][i], x0 = *x, xp = (float)(x0 + FD_H), xm = (float)(x0 - FD_H); + float Lpf = 0, Lmf = 0; + double Lp = 0, Lm = 0; + *x = xp; int e1 = lin_run(g, &F, &Lpf, NULL, NULL, &Lp); + *x = xm; int e2 = lin_run(g, &F, &Lmf, NULL, NULL, &Lm); + *x = x0; + double fd = (Lp - Lm) / ((double)xp - (double)xm); + if (e1 || e2 || !fd_ok((double)fgrads[off + i], fd)) fbad++; + } + CHECK(fbad == 0, "composite: %zu parameter gradients disagree with central FD", fbad); +} + +/* Two full runs in two contexts: bit-identical gradients and loss value id. */ +static void test_determinism(void) { + LinData D; + lin_data(&D); + OmegaTensorCtx *c2 = NULL; + int rc = omega_tensor_ctx_create(1024, omega_tensor_cpu_realization(), &c2); + CHECK(rc == 0, "determinism: second ctx rc %d", rc); + if (rc) return; + float l1, l2, g1[8], g2[8]; + uint8_t id1[32], id2[32]; + int r1 = lin_run(g, &D, &l1, g1, id1, NULL), r2 = lin_run(c2, &D, &l2, g2, id2, NULL); + CHECK(r1 == 0 && r2 == 0, "determinism: runs rc %d %d", r1, r2); + CHECK(memcmp(g1, g2, sizeof(g1)) == 0, "determinism: gradients differ between two runs"); + CHECK(memcmp(id1, id2, 32) == 0, "determinism: loss value id differs between two runs"); + /* counterexample: one flipped low bit must be seen */ + float g3[8]; + memcpy(g3, g1, sizeof(g1)); + uint32_t bits; + memcpy(&bits, &g3[3], 4); bits ^= 1u; memcpy(&g3[3], &bits, 4); + CHECK(memcmp(g1, g3, sizeof(g1)) != 0, "determinism comparator missed a one-bit difference"); + uint32_t lt, ls; + omega_tensor_live_counts(c2, <, &ls); + CHECK(lt == 0 && ls == 0, "determinism: second ctx leaked %u tensors %u storages", lt, ls); + omega_tensor_ctx_destroy(c2); +} + +/* ---- error paths ------------------------------------------------------------------------- */ + +static void live(uint32_t *lt, uint32_t *ls) { omega_tensor_live_counts(g, lt, ls); } + +static void test_errors(void) { + OmegaAdNode nodes[3]; + OmegaAdTape t; + uint64_t s34[2] = { 3, 4 }, s5[1] = { 5 }, s4[1] = { 4 }, s35[2] = { 3, 5 }, s42[2] = { 4, 2 }; + float d[20]; + for (int i = 0; i < 20; i++) d[i] = urand(-1, 1); + OmegaTensor a = mk(2, s34, d), b5 = mk(1, s5, d), b4 = mk(1, s4, d), m35 = mk(2, s35, d), m42 = mk(2, s42, d); + + /* init refusals, with the valid call as counterexample */ + CHECK(omega_ad_tape_init(&t, g, nodes, 0, NULL, 0) == OMEGA_AD_ERR_BAD_ARGS, "capacity 0 accepted"); + CHECK(omega_ad_tape_init(&t, g, NULL, 3, NULL, 0) == OMEGA_AD_ERR_BAD_ARGS, "NULL nodes accepted"); + CHECK(omega_ad_tape_init(&t, g, nodes, 3, NULL, 5) == OMEGA_AD_ERR_BAD_ARGS, "NULL scratch with count accepted"); + CHECK(omega_ad_tape_init(&t, g, nodes, 3, NULL, 0) == 0, "valid init refused"); + + /* tape capacity: 3 nodes fit, the 4th is refused and nothing leaks */ + uint32_t ia = 0, ib = 0, iy = 0, iz = 77; + int rc = omega_ad_leaf(&t, a, true, &ia); + if (!rc) rc = omega_ad_leaf(&t, b4, true, &ib); + if (!rc) rc = omega_ad_binary(&t, OMEGA_AD_ADD, ia, ib, &iy); + CHECK(rc == 0 && t.count == 3, "3 nodes on a capacity-3 tape: rc %d count %u", rc, t.count); + uint32_t lt0, ls0, lt1, ls1; + live(<0, &ls0); + rc = omega_ad_binary(&t, OMEGA_AD_ADD, iy, ib, &iz); + live(<1, &ls1); + CHECK(rc == OMEGA_AD_ERR_TAPE_FULL, "full tape: rc %d, want TAPE_FULL", rc); + CHECK(t.count == 3 && iz == 77 && lt0 == lt1 && ls0 == ls1, "full tape changed state (count %u, live %u->%u)", + t.count, lt0, lt1); + CHECK(omega_ad_leaf(&t, a, true, &iz) == OMEGA_AD_ERR_TAPE_FULL, "leaf on full tape accepted"); + omega_ad_tape_release(&t); + + /* shape mismatches: tensor error passed through, tape and ctx unchanged */ + OmegaAdNode n2[8]; + float scratch[6]; + omega_ad_tape_init(&t, g, n2, 8, scratch, 6); + uint32_t i35 = 0, i42 = 0, i5 = 0; + omega_ad_leaf(&t, a, true, &ia); + omega_ad_leaf(&t, b5, true, &i5); + omega_ad_leaf(&t, m35, true, &i35); + omega_ad_leaf(&t, m42, true, &i42); + CHECK(omega_ad_sqrt(&t, 99, &iz) == OMEGA_AD_ERR_BAD_ARGS, "node id 99 accepted"); + live(<0, &ls0); + uint32_t before = t.count; + int e1 = omega_ad_binary(&t, OMEGA_AD_ADD, ia, i5, &iz); + int e2 = omega_ad_matmul(&t, i35, i42, &iz); + uint64_t s4b[1] = { 4 }; + int e3 = omega_ad_broadcast(&t, i5, 1, s4b, &iz); + int e4 = omega_ad_reduce(&t, OMEGA_AD_SUM, ia, 2, false, &iz); + int e5 = omega_ad_binary(&t, OMEGA_AD_MATMUL, ia, ia, &iz); + live(<1, &ls1); + CHECK(e1 == OMEGA_TENSOR_ERR_SHAPE, "[3,4]+[5]: rc %d, want TENSOR_ERR_SHAPE", e1); + CHECK(e2 == OMEGA_TENSOR_ERR_SHAPE, "[3,5]x[4,2]: rc %d, want TENSOR_ERR_SHAPE", e2); + CHECK(e3 == OMEGA_TENSOR_ERR_SHAPE, "broadcast [5]->[4]: rc %d, want TENSOR_ERR_SHAPE", e3); + CHECK(e4 == OMEGA_TENSOR_ERR_AXIS, "reduce axis 2 of rank 2: rc %d, want TENSOR_ERR_AXIS", e4); + CHECK(e5 == OMEGA_AD_ERR_BAD_ARGS, "binary with MATMUL op: rc %d, want BAD_ARGS", e5); + CHECK(t.count == before && lt0 == lt1 && ls0 == ls1, "refused ops changed the tape or leaked"); + uint32_t imm = 0; + CHECK(omega_ad_matmul(&t, i35, i35, &imm) == OMEGA_TENSOR_ERR_SHAPE, "[3,5]x[3,5] accepted"); + /* counterexample: compatible shapes record (MAX below) */ + uint32_t imax = 0; + rc = omega_ad_binary(&t, OMEGA_AD_MAX, ia, ia, &imax); /* [3,4]: backward needs 36 scratch floats */ + CHECK(rc == 0, "max record rc %d", rc); + /* seed / root shape (enough scratch, so only the shape can refuse) */ + float big[36]; + t.scratch = big; t.scratch_count = 36; + OmegaTensor seed34 = mk(2, s34, d); + CHECK(omega_ad_backward(&t, imax) == OMEGA_AD_ERR_SHAPE, "scalar seed accepted for a [3,4] root"); + CHECK(omega_ad_backward_seed(&t, imax, b4) == OMEGA_AD_ERR_SHAPE, "seed [4] accepted for root [3,4]"); + /* scratch: 6 floats for MAX [3,4] (needs 36) is refused */ + t.scratch = scratch; t.scratch_count = 6; + CHECK(omega_ad_backward_seed(&t, imax, seed34) == OMEGA_AD_ERR_SCRATCH, "6 floats of scratch accepted for MAX [3,4]"); + size_t need = 0; + CHECK(omega_ad_scratch_need(&t, &need) == 0 && need == 36, "scratch need %zu, want 36", need); + t.scratch = big; t.scratch_count = 36; + CHECK(!t.backward_done, "refused backward marked the tape done"); + rc = omega_ad_backward_seed(&t, imax, seed34); + CHECK(rc == 0, "valid seed refused: rc %d", rc); + CHECK(omega_ad_backward_seed(&t, imax, seed34) == OMEGA_AD_ERR_STATE, "second backward accepted"); + CHECK(omega_ad_sqrt(&t, ia, &iz) == OMEGA_AD_ERR_STATE, "recording after backward accepted"); + OmegaTensor gg; + CHECK(omega_ad_grad(&t, ia, &gg) == 0, "max input has no grad"); + CHECK(omega_ad_grad(&t, i35, &gg) == OMEGA_AD_ERR_NO_GRAD, "unreached leaf has a grad"); + float tiny[11]; + CHECK(omega_ad_grad_read_f32(&t, ia, tiny, 11) == OMEGA_AD_ERR_COUNT, "short grad read accepted"); + /* flatten: exact count only, nothing written otherwise */ + float flat[13]; + for (int i = 0; i < 13; i++) flat[i] = 7.0f; + uint32_t one_id[1] = { ia }; + CHECK(omega_ad_grads_flatten(&t, one_id, 1, flat, 13) == OMEGA_AD_ERR_COUNT, "flatten count 13 for 12 accepted"); + bool untouched = true; + for (int i = 0; i < 13; i++) untouched = untouched && flat[i] == 7.0f; + CHECK(untouched, "refused flatten wrote the buffer"); + CHECK(omega_ad_grads_flatten(&t, one_id, 1, flat, 12) == 0, "flatten count 12 refused"); + float direct[12]; + omega_ad_grad_read_f32(&t, ia, direct, 12); + CHECK(memcmp(direct, flat, sizeof(direct)) == 0, "flatten differs from grad read"); + omega_ad_tape_release(&t); + omega_tensor_release(g, seed34); + + /* root without grad; F16 leaf refused */ + omega_ad_tape_init(&t, g, nodes, 3, NULL, 0); + omega_ad_leaf(&t, a, false, &ia); + rc = omega_ad_binary(&t, OMEGA_AD_ADD, ia, ia, &iy); + CHECK(rc == 0, "no-grad add rc %d", rc); + CHECK(omega_ad_backward_seed(&t, iy, a) == OMEGA_AD_ERR_NO_GRAD, "backward from a no-grad root accepted"); + uint16_t h[4] = { 0x3c00, 0x3c00, 0x3c00, 0x3c00 }; + OmegaTensor th; + rc = omega_tensor_from_data(g, OMEGA_DT_F16, 1, s4, h, &th); + CHECK(rc == 0, "f16 tensor rc %d", rc); + CHECK(omega_ad_leaf(&t, th, true, &iz) == OMEGA_TENSOR_ERR_DTYPE, "F16 leaf accepted"); + omega_ad_tape_release(&t); + omega_tensor_release(g, th); + + omega_tensor_release(g, a); omega_tensor_release(g, b5); omega_tensor_release(g, b4); + omega_tensor_release(g, m35); omega_tensor_release(g, m42); +} + +int main(void) { + if (!omega_numeric_fpenv_ok()) { printf("FPCR not RNE/no-FTZ: refusing to run\n"); return 2; } + if (omega_tensor_ctx_create(4096, omega_tensor_cpu_realization(), &g)) { printf("ctx\n"); return 2; } + for (size_t i = 0; i < NCASES; i++) test_op_case(&CASES[i]); + test_comparators_reject(); + test_max_ties(); + test_composite(); + test_determinism(); + test_errors(); + uint32_t lt, ls; + omega_tensor_live_counts(g, <, &ls); + CHECK(lt == 0 && ls == 0, "no leaked tensors (%u) or storage (%u)", lt, ls); + omega_tensor_ctx_destroy(g); + printf("M21 OMEGA_AUTODIFF CPU tests: %d pass, %d fail\n", g_pass, g_fail); + printf("M21 verdict: NOT QUALIFIED (CPU tier only; GB10 NOT_RUN)\n"); + return g_fail ? 1 : 0; +} diff --git a/tools/autodiff_mutations.sh b/tools/autodiff_mutations.sh new file mode 100755 index 000000000..3288488aa --- /dev/null +++ b/tools/autodiff_mutations.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# M21 OMEGA_AUTODIFF mutation sweep. For each rule marked MUT:<name> in +# src/autodiff/*.c, copy src/autodiff to a scratch directory, break that one +# rule, rebuild the CPU test against the copy and require the test to FAIL. +# A mutation that does not apply, does not build, or that the tests do not +# catch, fails the sweep. The source tree is never edited. CPU only, no +# device. Shell only (no Python). +set -u +cd "$(dirname "$0")/.." || exit 2 +SCRATCH=$(mktemp -d "${TMPDIR:-/tmp}/autodiff-mut.XXXXXX") || exit 2 +trap 'rm -rf "$SCRATCH"' EXIT INT TERM +TENSOR="src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c \ +src/omega_numeric_reduce.c src/omega_numeric_transc.c" +DEPS="src/omega_numeric.c src/omega_numeric_provenance.c src/omega_blackwell_encoder.c \ +src/omega_blackwell_codegen.c src/omega_blackwell_matmul.c src/omega_blackwell_qmd.c src/sha256.c" +FLAGS="-std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -O2 -DOMEGA_NUMERIC_CPU_ONLY" + +# name|file|sed expression (applied only to the line carrying MUT:<name>) +# DIV_FORMULA computes gb as -((g * y) / b) instead of -(g * (y / b)): the same +# real number with the same rounding count, so it stays inside the per-op +# contract and the 1e-3 FD bound; it is aimed at the bit-exact layer. +MUTATIONS='TAPE_WALK|omega_autodiff.c|s/root + 1; i-- > 0/root; i-- > 0/ +ACCUMULATE|omega_autodiff.c|s/omega_tensor_binary(t->ctx, OMEGA_TB_ADD, n->grad, contrib, &sum)/omega_tensor_contiguous(t->ctx, contrib, \&sum)/ +UNBROADCAST|omega_autodiff.c|s/if (target->shape/if (0 \&\& target->shape/ +SUB_NEGATE|omega_autodiff.c|s/-1\.0f/1.0f/ +MUL_OPERAND|omega_autodiff.c|s/t->nodes\[n->in1\]\.value/t->nodes[n->in0].value/ +MATMUL_TRANSPOSE|omega_autodiff.c|s/matmul(t->ctx, g, tmp, &c)/matmul(t->ctx, g, nb->value, \&c)/ +SQRT_TWICE|omega_autodiff.c|s/omega_tensor_binary(t->ctx, OMEGA_TB_ADD, n->value, n->value, &tmp)/omega_tensor_contiguous(t->ctx, n->value, \&tmp)/ +MEAN_DIVISOR|omega_autodiff.c|s/(float)len/(float)(len + 1)/ +MAX_ROUTE|omega_autodiff.c|s/return a > b;/return a < b;/ +MAX_TIE|omega_autodiff.c|s/return a > b;/return a >= b;/ +DIV_B_SIGN|omega_autodiff.c|s/-1\.0f/1.0f/ +DIV_FORMULA|omega_autodiff.c|{s/OMEGA_TB_DIV, n->value, nb->value, &tmp)/OMEGA_TB_MUL, g, n->value, \&tmp)/;s/OMEGA_TB_MUL, g, tmp, &c2)/OMEGA_TB_DIV, tmp, nb->value, \&c2)/}' + +build() { # $1 = autodiff source dir, $2 = output binary + gcc $FLAGS -Isrc -Isrc/tensor -I"$1" -o "$2" tests/test_omega_autodiff.c "$1/omega_autodiff.c" \ + $TENSOR $DEPS +} + +# Baseline: the unmutated build must PASS, otherwise every mutant would +# look "caught" (e.g. the test refusing an unsuitable FP environment). +if ! build src/autodiff "$SCRATCH/base" > "$SCRATCH/base.log" 2>&1 || \ + ! "$SCRATCH/base" > "$SCRATCH/base.run" 2>&1; then + head -5 "$SCRATCH/base.log" "$SCRATCH/base.run" 2>/dev/null + echo "autodiff mutation sweep: FAIL (unmutated baseline does not pass)"; exit 1 +fi +fail=0 +total=0 +old_ifs=$IFS +IFS=' +' +for m in $MUTATIONS; do + IFS=$old_ifs + IFS='|' read -r name file expr <<EOM +$m +EOM + IFS=$old_ifs + total=$((total + 1)) + rm -rf "$SCRATCH/autodiff" && cp -r src/autodiff "$SCRATCH/autodiff" + sed -i "/MUT:$name/ $expr" "$SCRATCH/autodiff/$file" + if cmp -s "src/autodiff/$file" "$SCRATCH/autodiff/$file"; then + echo "MUTATION $name: NOT APPLIED (marker or pattern missing)"; fail=1; continue + fi + if ! build "$SCRATCH/autodiff" "$SCRATCH/t" > "$SCRATCH/build.log" 2>&1; then + head -5 "$SCRATCH/build.log" + echo "MUTATION $name: does not build (fix the sed expression)"; fail=1; continue + fi + if "$SCRATCH/t" > "$SCRATCH/run.log" 2>&1; then + echo "MUTATION $name: NOT CAUGHT (tests still pass)"; fail=1 + else + echo "MUTATION $name: caught ($(grep -c '^FAIL' "$SCRATCH/run.log") failing checks)" + fi +done +IFS=$old_ifs +if [ "$total" -lt 5 ]; then echo "autodiff mutation sweep: FAIL (fewer than 5 mutations)"; exit 1; fi +if [ "$fail" -ne 0 ]; then echo "autodiff mutation sweep: FAIL"; exit 1; fi +echo "autodiff mutation sweep: PASS ($total of $total mutations caught)"