Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/src/autodiff/omega_autodiff.h # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / src / autodiff / omega_autodiff.h` 190 lines ยท 10275 bytes Raw Blame History 1 /* SPDX-License-Identifier: Apache-2.0 2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef OMEGA_AUTODIFF_H 18 #define OMEGA_AUTODIFF_H 19 20 /* 21 * M21 OMEGA_AUTODIFF, CPU tier (docs/autodiff/M21_OMEGA_AUTODIFF.md). 22 * 23 * A reverse-mode tape over the M20 OMEGA_TENSOR ops that exist today 24 * (src/tensor/omega_tensor.h). Forward: every recorded op is one M20 call 25 * whose result is kept on the tape. Backward: walks the tape from the root 26 * down to node 0 and builds every gradient with M20 calls (binary ADD / SUB / 27 * MUL / DIV, matmul, transpose, reshape, broadcast_to, reduce SUM), so the 28 * backward pass runs on the same E1 realization as the forward pass. The one 29 * exception is the MAX routing step (see OMEGA_AD_MAX): it is a data move 30 * done on the host in the caller's scratch buffer, because M20 has no 31 * mask-producing op yet (tensor change request CR-3 in the doc). 32 * 33 * Determinism. No hidden global state, no heap allocation in this module: 34 * the caller provides the node array (explicit capacity), the scratch buffer 35 * and the M20 context (whose slot capacity bounds every tensor made here). 36 * Backward walks nodes in strictly decreasing index order; for each node the 37 * contribution to in0 is accumulated before the contribution to in1; several 38 * contributions to one node are added in that order with M20 ADD. Same tape, 39 * same inputs, same bits. 40 * 41 * Ownership. Leaf values belong to the caller and must stay live until 42 * omega_ad_tape_release. Every non-leaf value and every gradient is a dense 43 * row-major tensor owned by the tape and released by omega_ad_tape_release. 44 * Handles returned by omega_ad_value / omega_ad_grad are borrowed. 45 * 46 * Errors. A forward call that fails leaves the tape unchanged (no node, no 47 * leaked tensor). Errors of the M20 layer are passed through unchanged 48 * (OMEGA_TENSOR_ERR_*, -1..-11); the tape's own errors are OMEGA_AD_ERR_*. 49 * A backward call that fails marks the tape failed (OMEGA_AD_ERR_STATE on 50 * every later backward or grad call); release it and rebuild. 51 * 52 * Error contract (per op, "local"): every vector-Jacobian product below is 53 * compared with exact real arithmetic applied to the float32 values that are 54 * actually on the tape (stored forward values and the incoming gradient g). 55 * u = 2^-24, gamma(k) = k*u / (1 - k*u). L(m) = number of E1 reduction 56 * levels for m terms = max(1, ceil(log32 m)); one level is a 5-step 57 * pairwise lane tree, so a declared-order sum of m terms has error 58 * <= gamma(5*L(m)) * sum|terms| (E1 reduction contract, padding with -0.0 59 * is exact). D(x) = sum of 5*L(m) over every reduction "unbroadcast" makes 60 * to bring a gradient back to x's shape (m > 1 only; D = 0 when x was not 61 * broadcast). Bounds hold when no intermediate overflows or goes subnormal. 62 * 63 * op gradient bound per element of grad x 64 * ADD ga = unb(g), gb = unb(g) gamma(D(x)) * sum|g| 65 * SUB ga = unb(g), gb = -unb(g) gamma(D(x)) * sum|g| 66 * MUL ga = unb(g*b), gb = unb(g*a) gamma(D(x)+1) * sum|g*other| 67 * DIV ga = unb(g/b) gamma(D(a)+1) * sum|g/b| 68 * gb = -unb(g*(y/b)), y = a/b gamma(D(b)+3) * sum|g*a/b^2| 69 * MAX routed g (see OMEGA_AD_MAX) gamma(D(x)) * sum|routed g| 70 * SQRT ga = g / (y + y), y = sqrt(a) gamma(2) * |g / (2 sqrt(a))| 71 * MATMUL gA = unb(g @ B^T) gamma(1 + 5*L(N) + D(A)) * sum|g||B| 72 * [..,M,K]x gB = unb(A^T @ g) gamma(1 + 5*L(M) + D(B)) * sum|A||g| 73 * [..,K,N] 74 * TRANSPOSE ga = g^T 0 (exact) 75 * BROADCAST ga = unb(g) gamma(D(a)) * sum|g| 76 * SUM(axis) ga = broadcast(g) 0 (exact) 77 * MEAN(axis) ga = broadcast(g) / n gamma(1) * |g / n| (n <= 2^24) 78 * fan-out k contributions added in order extra gamma(k-1) * sum|contrib| 79 * 80 * Not thread safe: one tape per thread, like the M20 context. 81 */ 82 83 #include 84 #include 85 #include 86 87 #include "omega_tensor.h" 88 89 #define OMEGA_AD_NONE UINT32_MAX 90 91 typedef enum { 92 OMEGA_AD_OK = 0, 93 OMEGA_AD_ERR_BAD_ARGS = -101, /* NULL, unknown op, node id out of range */ 94 OMEGA_AD_ERR_TAPE_FULL = -102, /* count == capacity: nothing recorded */ 95 OMEGA_AD_ERR_SHAPE = -103, /* seed/root shape, gradient shape drift */ 96 OMEGA_AD_ERR_STATE = -104, /* backward already ran, or failed */ 97 OMEGA_AD_ERR_NO_GRAD = -105, /* node does not require / did not get one */ 98 OMEGA_AD_ERR_SCRATCH = -106, /* scratch smaller than omega_ad_scratch_need */ 99 OMEGA_AD_ERR_COUNT = -107 /* flatten: element count != buffer count */ 100 } OmegaAdStatus; 101 102 typedef enum { 103 OMEGA_AD_LEAF = 0, 104 OMEGA_AD_ADD, /* M20 binary ADD, numpy broadcast */ 105 OMEGA_AD_SUB, /* M20 binary SUB */ 106 OMEGA_AD_MUL, /* M20 binary MUL */ 107 OMEGA_AD_DIV, /* M20 binary DIV (correctly rounded) */ 108 /* M20 binary MAX (FMNMX_MAX, NaN is missing data). Subgradient rule: 109 * g goes to a when b is NaN and a is not, or when a > b; otherwise to b 110 * (ties, including -0 vs +0, and a NaN go to b). relu(x) = MAX(x, 0) 111 * therefore has gradient 0 at x == 0. Needs 3 * elements(y) floats of 112 * caller scratch at backward time. */ 113 OMEGA_AD_MAX, 114 OMEGA_AD_SQRT, /* M20 unary SQRT (correctly rounded); grad at 0 = inf */ 115 OMEGA_AD_MATMUL, /* M20 matmul, rank >= 2, batched broadcast */ 116 OMEGA_AD_TRANSPOSE, /* swap last two axes; value is a dense copy */ 117 OMEGA_AD_BROADCAST, /* broadcast_to; value is a dense copy */ 118 OMEGA_AD_SUM, /* M20 reduce SUM along one axis */ 119 OMEGA_AD_MEAN, /* M20 reduce MEAN along one axis */ 120 OMEGA_AD_OP_COUNT 121 } OmegaAdOp; 122 123 typedef struct { 124 OmegaAdOp op; 125 uint32_t in0, in1; /* node ids or OMEGA_AD_NONE */ 126 uint32_t axis; /* SUM / MEAN */ 127 bool keepdims; /* SUM / MEAN */ 128 bool requires_grad; /* leaf: caller's choice; op: any input's */ 129 bool owns_value; /* false only for leaves */ 130 bool has_grad; 131 OmegaTensor value; 132 OmegaTensor grad; /* valid when has_grad; dense, owned by tape */ 133 } OmegaAdNode; 134 135 typedef struct { 136 OmegaTensorCtx *ctx; 137 OmegaAdNode *nodes; /* caller array of `capacity` nodes */ 138 uint32_t capacity; 139 uint32_t count; 140 float *scratch; /* caller buffer, may be NULL if no MAX node */ 141 size_t scratch_count; 142 bool backward_done; 143 bool failed; 144 } OmegaAdTape; 145 146 /* capacity >= 1. scratch may be NULL with scratch_count 0. */ 147 int omega_ad_tape_init(OmegaAdTape *t, OmegaTensorCtx *ctx, OmegaAdNode *nodes, uint32_t capacity, 148 float *scratch, size_t scratch_count); 149 /* Releases every tensor the tape owns (values of op nodes, all gradients). 150 * Leaves' values stay with the caller. The tape is empty afterwards. */ 151 void omega_ad_tape_release(OmegaAdTape *t); 152 153 /* ---- forward recording ----------------------------------------------------- */ 154 /* value must be a live F32 tensor; the tape borrows it. */ 155 int omega_ad_leaf(OmegaAdTape *t, OmegaTensor value, bool requires_grad, uint32_t *id); 156 /* op in OMEGA_AD_ADD .. OMEGA_AD_MAX. */ 157 int omega_ad_binary(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t b, uint32_t *id); 158 int omega_ad_sqrt(OmegaAdTape *t, uint32_t a, uint32_t *id); 159 int omega_ad_matmul(OmegaAdTape *t, uint32_t a, uint32_t b, uint32_t *id); 160 int omega_ad_transpose(OmegaAdTape *t, uint32_t a, uint32_t *id); 161 int omega_ad_broadcast(OmegaAdTape *t, uint32_t a, uint32_t rank, const uint64_t *shape, uint32_t *id); 162 /* op is OMEGA_AD_SUM or OMEGA_AD_MEAN. */ 163 int omega_ad_reduce(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t axis, bool keepdims, uint32_t *id); 164 165 /* Borrowed handle of a node's forward value. */ 166 int omega_ad_value(const OmegaAdTape *t, uint32_t id, OmegaTensor *out); 167 /* Floats of scratch the backward pass of this tape needs (MAX nodes). */ 168 int omega_ad_scratch_need(const OmegaAdTape *t, size_t *floats); 169 170 /* ---- backward ---------------------------------------------------------------- */ 171 /* Root must have exactly one element; seed gradient 1.0. Runs once per tape. */ 172 int omega_ad_backward(OmegaAdTape *t, uint32_t root); 173 /* Vector-Jacobian product: seed has exactly the root's shape (copied). */ 174 int omega_ad_backward_seed(OmegaAdTape *t, uint32_t root, OmegaTensor seed); 175 176 /* Borrowed handle of a node's gradient (dense row-major, node's shape). */ 177 int omega_ad_grad(const OmegaAdTape *t, uint32_t id, OmegaTensor *out); 178 /* Copies one gradient out: count must equal the node's element count. */ 179 int omega_ad_grad_read_f32(const OmegaAdTape *t, uint32_t id, float *out, size_t count); 180 /* 181 * M22 bridge: writes the gradients of ids[0..n) back to back, each in 182 * logical row-major order, into one flat float32 buffer of exactly `count` 183 * elements. This is the layout tg_sgd_step (src/train/tg_sgd.h) consumes when 184 * the shadow's parameters are laid out in the same id order. Nothing is 185 * written unless the total element count equals `count`. 186 */ 187 int omega_ad_grads_flatten(const OmegaAdTape *t, const uint32_t *ids, uint32_t n, float *out, 188 size_t count); 189 190 #endif /* OMEGA_AUTODIFF_H */