interplane.Get Omega
Read in your language

omega-mv

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

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / autodiff / omega_autodiff.c

587 lines · 21866 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/*
18 * M21 OMEGA_AUTODIFF, CPU tier: reverse-mode tape over M20 tensor ops.
19 * Meaning, determinism rules and the per-op error contract are stated in
20 * omega_autodiff.h and docs/autodiff/M21_OMEGA_AUTODIFF.md.
21 *
22 * Lines marked MUT:<NAME> are the targets of tools/autodiff_mutations.sh.
23 * No heap allocation here; no floating-point arithmetic except through M20
24 * calls (the MAX routing step only compares and moves values).
25 */
26#include "omega_autodiff.h"
27#include "omega_api_decl.h"
28
29_Static_assert(OMEGA_TENSOR_MAX_RANK == 8, "gradient_shape.om uses eight reduction steps");
30
31#include <string.h>
32
33/* ---- small helpers ---------------------------------------------------------- */
34
35static void rel(OmegaAdTape *t, OmegaTensor x) {
36 (void)omega_tensor_release(t->ctx, x);
37}
38
39static bool node_ok(const OmegaAdTape *t, uint32_t id) {
40 return t && id < t->count;
41}
42
43static int can_record(const OmegaAdTape *t) {
44 if (!t || !t->ctx || !t->nodes) return OMEGA_AD_ERR_BAD_ARGS;
45 if (t->backward_done || t->failed) return OMEGA_AD_ERR_STATE;
46 if (t->count >= t->capacity) return OMEGA_AD_ERR_TAPE_FULL;
47 return OMEGA_AD_OK;
48}
49
50static uint32_t push(OmegaAdTape *t, OmegaAdOp op, uint32_t in0, uint32_t in1, uint32_t axis,
51 bool keepdims, bool requires_grad, bool owns, OmegaTensor value) {
52 OmegaAdNode *n = &t->nodes[t->count];
53 memset(n, 0, sizeof(*n));
54 n->op = op;
55 n->in0 = in0;
56 n->in1 = in1;
57 n->axis = axis;
58 n->keepdims = keepdims;
59 n->requires_grad = requires_grad;
60 n->owns_value = owns;
61 n->has_grad = false;
62 n->value = value;
63 return t->count++;
64}
65
66static bool same_shape(const OmegaTensorInfo *x, const OmegaTensorInfo *y) {
67 return ad_same_shape(x->shape, x->rank, y->shape, y->rank);
68}
69
70/* Rank-0 F32 constant. */
71static int scalar(OmegaAdTape *t, float v, OmegaTensor *out) {
72 uint64_t dummy = 1;
73 return omega_tensor_from_f32(t->ctx, 0, &dummy, &v, out);
74}
75
76/* out = x * k (x borrowed). With k = -1 this is an exact negation. */
77static int scale(OmegaAdTape *t, OmegaTensor x, float k, OmegaTensor *out) {
78 OmegaTensor c;
79 int rc = scalar(t, k, &c);
80 if (rc) return rc;
81 rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, x, c, out);
82 rel(t, c);
83 return rc;
84}
85
86/*
87 * Sum a gradient (owned, consumed on every path) back to the shape of
88 * `target`: first the extra leading axes (reduce SUM over axis 0, one at a
89 * time), then every axis where target has size 1 and the gradient does not
90 * (reduce SUM with keepdims). Returns a dense owned tensor in *out.
91 */
92static int unbroadcast(OmegaAdTape *t, OmegaTensor full, const OmegaTensorInfo *target, OmegaTensor *out) {
93 OmegaTensor cur = full;
94 OmegaTensorInfo ci;
95 int rc = omega_tensor_info(t->ctx, cur, &ci);
96 if (rc) { rel(t, cur); return rc; }
97 uint8_t steps[OMEGA_TENSOR_MAX_RANK];
98 int64_t count = ad_unbroadcast_steps(ci.shape, ci.rank, target->shape, target->rank, steps);
99 if (count < 0) { rel(t, cur); return OMEGA_AD_ERR_SHAPE; }
100 for (int64_t i = 0; i < count; i++) {
101 OmegaTensor next;
102 rc = omega_tensor_reduce(t->ctx, OMEGA_TR_SUM, cur, steps[i] / 2, steps[i] & 1, &next);
103 rel(t, cur);
104 if (rc) return rc;
105 cur = next;
106 }
107 *out = cur;
108 return OMEGA_AD_OK;
109}
110
111/* Add an owned, already shape-matched contribution into node idx's grad. */
112static int accumulate(OmegaAdTape *t, uint32_t idx, OmegaTensor contrib) {
113 OmegaAdNode *n = &t->nodes[idx];
114 OmegaTensorInfo vi, gi;
115 int rc = omega_tensor_info(t->ctx, n->value, &vi);
116 if (!rc) rc = omega_tensor_info(t->ctx, contrib, &gi);
117 if (rc) { rel(t, contrib); return rc; }
118 if (!same_shape(&vi, &gi)) { rel(t, contrib); return OMEGA_AD_ERR_SHAPE; }
119 if (!n->has_grad) {
120 n->grad = contrib;
121 n->has_grad = true;
122 return OMEGA_AD_OK;
123 }
124 OmegaTensor sum;
125 rc = omega_tensor_binary(t->ctx, OMEGA_TB_ADD, n->grad, contrib, &sum); /* MUT:ACCUMULATE */
126 rel(t, contrib);
127 if (rc) return rc;
128 rel(t, n->grad);
129 n->grad = sum;
130 return OMEGA_AD_OK;
131}
132
133/* Give node idx the contribution `full` (owned, consumed): unbroadcast to the
134 * node's shape, then accumulate. No-op (but still consumes) when the node
135 * does not require a gradient. */
136static int contribute(OmegaAdTape *t, uint32_t idx, OmegaTensor full) {
137 OmegaAdNode *n = &t->nodes[idx];
138 if (!n->requires_grad) { rel(t, full); return OMEGA_AD_OK; }
139 OmegaTensorInfo vi;
140 int rc = omega_tensor_info(t->ctx, n->value, &vi);
141 if (rc) { rel(t, full); return rc; }
142 OmegaTensor u;
143 rc = unbroadcast(t, full, &vi, &u);
144 if (rc) return rc;
145 return accumulate(t, idx, u);
146}
147
148static bool wants(const OmegaAdTape *t, uint32_t idx) {
149 return idx != OMEGA_AD_NONE && t->nodes[idx].requires_grad;
150}
151
152/* MAX subgradient rule (header): true when g goes to a. */
153static bool max_routes_to_a(float a, float b) {
154 if (a != a) return false;
155 if (b != b) return true;
156 return a > b; /* MUT:MAX_ROUTE MUT:MAX_TIE */
157}
158
159/* ---- per-op backward ------------------------------------------------------------ */
160
161static int backward_max(OmegaAdTape *t, const OmegaAdNode *n) {
162 OmegaTensorInfo yi;
163 int rc = omega_tensor_info(t->ctx, n->value, &yi);
164 if (rc) return rc;
165 size_t m = (size_t)yi.elements;
166 if (!t->scratch || t->scratch_count / 3 < m) return OMEGA_AD_ERR_SCRATCH;
167 float *sa = t->scratch, *sb = t->scratch + m, *sg = t->scratch + 2 * m;
168 const uint32_t ins[2] = { n->in0, n->in1 };
169 float *dst[2] = { sa, sb };
170 for (int k = 0; k < 2; k++) {
171 OmegaTensor v;
172 rc = omega_tensor_broadcast_to(t->ctx, t->nodes[ins[k]].value, yi.rank, yi.shape, &v);
173 if (rc) return rc;
174 rc = omega_tensor_read_f32(t->ctx, v, dst[k], m);
175 rel(t, v);
176 if (rc) return rc;
177 }
178 rc = omega_tensor_read_f32(t->ctx, n->grad, sg, m);
179 if (rc) return rc;
180 for (size_t i = 0; i < m; i++) {
181 bool to_a = max_routes_to_a(sa[i], sb[i]);
182 float g = sg[i];
183 sa[i] = to_a ? g : 0.0f;
184 sb[i] = to_a ? 0.0f : g;
185 }
186 for (int k = 0; k < 2; k++) {
187 if (!wants(t, ins[k])) continue;
188 OmegaTensor full;
189 rc = omega_tensor_from_f32(t->ctx, yi.rank, yi.shape, dst[k], &full);
190 if (rc) return rc;
191 rc = contribute(t, ins[k], full);
192 if (rc) return rc;
193 }
194 return OMEGA_AD_OK;
195}
196
197/* Gradient of a SUM/MEAN input: g put back on the reduced axis and broadcast
198 * to the input's shape (dense owned copy in *out). */
199static int expand_reduced(OmegaAdTape *t, const OmegaAdNode *n, OmegaTensor *out, uint64_t *axis_len) {
200 OmegaTensorInfo ai, gi;
201 int rc = omega_tensor_info(t->ctx, t->nodes[n->in0].value, &ai);
202 if (!rc) rc = omega_tensor_info(t->ctx, n->grad, &gi);
203 if (rc) return rc;
204 uint64_t kshape[OMEGA_TENSOR_MAX_RANK];
205 ad_restore_axis(ai.shape, ai.rank, n->axis, kshape, ai.rank);
206 OmegaTensor r, b;
207 rc = omega_tensor_reshape(t->ctx, n->grad, ai.rank, kshape, &r);
208 if (rc) return rc;
209 rc = omega_tensor_broadcast_to(t->ctx, r, ai.rank, ai.shape, &b);
210 if (rc) { rel(t, r); return rc; }
211 rc = omega_tensor_contiguous(t->ctx, b, out);
212 rel(t, b);
213 rel(t, r);
214 *axis_len = ai.shape[n->axis];
215 return rc;
216}
217
218static int node_backward(OmegaAdTape *t, const OmegaAdNode *n) {
219 const OmegaTensor g = n->grad;
220 OmegaTensor c = { 0, 0 }, c2 = { 0, 0 }, tmp = { 0, 0 };
221 int rc = OMEGA_AD_OK;
222 switch (n->op) {
223 case OMEGA_AD_LEAF:
224 return OMEGA_AD_OK;
225 case OMEGA_AD_ADD:
226 case OMEGA_AD_SUB:
227 if (wants(t, n->in0)) {
228 rc = omega_tensor_contiguous(t->ctx, g, &c);
229 if (!rc) rc = contribute(t, n->in0, c);
230 if (rc) return rc;
231 }
232 if (wants(t, n->in1)) {
233 if (n->op == OMEGA_AD_ADD) rc = omega_tensor_contiguous(t->ctx, g, &c);
234 else rc = scale(t, g, -1.0f, &c); /* MUT:SUB_NEGATE */
235 if (!rc) rc = contribute(t, n->in1, c);
236 }
237 return rc;
238 case OMEGA_AD_MUL: {
239 if (wants(t, n->in0)) {
240 rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, g, t->nodes[n->in1].value, &c); /* MUT:MUL_OPERAND */
241 if (!rc) rc = contribute(t, n->in0, c);
242 if (rc) return rc;
243 }
244 if (wants(t, n->in1)) {
245 rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, g, t->nodes[n->in0].value, &c);
246 if (!rc) rc = contribute(t, n->in1, c);
247 }
248 return rc;
249 }
250 case OMEGA_AD_DIV: {
251 const OmegaAdNode *nb = &t->nodes[n->in1];
252 if (wants(t, n->in0)) {
253 rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, g, nb->value, &c);
254 if (!rc) rc = contribute(t, n->in0, c);
255 if (rc) return rc;
256 }
257 if (wants(t, n->in1)) {
258 /* gb = -(g * (y / b)) */
259 rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, n->value, nb->value, &tmp); /* MUT:DIV_FORMULA */
260 if (rc) return rc;
261 rc = omega_tensor_binary(t->ctx, OMEGA_TB_MUL, g, tmp, &c2); /* MUT:DIV_FORMULA */
262 rel(t, tmp);
263 if (rc) return rc;
264 rc = scale(t, c2, -1.0f, &c); /* MUT:DIV_B_SIGN */
265 rel(t, c2);
266 if (!rc) rc = contribute(t, n->in1, c);
267 }
268 return rc;
269 }
270 case OMEGA_AD_MAX:
271 return backward_max(t, n);
272 case OMEGA_AD_SQRT:
273 if (!wants(t, n->in0)) return OMEGA_AD_OK;
274 rc = omega_tensor_binary(t->ctx, OMEGA_TB_ADD, n->value, n->value, &tmp); /* MUT:SQRT_TWICE */
275 if (rc) return rc;
276 rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, g, tmp, &c);
277 rel(t, tmp);
278 if (!rc) rc = contribute(t, n->in0, c);
279 return rc;
280 case OMEGA_AD_MATMUL: {
281 const OmegaAdNode *na = &t->nodes[n->in0], *nb = &t->nodes[n->in1];
282 if (wants(t, n->in0)) {
283 /* gA = g @ B^T */
284 rc = omega_tensor_transpose(t->ctx, nb->value, &tmp);
285 if (rc) return rc;
286 rc = omega_tensor_matmul(t->ctx, g, tmp, &c); /* MUT:MATMUL_TRANSPOSE */
287 rel(t, tmp);
288 if (!rc) rc = contribute(t, n->in0, c);
289 if (rc) return rc;
290 }
291 if (wants(t, n->in1)) {
292 /* gB = A^T @ g */
293 rc = omega_tensor_transpose(t->ctx, na->value, &tmp);
294 if (rc) return rc;
295 rc = omega_tensor_matmul(t->ctx, tmp, g, &c);
296 rel(t, tmp);
297 if (!rc) rc = contribute(t, n->in1, c);
298 }
299 return rc;
300 }
301 case OMEGA_AD_TRANSPOSE:
302 if (!wants(t, n->in0)) return OMEGA_AD_OK;
303 rc = omega_tensor_transpose(t->ctx, g, &tmp);
304 if (rc) return rc;
305 rc = omega_tensor_contiguous(t->ctx, tmp, &c);
306 rel(t, tmp);
307 if (!rc) rc = contribute(t, n->in0, c);
308 return rc;
309 case OMEGA_AD_BROADCAST:
310 if (!wants(t, n->in0)) return OMEGA_AD_OK;
311 rc = omega_tensor_contiguous(t->ctx, g, &c);
312 if (!rc) rc = contribute(t, n->in0, c);
313 return rc;
314 case OMEGA_AD_SUM:
315 case OMEGA_AD_MEAN: {
316 if (!wants(t, n->in0)) return OMEGA_AD_OK;
317 uint64_t len = 0;
318 rc = expand_reduced(t, n, &c2, &len);
319 if (rc) return rc;
320 if (n->op == OMEGA_AD_SUM) return contribute(t, n->in0, c2);
321 OmegaTensor nt;
322 rc = scalar(t, (float)len, &nt); /* MUT:MEAN_DIVISOR */
323 if (rc) { rel(t, c2); return rc; }
324 rc = omega_tensor_binary(t->ctx, OMEGA_TB_DIV, c2, nt, &c);
325 rel(t, nt);
326 rel(t, c2);
327 if (!rc) rc = contribute(t, n->in0, c);
328 return rc;
329 }
330 default:
331 return OMEGA_AD_ERR_BAD_ARGS;
332 }
333}
334
335/* ---- public API ------------------------------------------------------------------ */
336
337int omega_ad_tape_init(OmegaAdTape *t, OmegaTensorCtx *ctx, OmegaAdNode *nodes, uint32_t capacity,
338 float *scratch, size_t scratch_count) {
339 if (!t || !ctx || !nodes || capacity == 0 || capacity == OMEGA_AD_NONE ||
340 (!scratch && scratch_count)) return OMEGA_AD_ERR_BAD_ARGS;
341 memset(t, 0, sizeof(*t));
342 t->ctx = ctx;
343 t->nodes = nodes;
344 t->capacity = capacity;
345 t->scratch = scratch;
346 t->scratch_count = scratch_count;
347 return OMEGA_AD_OK;
348}
349
350void omega_ad_tape_release(OmegaAdTape *t) {
351 if (!t || !t->nodes || !t->ctx) return;
352 for (uint32_t i = t->count; i-- > 0;) {
353 OmegaAdNode *n = &t->nodes[i];
354 if (n->has_grad) rel(t, n->grad);
355 if (n->owns_value) rel(t, n->value);
356 n->has_grad = false;
357 n->owns_value = false;
358 }
359 t->count = 0;
360 t->backward_done = false;
361 t->failed = false;
362}
363
364int omega_ad_leaf(OmegaAdTape *t, OmegaTensor value, bool requires_grad, uint32_t *id) {
365 int rc = can_record(t);
366 if (rc) return rc;
367 if (!id) return OMEGA_AD_ERR_BAD_ARGS;
368 OmegaTensorInfo vi;
369 rc = omega_tensor_info(t->ctx, value, &vi);
370 if (rc) return rc;
371 if (vi.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE;
372 *id = push(t, OMEGA_AD_LEAF, OMEGA_AD_NONE, OMEGA_AD_NONE, 0, false, requires_grad, false, value);
373 return OMEGA_AD_OK;
374}
375
376static int record_op(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t b, uint32_t axis,
377 bool keepdims, OmegaTensor value, uint32_t *id) {
378 bool rg = t->nodes[a].requires_grad || (b != OMEGA_AD_NONE && t->nodes[b].requires_grad);
379 *id = push(t, op, a, b, axis, keepdims, rg, true, value);
380 return OMEGA_AD_OK;
381}
382
383int omega_ad_binary(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t b, uint32_t *id) {
384 int rc = can_record(t);
385 if (rc) return rc;
386 if (!id || !node_ok(t, a) || !node_ok(t, b)) return OMEGA_AD_ERR_BAD_ARGS;
387 OmegaTensorBinaryOp bop;
388 switch (op) {
389 case OMEGA_AD_ADD: bop = OMEGA_TB_ADD; break;
390 case OMEGA_AD_SUB: bop = OMEGA_TB_SUB; break;
391 case OMEGA_AD_MUL: bop = OMEGA_TB_MUL; break;
392 case OMEGA_AD_DIV: bop = OMEGA_TB_DIV; break;
393 case OMEGA_AD_MAX: bop = OMEGA_TB_MAX; break;
394 default: return OMEGA_AD_ERR_BAD_ARGS;
395 }
396 OmegaTensor y;
397 rc = omega_tensor_binary(t->ctx, bop, t->nodes[a].value, t->nodes[b].value, &y);
398 if (rc) return rc;
399 return record_op(t, op, a, b, 0, false, y, id);
400}
401
402int omega_ad_sqrt(OmegaAdTape *t, uint32_t a, uint32_t *id) {
403 int rc = can_record(t);
404 if (rc) return rc;
405 if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS;
406 OmegaTensor y;
407 rc = omega_tensor_unary(t->ctx, OMEGA_TU_SQRT, t->nodes[a].value, &y);
408 if (rc) return rc;
409 return record_op(t, OMEGA_AD_SQRT, a, OMEGA_AD_NONE, 0, false, y, id);
410}
411
412int omega_ad_matmul(OmegaAdTape *t, uint32_t a, uint32_t b, uint32_t *id) {
413 int rc = can_record(t);
414 if (rc) return rc;
415 if (!id || !node_ok(t, a) || !node_ok(t, b)) return OMEGA_AD_ERR_BAD_ARGS;
416 OmegaTensor y;
417 rc = omega_tensor_matmul(t->ctx, t->nodes[a].value, t->nodes[b].value, &y);
418 if (rc) return rc;
419 return record_op(t, OMEGA_AD_MATMUL, a, b, 0, false, y, id);
420}
421
422int omega_ad_transpose(OmegaAdTape *t, uint32_t a, uint32_t *id) {
423 int rc = can_record(t);
424 if (rc) return rc;
425 if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS;
426 OmegaTensor v, y;
427 rc = omega_tensor_transpose(t->ctx, t->nodes[a].value, &v);
428 if (rc) return rc;
429 rc = omega_tensor_contiguous(t->ctx, v, &y);
430 rel(t, v);
431 if (rc) return rc;
432 return record_op(t, OMEGA_AD_TRANSPOSE, a, OMEGA_AD_NONE, 0, false, y, id);
433}
434
435int omega_ad_broadcast(OmegaAdTape *t, uint32_t a, uint32_t rank, const uint64_t *shape, uint32_t *id) {
436 int rc = can_record(t);
437 if (rc) return rc;
438 if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS;
439 OmegaTensor v, y;
440 rc = omega_tensor_broadcast_to(t->ctx, t->nodes[a].value, rank, shape, &v);
441 if (rc) return rc;
442 rc = omega_tensor_contiguous(t->ctx, v, &y);
443 rel(t, v);
444 if (rc) return rc;
445 return record_op(t, OMEGA_AD_BROADCAST, a, OMEGA_AD_NONE, 0, false, y, id);
446}
447
448int omega_ad_reduce(OmegaAdTape *t, OmegaAdOp op, uint32_t a, uint32_t axis, bool keepdims, uint32_t *id) {
449 int rc = can_record(t);
450 if (rc) return rc;
451 if (!id || !node_ok(t, a)) return OMEGA_AD_ERR_BAD_ARGS;
452 OmegaTensorReduceOp rop;
453 if (op == OMEGA_AD_SUM) rop = OMEGA_TR_SUM;
454 else if (op == OMEGA_AD_MEAN) rop = OMEGA_TR_MEAN;
455 else return OMEGA_AD_ERR_BAD_ARGS;
456 OmegaTensor y;
457 rc = omega_tensor_reduce(t->ctx, rop, t->nodes[a].value, axis, keepdims, &y);
458 if (rc) return rc;
459 return record_op(t, op, a, OMEGA_AD_NONE, axis, keepdims, y, id);
460}
461
462int omega_ad_value(const OmegaAdTape *t, uint32_t id, OmegaTensor *out) {
463 if (!out || !node_ok(t, id)) return OMEGA_AD_ERR_BAD_ARGS;
464 *out = t->nodes[id].value;
465 return OMEGA_AD_OK;
466}
467
468int omega_ad_scratch_need(const OmegaAdTape *t, size_t *floats) {
469 if (!t || !t->nodes || !floats) return OMEGA_AD_ERR_BAD_ARGS;
470 size_t need = 0;
471 for (uint32_t i = 0; i < t->count; i++) {
472 if (t->nodes[i].op != OMEGA_AD_MAX) continue;
473 OmegaTensorInfo yi;
474 int rc = omega_tensor_info(t->ctx, t->nodes[i].value, &yi);
475 if (rc) return rc;
476 if (yi.elements > SIZE_MAX / 3) return OMEGA_TENSOR_ERR_CAPACITY;
477 if ((size_t)yi.elements * 3 > need) need = (size_t)yi.elements * 3;
478 }
479 *floats = need;
480 return OMEGA_AD_OK;
481}
482
483/* Runs the walk once the root's seed gradient is in place. */
484static int run_backward(OmegaAdTape *t, uint32_t root) {
485 for (uint32_t i = root + 1; i-- > 0;) { /* MUT:TAPE_WALK */
486 const OmegaAdNode *n = &t->nodes[i];
487 if (!n->has_grad || n->op == OMEGA_AD_LEAF) continue;
488 int rc = node_backward(t, n);
489 if (rc) return rc;
490 }
491 return OMEGA_AD_OK;
492}
493
494static int begin_backward(OmegaAdTape *t, uint32_t root, OmegaTensorInfo *ri) {
495 if (!t || !t->ctx || !t->nodes) return OMEGA_AD_ERR_BAD_ARGS;
496 if (t->backward_done || t->failed) return OMEGA_AD_ERR_STATE;
497 if (!node_ok(t, root)) return OMEGA_AD_ERR_BAD_ARGS;
498 if (!t->nodes[root].requires_grad) return OMEGA_AD_ERR_NO_GRAD;
499 size_t need = 0;
500 int rc = omega_ad_scratch_need(t, &need);
501 if (rc) return rc;
502 if (need > t->scratch_count) return OMEGA_AD_ERR_SCRATCH;
503 return omega_tensor_info(t->ctx, t->nodes[root].value, ri);
504}
505
506static int finish_backward(OmegaAdTape *t, uint32_t root, OmegaTensor seed_owned) {
507 OmegaAdNode *r = &t->nodes[root];
508 r->grad = seed_owned;
509 r->has_grad = true;
510 t->backward_done = true;
511 int rc = run_backward(t, root);
512 if (rc) t->failed = true;
513 return rc;
514}
515
516int omega_ad_backward(OmegaAdTape *t, uint32_t root) {
517 OmegaTensorInfo ri;
518 int rc = begin_backward(t, root, &ri);
519 if (rc) return rc;
520 if (ri.elements != 1) return OMEGA_AD_ERR_SHAPE;
521 const float one = 1.0f;
522 OmegaTensor seed;
523 rc = omega_tensor_from_f32(t->ctx, ri.rank, ri.shape, &one, &seed);
524 if (rc) return rc;
525 return finish_backward(t, root, seed);
526}
527
528int omega_ad_backward_seed(OmegaAdTape *t, uint32_t root, OmegaTensor seed) {
529 OmegaTensorInfo ri, si;
530 int rc = begin_backward(t, root, &ri);
531 if (rc) return rc;
532 rc = omega_tensor_info(t->ctx, seed, &si);
533 if (rc) return rc;
534 if (si.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE;
535 if (!same_shape(&ri, &si)) return OMEGA_AD_ERR_SHAPE;
536 OmegaTensor s;
537 rc = omega_tensor_contiguous(t->ctx, seed, &s);
538 if (rc) return rc;
539 return finish_backward(t, root, s);
540}
541
542int omega_ad_grad(const OmegaAdTape *t, uint32_t id, OmegaTensor *out) {
543 if (!out || !node_ok(t, id)) return OMEGA_AD_ERR_BAD_ARGS;
544 if (t->failed) return OMEGA_AD_ERR_STATE;
545 if (!t->nodes[id].has_grad) return OMEGA_AD_ERR_NO_GRAD;
546 *out = t->nodes[id].grad;
547 return OMEGA_AD_OK;
548}
549
550int omega_ad_grad_read_f32(const OmegaAdTape *t, uint32_t id, float *out, size_t count) {
551 OmegaTensor g;
552 int rc = omega_ad_grad(t, id, &g);
553 if (rc) return rc;
554 if (!out) return OMEGA_AD_ERR_BAD_ARGS;
555 OmegaTensorInfo gi;
556 rc = omega_tensor_info(t->ctx, g, &gi);
557 if (rc) return rc;
558 if (gi.elements != count) return OMEGA_AD_ERR_COUNT;
559 return omega_tensor_read_f32(t->ctx, g, out, count);
560}
561
562int omega_ad_grads_flatten(const OmegaAdTape *t, const uint32_t *ids, uint32_t n, float *out,
563 size_t count) {
564 if (!t || !ids || !out || n == 0) return OMEGA_AD_ERR_BAD_ARGS;
565 size_t total = 0;
566 for (uint32_t k = 0; k < n; k++) {
567 OmegaTensor g;
568 OmegaTensorInfo gi;
569 int rc = omega_ad_grad(t, ids[k], &g);
570 if (!rc) rc = omega_tensor_info(t->ctx, g, &gi);
571 if (rc) return rc;
572 if (gi.elements > count - total) return OMEGA_AD_ERR_COUNT;
573 total += (size_t)gi.elements;
574 }
575 if (total != count) return OMEGA_AD_ERR_COUNT;
576 size_t off = 0;
577 for (uint32_t k = 0; k < n; k++) {
578 OmegaTensor g;
579 OmegaTensorInfo gi;
580 int rc = omega_ad_grad(t, ids[k], &g);
581 if (!rc) rc = omega_tensor_info(t->ctx, g, &gi);
582 if (!rc) rc = omega_tensor_read_f32(t->ctx, g, out + off, (size_t)gi.elements);
583 if (rc) return rc;
584 off += (size_t)gi.elements;
585 }
586 return OMEGA_AD_OK;
587}