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#136 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/79254c872dd82da5.bundle -o 79254c872dd82da5.bundle git fetch 79254c872dd82da5.bundle refs/pull/136/head
Provenance
github-import 1
aien-dev/omega-mv
136
15946830aa096c9cf47eeeaff2dd240083276b43
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":136,"url":"https://github.com/aien-dev/omega-mv/pull/136","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:29Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index f45ebab02..58151530c 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -27,6 +27,8 @@ name: Host suites 2 # test-r16-negative-mutants 5 min (Spark: 4.3 min) # argus : test-argus-runtime test-machine-identity-argus # numeric2 : test-numeric-reduce-cpu test-divsqrt-host 6 s +# tensor : test-tensor (M20 CPU tier, plain + ASan/UBSan + default-build +# no-test-hook nm check) test-tensor-mutations # Pinned dependencies are read from physics.lock, aienos.lock and argus.lock. # # Deliberately NOT here: @@ -101,6 +103,7 @@ jobs: runtime: ${{ steps.f.outputs.runtime }} argus: ${{ steps.f.outputs.argus }} numeric2: ${{ steps.f.outputs.numeric2 }} + tensor: ${{ steps.f.outputs.tensor }} steps: - uses: actions/checkout@v4 with: @@ -143,6 +146,7 @@ jobs: sel runtime "$core|^src/(runtime|fabric)/|^tests/runtime/|^mk/fabric\.mk$|^tests/(r15_receipt_test\.sh|r16_[a-z_]+/)|^tools/(r15_|r16_|omegatool\.c)|^spec/r16-|^docs/r16-|^evidence/R15/|^(physics|aienos)\.lock$" sel argus "^src/runtime/|^tests/runtime/|^tests/bench_rx_argus\.c$|^mk/machine-identity\.mk$|^src/(sha256|omega_evidence)\.|^(physics|aienos|argus)\.lock$" sel numeric2 "^tests/(test_omega_reduce|test_omega_divsqrt_gb10)\.c$|^tests/numeric_oracle\.h$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" + sel tensor "^src/tensor/|^tests/test_omega_tensor\.c$|^tools/tensor_mutations\.sh$|^mk/tensor\.mk$|^src/(omega_numeric|omega_blackwell_(encoder|codegen|matmul|qmd)|sha256)" visor: needs: changes @@ -385,3 +389,18 @@ jobs: fetch-depth: 0 - name: Reduce CPU tier and GB10 div/sqrt sequences on the host (CPU only) run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-numeric-reduce-cpu test-divsqrt-host + + tensor: + needs: changes + if: needs.changes.outputs.tensor == 'true' + runs-on: ubuntu-24.04-arm + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - name: M20 OMEGA_TENSOR CPU tier (plain + ASan/UBSan, test hook absent from default build; CPU only) + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-tensor + - name: M20 OMEGA_TENSOR mutation sweep (each rule must turn the tests red) + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-tensor-mutations diff --git a/docs/tensor/.crumb b/docs/tensor/.crumb new file mode 100644 index 000000000..31cee0a8a --- /dev/null +++ b/docs/tensor/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "docs/tensor", + "layer": "docs/tensor", + "purpose": "M20 OMEGA_TENSOR spec and qualification checklist" +} diff --git a/docs/tensor/M20_OMEGA_TENSOR.md b/docs/tensor/M20_OMEGA_TENSOR.md new file mode 100644 index 000000000..9e32f298b --- /dev/null +++ b/docs/tensor/M20_OMEGA_TENSOR.md @@ -0,0 +1,129 @@ +# M20 OMEGA_TENSOR: semantic layer and CPU realization + +Status 2026-10-01: **M20 NOT QUALIFIED.** The semantic layer and the CPU +realization exist and pass their CPU tests. E1 (numeric closure) PASSED on +main 4863803 (receipt merged in omega#177). M20 qualification is blocked on +GB10 parity, which has not run, crash-safe storage and a receipt. + +Plan source: `aien-architecture/CURRENT_EXECUTION_PLAN.md`, section +"E2. M20 OMEGA_TENSOR". "M20" here means OMEGA_TENSOR only; the runtime +composition program is COMPOSITION-1/2, not M20. + +## Files + +| File | Role | +|---|---| +| `src/tensor/omega_tensor.h` | The meaning: dtypes, shapes, strides, views, identity, storage lifetime, every op's definition, the realization table | +| `src/tensor/omega_tensor.c` | Semantic layer: checks, descriptor arithmetic, data movement. No floating-point arithmetic | +| `src/tensor/omega_tensor_cpu.c` | CPU realization table (E1 CPU tier) | +| `src/tensor/omega_tensor_reduce_seam.{h,c}` | The single seam to the E1 reduction contract (PR #134) | +| `tests/test_omega_tensor.c` | CPU tests against an independent naive reference | +| `tools/tensor_mutations.sh` | Source mutation sweep | +| `mk/tensor.mk` | `make test-tensor`, `make test-tensor-mutations`, `make test-tensor-e1-reduce` | + +## Definitions + +- **Tensor**: immutable. dtype, rank 0..8, every dimension >= 1, at most + 2^30 elements. No API writes into an existing tensor: creation copies the + caller's data, every op returns a new tensor, views share storage + read-only. +- **Dtypes**: FP32 is the arithmetic dtype. F16 and BF16 are storage dtypes; + arithmetic on them is refused. `omega_tensor_cast` converts with the E1 ops + (F32_TO_F16 / F32_TO_BF16 RNE, F16_TO_F32 / BF16_TO_F32 exact). + F16 <-> BF16 directly is refused. +- **Strides**: in elements, >= 0. Zero only in broadcast views. Negative + strides are not defined. +- **Value identity** (`omega_tensor_value_id`): SHA-256 over + `OMEGA_TENSOR_VALUE_ID_V1`, dtype, rank, shape and the elements in logical + row-major order, every NaN canonicalized (NaN payload is not semantic), + -0 and +0 distinct. Strides, offset and storage are not part of it: a + transposed view and its dense copy have the same value id. +- **Storage identity**: storage slot + 64-bit generation. +- **View identity** (`omega_tensor_view_id`): storage identity + parent + tensor + dtype + offset + shape + strides. +- **Storage lifetime**: releasing bumps the slot generation; any access + through an older handle, including every view of released storage, returns + `OMEGA_TENSOR_ERR_STALE` and computes nothing. A reused slot always has a + new generation (no ABA). A slot whose generation reaches UINT64_MAX is + retired forever instead of wrapping. Releasing a view releases only the + view descriptor; releasing the owning tensor releases its storage too. +- **Broadcasting** (numpy rules): align at the trailing axis, missing leading + axes count as 1, per axis sizes must be equal or one of them 1; result is + the larger. Otherwise `OMEGA_TENSOR_ERR_SHAPE`. +- **Views**: permute / transpose (last two axes), slice (start < stop <= dim, + step >= 1), reshape (view only if row-major contiguous, else + `OMEGA_TENSOR_ERR_NOT_CONTIGUOUS`; `omega_tensor_contiguous` makes the copy + explicit), broadcast_to (zero strides). Every view is bounds checked + against its storage when made. +- **Elementwise**: SQRT; ADD, SUB, MUL, DIV (omega_math_div), MIN, MAX, the + 14 compare-select predicates (out = P(a, b) ? a : b); FMA (a*b+c rounded + once). All E1 scalar ops, all operands broadcast together. +- **Reductions** along one axis, SUM / MAX / MIN / MEAN, keepdims optional, + order `RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL` + (identical string to E1 WP-D, PR #134). +- **Matmul**: `[M,K] x [K,N]`, any M, N, K >= 1, and batched + `[...,M,K] x [...,K,N]` with broadcast batch axes. Declared order + `OMEGA_TENSOR_MATMUL_DECLARED_ORDER`: each product rounded once (FMUL RNE, + no fusion), then the E1 SUM tree above over k. A Tensor Core / FFMA-chain + realization computes different bits and must declare its own bounded + contract. +- **Meaning vs realization**: `OmegaTensorRealization` is a function table + (elementwise E1 op over dense buffers, reduce over a dense row, declared + order string). The semantic layer refuses a table whose order string is not + the declared one. CPU fills it now; GB10 SIMT / Tensor Core fill it later. + No GB10 code is referenced by the semantic layer. + +### What "beyond the old narrow kernel" means + +The old M18 tensor matmul (`src/omega_blackwell_matmul.*`) takes raw +contiguous buffers, caps M, K, N at 1024, supports INT32 / FP16 / BF16 inputs +with no declared FP32 accumulation order, and has no strides, views, +broadcast or batch. `src/omega_matvec.*` is a uint64 matrix-vector with fixed +maximum shapes. M20 here: any shape up to 2^30 elements, FP32 with a named +accumulation order, strided / transposed / sliced / broadcast operands, +broadcast batches. The GB10 realization of this general matmul does not +exist yet. + +## Reduction seam + +The seam calls `omega_reduce_cpu` from `src/omega_numeric_reduce.h` (E1 WP-D, +omega #134, merged c54d492); a `_Static_assert` and a runtime check pin the +order string. Before #134 merged, a local copy of the order was cross-checked +bit-identical against #134 head 6da80bf (same KAT value id); that copy is now +removed. Order and padding mutations are caught by the E1 WP-D suite. + +## Qualification checklist (plan E2) + +| Item | Status | Evidence | +|---|---|---| +| Shape / type checks | PASS (CPU) | `test-tensor`: rank, zero dim, size overflow, dtype, K mismatch, axis, perm, unknown op refusals | +| Broadcasting | PASS (CPU) | 8 shape cases incl. 3 refusals; 5 value cases x 20 binary ops vs index-arithmetic reference; broadcast_to zero strides | +| Views / strides | PASS (CPU) | permute, slice with steps, transpose of slice == slice of transpose, view of view of view, zero-stride transpose, reshape refusals, bounds | +| Generation safety | PASS (CPU) | use after release, double release, stale view of released storage (read, info, op, matmul, view, id), no ABA on slot reuse, UINT64_MAX retirement | +| Immutability / no in-place | PASS (CPU) | no write API exists; input value ids unchanged by every op; outputs never alias inputs | +| CPU parity | PASS (CPU) | every op bit-exact vs independent reference (omega_ref_*, omega_ieee_div/sqrt, omega_ref_ffma_int, own tree copy), random + all special pairs | +| General matmul | PASS (CPU) | 1x1x1, 7x13x5, 64x64x64, 129x3x257, 3x1025x2, 1x33x1, strided views, batched broadcast [2,1,3,4]x[5,4,6] | +| Reductions | PASS (CPU) | lengths 1..32769 across tile/level edges, every axis of [3,37,5], keepdims, view vs copy, -0 sum | +| Mutation / refusal | PASS (CPU) | `test-tensor-mutations`: 5/5 source mutations caught; 2 in-process mutant realizations (sequential sum, FFMA chain) caught; wrong order string refused | +| Determinism | PASS (CPU) | repeated run same value id; frozen KAT value id in the test | +| Test-only hook not in library | PASS (CPU) | `omega_tensor_test_set_storage_generation` exists only under `-DOMEGA_TENSOR_TEST_HOOKS` (test builds in `mk/tensor.mk`); `test-tensor-no-hooks` (run by `test-tensor`) builds the default objects and fails if `nm` shows the symbol | +| CI | WIRED | `host-suites-2.yml` job `tensor`: `test-tensor` + `test-tensor-mutations` on the AArch64 hosted runner (not the Spark, not a qualification) | +| GB10 parity | NOT_RUN | no GB10 realization table yet; no chip run in this work | +| GB10 general matmul (Tensor Core beyond narrow K/tile) | MISSING_IMPLEMENTATION | | +| Crash-safe storage lifetime | MISSING_IMPLEMENTATION | storage is in-process memory only; no persistence or crash recovery | +| Reproducible receipt | MISSING_IMPLEMENTATION | no content-addressed receipt writer for this gate yet | +| E1 numeric closure | PASS (on main) | E1 PASSED on main 4863803; receipt merged in omega#177 | + +**M20 verdict: not qualified.** GB10 parity NOT_RUN; crash-safe storage +lifetime and receipt MISSING_IMPLEMENTATION. + +## Open seams + +1. Reductions: DONE, the seam calls `omega_reduce_cpu` (#134 merged). +2. Transcendentals (#127): the E1 bounded contract is merged (E1 PASS on + main 4863803), so adding EXP / LOG / ... to `OmegaTensorUnaryOp` is a + follow-up, not blocked. +3. GB10 realization table: elementwise through the E1 SIMT ops, reduce + through `omega_reduce_gb10`, matmul either products + tree (bit-exact to + this contract) or a Tensor Core path with its own declared bounded + contract. diff --git a/mk/tensor.mk b/mk/tensor.mk new file mode 100644 index 000000000..8af258b76 --- /dev/null +++ b/mk/tensor.mk @@ -0,0 +1,64 @@ +# M20 OMEGA_TENSOR (docs/tensor/M20_OMEGA_TENSOR.md): semantic tensor layer + +# CPU realization. Files under src/tensor/ and tests/test_omega_tensor.c. +# Picked up by `-include mk/*.mk`. Not part of `all` or `test`. CPU only: +# opens no device, never touches the GB10. +# +# test-tensor CPU tests plain and with ASan/UBSan, then +# test-tensor-no-hooks +# test-tensor-no-hooks builds src/tensor/*.c with the default (library) +# flags and requires, via nm, that the test-only +# hook omega_tensor_test_set_storage_generation is +# absent. Only the test binaries define +# OMEGA_TENSOR_TEST_HOOKS. +# test-tensor-mutations applies each MUT: source mutation in a scratch copy +# and proves test-tensor's binary then fails +# test-tensor-e1-reduce alias of test-tensor (the reduction seam always +# calls omega_reduce_cpu, E1 WP-D, omega #134) +ifndef TENSOR_MK +TENSOR_MK := 1 +.PHONY: test-tensor test-tensor-no-hooks test-tensor-mutations test-tensor-e1-reduce +TENSOR_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -ffp-contract=off -Isrc -Isrc/tensor \ + -DOMEGA_NUMERIC_CPU_ONLY +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 +TENSOR_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 +TENSOR_HDRS = src/tensor/omega_tensor.h src/tensor/omega_tensor_reduce_seam.h src/omega_numeric_reduce.h src/omega_numeric.h src/sha256.h +# Test builds only: compiles the test-only storage-generation hook. +TENSOR_TEST_FLAGS = -DOMEGA_TENSOR_TEST_HOOKS +TENSOR_HOOK_SYMS = omega_tensor_test_set_storage_generation + +$(OUT_DIR)/test_omega_tensor: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) + @mkdir -p $(OUT_DIR) + gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O2 -o $@ tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) + +$(OUT_DIR)/test_omega_tensor_asan: tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) $(TENSOR_HDRS) + @mkdir -p $(OUT_DIR) + gcc $(TENSOR_CFLAGS) $(TENSOR_TEST_FLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ + -o $@ tests/test_omega_tensor.c $(TENSOR_SRCS) $(TENSOR_DEPS) + +test-tensor: $(OUT_DIR)/test_omega_tensor $(OUT_DIR)/test_omega_tensor_asan + ./$(OUT_DIR)/test_omega_tensor + ./$(OUT_DIR)/test_omega_tensor_asan + $(MAKE) --no-print-directory test-tensor-no-hooks + +# Default (library) build of the tensor sources: no OMEGA_TENSOR_TEST_HOOKS. +# Fails if any test-only hook symbol is defined or referenced in the objects. +test-tensor-no-hooks: src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c $(TENSOR_HDRS) + @mkdir -p $(OUT_DIR)/tensor-lib + gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor.o src/tensor/omega_tensor.c + gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor_cpu.o src/tensor/omega_tensor_cpu.c + gcc $(TENSOR_CFLAGS) -O2 -c -o $(OUT_DIR)/tensor-lib/omega_tensor_reduce_seam.o src/tensor/omega_tensor_reduce_seam.c + @nm $(OUT_DIR)/tensor-lib/omega_tensor.o | grep -q " T omega_tensor_ctx_create\b" \ + || { echo "test-tensor-no-hooks: FAIL (nm sanity: omega_tensor_ctx_create not found)"; exit 1; } + @for s in $(TENSOR_HOOK_SYMS); do \ + if nm $(OUT_DIR)/tensor-lib/*.o | grep -q "\b$$s\b"; then \ + echo "test-tensor-no-hooks: FAIL ($$s present in default build)"; exit 1; fi; \ + done; echo "test-tensor-no-hooks: PASS (test-only hook absent from default build)" + +test-tensor-mutations: + tools/tensor_mutations.sh + +# Kept as an alias: the seam now always calls omega_reduce_cpu (E1 WP-D, #134 merged). +test-tensor-e1-reduce: test-tensor +endif diff --git a/src/tensor/.crumb b/src/tensor/.crumb new file mode 100644 index 000000000..f3e5491a1 --- /dev/null +++ b/src/tensor/.crumb @@ -0,0 +1,6 @@ +{ + "schema_version": "1.0.0", + "name": "src/tensor", + "layer": "src/tensor", + "purpose": "M20 OMEGA_TENSOR: immutable tensor semantic layer, views, generation-checked storage, CPU realization over E1 (not qualified)" +} diff --git a/src/tensor/omega_tensor.c b/src/tensor/omega_tensor.c new file mode 100644 index 000000000..804a60219 --- /dev/null +++ b/src/tensor/omega_tensor.c @@ -0,0 +1,799 @@ +/* + * M20 OMEGA_TENSOR semantic layer (see omega_tensor.h). This file holds the + * meaning: shapes, strides, views, storage lifetime, identity, and the + * definition of each op as index movement plus calls into the realization. + * It performs no floating-point arithmetic of its own. + */ +#include "omega_tensor.h" + +#include <stdlib.h> +#include <string.h> + +#include "sha256.h" + +typedef struct { + uint64_t gen; + bool live; + bool retired; /* generation reached UINT64_MAX: never reused */ + OmegaDType dtype; + uint64_t elems; + void *data; +} StorageSlot; + +typedef struct { + uint64_t gen; + bool live; + bool retired; + bool owns_storage; + OmegaTensorInfo info; +} TensorSlot; + +struct OmegaTensorCtx { + uint32_t cap; + StorageSlot *st; + TensorSlot *ts; + const OmegaTensorRealization *real; + int last_numeric; +}; + +size_t omega_dtype_size(OmegaDType dt) { + switch (dt) { + case OMEGA_DT_F32: return 4; + case OMEGA_DT_F16: + case OMEGA_DT_BF16: return 2; + default: return 0; + } +} + +/* ---- generations ------------------------------------------------------- */ + +static void bump_generation(uint64_t *gen, bool *retired) { + if (*gen == UINT64_MAX) *retired = true; /* never wrap */ + else (*gen)++; /* MUT:RELEASE_BUMP */ +} + +int omega_tensor_ctx_create(uint32_t capacity, const OmegaTensorRealization *real, + OmegaTensorCtx **out) { + if (!out || capacity == 0 || !real) return OMEGA_TENSOR_ERR_BAD_ARGS; + *out = NULL; + if (!real->name || !real->elementwise || !real->reduce || !real->reduce_order || + strcmp(real->reduce_order, OMEGA_TENSOR_REDUCE_DECLARED_ORDER) != 0) + return OMEGA_TENSOR_ERR_REALIZATION; + OmegaTensorCtx *c = calloc(1, sizeof(*c)); + if (!c) return OMEGA_TENSOR_ERR_CAPACITY; + c->st = calloc(capacity, sizeof(StorageSlot)); + c->ts = calloc(capacity, sizeof(TensorSlot)); + if (!c->st || !c->ts) { free(c->st); free(c->ts); free(c); return OMEGA_TENSOR_ERR_CAPACITY; } + for (uint32_t i = 0; i < capacity; i++) { c->st[i].gen = 1; c->ts[i].gen = 1; } + c->cap = capacity; + c->real = real; + *out = c; + return OMEGA_TENSOR_OK; +} + +void omega_tensor_ctx_destroy(OmegaTensorCtx *ctx) { + if (!ctx) return; + for (uint32_t i = 0; i < ctx->cap; i++) free(ctx->st[i].data); + free(ctx->st); + free(ctx->ts); + free(ctx); +} + +int omega_tensor_last_numeric_error(const OmegaTensorCtx *ctx) { return ctx ? ctx->last_numeric : 0; } + +#ifdef OMEGA_TENSOR_TEST_HOOKS /* test build only, see omega_tensor.h */ +int omega_tensor_test_set_storage_generation(OmegaTensorCtx *ctx, uint32_t slot, uint64_t gen) { + if (!ctx || slot >= ctx->cap || gen == 0) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (ctx->st[slot].live || ctx->st[slot].retired) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (gen <= ctx->st[slot].gen) return OMEGA_TENSOR_ERR_BAD_ARGS; /* forward only: a rollback would revive stale handles (Codex) */ + ctx->st[slot].gen = gen; + return OMEGA_TENSOR_OK; +} +#endif + +static StorageSlot *storage_get(const OmegaTensorCtx *ctx, OmegaStorageHandle h) { + if (h.slot >= ctx->cap) return NULL; + StorageSlot *s = &ctx->st[h.slot]; + if (!s->live || s->gen != h.generation) return NULL; /* MUT:STORAGE_GEN_CHECK */ + return s; +} + +bool omega_tensor_storage_valid(const OmegaTensorCtx *ctx, OmegaStorageHandle s) { + return ctx && storage_get(ctx, s) != NULL; +} + +/* Tensor descriptor lookup; also requires its storage to be valid. */ +static int tensor_get(const OmegaTensorCtx *ctx, OmegaTensor t, TensorSlot **ts, StorageSlot **st) { + if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (t.slot >= ctx->cap) return OMEGA_TENSOR_ERR_STALE; + TensorSlot *x = &ctx->ts[t.slot]; + if (!x->live || x->gen != t.generation) return OMEGA_TENSOR_ERR_STALE; + StorageSlot *s = storage_get(ctx, x->info.storage); + if (!s) return OMEGA_TENSOR_ERR_STALE; + if (ts) *ts = x; + if (st) *st = s; + return OMEGA_TENSOR_OK; +} + +static int storage_alloc(OmegaTensorCtx *ctx, OmegaDType dt, uint64_t elems, OmegaStorageHandle *h) { + size_t es = omega_dtype_size(dt); + if (!es || elems == 0 || elems > OMEGA_TENSOR_MAX_ELEMS) return OMEGA_TENSOR_ERR_CAPACITY; + for (uint32_t i = 0; i < ctx->cap; i++) { + StorageSlot *s = &ctx->st[i]; + if (s->live || s->retired) continue; + void *d = calloc((size_t)elems, es); + if (!d) return OMEGA_TENSOR_ERR_CAPACITY; + s->live = true; + s->dtype = dt; + s->elems = elems; + s->data = d; + h->slot = i; + h->generation = s->gen; + return OMEGA_TENSOR_OK; + } + return OMEGA_TENSOR_ERR_CAPACITY; +} + +static void storage_release(OmegaTensorCtx *ctx, OmegaStorageHandle h) { + StorageSlot *s = storage_get(ctx, h); + if (!s) return; + free(s->data); + s->data = NULL; + s->live = false; + bump_generation(&s->gen, &s->retired); +} + +static int tensor_slot_alloc(OmegaTensorCtx *ctx, const OmegaTensorInfo *info, bool owns, OmegaTensor *out) { + for (uint32_t i = 0; i < ctx->cap; i++) { + TensorSlot *x = &ctx->ts[i]; + if (x->live || x->retired) continue; + x->live = true; + x->owns_storage = owns; + x->info = *info; + out->slot = i; + out->generation = x->gen; + return OMEGA_TENSOR_OK; + } + return OMEGA_TENSOR_ERR_CAPACITY; +} + +int omega_tensor_release(OmegaTensorCtx *ctx, OmegaTensor t) { + if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (t.slot >= ctx->cap) return OMEGA_TENSOR_ERR_STALE; + TensorSlot *x = &ctx->ts[t.slot]; + if (!x->live || x->gen != t.generation) return OMEGA_TENSOR_ERR_STALE; + if (x->owns_storage) storage_release(ctx, x->info.storage); + x->live = false; + bump_generation(&x->gen, &x->retired); + return OMEGA_TENSOR_OK; +} + +/* ---- shapes ------------------------------------------------------------- */ + +static int shape_check(uint32_t rank, const uint64_t *shape, uint64_t *elems) { + if (rank > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; + if (rank && !shape) return OMEGA_TENSOR_ERR_BAD_ARGS; + uint64_t n = 1; + for (uint32_t d = 0; d < rank; d++) { + if (shape[d] == 0) return OMEGA_TENSOR_ERR_SHAPE; + if (shape[d] > OMEGA_TENSOR_MAX_ELEMS || __builtin_mul_overflow(n, shape[d], &n) || + n > OMEGA_TENSOR_MAX_ELEMS) + return OMEGA_TENSOR_ERR_CAPACITY; + } + *elems = n; + return OMEGA_TENSOR_OK; +} + +static void dense_strides(uint32_t rank, const uint64_t *shape, uint64_t *strides) { + uint64_t s = 1; + for (uint32_t d = rank; d-- > 0;) { + strides[d] = s; + s *= shape[d]; + } +} + +/* Largest storage index a descriptor reaches must lie inside the storage. */ +static int bounds_check(const OmegaTensorInfo *in, uint64_t storage_elems) { + uint64_t hi = in->offset; + for (uint32_t d = 0; d < in->rank; d++) { + uint64_t step; + if (__builtin_mul_overflow(in->shape[d] - 1, in->strides[d], &step) || + __builtin_add_overflow(hi, step, &hi)) + return OMEGA_TENSOR_ERR_BOUNDS; + } + return hi < storage_elems ? OMEGA_TENSOR_OK : OMEGA_TENSOR_ERR_BOUNDS; +} + +int omega_tensor_broadcast_shape(uint32_t ra, const uint64_t *sa, uint32_t rb, const uint64_t *sb, + uint32_t *rout, uint64_t *sout) { + if (!rout || !sout || (ra && !sa) || (rb && !sb)) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (ra > OMEGA_TENSOR_MAX_RANK || rb > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; + uint32_t r = ra > rb ? ra : rb; + uint64_t tmp[OMEGA_TENSOR_MAX_RANK]; + for (uint32_t i = 0; i < r; i++) { /* i counts from the trailing axis */ + uint64_t da = i < ra ? sa[ra - 1 - i] : 1; + uint64_t db = i < rb ? sb[rb - 1 - i] : 1; + if (da == 0 || db == 0) return OMEGA_TENSOR_ERR_SHAPE; + if (da != db && da != 1 && db != 1) return OMEGA_TENSOR_ERR_SHAPE; + tmp[r - 1 - i] = da > db ? da : db; + } + memcpy(sout, tmp, r * sizeof(uint64_t)); + *rout = r; + return OMEGA_TENSOR_OK; +} + +/* Directional broadcast of a descriptor to (rank, shape): stride 0 on every + * expanded axis. Pure descriptor arithmetic. */ +static int broadcast_info(const OmegaTensorInfo *in, uint32_t rank, const uint64_t *shape, + OmegaTensorInfo *out) { + if (rank < in->rank) return OMEGA_TENSOR_ERR_SHAPE; + uint64_t n; + int rc = shape_check(rank, shape, &n); + if (rc) return rc; + OmegaTensorInfo o = *in; + o.rank = rank; + for (uint32_t i = 0; i < rank; i++) { + uint32_t d = rank - 1 - i; + if (i < in->rank) { + uint32_t sd = in->rank - 1 - i; + if (in->shape[sd] == shape[d]) { o.shape[d] = shape[d]; o.strides[d] = in->strides[sd]; } + else if (in->shape[sd] == 1) { o.shape[d] = shape[d]; o.strides[d] = 0; } /* MUT:BCAST_ZERO_STRIDE */ + else return OMEGA_TENSOR_ERR_SHAPE; + } else { + o.shape[d] = shape[d]; + o.strides[d] = 0; + } + } + for (uint32_t d = rank; d < OMEGA_TENSOR_MAX_RANK; d++) { o.shape[d] = 0; o.strides[d] = 0; } + o.elements = n; + *out = o; + return OMEGA_TENSOR_OK; +} + +/* Copy every element in logical row-major order into dst (element size es). */ +static void gather(const StorageSlot *s, const OmegaTensorInfo *in, void *dst) { + size_t es = omega_dtype_size(in->dtype); + uint64_t idx[OMEGA_TENSOR_MAX_RANK] = {0}; + uint64_t pos = in->offset; + const uint8_t *src = s->data; + uint8_t *d = dst; + for (uint64_t e = 0; e < in->elements; e++) { + memcpy(d + e * es, src + pos * es, es); + for (uint32_t ax = in->rank; ax-- > 0;) { + if (++idx[ax] < in->shape[ax]) { pos += in->strides[ax]; break; } + pos -= (in->shape[ax] - 1) * in->strides[ax]; + idx[ax] = 0; + } + } +} + +/* New tensor owning fresh dense storage. *data receives the storage buffer + * for the caller to fill before anyone else can see the tensor. */ +static int new_dense(OmegaTensorCtx *ctx, OmegaDType dt, uint32_t rank, const uint64_t *shape, + OmegaTensor *out, void **data) { + uint64_t n; + int rc = shape_check(rank, shape, &n); + if (rc) return rc; + OmegaStorageHandle h; + rc = storage_alloc(ctx, dt, n, &h); + if (rc) return rc; + OmegaTensorInfo info; + memset(&info, 0, sizeof(info)); + info.dtype = dt; + info.rank = rank; + if (rank) memcpy(info.shape, shape, rank * sizeof(uint64_t)); + dense_strides(rank, info.shape, info.strides); + info.elements = n; + info.storage = h; + info.is_view = false; + rc = tensor_slot_alloc(ctx, &info, true, out); + if (rc) { storage_release(ctx, h); return rc; } + ctx->ts[out->slot].info.parent = *out; + *data = ctx->st[h.slot].data; + return OMEGA_TENSOR_OK; +} + +/* ---- creation / inspection --------------------------------------------- */ + +int omega_tensor_from_data(OmegaTensorCtx *ctx, OmegaDType dtype, uint32_t rank, + const uint64_t *shape, const void *data, OmegaTensor *out) { + if (!ctx || !data || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (!omega_dtype_size(dtype)) return OMEGA_TENSOR_ERR_DTYPE; + void *buf; + int rc = new_dense(ctx, dtype, rank, shape, out, &buf); + if (rc) return rc; + memcpy(buf, data, (size_t)ctx->ts[out->slot].info.elements * omega_dtype_size(dtype)); + return OMEGA_TENSOR_OK; +} + +int omega_tensor_from_f32(OmegaTensorCtx *ctx, uint32_t rank, const uint64_t *shape, + const float *data, OmegaTensor *out) { + return omega_tensor_from_data(ctx, OMEGA_DT_F32, rank, shape, data, out); +} + +int omega_tensor_info(const OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensorInfo *out) { + TensorSlot *x; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, NULL); + if (rc) return rc; + *out = x->info; + return OMEGA_TENSOR_OK; +} + +int omega_tensor_read(const OmegaTensorCtx *ctx, OmegaTensor t, void *out, size_t out_bytes) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + if (out_bytes < x->info.elements * omega_dtype_size(x->info.dtype)) return OMEGA_TENSOR_ERR_CAPACITY; + gather(s, &x->info, out); + return OMEGA_TENSOR_OK; +} + +int omega_tensor_read_f32(const OmegaTensorCtx *ctx, OmegaTensor t, float *out, size_t count) { + TensorSlot *x; + int rc = tensor_get(ctx, t, &x, NULL); + if (rc) return rc; + if (x->info.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + return omega_tensor_read(ctx, t, out, count * sizeof(float)); +} + +static void put_u64(sha256_ctx *h, uint64_t v) { + uint8_t b[8]; + for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i)); + sha256_update(h, b, 8); +} + +/* Canonical element bits: every NaN becomes the canonical quiet NaN. */ +static uint32_t canon_bits(OmegaDType dt, const uint8_t *p) { + if (dt == OMEGA_DT_F32) { + uint32_t u; + memcpy(&u, p, 4); + return ((u & 0x7f800000U) == 0x7f800000U && (u & 0x007fffffU)) ? 0x7fc00000U : u; + } + uint16_t h; + memcpy(&h, p, 2); + if (dt == OMEGA_DT_F16) return ((h & 0x7c00U) == 0x7c00U && (h & 0x03ffU)) ? 0x7e00U : h; + return ((h & 0x7f80U) == 0x7f80U && (h & 0x007fU)) ? 0x7fc0U : h; +} + +int omega_tensor_value_id(const OmegaTensorCtx *ctx, OmegaTensor t, uint8_t id[32]) { + TensorSlot *x; + StorageSlot *s; + if (!id) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + size_t es = omega_dtype_size(x->info.dtype); + uint8_t *buf = malloc((size_t)x->info.elements * es); + if (!buf) return OMEGA_TENSOR_ERR_CAPACITY; + gather(s, &x->info, buf); + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, (const uint8_t *)OMEGA_TENSOR_VALUE_ID_DOMAIN, sizeof(OMEGA_TENSOR_VALUE_ID_DOMAIN)); + put_u64(&h, (uint64_t)x->info.dtype); + put_u64(&h, x->info.rank); + for (uint32_t d = 0; d < x->info.rank; d++) put_u64(&h, x->info.shape[d]); + for (uint64_t e = 0; e < x->info.elements; e++) { + uint32_t c = canon_bits(x->info.dtype, buf + e * es); + uint8_t b[4] = {(uint8_t)c, (uint8_t)(c >> 8), (uint8_t)(c >> 16), (uint8_t)(c >> 24)}; + sha256_update(&h, b, es); + } + sha256_final(&h, id); + free(buf); + return OMEGA_TENSOR_OK; +} + +int omega_tensor_value_equal(const OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, bool *eq) { + TensorSlot *xa, *xb; + StorageSlot *sa, *sb; + if (!eq) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, a, &xa, &sa); + if (!rc) rc = tensor_get(ctx, b, &xb, &sb); + if (rc) return rc; + *eq = false; + if (xa->info.dtype != xb->info.dtype || xa->info.rank != xb->info.rank) return OMEGA_TENSOR_OK; + for (uint32_t d = 0; d < xa->info.rank; d++) + if (xa->info.shape[d] != xb->info.shape[d]) return OMEGA_TENSOR_OK; + size_t es = omega_dtype_size(xa->info.dtype); + size_t bytes = (size_t)xa->info.elements * es; + uint8_t *ba = malloc(bytes), *bb = malloc(bytes); + if (!ba || !bb) { free(ba); free(bb); return OMEGA_TENSOR_ERR_CAPACITY; } + gather(sa, &xa->info, ba); + gather(sb, &xb->info, bb); + bool same = true; + for (uint64_t e = 0; e < xa->info.elements && same; e++) + same = canon_bits(xa->info.dtype, ba + e * es) == canon_bits(xb->info.dtype, bb + e * es); + free(ba); + free(bb); + *eq = same; + return OMEGA_TENSOR_OK; +} + +int omega_tensor_view_id(const OmegaTensorCtx *ctx, OmegaTensor t, uint8_t id[32]) { + TensorSlot *x; + if (!id) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, NULL); + if (rc) return rc; + const OmegaTensorInfo *in = &x->info; + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, (const uint8_t *)OMEGA_TENSOR_VIEW_ID_DOMAIN, sizeof(OMEGA_TENSOR_VIEW_ID_DOMAIN)); + put_u64(&h, in->storage.slot); + put_u64(&h, in->storage.generation); + put_u64(&h, in->parent.slot); + put_u64(&h, in->parent.generation); + put_u64(&h, (uint64_t)in->dtype); + put_u64(&h, in->offset); + put_u64(&h, in->rank); + for (uint32_t d = 0; d < in->rank; d++) { put_u64(&h, in->shape[d]); put_u64(&h, in->strides[d]); } + sha256_final(&h, id); + return OMEGA_TENSOR_OK; +} + +/* ---- views -------------------------------------------------------------- */ + +static int register_view(OmegaTensorCtx *ctx, OmegaTensor parent, const StorageSlot *s, + OmegaTensorInfo *v, OmegaTensor *out) { + int rc = bounds_check(v, s->elems); + if (rc) return rc; + v->is_view = true; + v->parent = parent; + return tensor_slot_alloc(ctx, v, false, out); +} + +int omega_tensor_permute(OmegaTensorCtx *ctx, OmegaTensor t, const uint32_t *perm, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + const OmegaTensorInfo *in = &x->info; + if (in->rank && !perm) return OMEGA_TENSOR_ERR_BAD_ARGS; + bool seen[OMEGA_TENSOR_MAX_RANK] = {false}; + OmegaTensorInfo v = *in; + for (uint32_t d = 0; d < in->rank; d++) { + if (perm[d] >= in->rank || seen[perm[d]]) return OMEGA_TENSOR_ERR_AXIS; + seen[perm[d]] = true; + v.shape[d] = in->shape[perm[d]]; + v.strides[d] = in->strides[perm[d]]; /* MUT:PERMUTE_STRIDES */ + } + return register_view(ctx, t, s, &v, out); +} + +int omega_tensor_transpose(OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensor *out) { + TensorSlot *x; + int rc = tensor_get(ctx, t, &x, NULL); + if (rc) return rc; + uint32_t r = x->info.rank; + if (r < 2) return OMEGA_TENSOR_ERR_RANK; + uint32_t perm[OMEGA_TENSOR_MAX_RANK]; + for (uint32_t d = 0; d < r; d++) perm[d] = d; + perm[r - 2] = r - 1; + perm[r - 1] = r - 2; + return omega_tensor_permute(ctx, t, perm, out); +} + +int omega_tensor_slice(OmegaTensorCtx *ctx, OmegaTensor t, const uint64_t *start, + const uint64_t *stop, const uint64_t *step, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + const OmegaTensorInfo *in = &x->info; + if (in->rank == 0) return OMEGA_TENSOR_ERR_RANK; + if (!start || !stop) return OMEGA_TENSOR_ERR_BAD_ARGS; + OmegaTensorInfo v = *in; + uint64_t n = 1; + for (uint32_t d = 0; d < in->rank; d++) { + uint64_t st = step ? step[d] : 1; + if (st == 0) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (stop[d] > in->shape[d]) return OMEGA_TENSOR_ERR_BOUNDS; + if (start[d] >= stop[d]) return OMEGA_TENSOR_ERR_SHAPE; + v.shape[d] = (stop[d] - start[d] - 1) / st + 1; /* ceil, no overflow */ + uint64_t so; + if (__builtin_mul_overflow(start[d], in->strides[d], &so) || /* MUT:SLICE_OFFSET */ + __builtin_add_overflow(v.offset, so, &v.offset)) + return OMEGA_TENSOR_ERR_BOUNDS; + /* A single-element axis never uses its stride; 0 avoids overflow. */ + if (v.shape[d] == 1) v.strides[d] = 0; + else if (__builtin_mul_overflow(in->strides[d], st, &v.strides[d])) return OMEGA_TENSOR_ERR_BOUNDS; + n *= v.shape[d]; + } + v.elements = n; + return register_view(ctx, t, s, &v, out); +} + +static bool is_row_major(const OmegaTensorInfo *in) { + uint64_t expect = 1; + for (uint32_t d = in->rank; d-- > 0;) { + if (in->shape[d] != 1 && in->strides[d] != expect) return false; + expect *= in->shape[d]; + } + return true; +} + +int omega_tensor_reshape(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, + const uint64_t *shape, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + uint64_t n; + rc = shape_check(rank, shape, &n); + if (rc) return rc; + if (n != x->info.elements) return OMEGA_TENSOR_ERR_SHAPE; + if (!is_row_major(&x->info)) return OMEGA_TENSOR_ERR_NOT_CONTIGUOUS; + OmegaTensorInfo v = x->info; + v.rank = rank; + memset(v.shape, 0, sizeof(v.shape)); + memset(v.strides, 0, sizeof(v.strides)); + if (rank) memcpy(v.shape, shape, rank * sizeof(uint64_t)); + dense_strides(rank, v.shape, v.strides); + return register_view(ctx, t, s, &v, out); +} + +int omega_tensor_broadcast_to(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, + const uint64_t *shape, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + if (rank > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; + OmegaTensorInfo v; + rc = broadcast_info(&x->info, rank, shape, &v); + if (rc) return rc; + return register_view(ctx, t, s, &v, out); +} + +/* ---- ops ---------------------------------------------------------------- */ + +static int numeric_fail(OmegaTensorCtx *ctx, int code, OmegaTensor made) { + ctx->last_numeric = code; + omega_tensor_release(ctx, made); + return OMEGA_TENSOR_ERR_NUMERIC; +} + +int omega_tensor_contiguous(OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + OmegaTensorInfo in = x->info; /* copy: slot table may be reused below */ + void *buf; + rc = new_dense(ctx, in.dtype, in.rank, in.shape, out, &buf); + if (rc) return rc; + gather(s, &in, buf); + return OMEGA_TENSOR_OK; +} + +int omega_tensor_cast(OmegaTensorCtx *ctx, OmegaTensor t, OmegaDType to, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + if (!omega_dtype_size(to)) return OMEGA_TENSOR_ERR_DTYPE; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + OmegaTensorInfo in = x->info; + if (in.dtype == to) return omega_tensor_contiguous(ctx, t, out); + if (in.dtype != OMEGA_DT_F32 && to != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + size_t n = (size_t)in.elements; + float *src = malloc(n * sizeof(float)), *dst = malloc(n * sizeof(float)); + if (!src || !dst) { free(src); free(dst); return OMEGA_TENSOR_ERR_CAPACITY; } + OmegaNumericOp op; + if (in.dtype == OMEGA_DT_F32) { + gather(s, &in, src); + op = to == OMEGA_DT_F16 ? OMEGA_NOP_F32_TO_F16 : OMEGA_NOP_F32_TO_BF16; + } else { + uint16_t *h = malloc(n * sizeof(uint16_t)); + if (!h) { free(src); free(dst); return OMEGA_TENSOR_ERR_CAPACITY; } + gather(s, &in, h); + for (size_t i = 0; i < n; i++) src[i] = omega_bits_to_float(h[i]); + free(h); + op = in.dtype == OMEGA_DT_F16 ? OMEGA_NOP_F16_TO_F32 : OMEGA_NOP_BF16_TO_F32; + } + void *buf; + rc = new_dense(ctx, to, in.rank, in.shape, out, &buf); + if (rc) { free(src); free(dst); return rc; } + int nrc = ctx->real->elementwise(op, src, NULL, NULL, dst, n); + if (nrc) { free(src); free(dst); return numeric_fail(ctx, nrc, *out); } + if (to == OMEGA_DT_F32) { + memcpy(buf, dst, n * sizeof(float)); + } else { + uint16_t *o = buf; + for (size_t i = 0; i < n; i++) o[i] = (uint16_t)(omega_float_to_bits(dst[i]) & 0xffffU); + } + free(src); + free(dst); + return OMEGA_TENSOR_OK; +} + +static const OmegaNumericOp BINARY_MAP[OMEGA_TB_COUNT] = { + [OMEGA_TB_ADD] = OMEGA_NOP_FADD, [OMEGA_TB_SUB] = OMEGA_NOP_FSUB, + [OMEGA_TB_MUL] = OMEGA_NOP_FMUL, [OMEGA_TB_DIV] = OMEGA_NOP_DIV, + [OMEGA_TB_MIN] = OMEGA_NOP_FMNMX_MIN, [OMEGA_TB_MAX] = OMEGA_NOP_FMNMX_MAX, + [OMEGA_TB_SEL_GE] = OMEGA_NOP_FSETP_SEL, [OMEGA_TB_SEL_LT] = OMEGA_NOP_FSETP_LT_SEL, + [OMEGA_TB_SEL_LE] = OMEGA_NOP_FSETP_LE_SEL, [OMEGA_TB_SEL_GT] = OMEGA_NOP_FSETP_GT_SEL, + [OMEGA_TB_SEL_EQ] = OMEGA_NOP_FSETP_EQ_SEL, [OMEGA_TB_SEL_NE] = OMEGA_NOP_FSETP_NE_SEL, + [OMEGA_TB_SEL_NUM] = OMEGA_NOP_FSETP_NUM_SEL, [OMEGA_TB_SEL_NAN] = OMEGA_NOP_FSETP_NAN_SEL, + [OMEGA_TB_SEL_LTU] = OMEGA_NOP_FSETP_LTU_SEL, [OMEGA_TB_SEL_LEU] = OMEGA_NOP_FSETP_LEU_SEL, + [OMEGA_TB_SEL_GTU] = OMEGA_NOP_FSETP_GTU_SEL, [OMEGA_TB_SEL_GEU] = OMEGA_NOP_FSETP_GEU_SEL, + [OMEGA_TB_SEL_EQU] = OMEGA_NOP_FSETP_EQU_SEL, [OMEGA_TB_SEL_NEU] = OMEGA_NOP_FSETP_NEU_SEL, +}; + +/* Elementwise over 1..3 F32 operands broadcast together. */ +static int elementwise_n(OmegaTensorCtx *ctx, OmegaNumericOp op, unsigned arity, const OmegaTensor *ops, + OmegaTensor *out) { + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + TensorSlot *x[3]; + StorageSlot *s[3]; + for (unsigned i = 0; i < arity; i++) { + int rc = tensor_get(ctx, ops[i], &x[i], &s[i]); + if (rc) return rc; + } + for (unsigned i = 0; i < arity; i++) + if (x[i]->info.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + uint32_t r = x[0]->info.rank; + uint64_t shape[OMEGA_TENSOR_MAX_RANK]; + if (r) memcpy(shape, x[0]->info.shape, r * sizeof(uint64_t)); + for (unsigned i = 1; i < arity; i++) { + int rc = omega_tensor_broadcast_shape(r, shape, x[i]->info.rank, x[i]->info.shape, &r, shape); + if (rc) return rc; + } + OmegaTensorInfo bi[3]; + for (unsigned i = 0; i < arity; i++) { + int rc = broadcast_info(&x[i]->info, r, shape, &bi[i]); + if (rc) return rc; + } + size_t n = (size_t)bi[0].elements; + float *in[3] = {NULL, NULL, NULL}; + for (unsigned i = 0; i < arity; i++) { + in[i] = malloc(n * sizeof(float)); + if (!in[i]) { for (unsigned j = 0; j < i; j++) free(in[j]); return OMEGA_TENSOR_ERR_CAPACITY; } + gather(s[i], &bi[i], in[i]); + } + void *buf; + int rc = new_dense(ctx, OMEGA_DT_F32, r, shape, out, &buf); + if (!rc) { + int nrc = ctx->real->elementwise(op, in[0], in[1], in[2], buf, n); + if (nrc) rc = numeric_fail(ctx, nrc, *out); + } + for (unsigned i = 0; i < arity; i++) free(in[i]); + return rc; +} + +int omega_tensor_unary(OmegaTensorCtx *ctx, OmegaTensorUnaryOp op, OmegaTensor a, OmegaTensor *out) { + if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; + if ((unsigned)op >= OMEGA_TU_COUNT) return OMEGA_TENSOR_ERR_BAD_ARGS; + return elementwise_n(ctx, OMEGA_NOP_SQRT, 1, &a, out); +} + +int omega_tensor_binary(OmegaTensorCtx *ctx, OmegaTensorBinaryOp op, OmegaTensor a, OmegaTensor b, + OmegaTensor *out) { + if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; + if ((unsigned)op >= OMEGA_TB_COUNT) return OMEGA_TENSOR_ERR_BAD_ARGS; + OmegaTensor ops[2] = {a, b}; + return elementwise_n(ctx, BINARY_MAP[op], 2, ops, out); +} + +int omega_tensor_fma(OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, OmegaTensor c, OmegaTensor *out) { + if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; + OmegaTensor ops[3] = {a, b, c}; + return elementwise_n(ctx, OMEGA_NOP_FFMA_V, 3, ops, out); +} + +int omega_tensor_reduce(OmegaTensorCtx *ctx, OmegaTensorReduceOp op, OmegaTensor t, uint32_t axis, + bool keepdims, OmegaTensor *out) { + TensorSlot *x; + StorageSlot *s; + if (!out || (unsigned)op >= OMEGA_TR_COUNT) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, t, &x, &s); + if (rc) return rc; + OmegaTensorInfo in = x->info; + if (in.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + if (in.rank == 0) return OMEGA_TENSOR_ERR_RANK; + if (axis >= in.rank) return OMEGA_TENSOR_ERR_AXIS; + /* Move the axis last (descriptor only), gather rows densely. */ + OmegaTensorInfo moved = in; + uint32_t k = 0; + for (uint32_t d = 0; d < in.rank; d++) { + if (d == axis) continue; + moved.shape[k] = in.shape[d]; + moved.strides[k] = in.strides[d]; + k++; + } + moved.shape[k] = in.shape[axis]; + moved.strides[k] = in.strides[axis]; + size_t n = (size_t)in.shape[axis], rows = (size_t)(in.elements / in.shape[axis]); + uint32_t orank = keepdims ? in.rank : in.rank - 1; + uint64_t oshape[OMEGA_TENSOR_MAX_RANK]; + for (uint32_t d = 0, j = 0; d < in.rank; d++) { + if (d == axis) { if (keepdims) oshape[j++] = 1; continue; } + oshape[j++] = in.shape[d]; + } + float *dense = malloc((size_t)in.elements * sizeof(float)); + if (!dense) return OMEGA_TENSOR_ERR_CAPACITY; + gather(s, &moved, dense); + void *buf; + rc = new_dense(ctx, OMEGA_DT_F32, orank, oshape, out, &buf); + if (!rc) { + float *o = buf; + for (size_t r = 0; r < rows; r++) { + int nrc = ctx->real->reduce(op, dense + r * n, n, &o[r]); + if (nrc) { rc = numeric_fail(ctx, nrc, *out); break; } + } + } + free(dense); + return rc; +} + +int omega_tensor_matmul(OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, OmegaTensor *out) { + TensorSlot *xa, *xb; + StorageSlot *sa, *sb; + if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; + int rc = tensor_get(ctx, a, &xa, &sa); + if (!rc) rc = tensor_get(ctx, b, &xb, &sb); + if (rc) return rc; + OmegaTensorInfo ia = xa->info, ib = xb->info; + if (ia.dtype != OMEGA_DT_F32 || ib.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; + if (ia.rank < 2 || ib.rank < 2) return OMEGA_TENSOR_ERR_RANK; + uint64_t M = ia.shape[ia.rank - 2], K = ia.shape[ia.rank - 1]; + uint64_t K2 = ib.shape[ib.rank - 2], N = ib.shape[ib.rank - 1]; + if (K != K2) return OMEGA_TENSOR_ERR_SHAPE; + uint32_t br; + uint64_t bshape[OMEGA_TENSOR_MAX_RANK]; + rc = omega_tensor_broadcast_shape(ia.rank - 2, ia.shape, ib.rank - 2, ib.shape, &br, bshape); + if (rc) return rc; + if (br + 2 > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; + uint64_t sha[OMEGA_TENSOR_MAX_RANK], shb[OMEGA_TENSOR_MAX_RANK], sho[OMEGA_TENSOR_MAX_RANK]; + memcpy(sha, bshape, br * sizeof(uint64_t)); + memcpy(shb, bshape, br * sizeof(uint64_t)); + memcpy(sho, bshape, br * sizeof(uint64_t)); + sha[br] = M; sha[br + 1] = K; + shb[br] = K; shb[br + 1] = N; + sho[br] = M; sho[br + 1] = N; + OmegaTensorInfo va, vb; + rc = broadcast_info(&ia, br + 2, sha, &va); + if (!rc) rc = broadcast_info(&ib, br + 2, shb, &vb); + if (rc) return rc; + /* B with its last two axes swapped, so each column is a dense row. */ + uint64_t t0 = vb.shape[br], t1 = vb.strides[br]; + vb.shape[br] = vb.shape[br + 1]; vb.strides[br] = vb.strides[br + 1]; + vb.shape[br + 1] = t0; vb.strides[br + 1] = t1; + uint64_t batches = va.elements / (M * K); + float *A = malloc((size_t)va.elements * sizeof(float)); + float *BT = malloc((size_t)vb.elements * sizeof(float)); + float *prod = malloc((size_t)K * sizeof(float)); + if (!A || !BT || !prod) { free(A); free(BT); free(prod); return OMEGA_TENSOR_ERR_CAPACITY; } + gather(sa, &va, A); + gather(sb, &vb, BT); + void *buf; + rc = new_dense(ctx, OMEGA_DT_F32, br + 2, sho, out, &buf); + if (!rc) { + float *o = buf; + for (uint64_t bt = 0; bt < batches && !rc; bt++) + for (uint64_t i = 0; i < M && !rc; i++) + for (uint64_t j = 0; j < N && !rc; j++) { + const float *ar = A + (bt * M + i) * K; + const float *bc = BT + (bt * N + j) * K; + int nrc = ctx->real->elementwise(OMEGA_NOP_FMUL, ar, bc, NULL, prod, (size_t)K); + if (!nrc) nrc = ctx->real->reduce(OMEGA_TR_SUM, prod, (size_t)K, &o[(bt * M + i) * N + j]); + if (nrc) rc = numeric_fail(ctx, nrc, *out); + } + } + free(A); + free(BT); + free(prod); + return rc; +} + +void omega_tensor_live_counts(const OmegaTensorCtx *ctx, uint32_t *tensors, uint32_t *storages) { + uint32_t t = 0, s = 0; + for (uint32_t i = 0; ctx && i < ctx->cap; i++) { t += ctx->ts[i].live; s += ctx->st[i].live; } + if (tensors) *tensors = t; + if (storages) *storages = s; +} diff --git a/src/tensor/omega_tensor.h b/src/tensor/omega_tensor.h new file mode 100644 index 000000000..1611c179b --- /dev/null +++ b/src/tensor/omega_tensor.h @@ -0,0 +1,266 @@ +#ifndef OMEGA_TENSOR_H +#define OMEGA_TENSOR_H + +/* + * M20 OMEGA_TENSOR: immutable semantic tensors (docs/tensor/M20_OMEGA_TENSOR.md). + * + * Meaning and realization are separate. This header defines what a tensor is + * and what each op computes. Arithmetic is never done here: every arithmetic + * step goes through an OmegaTensorRealization (a table of functions). The + * semantic layer only moves data (gathers elements by index) and checks. + * The CPU realization (omega_tensor_cpu_realization) is the only one today; + * a GB10 SIMT or Tensor Core realization plugs into the same table later and + * must reproduce the declared bits, or declare its own bounded contract. + * + * Tensors are immutable. There is no API that writes into an existing tensor: + * creation copies the caller's data into new storage, every op returns a new + * tensor, and views (permute, slice, reshape, broadcast) share the parent's + * storage read-only and never change the parent. + * + * Identity: + * value identity = dtype + shape + element values in logical row-major + * order (NaN payload is not semantic: every NaN counts as + * the canonical quiet NaN; -0 and +0 differ). Strides, + * offset and storage are NOT part of it: "physical layout + * is not identity". omega_tensor_value_id hashes exactly + * this (SHA-256, OMEGA_TENSOR_VALUE_ID_DOMAIN). + * storage identity = the allocation: storage slot + 64-bit generation. + * view identity = storage identity + offset + shape + strides + dtype, + * plus the parent tensor it was taken from. + * + * Storage lifetime: every storage slot carries a 64-bit generation. A handle + * is valid only while its generation equals the slot's and the slot is live. + * Releasing bumps the generation, so every older handle (and every view of + * that storage) fails closed with OMEGA_TENSOR_ERR_STALE. A slot whose + * generation reaches UINT64_MAX is retired forever instead of wrapping. + * + * Shapes: rank 0..OMEGA_TENSOR_MAX_RANK, every dimension >= 1 (no empty + * tensors), total elements <= OMEGA_TENSOR_MAX_ELEMS. Strides are counted in + * elements and are >= 0; 0 appears only in broadcast views. Negative strides + * are not defined (refused). + * + * Dtypes: F32 is the arithmetic dtype. F16 and BF16 are storage dtypes: any + * arithmetic op on them is refused (OMEGA_TENSOR_ERR_DTYPE); convert first + * with omega_tensor_cast, which uses the E1 conversion ops + * (F32_TO_F16 / F32_TO_BF16 RNE, F16_TO_F32 / BF16_TO_F32 exact). + * + * Not thread safe: one context per thread. + */ + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +#include "omega_numeric.h" + +#define OMEGA_TENSOR_MAX_RANK 8u +#define OMEGA_TENSOR_MAX_ELEMS ((uint64_t)1 << 30) +#define OMEGA_TENSOR_VALUE_ID_DOMAIN "OMEGA_TENSOR_VALUE_ID_V1" +#define OMEGA_TENSOR_VIEW_ID_DOMAIN "OMEGA_TENSOR_VIEW_ID_V1" + +/* Frozen reduction order: must equal OMEGA_REDUCE_DECLARED_ORDER of the E1 + * reduction contract (docs/numeric/E1_REDUCTION_CONTRACT.md, omega PR #134). + * See src/tensor/omega_tensor_reduce_seam.h. */ +#define OMEGA_TENSOR_REDUCE_DECLARED_ORDER \ + "RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL" + +/* + * Declared accumulation order of matmul. For every output element + * out[..., i, j]: products p[k] = FMUL_RNE(a[..., i, k], b[..., k, j]) for + * k = 0..K-1 (each rounded once, no fused multiply-add), then + * out = E1 REDUCE_SUM over p[0..K) in OMEGA_TENSOR_REDUCE_DECLARED_ORDER. + * A realization that fuses (FFMA chain, Tensor Core MMA) computes different + * bits and must declare its own bounded contract instead of this one. + */ +#define OMEGA_TENSOR_MATMUL_DECLARED_ORDER \ + "MATMUL_V1_FMUL_RNE_PRODUCTS_THEN_E1_REDUCE_SUM_" \ + "RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL" + +typedef enum { + OMEGA_TENSOR_OK = 0, + OMEGA_TENSOR_ERR_BAD_ARGS = -1, /* NULL pointer, unknown op/enum */ + OMEGA_TENSOR_ERR_RANK = -2, /* rank out of range for this op */ + OMEGA_TENSOR_ERR_SHAPE = -3, /* dims mismatch / not broadcastable */ + OMEGA_TENSOR_ERR_DTYPE = -4, /* dtype not allowed for this op */ + OMEGA_TENSOR_ERR_STALE = -5, /* handle generation does not match */ + OMEGA_TENSOR_ERR_BOUNDS = -6, /* view reaches outside its storage */ + OMEGA_TENSOR_ERR_NOT_CONTIGUOUS = -7, /* reshape of a non row-major layout */ + OMEGA_TENSOR_ERR_CAPACITY = -8, /* no free slot / size overflow / OOM */ + OMEGA_TENSOR_ERR_AXIS = -9, /* axis / permutation invalid */ + OMEGA_TENSOR_ERR_NUMERIC = -10, /* realization refused (E1 code kept) */ + OMEGA_TENSOR_ERR_REALIZATION = -11 /* realization table incomplete */ +} OmegaTensorStatus; + +typedef enum { + OMEGA_DT_F32 = 1, + OMEGA_DT_F16 = 2, + OMEGA_DT_BF16 = 3 +} OmegaDType; + +/* Opaque handles. Copying a handle never copies or shares write access. */ +typedef struct { uint32_t slot; uint64_t generation; } OmegaStorageHandle; +typedef struct { uint32_t slot; uint64_t generation; } OmegaTensor; + +/* Elementwise ops. Every op is an E1 scalar op applied per element. */ +typedef enum { + OMEGA_TU_SQRT = 0, /* omega_math_sqrt, correctly rounded */ + OMEGA_TU_COUNT +} OmegaTensorUnaryOp; + +typedef enum { + OMEGA_TB_ADD = 0, /* FADD RNE */ + OMEGA_TB_SUB, /* FSUB RNE */ + OMEGA_TB_MUL, /* FMUL RNE */ + OMEGA_TB_DIV, /* omega_math_div, correctly rounded */ + OMEGA_TB_MIN, /* FMNMX_MIN: NaN is missing data, -0 < +0 */ + OMEGA_TB_MAX, /* FMNMX_MAX */ + /* compare-select: out = P(a, b) ? a : b (E1 FSETP_<P>_SEL) */ + OMEGA_TB_SEL_GE, OMEGA_TB_SEL_LT, OMEGA_TB_SEL_LE, OMEGA_TB_SEL_GT, + OMEGA_TB_SEL_EQ, OMEGA_TB_SEL_NE, OMEGA_TB_SEL_NUM, OMEGA_TB_SEL_NAN, + OMEGA_TB_SEL_LTU, OMEGA_TB_SEL_LEU, OMEGA_TB_SEL_GTU, OMEGA_TB_SEL_GEU, + OMEGA_TB_SEL_EQU, OMEGA_TB_SEL_NEU, + OMEGA_TB_COUNT +} OmegaTensorBinaryOp; + +typedef enum { + OMEGA_TR_SUM = 0, /* identity -0.0 */ + OMEGA_TR_MAX, /* FMNMX_MAX, identity quiet NaN */ + OMEGA_TR_MIN, /* FMNMX_MIN, identity quiet NaN */ + OMEGA_TR_MEAN, /* omega_math_div(SUM, (float)n), n <= 2^24 */ + OMEGA_TR_COUNT +} OmegaTensorReduceOp; + +/* + * Realization table. All buffers are dense and contiguous; the semantic + * layer gathers strided/broadcast operands before calling. + * elementwise: out[i] = op(a[i], b[i], c[i]) for an E1 OmegaNumericOp, + * with the omega_numeric_cpu_realize argument conventions + * (b/c may be NULL when the op does not read them). + * reduce: *out = reduce(op, x[0..n)) in OMEGA_TENSOR_REDUCE_DECLARED_ORDER. + * reduce_order must equal OMEGA_TENSOR_REDUCE_DECLARED_ORDER. + * Return 0 or an OMEGA_NUMERIC_* code (kept in the context, mapped to + * OMEGA_TENSOR_ERR_NUMERIC). + */ +typedef struct { + const char *name; + const char *reduce_order; + int (*elementwise)(OmegaNumericOp op, const float *a, const float *b, const float *c, + float *out, size_t n); + int (*reduce)(OmegaTensorReduceOp op, const float *x, size_t n, float *out); +} OmegaTensorRealization; + +const OmegaTensorRealization *omega_tensor_cpu_realization(void); + +typedef struct OmegaTensorCtx OmegaTensorCtx; + +/* capacity = number of storage slots and of tensor descriptor slots. */ +int omega_tensor_ctx_create(uint32_t capacity, const OmegaTensorRealization *real, + OmegaTensorCtx **out); +void omega_tensor_ctx_destroy(OmegaTensorCtx *ctx); +/* Last OMEGA_NUMERIC_* code a realization returned (0 if none). */ +int omega_tensor_last_numeric_error(const OmegaTensorCtx *ctx); + +/* ---- creation (copies data; data is logical row-major in dtype) ---------- */ +int omega_tensor_from_data(OmegaTensorCtx *ctx, OmegaDType dtype, uint32_t rank, + const uint64_t *shape, const void *data, OmegaTensor *out); +int omega_tensor_from_f32(OmegaTensorCtx *ctx, uint32_t rank, const uint64_t *shape, + const float *data, OmegaTensor *out); + +/* + * Release. On a tensor that owns its storage (made by from_data or an op), + * releases the descriptor AND the storage: every view of that storage turns + * stale. On a view, releases only the view descriptor. Releasing twice, or + * through any stale handle, returns OMEGA_TENSOR_ERR_STALE and changes nothing. + */ +int omega_tensor_release(OmegaTensorCtx *ctx, OmegaTensor t); + +/* ---- read-only inspection ------------------------------------------------- */ +typedef struct { + OmegaDType dtype; + uint32_t rank; + uint64_t shape[OMEGA_TENSOR_MAX_RANK]; + uint64_t strides[OMEGA_TENSOR_MAX_RANK]; /* elements, >= 0 */ + uint64_t offset; /* elements */ + uint64_t elements; + OmegaStorageHandle storage; + bool is_view; + OmegaTensor parent; /* tensor the view was taken from */ +} OmegaTensorInfo; + +int omega_tensor_info(const OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensorInfo *out); +/* Copies elements out in logical row-major order (elem size of the dtype). */ +int omega_tensor_read(const OmegaTensorCtx *ctx, OmegaTensor t, void *out, size_t out_bytes); +int omega_tensor_read_f32(const OmegaTensorCtx *ctx, OmegaTensor t, float *out, size_t count); +int omega_tensor_value_id(const OmegaTensorCtx *ctx, OmegaTensor t, uint8_t id[32]); +/* Semantic equality: same dtype, shape and values (NaN class, -0 != +0). */ +int omega_tensor_value_equal(const OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, bool *eq); +int omega_tensor_view_id(const OmegaTensorCtx *ctx, OmegaTensor t, uint8_t id[32]); +bool omega_tensor_storage_valid(const OmegaTensorCtx *ctx, OmegaStorageHandle s); +size_t omega_dtype_size(OmegaDType dt); + +/* ---- views (share storage, never copy, never mutate the parent) ---------- */ +/* out dim d = in dim perm[d]. */ +int omega_tensor_permute(OmegaTensorCtx *ctx, OmegaTensor t, const uint32_t *perm, OmegaTensor *out); +/* Swaps the last two axes (rank >= 2). */ +int omega_tensor_transpose(OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensor *out); +/* Per axis: start < stop <= dim, step >= 1; out dim = ceil((stop-start)/step). + * step may be NULL (all 1). */ +int omega_tensor_slice(OmegaTensorCtx *ctx, OmegaTensor t, const uint64_t *start, + const uint64_t *stop, const uint64_t *step, OmegaTensor *out); +/* View only if t is row-major contiguous (strides equal the dense row-major + * strides, ignoring axes of size 1); otherwise OMEGA_TENSOR_ERR_NOT_CONTIGUOUS. + * Use omega_tensor_contiguous first to get a copy. */ +int omega_tensor_reshape(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, + const uint64_t *shape, OmegaTensor *out); +/* Broadcast view (numpy rules, see omega_tensor_broadcast_shape): stride 0 on + * expanded axes. */ +int omega_tensor_broadcast_to(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, + const uint64_t *shape, OmegaTensor *out); + +/* ---- new tensors ---------------------------------------------------------- */ +/* Dense row-major copy with its own storage (same value identity). */ +int omega_tensor_contiguous(OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensor *out); +/* F32 <-> F16/BF16 via E1 conversion ops; same dtype = contiguous copy; + * F16 <-> BF16 is refused (go through F32 explicitly). */ +int omega_tensor_cast(OmegaTensorCtx *ctx, OmegaTensor t, OmegaDType to, OmegaTensor *out); + +/* + * Broadcasting (numpy rules, stated): align shapes at the trailing axis; the + * missing leading axes of the shorter shape count as 1; for every axis the + * two sizes must be equal or one of them must be 1; the result size is the + * larger. Anything else is OMEGA_TENSOR_ERR_SHAPE. + */ +int omega_tensor_broadcast_shape(uint32_t ra, const uint64_t *sa, uint32_t rb, const uint64_t *sb, + uint32_t *rout, uint64_t *sout); + +int omega_tensor_unary(OmegaTensorCtx *ctx, OmegaTensorUnaryOp op, OmegaTensor a, OmegaTensor *out); +int omega_tensor_binary(OmegaTensorCtx *ctx, OmegaTensorBinaryOp op, OmegaTensor a, OmegaTensor b, + OmegaTensor *out); +/* a*b + c rounded once (E1 FFMA), all three broadcast together. */ +int omega_tensor_fma(OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, OmegaTensor c, OmegaTensor *out); + +/* Reduce along one axis. keepdims keeps that axis with size 1. */ +int omega_tensor_reduce(OmegaTensorCtx *ctx, OmegaTensorReduceOp op, OmegaTensor t, uint32_t axis, + bool keepdims, OmegaTensor *out); + +/* + * General matmul, OMEGA_TENSOR_MATMUL_DECLARED_ORDER, F32 only. + * Rank 2: [M,K] x [K,N] -> [M,N], any M, N, K >= 1. + * Rank >= 3 (batched): [...,M,K] x [...,K,N]; the batch axes broadcast with + * the numpy rules above; both operands must have rank >= 2. + */ +int omega_tensor_matmul(OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, OmegaTensor *out); + +/* Live tensor descriptors and live storage slots (lifetime audits). */ +void omega_tensor_live_counts(const OmegaTensorCtx *ctx, uint32_t *tensors, uint32_t *storages); + +#ifdef OMEGA_TENSOR_TEST_HOOKS +/* Test-only: set the generation of a free storage slot, to exercise the + * UINT64_MAX retirement rule without 2^64 releases. Refused on a live slot. + * Compiled only when OMEGA_TENSOR_TEST_HOOKS is defined (the test build in + * mk/tensor.mk); the default library build does not contain this symbol and + * test-tensor-no-hooks checks that with nm. */ +int omega_tensor_test_set_storage_generation(OmegaTensorCtx *ctx, uint32_t slot, uint64_t gen); +#endif + +#endif /* OMEGA_TENSOR_H */ diff --git a/src/tensor/omega_tensor_cpu.c b/src/tensor/omega_tensor_cpu.c new file mode 100644 index 000000000..15ec48ad0 --- /dev/null +++ b/src/tensor/omega_tensor_cpu.c @@ -0,0 +1,19 @@ +/* CPU realization of M20 OMEGA_TENSOR: the E1 CPU tier (explicit AArch64 + * instructions in omega_numeric_cpu_realize) for elementwise ops, and the + * reduction seam for reductions. No arithmetic outside those two. */ +#include "omega_tensor.h" +#include "omega_tensor_reduce_seam.h" + +static int cpu_elementwise(OmegaNumericOp op, const float *a, const float *b, const float *c, + float *out, size_t n) { + return omega_numeric_cpu_realize(op, a, b, c, out, n); +} + +static const OmegaTensorRealization CPU_REALIZATION = { + .name = "CPU_E1_TIER", + .reduce_order = OMEGA_TENSOR_REDUCE_DECLARED_ORDER, + .elementwise = cpu_elementwise, + .reduce = omega_tensor_seam_reduce_cpu, +}; + +const OmegaTensorRealization *omega_tensor_cpu_realization(void) { return &CPU_REALIZATION; } diff --git a/src/tensor/omega_tensor_reduce_seam.c b/src/tensor/omega_tensor_reduce_seam.c new file mode 100644 index 000000000..af33b320f --- /dev/null +++ b/src/tensor/omega_tensor_reduce_seam.c @@ -0,0 +1,29 @@ +#include "omega_tensor_reduce_seam.h" + +#include <stdlib.h> +#include <string.h> + +#include "omega_numeric.h" + +#include "omega_numeric_reduce.h" + +_Static_assert(sizeof(OMEGA_REDUCE_DECLARED_ORDER) == sizeof(OMEGA_TENSOR_REDUCE_DECLARED_ORDER), + "tensor reduce order must equal the E1 reduction order"); + +int omega_tensor_seam_reduce_cpu(OmegaTensorReduceOp op, const float *x, size_t n, float *out) { + if (strcmp(OMEGA_REDUCE_DECLARED_ORDER, OMEGA_TENSOR_REDUCE_DECLARED_ORDER) != 0) + return OMEGA_NUMERIC_ERR_BAD_ARGS; + OmegaReduceOp r; + switch (op) { + case OMEGA_TR_SUM: r = OMEGA_RED_SUM; break; + case OMEGA_TR_MAX: r = OMEGA_RED_MAX; break; + case OMEGA_TR_MIN: r = OMEGA_RED_MIN; break; + case OMEGA_TR_MEAN: r = OMEGA_RED_MEAN; break; + default: return OMEGA_NUMERIC_ERR_BAD_ARGS; + } + if (n == 0) return OMEGA_NUMERIC_ERR_BAD_ARGS; + return omega_reduce_cpu(r, x, n, out); +} + +const char *omega_tensor_seam_reduce_source(void) { return "E1_WP_D_OMEGA_REDUCE_CPU"; } + diff --git a/src/tensor/omega_tensor_reduce_seam.h b/src/tensor/omega_tensor_reduce_seam.h new file mode 100644 index 000000000..aeb6e9947 --- /dev/null +++ b/src/tensor/omega_tensor_reduce_seam.h @@ -0,0 +1,33 @@ +#ifndef OMEGA_TENSOR_REDUCE_SEAM_H +#define OMEGA_TENSOR_REDUCE_SEAM_H + +/* + * The one place where tensor reductions meet the E1 reduction contract. + * + * The order is OMEGA_TENSOR_REDUCE_DECLARED_ORDER (omega_tensor.h), the same + * string as OMEGA_REDUCE_DECLARED_ORDER in src/omega_numeric_reduce.h of the + * E1 WP-D reductions (omega PR #134, docs/numeric/E1_REDUCTION_CONTRACT.md): + * + * level 0 values are x[0..n). One level turns len values into ceil(len/32) + * values: value j of the next level is the 32-lane warp tree (lane i + * combines with lane i+d for d = 16, 8, 4, 2, 1, lower lane on the left) + * over values [32j, 32j+32) of this level, positions >= len filled with the + * identity (SUM/MEAN: -0.0, MAX/MIN: quiet NaN). At least one level is + * applied; levels repeat until one value is left. MEAN = omega_math_div(SUM, + * (float)n), 1 <= n <= 2^24. + * + * The seam calls omega_reduce_cpu (src/omega_numeric_reduce.h, E1 WP-D, + * omega #134); the local copy of the order used before #134 merged is gone. + * The test checks the order string and the bits against an independent + * reference of the definition. + */ + +#include <stddef.h> +#include "omega_tensor.h" + +/* Returns 0 or an OMEGA_NUMERIC_* code. n >= 1. */ +int omega_tensor_seam_reduce_cpu(OmegaTensorReduceOp op, const float *x, size_t n, float *out); +/* Reduction source linked: "E1_WP_D_OMEGA_REDUCE_CPU". */ +const char *omega_tensor_seam_reduce_source(void); + +#endif /* OMEGA_TENSOR_REDUCE_SEAM_H */ diff --git a/tests/test_omega_tensor.c b/tests/test_omega_tensor.c new file mode 100644 index 000000000..60da5939f --- /dev/null +++ b/tests/test_omega_tensor.c @@ -0,0 +1,817 @@ +/* + * M20 OMEGA_TENSOR CPU tests (docs/tensor/M20_OMEGA_TENSOR.md). + * + * The expected values come from an independent naive reference written in + * this file straight from the definitions: logical row-major arrays, index + * arithmetic on shapes only (never on the tensor's strides), the E1 scalar + * reference functions (omega_ref_*, omega_ieee_div/sqrt, omega_ref_ffma_int), + * and its own copy of the frozen reduction tree. Every comparison is bit + * exact (any NaN equals any NaN: NaN payload is not semantic). + * No GPU, no device, no libm. + */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#ifndef OMEGA_TENSOR_TEST_HOOKS +#error "test_omega_tensor.c needs -DOMEGA_TENSOR_TEST_HOOKS (set by mk/tensor.mk test build)" +#endif +#include "omega_numeric.h" +#include "omega_tensor.h" +#include "omega_tensor_reduce_seam.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 uint64_t g_rng = 0x9e3779b97f4a7c15ULL; +static uint64_t rnd(void) { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return g_rng; } + +static const uint32_t SPECIALS[] = { + 0x00000000U, 0x80000000U, 0x7f800000U, 0xff800000U, 0x7fc00000U, 0x7fa00001U, 0xffc00123U, + 0x00000001U, 0x80000001U, 0x007fffffU, 0x00800000U, 0x7f7fffffU, 0xff7fffffU, 0x3f800000U, + 0xbf800000U, 0x3f000000U, 0x4b800000U, 0x33800000U, 0x3effffffU, 0x7f000000U, +}; +#define NSPECIAL (sizeof(SPECIALS) / sizeof(SPECIALS[0])) + +/* Random FP32: 1/4 specials, 1/4 small-range normals, 1/2 raw bit patterns. */ +static float rand_f32(void) { + uint64_t r = rnd(); + switch (r & 3u) { + case 0: return omega_bits_to_float(SPECIALS[(r >> 8) % NSPECIAL]); + case 1: return omega_bits_to_float((uint32_t)((r >> 32) & 0x807fffffU) | ((uint32_t)(120 + ((r >> 8) % 16)) << 23)); + default: return omega_bits_to_float((uint32_t)(r >> 16)); + } +} +/* Finite moderate values (for matmul / sums so results are not all NaN). */ +static float rand_mod(void) { + uint64_t r = rnd(); + if ((r & 63u) == 0) return omega_bits_to_float(SPECIALS[(r >> 8) % NSPECIAL]); + return omega_bits_to_float((uint32_t)((r >> 32) & 0x807fffffU) | ((uint32_t)(110 + ((r >> 8) % 30)) << 23)); +} +static void fill(float *x, size_t n, float (*g)(void)) { for (size_t i = 0; i < n; i++) x[i] = g(); } + +static bool same(float a, float b) { return omega_numeric_bits_equal(a, b); } +static size_t mismatches(const float *a, const float *b, size_t n) { + size_t m = 0; + for (size_t i = 0; i < n; i++) m += !same(a[i], b[i]); + return m; +} +static uint64_t prod(uint32_t r, const uint64_t *s) { uint64_t n = 1; for (uint32_t i = 0; i < r; i++) n *= s[i]; return n; } + +/* ---- independent reference ------------------------------------------------ */ + +typedef float (*Bin)(float, float); +static int g_selop; +static float r_add(float a, float b) { return omega_ref_fadd(a, b); } +static float r_sub(float a, float b) { return omega_ref_fsub(a, b); } +static float r_mul(float a, float b) { return omega_ref_fmul(a, b); } +static float r_div(float a, float b) { return omega_ieee_div(a, b); } +static float r_min(float a, float b) { return omega_ref_fmin(a, b); } +static float r_max(float a, float b) { return omega_ref_fmax(a, b); } +static float r_sel(float a, float b) { return omega_ref_fsetp_pred(g_selop, a, b) == 1 ? a : b; } + +typedef struct { OmegaTensorBinaryOp op; Bin f; int selop; const char *name; } BinCase; +static const BinCase BIN_CASES[] = { + {OMEGA_TB_ADD, r_add, 0, "ADD"}, {OMEGA_TB_SUB, r_sub, 0, "SUB"}, {OMEGA_TB_MUL, r_mul, 0, "MUL"}, + {OMEGA_TB_DIV, r_div, 0, "DIV"}, {OMEGA_TB_MIN, r_min, 0, "MIN"}, {OMEGA_TB_MAX, r_max, 0, "MAX"}, + {OMEGA_TB_SEL_GE, r_sel, OMEGA_NOP_FSETP_SEL, "SEL_GE"}, {OMEGA_TB_SEL_LT, r_sel, OMEGA_NOP_FSETP_LT_SEL, "SEL_LT"}, + {OMEGA_TB_SEL_LE, r_sel, OMEGA_NOP_FSETP_LE_SEL, "SEL_LE"}, {OMEGA_TB_SEL_GT, r_sel, OMEGA_NOP_FSETP_GT_SEL, "SEL_GT"}, + {OMEGA_TB_SEL_EQ, r_sel, OMEGA_NOP_FSETP_EQ_SEL, "SEL_EQ"}, {OMEGA_TB_SEL_NE, r_sel, OMEGA_NOP_FSETP_NE_SEL, "SEL_NE"}, + {OMEGA_TB_SEL_NUM, r_sel, OMEGA_NOP_FSETP_NUM_SEL, "SEL_NUM"}, {OMEGA_TB_SEL_NAN, r_sel, OMEGA_NOP_FSETP_NAN_SEL, "SEL_NAN"}, + {OMEGA_TB_SEL_LTU, r_sel, OMEGA_NOP_FSETP_LTU_SEL, "SEL_LTU"}, {OMEGA_TB_SEL_LEU, r_sel, OMEGA_NOP_FSETP_LEU_SEL, "SEL_LEU"}, + {OMEGA_TB_SEL_GTU, r_sel, OMEGA_NOP_FSETP_GTU_SEL, "SEL_GTU"}, {OMEGA_TB_SEL_GEU, r_sel, OMEGA_NOP_FSETP_GEU_SEL, "SEL_GEU"}, + {OMEGA_TB_SEL_EQU, r_sel, OMEGA_NOP_FSETP_EQU_SEL, "SEL_EQU"}, {OMEGA_TB_SEL_NEU, r_sel, OMEGA_NOP_FSETP_NEU_SEL, "SEL_NEU"}, +}; +#define NBIN (sizeof(BIN_CASES) / sizeof(BIN_CASES[0])) + +/* Index of logical element `flat` of out shape (ro, so) inside an operand of + * shape (ra, sa) under numpy broadcasting (dense row-major operand). */ +static uint64_t bcast_src(uint64_t flat, uint32_t ro, const uint64_t *so, uint32_t ra, const uint64_t *sa) { + uint64_t idx[8]; + for (uint32_t d = ro; d-- > 0;) { idx[d] = flat % so[d]; flat /= so[d]; } + uint64_t src = 0; + for (uint32_t d = 0; d < ra; d++) { + uint64_t i = idx[ro - ra + d]; + src = src * sa[d] + (sa[d] == 1 ? 0 : i); + } + return src; +} + +static float ref_tree(OmegaTensorReduceOp op, const float *x, size_t n) { + float pad = omega_bits_to_float(op == OMEGA_TR_SUM || op == OMEGA_TR_MEAN ? 0x80000000U : 0x7fc00000U); + float *lvl = malloc(n * sizeof(float)); + memcpy(lvl, x, n * sizeof(float)); + size_t len = n; + int levels = 0; + while (levels == 0 || len > 1) { + size_t out = 0; + for (size_t base = 0; base < len; base += 32) { + float v[32]; + for (int l = 0; l < 32; l++) v[l] = base + (size_t)l < len ? lvl[base + (size_t)l] : pad; + static const int deltas[5] = {16, 8, 4, 2, 1}; + for (int k = 0; k < 5; k++) + for (int i = 0; i < deltas[k]; i++) { + float a = v[i], b = v[i + deltas[k]]; + v[i] = op == OMEGA_TR_MAX ? omega_ref_fmax(a, b) + : op == OMEGA_TR_MIN ? omega_ref_fmin(a, b) : omega_ref_fadd(a, b); + } + lvl[out++] = v[0]; + } + len = out; + levels++; + } + float r = lvl[0]; + free(lvl); + if (op == OMEGA_TR_MEAN) r = omega_ieee_div(r, (float)n); + return r; +} + +/* Reference matmul on dense row-major [M,K] x [K,N]. */ +static void ref_matmul(const float *a, const float *b, float *o, size_t M, size_t K, size_t N) { + float *p = malloc(K * sizeof(float)); + for (size_t i = 0; i < M; i++) + for (size_t j = 0; j < N; j++) { + for (size_t k = 0; k < K; k++) p[k] = omega_ref_fmul(a[i * K + k], b[k * N + j]); + o[i * N + j] = ref_tree(OMEGA_TR_SUM, p, K); + } + free(p); +} + +/* ---- helpers -------------------------------------------------------------- */ + +static OmegaTensorCtx *g; +static OmegaTensor mk(uint32_t rank, const uint64_t *shape, const float *data) { + OmegaTensor t; + int rc = omega_tensor_from_f32(g, rank, shape, data, &t); + if (rc) { printf("FATAL create rc=%d\n", rc); exit(2); } + return t; +} +static float *rd(OmegaTensor t) { + OmegaTensorInfo in; + if (omega_tensor_info(g, t, &in)) return NULL; + float *o = malloc((size_t)in.elements * sizeof(float)); + if (omega_tensor_read_f32(g, t, o, (size_t)in.elements)) { free(o); return NULL; } + return o; +} +static void vid(OmegaTensor t, uint8_t id[32]) { if (omega_tensor_value_id(g, t, id)) memset(id, 0xee, 32); } + +/* ---- 1. shape / type errors ------------------------------------------------ */ +static void test_shape_type(void) { + float d[64] = {0}; + uint64_t s9[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1}, s0[2] = {2, 0}, big[2] = {1u << 20, 1u << 11}; + OmegaTensor t; + CHECK(omega_tensor_from_f32(g, 9, s9, d, &t) == OMEGA_TENSOR_ERR_RANK, "rank 9 refused"); + CHECK(omega_tensor_from_f32(g, 2, s0, d, &t) == OMEGA_TENSOR_ERR_SHAPE, "zero dim refused"); + CHECK(omega_tensor_from_f32(g, 2, big, d, &t) == OMEGA_TENSOR_ERR_CAPACITY, "2^31 elements refused"); + CHECK(omega_tensor_from_data(g, (OmegaDType)9, 1, s9, d, &t) == OMEGA_TENSOR_ERR_DTYPE, "unknown dtype"); + uint64_t s23[2] = {2, 3}, s34[2] = {3, 4}, s4[1] = {4}, s32[2] = {3, 2}; + OmegaTensor a = mk(2, s23, d), b = mk(2, s34, d), c = mk(1, s4, d), e = mk(2, s32, d), o; + uint16_t h[6] = {0}; + OmegaTensor f16; + CHECK(omega_tensor_from_data(g, OMEGA_DT_F16, 2, s23, h, &f16) == 0, "f16 create"); + CHECK(omega_tensor_binary(g, OMEGA_TB_ADD, a, f16, &o) == OMEGA_TENSOR_ERR_DTYPE, "f16 arithmetic refused"); + CHECK(omega_tensor_reduce(g, OMEGA_TR_SUM, f16, 0, false, &o) == OMEGA_TENSOR_ERR_DTYPE, "f16 reduce refused"); + CHECK(omega_tensor_matmul(g, f16, e, &o) == OMEGA_TENSOR_ERR_DTYPE, "f16 matmul refused"); + CHECK(omega_tensor_cast(g, f16, OMEGA_DT_BF16, &o) == OMEGA_TENSOR_ERR_DTYPE, "f16->bf16 refused"); + CHECK(omega_tensor_binary(g, OMEGA_TB_ADD, a, b, &o) == OMEGA_TENSOR_ERR_SHAPE, "[2,3]+[3,4] refused"); + CHECK(omega_tensor_matmul(g, a, a, &o) == OMEGA_TENSOR_ERR_SHAPE, "matmul K mismatch"); + CHECK(omega_tensor_matmul(g, c, b, &o) == OMEGA_TENSOR_ERR_RANK, "matmul rank 1 refused"); + CHECK(omega_tensor_reduce(g, OMEGA_TR_SUM, a, 2, false, &o) == OMEGA_TENSOR_ERR_AXIS, "axis 2 of rank 2"); + CHECK(omega_tensor_binary(g, (OmegaTensorBinaryOp)99, a, a, &o) == OMEGA_TENSOR_ERR_BAD_ARGS, "unknown op"); + CHECK(omega_tensor_reduce(g, (OmegaTensorReduceOp)7, a, 0, false, &o) == OMEGA_TENSOR_ERR_BAD_ARGS, "unknown reduce"); + uint32_t bad_perm[2] = {0, 0}; + CHECK(omega_tensor_permute(g, a, bad_perm, &o) == OMEGA_TENSOR_ERR_AXIS, "duplicate perm axis"); + OmegaTensor sc = mk(0, NULL, d); + CHECK(omega_tensor_transpose(g, sc, &o) == OMEGA_TENSOR_ERR_RANK, "transpose of scalar"); + CHECK(omega_tensor_reduce(g, OMEGA_TR_SUM, sc, 0, false, &o) == OMEGA_TENSOR_ERR_RANK, "reduce of scalar"); + OmegaTensor ts[] = {a, b, c, e, f16, sc}; + for (size_t i = 0; i < sizeof(ts) / sizeof(ts[0]); i++) omega_tensor_release(g, ts[i]); + /* bad realization tables */ + OmegaTensorRealization bad = *omega_tensor_cpu_realization(); + OmegaTensorCtx *x; + bad.reduce_order = "SEQUENTIAL_LEFT_TO_RIGHT"; + CHECK(omega_tensor_ctx_create(4, &bad, &x) == OMEGA_TENSOR_ERR_REALIZATION, "wrong order string refused"); + bad = *omega_tensor_cpu_realization(); + bad.reduce = NULL; + CHECK(omega_tensor_ctx_create(4, &bad, &x) == OMEGA_TENSOR_ERR_REALIZATION, "missing reduce refused"); +} + +/* ---- 2. broadcasting -------------------------------------------------------- */ +static void bcase(uint32_t ra, const uint64_t *sa, uint32_t rb, const uint64_t *sb, int expect_rc, + uint32_t er, const uint64_t *es, const char *name) { + uint32_t r = 0; + uint64_t s[8]; + int rc = omega_tensor_broadcast_shape(ra, sa, rb, sb, &r, s); + bool ok = rc == expect_rc; + if (ok && rc == 0) ok = r == er && (er == 0 || memcmp(s, es, er * 8) == 0); + CHECK(ok, "broadcast shape %s rc=%d", name, rc); +} + +static void test_broadcast(void) { + uint64_t s31[] = {3, 1}, s14[] = {1, 4}, s34[] = {3, 4}, s4[] = {4}, s234[] = {2, 3, 4}; + uint64_t s23[] = {2, 3}, s32[] = {3, 2}, s54[] = {5, 4}, s41[] = {4, 1}, s1[] = {1}; + uint64_t s5114[] = {5, 1, 1, 4}, s736[] = {7, 3, 1}, s5734[] = {5, 7, 3, 4}; + bcase(2, s31, 2, s14, 0, 2, s34, "[3,1]x[1,4]"); + bcase(1, s4, 3, s234, 0, 3, s234, "[4]x[2,3,4]"); + bcase(0, NULL, 2, s23, 0, 2, s23, "scalar x [2,3]"); + bcase(1, s1, 1, s4, 0, 1, s4, "[1]x[4]"); + bcase(4, s5114, 3, s736, 0, 4, s5734, "[5,1,1,4]x[7,3,1]"); + bcase(2, s23, 2, s32, OMEGA_TENSOR_ERR_SHAPE, 0, NULL, "[2,3]x[3,2]"); + bcase(2, s54, 2, s41, OMEGA_TENSOR_ERR_SHAPE, 0, NULL, "[5,4]x[4,1]"); + bcase(1, s4, 2, s23, OMEGA_TENSOR_ERR_SHAPE, 0, NULL, "[4]x[2,3]"); + + /* value parity of broadcast ops against bcast_src index arithmetic */ + struct { uint32_t ra; uint64_t sa[4]; uint32_t rb; uint64_t sb[4]; } cs[] = { + {2, {3, 1}, 2, {1, 4}}, {1, {4}, 3, {2, 3, 4}}, {0, {0}, 2, {2, 3}}, + {4, {5, 1, 1, 4}, 3, {7, 3, 1}}, {3, {2, 1, 6}, 3, {2, 5, 1}}, + }; + for (size_t c = 0; c < sizeof(cs) / sizeof(cs[0]); c++) { + uint64_t na = prod(cs[c].ra, cs[c].sa), nb = prod(cs[c].rb, cs[c].sb); + float *da = malloc(na * 4), *db = malloc(nb * 4); + fill(da, na, rand_f32); + fill(db, nb, rand_f32); + OmegaTensor A = mk(cs[c].ra, cs[c].sa, da), B = mk(cs[c].rb, cs[c].sb, db); + uint32_t ro; + uint64_t so[8]; + omega_tensor_broadcast_shape(cs[c].ra, cs[c].sa, cs[c].rb, cs[c].sb, &ro, so); + uint64_t no = prod(ro, so); + float *ex = malloc(no * 4); + for (size_t k = 0; k < NBIN; k++) { + g_selop = BIN_CASES[k].selop; + for (uint64_t i = 0; i < no; i++) + ex[i] = BIN_CASES[k].f(da[bcast_src(i, ro, so, cs[c].ra, cs[c].sa)], + db[bcast_src(i, ro, so, cs[c].rb, cs[c].sb)]); + OmegaTensor O; + int rc = omega_tensor_binary(g, BIN_CASES[k].op, A, B, &O); + float *got = rc ? NULL : rd(O); + CHECK(got && mismatches(ex, got, no) == 0, "broadcast case %zu op %s rc=%d", c, BIN_CASES[k].name, rc); + free(got); + if (!rc) omega_tensor_release(g, O); + } + /* broadcast_to view: zero strides, values */ + OmegaTensor V; + CHECK(omega_tensor_broadcast_to(g, A, ro, so, &V) == 0, "broadcast_to case %zu", c); + OmegaTensorInfo vi; + omega_tensor_info(g, V, &vi); + bool zs = true; + for (uint32_t d = 0; d < ro; d++) { + bool expanded = d < ro - cs[c].ra || cs[c].sa[d - (ro - cs[c].ra)] == 1; + if (expanded && so[d] > 1 && vi.strides[d] != 0) zs = false; + } + CHECK(zs && vi.is_view, "broadcast_to zero strides case %zu", c); + float *gv = rd(V); + for (uint64_t i = 0; i < no; i++) ex[i] = da[bcast_src(i, ro, so, cs[c].ra, cs[c].sa)]; + CHECK(gv && mismatches(ex, gv, no) == 0, "broadcast_to values case %zu", c); + free(gv); + omega_tensor_release(g, V); + omega_tensor_release(g, A); + omega_tensor_release(g, B); + free(da); free(db); free(ex); + } + float d6[6] = {1, 2, 3, 4, 5, 6}; + uint64_t s3[] = {3}; + OmegaTensor A = mk(2, s23, d6), O; + CHECK(omega_tensor_broadcast_to(g, A, 1, s3, &O) == OMEGA_TENSOR_ERR_SHAPE, "broadcast_to lower rank refused"); + CHECK(omega_tensor_broadcast_to(g, A, 2, s32, &O) == OMEGA_TENSOR_ERR_SHAPE, "broadcast_to [2,3]->[3,2] refused"); + omega_tensor_release(g, A); +} + +/* ---- 3. views and strides ------------------------------------------------- */ +static void test_views(void) { + uint64_t s[3] = {4, 5, 6}; + float d[120]; + for (int i = 0; i < 120; i++) d[i] = (float)i; + OmegaTensor T = mk(3, s, d), P, S, TS, ST, V2, R, C, Z; + uint8_t before[32], after[32]; + vid(T, before); + /* permute (2,0,1): out[i][j][k] = T[j][k][i] */ + uint32_t perm[3] = {2, 0, 1}; + CHECK(omega_tensor_permute(g, T, perm, &P) == 0, "permute"); + float *gp = rd(P); + bool ok = gp != NULL; + for (int i = 0; ok && i < 6; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 5; k++) + ok = ok && (gp[(i * 4 + j) * 5 + k] == d[(j * 5 + k) * 6 + i]); + CHECK(ok, "permute values"); + free(gp); + /* slice [1:4:2, 0:5:2, 2:6] then transpose last two */ + uint64_t st[3] = {1, 0, 2}, sp[3] = {4, 5, 6}, sz[3] = {2, 2, 1}; + CHECK(omega_tensor_slice(g, T, st, sp, sz, &S) == 0, "slice"); + OmegaTensorInfo si; + omega_tensor_info(g, S, &si); + CHECK(si.shape[0] == 2 && si.shape[1] == 3 && si.shape[2] == 4 && si.offset == 1 * 30 + 2, "slice shape/offset"); + CHECK(omega_tensor_transpose(g, S, &TS) == 0, "transpose of slice"); + float *gts = rd(TS); + ok = gts != NULL; + for (int a = 0; ok && a < 2; a++) for (int k = 0; k < 4; k++) for (int j = 0; j < 3; j++) + ok = ok && (gts[(a * 4 + k) * 3 + j] == d[((1 + 2 * a) * 5 + 2 * j) * 6 + 2 + k]); + CHECK(ok, "transpose of slice values"); + free(gts); + /* slice of transpose == transpose of slice */ + OmegaTensor TT; + omega_tensor_transpose(g, T, &TT); + uint64_t st2[3] = {1, 2, 0}, sp2[3] = {4, 6, 5}, sz2[3] = {2, 1, 2}; + CHECK(omega_tensor_slice(g, TT, st2, sp2, sz2, &ST) == 0, "slice of transpose"); + bool eq = false; + omega_tensor_value_equal(g, ST, TS, &eq); + CHECK(eq, "slice(transpose) == transpose(slice)"); + /* view of a view of a view */ + uint64_t st3[3] = {1, 1, 1}, sp3[3] = {2, 3, 3}; + CHECK(omega_tensor_slice(g, TS, st3, sp3, NULL, &V2) == 0, "slice of transposed slice"); + float *gv2 = rd(V2); + ok = gv2 != NULL; + for (int k = 0; ok && k < 2; k++) for (int j = 0; j < 2; j++) /* a=1, k+1, j+1 */ + ok = ok && (gv2[k * 2 + j] == d[((1 + 2 * 1) * 5 + 2 * (j + 1)) * 6 + 2 + (k + 1)]); + CHECK(ok, "view of view of view values"); + free(gv2); + OmegaTensorInfo i2; + omega_tensor_info(g, V2, &i2); + CHECK(i2.storage.slot == si.storage.slot && i2.storage.generation == si.storage.generation, "views share storage"); + /* reshape: contiguous ok, transposed refused, copy then ok */ + uint64_t rs[2] = {20, 6}; + CHECK(omega_tensor_reshape(g, T, 2, rs, &R) == 0, "reshape contiguous"); + CHECK(omega_tensor_reshape(g, TT, 2, rs, &Z) == OMEGA_TENSOR_ERR_NOT_CONTIGUOUS, "reshape transposed refused"); + uint64_t rbad[2] = {7, 6}; + CHECK(omega_tensor_reshape(g, T, 2, rbad, &Z) == OMEGA_TENSOR_ERR_SHAPE, "reshape count mismatch"); + CHECK(omega_tensor_contiguous(g, TT, &C) == 0, "contiguous copy"); + uint64_t rs2[2] = {4, 30}; + OmegaTensor RC; + CHECK(omega_tensor_reshape(g, C, 2, rs2, &RC) == 0, "reshape of contiguous copy"); + OmegaTensorInfo ci; + omega_tensor_info(g, C, &ci); + CHECK(!ci.is_view && ci.storage.slot != si.storage.slot, "contiguous has own storage"); + eq = false; + omega_tensor_value_equal(g, C, TT, &eq); + CHECK(eq, "contiguous copy value-equal to its view"); + uint8_t id1[32], id2[32]; + vid(C, id1); vid(TT, id2); + CHECK(memcmp(id1, id2, 32) == 0, "layout is not identity: value ids equal"); + omega_tensor_view_id(g, C, id1); omega_tensor_view_id(g, TT, id2); + CHECK(memcmp(id1, id2, 32) != 0, "view ids differ"); + /* zero-stride: broadcast of a column, then slice and transpose of it */ + uint64_t c1[2] = {4, 1}, c46[2] = {4, 6}; + float col[4] = {10, 20, 30, 40}; + OmegaTensor K = mk(2, c1, col), KB, KBT; + omega_tensor_broadcast_to(g, K, 2, c46, &KB); + omega_tensor_transpose(g, KB, &KBT); + float *gk = rd(KBT); + ok = gk != NULL; + for (int i = 0; ok && i < 6; i++) for (int j = 0; j < 4; j++) ok = ok && (gk[i * 4 + j] == col[j]); + CHECK(ok, "transpose of zero-stride view"); + free(gk); + CHECK(omega_tensor_reshape(g, KB, 1, (uint64_t[]){24}, &Z) == OMEGA_TENSOR_ERR_NOT_CONTIGUOUS, + "reshape of zero-stride refused"); + /* bounds */ + uint64_t bs[3] = {0, 0, 0}, be[3] = {5, 5, 6}; + CHECK(omega_tensor_slice(g, T, bs, be, NULL, &Z) == OMEGA_TENSOR_ERR_BOUNDS, "slice past end"); + uint64_t ee[3] = {0, 5, 6}; + CHECK(omega_tensor_slice(g, T, bs, ee, NULL, &Z) == OMEGA_TENSOR_ERR_SHAPE, "empty slice refused"); + CHECK(omega_tensor_slice(g, T, bs, sp, (uint64_t[]){1, 0, 1}, &Z) == OMEGA_TENSOR_ERR_BAD_ARGS, "step 0"); + { /* step near 2^64: one element per axis, no overflow, value T[0][0][0] */ + OmegaTensor H; + uint64_t huge[3] = {UINT64_MAX, UINT64_MAX, UINT64_MAX / 3}; + float hv = -1; + CHECK(omega_tensor_slice(g, T, bs, sp, huge, &H) == 0 && omega_tensor_read_f32(g, H, &hv, 1) == 0 && + hv == d[0], "huge step slice"); + omega_tensor_release(g, H); + } + /* parent unchanged by all of the above */ + vid(T, after); + CHECK(memcmp(before, after, 32) == 0, "parent value id unchanged by views"); + OmegaTensor all[] = {RC, C, R, V2, ST, TT, TS, S, P, KBT, KB, K, T}; + for (size_t i = 0; i < sizeof(all) / sizeof(all[0]); i++) + CHECK(omega_tensor_release(g, all[i]) == 0, "release %zu", i); +} + +/* ---- 4. generation safety ------------------------------------------------- */ +static void test_generations(void) { + float d[6] = {1, 2, 3, 4, 5, 6}, o[6]; + uint64_t s[2] = {2, 3}; + OmegaTensor A = mk(2, s, d), V, W, O; + omega_tensor_transpose(g, A, &V); + OmegaTensorInfo ai; + omega_tensor_info(g, A, &ai); + /* releasing a view leaves the parent alive */ + omega_tensor_transpose(g, A, &W); + CHECK(omega_tensor_release(g, W) == 0, "release view"); + CHECK(omega_tensor_read_f32(g, W, o, 6) == OMEGA_TENSOR_ERR_STALE, "released view stale"); + CHECK(omega_tensor_read_f32(g, A, o, 6) == 0, "parent still valid after view release"); + /* releasing the owner makes every view stale */ + CHECK(omega_tensor_release(g, A) == 0, "release owner"); + CHECK(omega_tensor_read_f32(g, A, o, 6) == OMEGA_TENSOR_ERR_STALE, "use after release"); + CHECK(omega_tensor_release(g, A) == OMEGA_TENSOR_ERR_STALE, "double release"); + CHECK(!omega_tensor_storage_valid(g, ai.storage), "storage handle stale"); + CHECK(omega_tensor_read_f32(g, V, o, 6) == OMEGA_TENSOR_ERR_STALE, "stale view read"); + OmegaTensorInfo vi; + CHECK(omega_tensor_info(g, V, &vi) == OMEGA_TENSOR_ERR_STALE, "stale view info"); + CHECK(omega_tensor_binary(g, OMEGA_TB_ADD, V, V, &O) == OMEGA_TENSOR_ERR_STALE, "stale view op"); + CHECK(omega_tensor_matmul(g, V, V, &O) == OMEGA_TENSOR_ERR_STALE, "stale view matmul"); + CHECK(omega_tensor_transpose(g, V, &O) == OMEGA_TENSOR_ERR_STALE, "view of stale view"); + uint8_t id[32]; + CHECK(omega_tensor_value_id(g, V, id) == OMEGA_TENSOR_ERR_STALE, "stale value id"); + CHECK(omega_tensor_release(g, V) == 0, "stale view descriptor can still be released"); + /* no ABA: the reused slot gets a new generation */ + OmegaTensor B = mk(2, s, d); + OmegaTensorInfo bi; + omega_tensor_info(g, B, &bi); + CHECK(bi.storage.slot == ai.storage.slot && bi.storage.generation != ai.storage.generation, + "slot reused with new generation (slot %u gen %llu vs %llu)", bi.storage.slot, + (unsigned long long)bi.storage.generation, (unsigned long long)ai.storage.generation); + CHECK(omega_tensor_read_f32(g, A, o, 6) == OMEGA_TENSOR_ERR_STALE, "old handle not revived"); + CHECK(!omega_tensor_storage_valid(g, ai.storage), "old storage handle not revived"); + omega_tensor_release(g, B); + OmegaTensor bogus = {.slot = 999999, .generation = 1}; + CHECK(omega_tensor_read_f32(g, bogus, o, 6) == OMEGA_TENSOR_ERR_STALE, "out of range handle"); + + /* generation never wraps: slot retired at UINT64_MAX */ + OmegaTensorCtx *c1; + CHECK(omega_tensor_ctx_create(1, omega_tensor_cpu_realization(), &c1) == 0, "ctx cap 1"); + CHECK(omega_tensor_test_set_storage_generation(c1, 0, UINT64_MAX - 1) == 0, "set gen"); + CHECK(omega_tensor_test_set_storage_generation(c1, 0, 5) == OMEGA_TENSOR_ERR_BAD_ARGS, "set gen rollback refused (free slot)"); + CHECK(omega_tensor_test_set_storage_generation(c1, 0, UINT64_MAX - 1) == OMEGA_TENSOR_ERR_BAD_ARGS, "set gen same value refused"); + OmegaTensor t1, t2, t3; + omega_tensor_from_f32(c1, 2, s, d, &t1); + OmegaTensorInfo i1; + omega_tensor_info(c1, t1, &i1); + CHECK(i1.storage.generation == UINT64_MAX - 1, "gen max-1"); + CHECK(omega_tensor_test_set_storage_generation(c1, 0, 5) == OMEGA_TENSOR_ERR_BAD_ARGS, "set gen refused on live slot"); + omega_tensor_release(c1, t1); + CHECK(omega_tensor_from_f32(c1, 2, s, d, &t2) == 0, "alloc at gen max"); + omega_tensor_info(c1, t2, &i1); + CHECK(i1.storage.generation == UINT64_MAX, "gen max"); + omega_tensor_release(c1, t2); + CHECK(omega_tensor_from_f32(c1, 2, s, d, &t3) == OMEGA_TENSOR_ERR_CAPACITY, "retired slot never reused"); + CHECK(omega_tensor_read_f32(c1, t2, o, 6) == OMEGA_TENSOR_ERR_STALE, "handle at gen max stale after release"); + omega_tensor_ctx_destroy(c1); +} + +/* ---- 5. immutability ------------------------------------------------------ */ +static void test_immutability(void) { + float da[12], db[12]; + fill(da, 12, rand_f32); + fill(db, 12, rand_f32); + uint64_t s[2] = {3, 4}, s43[2] = {4, 3}; + OmegaTensor A = mk(2, s, da), B = mk(2, s, db), B2 = mk(2, s43, db), O; + uint8_t ia[32], ib[32], ib2[32], x[32]; + vid(A, ia); vid(B, ib); vid(B2, ib2); + for (size_t k = 0; k < NBIN; k++) { omega_tensor_binary(g, BIN_CASES[k].op, A, B, &O); omega_tensor_release(g, O); } + omega_tensor_fma(g, A, B, A, &O); omega_tensor_release(g, O); + omega_tensor_unary(g, OMEGA_TU_SQRT, A, &O); omega_tensor_release(g, O); + omega_tensor_reduce(g, OMEGA_TR_SUM, A, 1, false, &O); omega_tensor_release(g, O); + omega_tensor_matmul(g, A, B2, &O); omega_tensor_release(g, O); + omega_tensor_cast(g, A, OMEGA_DT_F16, &O); omega_tensor_release(g, O); + vid(A, x); CHECK(memcmp(ia, x, 32) == 0, "A unchanged by ops"); + vid(B, x); CHECK(memcmp(ib, x, 32) == 0, "B unchanged by ops"); + vid(B2, x); CHECK(memcmp(ib2, x, 32) == 0, "B2 unchanged by ops"); + /* outputs never alias inputs */ + omega_tensor_binary(g, OMEGA_TB_ADD, A, B, &O); + OmegaTensorInfo io, iA; + omega_tensor_info(g, O, &io); omega_tensor_info(g, A, &iA); + CHECK(!io.is_view && io.storage.slot != iA.storage.slot, "op output has its own storage"); + omega_tensor_release(g, O); + /* NaN payload is not semantic; -0 and +0 are */ + float n1[1] = {omega_bits_to_float(0x7fc00000U)}, n2[1] = {omega_bits_to_float(0xffa12345U)}; + float z1[1] = {0.0f}, z2[1] = {omega_bits_to_float(0x80000000U)}; + uint64_t s1[1] = {1}; + OmegaTensor N1 = mk(1, s1, n1), N2 = mk(1, s1, n2), Z1 = mk(1, s1, z1), Z2 = mk(1, s1, z2); + uint8_t a1[32], a2[32]; + vid(N1, a1); vid(N2, a2); + CHECK(memcmp(a1, a2, 32) == 0, "NaN payloads share a value id"); + vid(Z1, a1); vid(Z2, a2); + CHECK(memcmp(a1, a2, 32) != 0, "+0 and -0 differ"); + vid(A, a1); vid(B2, a2); + OmegaTensor AR; + omega_tensor_reshape(g, A, 2, s43, &AR); + vid(AR, a1); + CHECK(memcmp(a1, ia, 32) != 0, "shape is part of value identity"); + OmegaTensor all[] = {AR, A, B, B2, N1, N2, Z1, Z2}; + for (size_t i = 0; i < sizeof(all) / sizeof(all[0]); i++) omega_tensor_release(g, all[i]); +} + +/* ---- 6. CPU parity -------------------------------------------------------- */ +static void test_elementwise_parity(void) { + const size_t n = 4099; + float *a = malloc(n * 4), *b = malloc(n * 4), *c = malloc(n * 4), *ex = malloc(n * 4); + fill(a, n, rand_f32); fill(b, n, rand_f32); fill(c, n, rand_f32); + for (size_t i = 0; i < NSPECIAL * NSPECIAL && i < n; i++) { /* every special pair */ + a[i] = omega_bits_to_float(SPECIALS[i / NSPECIAL]); + b[i] = omega_bits_to_float(SPECIALS[i % NSPECIAL]); + } + uint64_t s[1] = {n}; + OmegaTensor A = mk(1, s, a), B = mk(1, s, b), Cc = mk(1, s, c), O; + for (size_t k = 0; k < NBIN; k++) { + g_selop = BIN_CASES[k].selop; + for (size_t i = 0; i < n; i++) ex[i] = BIN_CASES[k].f(a[i], b[i]); + int rc = omega_tensor_binary(g, BIN_CASES[k].op, A, B, &O); + float *got = rc ? NULL : rd(O); + CHECK(got && mismatches(ex, got, n) == 0, "parity %s rc=%d", BIN_CASES[k].name, rc); + free(got); + if (!rc) omega_tensor_release(g, O); + } + for (size_t i = 0; i < n; i++) ex[i] = omega_ieee_sqrt(a[i]); + int rc = omega_tensor_unary(g, OMEGA_TU_SQRT, A, &O); + float *got = rc ? NULL : rd(O); + CHECK(got && mismatches(ex, got, n) == 0, "parity SQRT"); + free(got); if (!rc) omega_tensor_release(g, O); + for (size_t i = 0; i < n; i++) ex[i] = omega_ref_ffma_int(a[i], b[i], c[i]); + rc = omega_tensor_fma(g, A, B, Cc, &O); + got = rc ? NULL : rd(O); + CHECK(got && mismatches(ex, got, n) == 0, "parity FMA"); + free(got); if (!rc) omega_tensor_release(g, O); + /* FMA with broadcast scalar c */ + float c0[1] = {c[7]}; + OmegaTensor C0 = mk(0, NULL, c0); + for (size_t i = 0; i < n; i++) ex[i] = omega_ref_ffma_int(a[i], b[i], c0[0]); + rc = omega_tensor_fma(g, A, B, C0, &O); + got = rc ? NULL : rd(O); + CHECK(got && mismatches(ex, got, n) == 0, "parity FMA broadcast c"); + free(got); if (!rc) omega_tensor_release(g, O); + /* casts */ + uint16_t *h = malloc(n * 2), *hg = malloc(n * 2); + for (size_t i = 0; i < n; i++) h[i] = omega_ref_f32_to_f16(a[i]); + rc = omega_tensor_cast(g, A, OMEGA_DT_F16, &O); + size_t mm = 0; + if (!rc) { omega_tensor_read(g, O, hg, n * 2); + for (size_t i = 0; i < n; i++) mm += !omega_numeric_compare_equal(OMEGA_CMP_F16_BITS, h[i], hg[i]); } + CHECK(!rc && mm == 0, "parity F32->F16 rc=%d mm=%zu", rc, mm); + if (!rc) { + OmegaTensor W; + int rc2 = omega_tensor_cast(g, O, OMEGA_DT_F32, &W); + for (size_t i = 0; i < n; i++) ex[i] = omega_ref_f16_to_f32(h[i]); + got = rc2 ? NULL : rd(W); + CHECK(got && mismatches(ex, got, n) == 0, "parity F16->F32"); + free(got); if (!rc2) omega_tensor_release(g, W); + omega_tensor_release(g, O); + } + rc = omega_tensor_cast(g, A, OMEGA_DT_BF16, &O); + if (omega_numeric_cpu_has_bf16()) { + for (size_t i = 0; i < n; i++) h[i] = omega_ref_f32_to_bf16(a[i]); + mm = 0; + if (!rc) { omega_tensor_read(g, O, hg, n * 2); + for (size_t i = 0; i < n; i++) mm += !omega_numeric_compare_equal(OMEGA_CMP_BF16_BITS, h[i], hg[i]); } + CHECK(!rc && mm == 0, "parity F32->BF16 rc=%d mm=%zu", rc, mm); + if (!rc) { + OmegaTensor W; + int rc2 = omega_tensor_cast(g, O, OMEGA_DT_F32, &W); + for (size_t i = 0; i < n; i++) ex[i] = omega_ref_bf16_to_f32(h[i]); + got = rc2 ? NULL : rd(W); + CHECK(got && mismatches(ex, got, n) == 0, "parity BF16->F32"); + free(got); if (!rc2) omega_tensor_release(g, W); + omega_tensor_release(g, O); + } + } else { + CHECK(rc == OMEGA_TENSOR_ERR_NUMERIC && omega_tensor_last_numeric_error(g) == OMEGA_NUMERIC_ERR_NOT_ENCODED, + "BF16 refused without FEAT_BF16"); + } + OmegaTensor all[] = {A, B, Cc, C0}; + for (size_t i = 0; i < 4; i++) omega_tensor_release(g, all[i]); + free(a); free(b); free(c); free(ex); free(h); free(hg); +} + +static void test_reduce_parity(void) { + /* 1-D lengths around the tile and level boundaries */ + static const size_t lens[] = {1, 2, 31, 32, 33, 63, 64, 1000, 1023, 1024, 1025, 32769}; + for (size_t li = 0; li < sizeof(lens) / sizeof(lens[0]); li++) { + size_t n = lens[li]; + float *x = malloc(n * 4); + fill(x, n, li % 2 ? rand_mod : rand_f32); + uint64_t s[1] = {n}; + OmegaTensor X = mk(1, s, x), O; + for (int op = 0; op < OMEGA_TR_COUNT; op++) { + float ex = ref_tree((OmegaTensorReduceOp)op, x, n), got = 0; + int rc = omega_tensor_reduce(g, (OmegaTensorReduceOp)op, X, 0, false, &O); + if (!rc) { omega_tensor_read_f32(g, O, &got, 1); omega_tensor_release(g, O); } + CHECK(!rc && same(ex, got), "reduce op %d n=%zu", op, n); + } + omega_tensor_release(g, X); + free(x); + } + /* signed zero: SUM of all -0 is -0 (pad is -0, not +0) */ + { + float nz[3] = {omega_bits_to_float(0x80000000U), omega_bits_to_float(0x80000000U), + omega_bits_to_float(0x80000000U)}, got = 0; + uint64_t s3[1] = {3}; + OmegaTensor Z = mk(1, s3, nz), O; + int rc = omega_tensor_reduce(g, OMEGA_TR_SUM, Z, 0, false, &O); + if (!rc) { omega_tensor_read_f32(g, O, &got, 1); omega_tensor_release(g, O); } + CHECK(!rc && omega_float_to_bits(got) == 0x80000000U, "SUM of -0s is -0"); + omega_tensor_release(g, Z); + } + /* every axis of a [3,37,5] tensor, plus keepdims and a strided view */ + uint64_t s[3] = {3, 37, 5}; + float x[555], ex[185], row[37]; + fill(x, 555, rand_mod); + OmegaTensor X = mk(3, s, x), XT, O; + for (uint32_t ax = 0; ax < 3; ax++) + for (int op = 0; op < OMEGA_TR_COUNT; op++) { + uint64_t n = s[ax], cnt = 0; + for (uint64_t i = 0; i < (ax == 0 ? 1 : 3); i++) + for (uint64_t j = 0; j < (ax == 1 ? 1 : 37); j++) + for (uint64_t k = 0; k < (ax == 2 ? 1 : 5); k++) { + for (uint64_t r = 0; r < n; r++) { + uint64_t ii = ax == 0 ? r : i, jj = ax == 1 ? r : j, kk = ax == 2 ? r : k; + row[r] = x[(ii * 37 + jj) * 5 + kk]; + } + ex[cnt++] = ref_tree((OmegaTensorReduceOp)op, row, n); + } + int rc = omega_tensor_reduce(g, (OmegaTensorReduceOp)op, X, ax, ax == 1, &O); + float *got = rc ? NULL : rd(O); + OmegaTensorInfo oi; + if (!rc) omega_tensor_info(g, O, &oi); + CHECK(got && mismatches(ex, got, cnt) == 0 && oi.rank == (ax == 1 ? 3u : 2u), + "reduce axis %u op %d", ax, op); + free(got); + if (!rc) omega_tensor_release(g, O); + } + /* reduce of a permuted view equals reduce of its contiguous copy */ + uint32_t perm[3] = {1, 2, 0}; + omega_tensor_permute(g, X, perm, &XT); + OmegaTensor XC, O1, O2; + omega_tensor_contiguous(g, XT, &XC); + omega_tensor_reduce(g, OMEGA_TR_SUM, XT, 0, false, &O1); + omega_tensor_reduce(g, OMEGA_TR_SUM, XC, 0, false, &O2); + bool eq = false; + omega_tensor_value_equal(g, O1, O2, &eq); + CHECK(eq, "reduce of view == reduce of copy"); + OmegaTensor all[] = {O1, O2, XC, XT, X}; + for (size_t i = 0; i < 5; i++) omega_tensor_release(g, all[i]); + CHECK(strcmp(omega_tensor_cpu_realization()->reduce_order, + "RECURSIVE_TILE32_PAIRWISE_TREE_LANE_DELTA_16_8_4_2_1_PAD_IDENTITY_MIN_ONE_LEVEL") == 0, + "reduce order string equals the E1 WP-D order"); +} + +static void check_matmul(size_t M, size_t K, size_t N, float (*gen)(void)) { + float *a = malloc(M * K * 4), *b = malloc(K * N * 4), *ex = malloc(M * N * 4); + fill(a, M * K, gen); + fill(b, K * N, gen); + ref_matmul(a, b, ex, M, K, N); + uint64_t sa[2] = {M, K}, sb[2] = {K, N}; + OmegaTensor A = mk(2, sa, a), B = mk(2, sb, b), O; + int rc = omega_tensor_matmul(g, A, B, &O); + float *got = rc ? NULL : rd(O); + size_t mm = got ? mismatches(ex, got, M * N) : M * N; + CHECK(mm == 0, "matmul %zux%zux%zu rc=%d mismatches=%zu", M, K, N, rc, mm); + free(got); + if (!rc) omega_tensor_release(g, O); + omega_tensor_release(g, A); + omega_tensor_release(g, B); + free(a); free(b); free(ex); +} + +static void test_matmul_parity(void) { + check_matmul(1, 1, 1, rand_mod); + check_matmul(1, 1, 1, rand_f32); + check_matmul(7, 13, 5, rand_mod); + check_matmul(7, 13, 5, rand_f32); + check_matmul(64, 64, 64, rand_mod); + check_matmul(129, 3, 257, rand_mod); + check_matmul(3, 1025, 2, rand_mod); /* K across two reduction levels */ + check_matmul(1, 33, 1, rand_mod); + /* strided operands: A^T as a view of a [K,M] tensor, B a slice */ + size_t M = 9, K = 40, N = 6; + float *at = malloc(K * M * 4), *bb = malloc(K * 2 * N * 4), *a = malloc(M * K * 4), *b = malloc(K * N * 4); + float *ex = malloc(M * N * 4); + fill(at, K * M, rand_mod); + fill(bb, K * 2 * N, rand_mod); + for (size_t i = 0; i < M; i++) for (size_t k = 0; k < K; k++) a[i * K + k] = at[k * M + i]; + for (size_t k = 0; k < K; k++) for (size_t j = 0; j < N; j++) b[k * N + j] = bb[k * 2 * N + 2 * j + 1]; + ref_matmul(a, b, ex, M, K, N); + uint64_t sat[2] = {K, M}, sbb[2] = {K, 2 * N}; + OmegaTensor AT = mk(2, sat, at), BB = mk(2, sbb, bb), AV, BV, O; + omega_tensor_transpose(g, AT, &AV); + omega_tensor_slice(g, BB, (uint64_t[]){0, 1}, (uint64_t[]){K, 2 * N}, (uint64_t[]){1, 2}, &BV); + int rc = omega_tensor_matmul(g, AV, BV, &O); + float *got = rc ? NULL : rd(O); + CHECK(got && mismatches(ex, got, M * N) == 0, "matmul of strided views"); + free(got); if (!rc) omega_tensor_release(g, O); + OmegaTensor vs[] = {AV, BV, AT, BB}; + for (size_t i = 0; i < 4; i++) omega_tensor_release(g, vs[i]); + free(at); free(bb); free(a); free(b); free(ex); + /* batched with broadcast batch axes: [2,1,3,4] x [5,4,6] -> [2,5,3,6] */ + uint64_t s1[4] = {2, 1, 3, 4}, s2[3] = {5, 4, 6}; + float x1[24], x2[120], e[180], o1[12], o2[24], r[18]; + fill(x1, 24, rand_mod); + fill(x2, 120, rand_mod); + for (int p = 0; p < 2; p++) for (int q = 0; q < 5; q++) { + memcpy(o1, x1 + p * 12, 48); + memcpy(o2, x2 + q * 24, 96); + ref_matmul(o1, o2, r, 3, 4, 6); + memcpy(e + (p * 5 + q) * 18, r, 72); + } + OmegaTensor X1 = mk(4, s1, x1), X2 = mk(3, s2, x2); + rc = omega_tensor_matmul(g, X1, X2, &O); + OmegaTensorInfo oi; + if (!rc) omega_tensor_info(g, O, &oi); + got = rc ? NULL : rd(O); + CHECK(got && oi.rank == 4 && oi.shape[0] == 2 && oi.shape[1] == 5 && oi.shape[2] == 3 && oi.shape[3] == 6 && + mismatches(e, got, 180) == 0, "batched broadcast matmul rc=%d", rc); + free(got); if (!rc) omega_tensor_release(g, O); + uint64_t s3[4] = {3, 1, 4, 6}; + OmegaTensor X3 = mk(4, s3, x2); + CHECK(omega_tensor_matmul(g, X1, X3, &O) == OMEGA_TENSOR_ERR_SHAPE, "batch axes [2,1] vs [3,1] refused"); + omega_tensor_release(g, X1); omega_tensor_release(g, X2); omega_tensor_release(g, X3); + CHECK(strstr(OMEGA_TENSOR_MATMUL_DECLARED_ORDER, OMEGA_TENSOR_REDUCE_DECLARED_ORDER) != NULL, + "matmul order names the reduce order"); +} + +/* ---- 7. mutation: a different order or fusion is caught ------------------ */ +static int seq_reduce(OmegaTensorReduceOp op, const float *x, size_t n, float *out) { + float acc = x[0]; + for (size_t i = 1; i < n; i++) acc = op == OMEGA_TR_MAX ? omega_ref_fmax(acc, x[i]) : omega_ref_fadd(acc, x[i]); + *out = acc; + return 0; +} +static int fma_chain_elementwise(OmegaNumericOp op, const float *a, const float *b, const float *c, + float *out, size_t n) { + if (op != OMEGA_NOP_FMUL) return omega_numeric_cpu_realize(op, a, b, c, out, n); + /* "fused" products: keep a*b exact-ish by folding into an FFMA chain in out[0] */ + float acc = 0.0f; + for (size_t i = 0; i < n; i++) { acc = omega_ref_ffma_int(a[i], b[i], acc); out[i] = 0.0f; } + out[0] = acc; + return 0; +} +static void test_mutations(void) { + const size_t M = 16, K = 300, N = 16; + float *a = malloc(M * K * 4), *b = malloc(K * N * 4), *ex = malloc(M * N * 4); + fill(a, M * K, rand_mod); + fill(b, K * N, rand_mod); + ref_matmul(a, b, ex, M, K, N); + uint64_t sa[2] = {M, K}, sb[2] = {K, N}; + OmegaTensorRealization mut[2]; + mut[0] = *omega_tensor_cpu_realization(); + mut[0].name = "MUTANT_SEQUENTIAL_SUM"; /* lies about its order string */ + mut[0].reduce = seq_reduce; + mut[1] = *omega_tensor_cpu_realization(); + mut[1].name = "MUTANT_FFMA_CHAIN"; + mut[1].elementwise = fma_chain_elementwise; + for (int m = 0; m < 2; m++) { + OmegaTensorCtx *c; + omega_tensor_ctx_create(16, &mut[m], &c); + OmegaTensor A, B, O; + omega_tensor_from_f32(c, 2, sa, a, &A); + omega_tensor_from_f32(c, 2, sb, b, &B); + float *got = malloc(M * N * 4); + int rc = omega_tensor_matmul(c, A, B, &O); + if (!rc) omega_tensor_read_f32(c, O, got, M * N); + size_t mm = rc ? M * N : mismatches(ex, got, M * N); + CHECK(mm > 0, "mutant %s caught (%zu of %zu outputs differ)", mut[m].name, mm, M * N); + free(got); + omega_tensor_ctx_destroy(c); + } + free(a); free(b); free(ex); +} + +/* ---- 8. determinism ------------------------------------------------------- */ +static void kat_digest(uint8_t out[32]) { + uint64_t save = g_rng; + g_rng = 0x0123456789abcdefULL; + float a[7 * 13], b[13 * 5]; + fill(a, 91, rand_mod); + fill(b, 65, rand_mod); + uint64_t sa[2] = {7, 13}, sb[2] = {13, 5}; + OmegaTensor A = mk(2, sa, a), B = mk(2, sb, b), P, R, Q; + omega_tensor_matmul(g, A, B, &P); + omega_tensor_reduce(g, OMEGA_TR_SUM, A, 1, true, &R); + omega_tensor_binary(g, OMEGA_TB_DIV, P, R, &Q); /* [7,5] / [7,1] */ + vid(Q, out); + OmegaTensor all[] = {A, B, P, R, Q}; + for (int i = 0; i < 5; i++) omega_tensor_release(g, all[i]); + g_rng = save; +} +static void test_determinism(void) { + uint8_t d1[32], d2[32]; + kat_digest(d1); + kat_digest(d2); + CHECK(memcmp(d1, d2, 32) == 0, "same inputs, same value id"); + char hex[65]; + for (int i = 0; i < 32; i++) sprintf(hex + 2 * i, "%02x", d1[i]); + printf("KAT value id (matmul 7x13x5, row-sum, div): %s\n", hex); + /* Frozen on 2026-10-01 from the first CPU run; any change to an op, the + * order or the value-id encoding changes it. */ + static const char frozen[] = "9efaa4bc9826cce169ae8da3796a188a48ca6ac0bbb7f71f7ba7f11cca46f991"; + CHECK(strcmp(frozen, hex) == 0, "KAT matches frozen %s", frozen); +} + +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; } + printf("reduce seam: %s\n", omega_tensor_seam_reduce_source()); + test_shape_type(); + test_broadcast(); + test_views(); + test_generations(); + test_immutability(); + test_elementwise_parity(); + test_reduce_parity(); + test_matmul_parity(); + test_mutations(); + test_determinism(); + /* every test released what it made */ + 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("M20 OMEGA_TENSOR CPU tests: %d pass, %d fail\n", g_pass, g_fail); + printf("M20 verdict: NOT QUALIFIED (CPU tier only; GB10 parity NOT_RUN)\n"); + return g_fail ? 1 : 0; +} diff --git a/tools/tensor_mutations.sh b/tools/tensor_mutations.sh new file mode 100755 index 000000000..6e08af277 --- /dev/null +++ b/tools/tensor_mutations.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# M20 OMEGA_TENSOR mutation sweep. For each rule marked MUT:<name> in +# src/tensor/*.c, copy src/tensor 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, or that the tests do not catch, fails the +# sweep. CPU only, no device. Shell only (no Python). +set -u +cd "$(dirname "$0")/.." || exit 2 +SCRATCH=$(mktemp -d "${TMPDIR:-/tmp}/tensor-mut.XXXXXX") || exit 2 +trap 'rm -rf "$SCRATCH"' EXIT INT TERM +DEPS="src/omega_numeric_reduce.c 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 -DOMEGA_TENSOR_TEST_HOOKS" + +# name|file|sed expression (applied only to the line carrying MUT:<name>) +# Reduction order and padding mutations live in the E1 WP-D suite +# (test-numeric-reduce-cpu, RED_DIFFERENT_ORDER_CAUGHT): the seam calls it. +MUTATIONS='RELEASE_BUMP|omega_tensor.c|s/(\*gen)++/(void)0/ +STORAGE_GEN_CHECK|omega_tensor.c|s/ || s->gen != h.generation// +BCAST_ZERO_STRIDE|omega_tensor.c|s/o.strides\[d\] = 0;/o.strides[d] = in->strides[sd];/ +PERMUTE_STRIDES|omega_tensor.c|s/in->strides\[perm\[d\]\]/in->strides[d]/ +SLICE_OFFSET|omega_tensor.c|s/start\[d\], in->strides\[d\]/start[d], 1/' + +# Baseline: the unmutated build must PASS, otherwise every mutant would +# look "caught" (e.g. the test refusing an unsuitable FP environment). +if ! gcc $FLAGS -Isrc -Isrc/tensor -o "$SCRATCH/base" tests/test_omega_tensor.c \ + src/tensor/omega_tensor.c src/tensor/omega_tensor_cpu.c src/tensor/omega_tensor_reduce_seam.c $DEPS \ + > "$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 "tensor 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 + total=$((total + 1)) + rm -rf "$SCRATCH/tensor" && cp -r src/tensor "$SCRATCH/tensor" + sed -i "/MUT:$name/ $expr" "$SCRATCH/tensor/$file" + if cmp -s "src/tensor/$file" "$SCRATCH/tensor/$file"; then + echo "MUTATION $name: NOT APPLIED (marker or pattern missing)"; fail=1; continue + fi + if ! gcc $FLAGS -Isrc -I"$SCRATCH/tensor" -o "$SCRATCH/t" tests/test_omega_tensor.c \ + "$SCRATCH/tensor/omega_tensor.c" "$SCRATCH/tensor/omega_tensor_cpu.c" \ + "$SCRATCH/tensor/omega_tensor_reduce_seam.c" $DEPS > "$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 [ "$fail" -ne 0 ]; then echo "tensor mutation sweep: FAIL"; exit 1; fi +echo "tensor mutation sweep: PASS ($total of $total mutations caught)"