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
omega-mv / src / tensor / omega_tensor.c
| 1 | /* SPDX-License-Identifier: Apache-2.0 |
| 2 | * Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | /* |
| 18 | * M20 OMEGA_TENSOR semantic layer (see omega_tensor.h). This file holds the |
| 19 | * meaning: shapes, strides, views, storage lifetime, identity, and the |
| 20 | * definition of each op as index movement plus calls into the realization. |
| 21 | * It performs no floating-point arithmetic of its own. |
| 22 | */ |
| 23 | #include "omega_tensor.h" |
| 24 | |
| 25 | #include <stdlib.h> |
| 26 | #include <string.h> |
| 27 | |
| 28 | #include "sha256.h" |
| 29 | #include "omega_native.h" |
| 30 | #include "omega_api_decl.h" |
| 31 | |
| 32 | typedef struct { |
| 33 | uint64_t gen; |
| 34 | bool live; |
| 35 | bool retired; /* generation reached UINT64_MAX: never reused */ |
| 36 | OmegaDType dtype; |
| 37 | uint64_t elems; |
| 38 | void *data; |
| 39 | } StorageSlot; |
| 40 | |
| 41 | typedef struct { |
| 42 | uint64_t gen; |
| 43 | bool live; |
| 44 | bool retired; |
| 45 | bool owns_storage; |
| 46 | OmegaTensorInfo info; |
| 47 | } TensorSlot; |
| 48 | |
| 49 | struct OmegaTensorCtx { |
| 50 | uint32_t cap; |
| 51 | StorageSlot *st; |
| 52 | TensorSlot *ts; |
| 53 | const OmegaTensorRealization *real; |
| 54 | int last_numeric; |
| 55 | }; |
| 56 | |
| 57 | size_t omega_dtype_size(OmegaDType dt) { |
| 58 | switch (dt) { |
| 59 | case OMEGA_DT_F32: return 4; |
| 60 | case OMEGA_DT_F16: |
| 61 | case OMEGA_DT_BF16: return 2; |
| 62 | default: return 0; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | /* ---- generations ------------------------------------------------------- */ |
| 67 | |
| 68 | static void bump_generation(uint64_t *gen, bool *retired) { |
| 69 | if (*gen == UINT64_MAX) *retired = true; /* never wrap */ |
| 70 | else (*gen)++; /* MUT:RELEASE_BUMP */ |
| 71 | } |
| 72 | |
| 73 | int omega_tensor_ctx_create(uint32_t capacity, const OmegaTensorRealization *real, |
| 74 | OmegaTensorCtx **out) { |
| 75 | if (!out || capacity == 0 || !real) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 76 | *out = NULL; |
| 77 | if (!real->name || !real->elementwise || !real->reduce || !real->reduce_order || |
| 78 | strcmp(real->reduce_order, OMEGA_TENSOR_REDUCE_DECLARED_ORDER) != 0) |
| 79 | return OMEGA_TENSOR_ERR_REALIZATION; |
| 80 | OmegaTensorCtx *c = calloc(1, sizeof(*c)); |
| 81 | if (!c) return OMEGA_TENSOR_ERR_CAPACITY; |
| 82 | c->st = calloc(capacity, sizeof(StorageSlot)); |
| 83 | c->ts = calloc(capacity, sizeof(TensorSlot)); |
| 84 | if (!c->st || !c->ts) { free(c->st); free(c->ts); free(c); return OMEGA_TENSOR_ERR_CAPACITY; } |
| 85 | for (uint32_t i = 0; i < capacity; i++) { c->st[i].gen = 1; c->ts[i].gen = 1; } |
| 86 | c->cap = capacity; |
| 87 | c->real = real; |
| 88 | *out = c; |
| 89 | return OMEGA_TENSOR_OK; |
| 90 | } |
| 91 | |
| 92 | void omega_tensor_ctx_destroy(OmegaTensorCtx *ctx) { |
| 93 | if (!ctx) return; |
| 94 | for (uint32_t i = 0; i < ctx->cap; i++) free(ctx->st[i].data); |
| 95 | free(ctx->st); |
| 96 | free(ctx->ts); |
| 97 | free(ctx); |
| 98 | } |
| 99 | |
| 100 | int omega_tensor_last_numeric_error(const OmegaTensorCtx *ctx) { return ctx ? ctx->last_numeric : 0; } |
| 101 | |
| 102 | #ifdef OMEGA_TENSOR_TEST_HOOKS /* test build only, see omega_tensor.h */ |
| 103 | int omega_tensor_test_set_storage_generation(OmegaTensorCtx *ctx, uint32_t slot, uint64_t gen) { |
| 104 | if (!ctx || slot >= ctx->cap || gen == 0) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 105 | if (ctx->st[slot].live || ctx->st[slot].retired) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 106 | if (gen <= ctx->st[slot].gen) return OMEGA_TENSOR_ERR_BAD_ARGS; /* forward only: a rollback would revive stale handles (Codex) */ |
| 107 | ctx->st[slot].gen = gen; |
| 108 | return OMEGA_TENSOR_OK; |
| 109 | } |
| 110 | #endif |
| 111 | |
| 112 | static StorageSlot *storage_get(const OmegaTensorCtx *ctx, OmegaStorageHandle h) { |
| 113 | if (h.slot >= ctx->cap) return NULL; |
| 114 | StorageSlot *s = &ctx->st[h.slot]; |
| 115 | if (!s->live || s->gen != h.generation) return NULL; /* MUT:STORAGE_GEN_CHECK */ |
| 116 | return s; |
| 117 | } |
| 118 | |
| 119 | bool omega_tensor_storage_valid(const OmegaTensorCtx *ctx, OmegaStorageHandle s) { |
| 120 | return ctx && storage_get(ctx, s) != NULL; |
| 121 | } |
| 122 | |
| 123 | /* Tensor descriptor lookup; also requires its storage to be valid. */ |
| 124 | static int tensor_get(const OmegaTensorCtx *ctx, OmegaTensor t, TensorSlot **ts, StorageSlot **st) { |
| 125 | if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 126 | if (t.slot >= ctx->cap) return OMEGA_TENSOR_ERR_STALE; |
| 127 | TensorSlot *x = &ctx->ts[t.slot]; |
| 128 | if (!x->live || x->gen != t.generation) return OMEGA_TENSOR_ERR_STALE; |
| 129 | StorageSlot *s = storage_get(ctx, x->info.storage); |
| 130 | if (!s) return OMEGA_TENSOR_ERR_STALE; |
| 131 | if (ts) *ts = x; |
| 132 | if (st) *st = s; |
| 133 | return OMEGA_TENSOR_OK; |
| 134 | } |
| 135 | |
| 136 | static int storage_alloc(OmegaTensorCtx *ctx, OmegaDType dt, uint64_t elems, OmegaStorageHandle *h) { |
| 137 | size_t es = omega_dtype_size(dt); |
| 138 | if (!es || elems == 0 || elems > OMEGA_TENSOR_MAX_ELEMS) return OMEGA_TENSOR_ERR_CAPACITY; |
| 139 | for (uint32_t i = 0; i < ctx->cap; i++) { |
| 140 | StorageSlot *s = &ctx->st[i]; |
| 141 | if (s->live || s->retired) continue; |
| 142 | void *d = calloc((size_t)elems, es); |
| 143 | if (!d) return OMEGA_TENSOR_ERR_CAPACITY; |
| 144 | s->live = true; |
| 145 | s->dtype = dt; |
| 146 | s->elems = elems; |
| 147 | s->data = d; |
| 148 | h->slot = i; |
| 149 | h->generation = s->gen; |
| 150 | return OMEGA_TENSOR_OK; |
| 151 | } |
| 152 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 153 | } |
| 154 | |
| 155 | static void storage_release(OmegaTensorCtx *ctx, OmegaStorageHandle h) { |
| 156 | StorageSlot *s = storage_get(ctx, h); |
| 157 | if (!s) return; |
| 158 | free(s->data); |
| 159 | s->data = NULL; |
| 160 | s->live = false; |
| 161 | bump_generation(&s->gen, &s->retired); |
| 162 | } |
| 163 | |
| 164 | static int tensor_slot_alloc(OmegaTensorCtx *ctx, const OmegaTensorInfo *info, bool owns, OmegaTensor *out) { |
| 165 | for (uint32_t i = 0; i < ctx->cap; i++) { |
| 166 | TensorSlot *x = &ctx->ts[i]; |
| 167 | if (x->live || x->retired) continue; |
| 168 | x->live = true; |
| 169 | x->owns_storage = owns; |
| 170 | x->info = *info; |
| 171 | out->slot = i; |
| 172 | out->generation = x->gen; |
| 173 | return OMEGA_TENSOR_OK; |
| 174 | } |
| 175 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 176 | } |
| 177 | |
| 178 | int omega_tensor_release(OmegaTensorCtx *ctx, OmegaTensor t) { |
| 179 | if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 180 | if (t.slot >= ctx->cap) return OMEGA_TENSOR_ERR_STALE; |
| 181 | TensorSlot *x = &ctx->ts[t.slot]; |
| 182 | if (!x->live || x->gen != t.generation) return OMEGA_TENSOR_ERR_STALE; |
| 183 | if (x->owns_storage) storage_release(ctx, x->info.storage); |
| 184 | x->live = false; |
| 185 | bump_generation(&x->gen, &x->retired); |
| 186 | return OMEGA_TENSOR_OK; |
| 187 | } |
| 188 | |
| 189 | /* ---- shapes ------------------------------------------------------------- */ |
| 190 | |
| 191 | _Static_assert(OMEGA_TENSOR_MAX_RANK == 8 && OMEGA_TENSOR_MAX_ELEMS == UINT64_C(1073741824) && |
| 192 | OMEGA_TENSOR_ERR_SHAPE == -3 && OMEGA_TENSOR_ERR_BOUNDS == -6 && |
| 193 | OMEGA_TENSOR_ERR_CAPACITY == -8, "seeded tensor shape limits and status codes"); |
| 194 | |
| 195 | static int shape_check(uint32_t rank, const uint64_t *shape, uint64_t *elems) { |
| 196 | if (rank > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; |
| 197 | if (rank && !shape) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 198 | if (!rank) { *elems = 1; return OMEGA_TENSOR_OK; } |
| 199 | uint64_t result; |
| 200 | if (omega2_tensor_shape_size(&result, shape, rank, elems, 1) != OMEGA_OK) |
| 201 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 202 | return (int)(int64_t)result; |
| 203 | } |
| 204 | |
| 205 | static int dense_strides(uint32_t rank, const uint64_t *shape, uint64_t *strides) { |
| 206 | uint64_t result; |
| 207 | if (rank && omega2_tensor_dense_strides(&result, shape, rank, strides, rank) != OMEGA_OK) |
| 208 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 209 | return OMEGA_TENSOR_OK; |
| 210 | } |
| 211 | |
| 212 | static int bounds_check(const OmegaTensorInfo *in, uint64_t storage_elems) { |
| 213 | uint64_t result; |
| 214 | if (omega2_tensor_view_bounds(&result, in->shape, in->rank, in->strides, in->rank, |
| 215 | in->offset, storage_elems) != OMEGA_OK) |
| 216 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 217 | return (int)(int64_t)result; |
| 218 | } |
| 219 | |
| 220 | int omega_tensor_broadcast_shape(uint32_t ra, const uint64_t *sa, uint32_t rb, const uint64_t *sb, |
| 221 | uint32_t *rout, uint64_t *sout) { |
| 222 | if (!rout || !sout || (ra && !sa) || (rb && !sb)) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 223 | if (ra > OMEGA_TENSOR_MAX_RANK || rb > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; |
| 224 | uint32_t r = ra > rb ? ra : rb; |
| 225 | if (!r) { *rout = 0; return OMEGA_TENSOR_OK; } |
| 226 | uint64_t tmp[OMEGA_TENSOR_MAX_RANK]; |
| 227 | uint64_t result; |
| 228 | if (omega2_tensor_broadcast_dims(&result, sa, ra, sb, rb, tmp, r) != OMEGA_OK) |
| 229 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 230 | if (result) return (int)(int64_t)result; |
| 231 | /* Inputs and output may overlap. Publish only a complete shape. */ |
| 232 | memcpy(sout, tmp, r * sizeof(uint64_t)); |
| 233 | *rout = r; |
| 234 | return OMEGA_TENSOR_OK; |
| 235 | } |
| 236 | |
| 237 | /* Directional broadcast of a descriptor to (rank, shape): stride 0 on every |
| 238 | * expanded axis. Pure descriptor arithmetic. */ |
| 239 | static int broadcast_info(const OmegaTensorInfo *in, uint32_t rank, const uint64_t *shape, |
| 240 | OmegaTensorInfo *out) { |
| 241 | if (rank < in->rank) return OMEGA_TENSOR_ERR_SHAPE; |
| 242 | uint64_t n; |
| 243 | int rc = shape_check(rank, shape, &n); |
| 244 | if (rc) return rc; |
| 245 | OmegaTensorInfo o = *in; |
| 246 | o.rank = rank; |
| 247 | for (uint32_t i = 0; i < rank; i++) { |
| 248 | uint32_t d = rank - 1 - i; |
| 249 | if (i < in->rank) { |
| 250 | uint32_t sd = in->rank - 1 - i; |
| 251 | if (in->shape[sd] == shape[d]) { o.shape[d] = shape[d]; o.strides[d] = in->strides[sd]; } |
| 252 | else if (in->shape[sd] == 1) { o.shape[d] = shape[d]; o.strides[d] = 0; } /* MUT:BCAST_ZERO_STRIDE */ |
| 253 | else return OMEGA_TENSOR_ERR_SHAPE; |
| 254 | } else { |
| 255 | o.shape[d] = shape[d]; |
| 256 | o.strides[d] = 0; |
| 257 | } |
| 258 | } |
| 259 | for (uint32_t d = rank; d < OMEGA_TENSOR_MAX_RANK; d++) { o.shape[d] = 0; o.strides[d] = 0; } |
| 260 | o.elements = n; |
| 261 | *out = o; |
| 262 | return OMEGA_TENSOR_OK; |
| 263 | } |
| 264 | |
| 265 | /* Copy every element in logical row-major order into dst (element size es). */ |
| 266 | static void gather(const StorageSlot *s, const OmegaTensorInfo *in, void *dst) { |
| 267 | size_t es = omega_dtype_size(in->dtype); |
| 268 | uint64_t desc[21] = {0}; |
| 269 | memcpy(desc, in->shape, sizeof(in->shape)); |
| 270 | memcpy(desc + 8, in->strides, sizeof(in->strides)); |
| 271 | desc[16] = in->rank; desc[17] = in->offset; desc[18] = es; desc[19] = in->elements; desc[20] = 0; |
| 272 | tensor_copy_op((const uint8_t *)s->data, (size_t)s->elems * es, |
| 273 | (uint8_t *)dst, (size_t)in->elements * es, desc); |
| 274 | } |
| 275 | |
| 276 | /* New tensor owning fresh dense storage. *data receives the storage buffer |
| 277 | * for the caller to fill before anyone else can see the tensor. */ |
| 278 | static int new_dense(OmegaTensorCtx *ctx, OmegaDType dt, uint32_t rank, const uint64_t *shape, |
| 279 | OmegaTensor *out, void **data) { |
| 280 | uint64_t n; |
| 281 | int rc = shape_check(rank, shape, &n); |
| 282 | if (rc) return rc; |
| 283 | OmegaStorageHandle h; |
| 284 | rc = storage_alloc(ctx, dt, n, &h); |
| 285 | if (rc) return rc; |
| 286 | OmegaTensorInfo info; |
| 287 | memset(&info, 0, sizeof(info)); |
| 288 | info.dtype = dt; |
| 289 | info.rank = rank; |
| 290 | if (rank) memcpy(info.shape, shape, rank * sizeof(uint64_t)); |
| 291 | rc = dense_strides(rank, info.shape, info.strides); |
| 292 | if (rc) { storage_release(ctx, h); return rc; } |
| 293 | info.elements = n; |
| 294 | info.storage = h; |
| 295 | info.is_view = false; |
| 296 | rc = tensor_slot_alloc(ctx, &info, true, out); |
| 297 | if (rc) { storage_release(ctx, h); return rc; } |
| 298 | ctx->ts[out->slot].info.parent = *out; |
| 299 | *data = ctx->st[h.slot].data; |
| 300 | return OMEGA_TENSOR_OK; |
| 301 | } |
| 302 | |
| 303 | /* ---- creation / inspection --------------------------------------------- */ |
| 304 | |
| 305 | int omega_tensor_from_data(OmegaTensorCtx *ctx, OmegaDType dtype, uint32_t rank, |
| 306 | const uint64_t *shape, const void *data, OmegaTensor *out) { |
| 307 | if (!ctx || !data || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 308 | if (!omega_dtype_size(dtype)) return OMEGA_TENSOR_ERR_DTYPE; |
| 309 | void *buf; |
| 310 | int rc = new_dense(ctx, dtype, rank, shape, out, &buf); |
| 311 | if (rc) return rc; |
| 312 | memcpy(buf, data, (size_t)ctx->ts[out->slot].info.elements * omega_dtype_size(dtype)); |
| 313 | return OMEGA_TENSOR_OK; |
| 314 | } |
| 315 | |
| 316 | int omega_tensor_from_f32(OmegaTensorCtx *ctx, uint32_t rank, const uint64_t *shape, |
| 317 | const float *data, OmegaTensor *out) { |
| 318 | return omega_tensor_from_data(ctx, OMEGA_DT_F32, rank, shape, data, out); |
| 319 | } |
| 320 | |
| 321 | int omega_tensor_info(const OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensorInfo *out) { |
| 322 | TensorSlot *x; |
| 323 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 324 | int rc = tensor_get(ctx, t, &x, NULL); |
| 325 | if (rc) return rc; |
| 326 | *out = x->info; |
| 327 | return OMEGA_TENSOR_OK; |
| 328 | } |
| 329 | |
| 330 | int omega_tensor_read(const OmegaTensorCtx *ctx, OmegaTensor t, void *out, size_t out_bytes) { |
| 331 | TensorSlot *x; |
| 332 | StorageSlot *s; |
| 333 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 334 | int rc = tensor_get(ctx, t, &x, &s); |
| 335 | if (rc) return rc; |
| 336 | if (out_bytes < x->info.elements * omega_dtype_size(x->info.dtype)) return OMEGA_TENSOR_ERR_CAPACITY; |
| 337 | gather(s, &x->info, out); |
| 338 | return OMEGA_TENSOR_OK; |
| 339 | } |
| 340 | |
| 341 | int omega_tensor_read_f32(const OmegaTensorCtx *ctx, OmegaTensor t, float *out, size_t count) { |
| 342 | TensorSlot *x; |
| 343 | int rc = tensor_get(ctx, t, &x, NULL); |
| 344 | if (rc) return rc; |
| 345 | if (x->info.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 346 | return omega_tensor_read(ctx, t, out, count * sizeof(float)); |
| 347 | } |
| 348 | |
| 349 | static void put_u64(sha256_ctx *h, uint64_t v) { |
| 350 | uint8_t b[8]; |
| 351 | for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i)); |
| 352 | sha256_update(h, b, 8); |
| 353 | } |
| 354 | |
| 355 | _Static_assert(OMEGA_DT_F32 == 1 && OMEGA_DT_F16 == 2 && OMEGA_DT_BF16 == 3, |
| 356 | "Omega tensor value dtype tags"); |
| 357 | enum { VALUE_CHUNK_BYTES = 65536 }; |
| 358 | |
| 359 | /* Compare a scalar value or a one-element tail without rewriting both buffers. */ |
| 360 | static uint32_t canon_bits(OmegaDType dtype, const uint8_t *p) { |
| 361 | uint32_t bits; |
| 362 | if (dtype == OMEGA_DT_F32) { |
| 363 | memcpy(&bits, p, sizeof bits); |
| 364 | } else { |
| 365 | uint16_t half; |
| 366 | memcpy(&half, p, sizeof half); |
| 367 | bits = half; |
| 368 | } |
| 369 | return (uint32_t)tensor_canonical_word((uint64_t)dtype, bits); |
| 370 | } |
| 371 | |
| 372 | /* Components are gathered in native byte order. The value domain is little-endian. */ |
| 373 | static void canonicalize_chunk(OmegaDType dtype, uint8_t *data, size_t bytes) { |
| 374 | const uint16_t one = 1; |
| 375 | tensor_value_bytes(data, bytes, (uint64_t)dtype, *(const uint8_t *)&one); |
| 376 | } |
| 377 | |
| 378 | int omega_tensor_value_id(const OmegaTensorCtx *ctx, OmegaTensor t, uint8_t id[32]) { |
| 379 | TensorSlot *x; |
| 380 | StorageSlot *s; |
| 381 | if (!id) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 382 | int rc = tensor_get(ctx, t, &x, &s); |
| 383 | if (rc) return rc; |
| 384 | size_t es = omega_dtype_size(x->info.dtype); |
| 385 | uint8_t *buf = malloc((size_t)x->info.elements * es); |
| 386 | if (!buf) return OMEGA_TENSOR_ERR_CAPACITY; |
| 387 | gather(s, &x->info, buf); |
| 388 | sha256_ctx h; |
| 389 | sha256_init(&h); |
| 390 | sha256_update(&h, (const uint8_t *)OMEGA_TENSOR_VALUE_ID_DOMAIN, sizeof(OMEGA_TENSOR_VALUE_ID_DOMAIN)); |
| 391 | put_u64(&h, (uint64_t)x->info.dtype); |
| 392 | put_u64(&h, x->info.rank); |
| 393 | for (uint32_t d = 0; d < x->info.rank; d++) put_u64(&h, x->info.shape[d]); |
| 394 | size_t bytes = (size_t)x->info.elements * es; |
| 395 | for (size_t pos = 0; pos < bytes;) { |
| 396 | size_t count = bytes - pos; |
| 397 | if (count > VALUE_CHUNK_BYTES) count = VALUE_CHUNK_BYTES; |
| 398 | canonicalize_chunk(x->info.dtype, buf + pos, count); |
| 399 | sha256_update(&h, buf + pos, count); |
| 400 | pos += count; |
| 401 | } |
| 402 | sha256_final(&h, id); |
| 403 | free(buf); |
| 404 | return OMEGA_TENSOR_OK; |
| 405 | } |
| 406 | |
| 407 | int omega_tensor_value_equal(const OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, bool *eq) { |
| 408 | TensorSlot *xa, *xb; |
| 409 | StorageSlot *sa, *sb; |
| 410 | if (!eq) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 411 | int rc = tensor_get(ctx, a, &xa, &sa); |
| 412 | if (!rc) rc = tensor_get(ctx, b, &xb, &sb); |
| 413 | if (rc) return rc; |
| 414 | *eq = false; |
| 415 | if (xa->info.dtype != xb->info.dtype || xa->info.rank != xb->info.rank) return OMEGA_TENSOR_OK; |
| 416 | for (uint32_t d = 0; d < xa->info.rank; d++) |
| 417 | if (xa->info.shape[d] != xb->info.shape[d]) return OMEGA_TENSOR_OK; |
| 418 | size_t es = omega_dtype_size(xa->info.dtype); |
| 419 | size_t bytes = (size_t)xa->info.elements * es; |
| 420 | uint8_t *ba = malloc(bytes), *bb = malloc(bytes); |
| 421 | if (!ba || !bb) { free(ba); free(bb); return OMEGA_TENSOR_ERR_CAPACITY; } |
| 422 | gather(sa, &xa->info, ba); |
| 423 | gather(sb, &xb->info, bb); |
| 424 | bool same = true; |
| 425 | for (size_t pos = 0; pos < bytes && same;) { |
| 426 | size_t count = bytes - pos; |
| 427 | if (count > VALUE_CHUNK_BYTES) count = VALUE_CHUNK_BYTES; |
| 428 | if (count == es) { |
| 429 | same = canon_bits(xa->info.dtype, ba + pos) == canon_bits(xb->info.dtype, bb + pos); |
| 430 | } else if (memcmp(ba + pos, bb + pos, count)) { |
| 431 | canonicalize_chunk(xa->info.dtype, ba + pos, count); |
| 432 | canonicalize_chunk(xb->info.dtype, bb + pos, count); |
| 433 | same = memcmp(ba + pos, bb + pos, count) == 0; |
| 434 | } |
| 435 | pos += count; |
| 436 | } |
| 437 | free(ba); |
| 438 | free(bb); |
| 439 | *eq = same; |
| 440 | return OMEGA_TENSOR_OK; |
| 441 | } |
| 442 | |
| 443 | int omega_tensor_view_id(const OmegaTensorCtx *ctx, OmegaTensor t, uint8_t id[32]) { |
| 444 | TensorSlot *x; |
| 445 | if (!id) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 446 | int rc = tensor_get(ctx, t, &x, NULL); |
| 447 | if (rc) return rc; |
| 448 | const OmegaTensorInfo *in = &x->info; |
| 449 | sha256_ctx h; |
| 450 | sha256_init(&h); |
| 451 | sha256_update(&h, (const uint8_t *)OMEGA_TENSOR_VIEW_ID_DOMAIN, sizeof(OMEGA_TENSOR_VIEW_ID_DOMAIN)); |
| 452 | put_u64(&h, in->storage.slot); |
| 453 | put_u64(&h, in->storage.generation); |
| 454 | put_u64(&h, in->parent.slot); |
| 455 | put_u64(&h, in->parent.generation); |
| 456 | put_u64(&h, (uint64_t)in->dtype); |
| 457 | put_u64(&h, in->offset); |
| 458 | put_u64(&h, in->rank); |
| 459 | for (uint32_t d = 0; d < in->rank; d++) { put_u64(&h, in->shape[d]); put_u64(&h, in->strides[d]); } |
| 460 | sha256_final(&h, id); |
| 461 | return OMEGA_TENSOR_OK; |
| 462 | } |
| 463 | |
| 464 | /* ---- views -------------------------------------------------------------- */ |
| 465 | |
| 466 | static int register_view(OmegaTensorCtx *ctx, OmegaTensor parent, const StorageSlot *s, |
| 467 | OmegaTensorInfo *v, OmegaTensor *out) { |
| 468 | int rc = bounds_check(v, s->elems); |
| 469 | if (rc) return rc; |
| 470 | v->is_view = true; |
| 471 | v->parent = parent; |
| 472 | return tensor_slot_alloc(ctx, v, false, out); |
| 473 | } |
| 474 | |
| 475 | int omega_tensor_permute(OmegaTensorCtx *ctx, OmegaTensor t, const uint32_t *perm, OmegaTensor *out) { |
| 476 | TensorSlot *x; |
| 477 | StorageSlot *s; |
| 478 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 479 | int rc = tensor_get(ctx, t, &x, &s); |
| 480 | if (rc) return rc; |
| 481 | const OmegaTensorInfo *in = &x->info; |
| 482 | if (in->rank && !perm) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 483 | bool seen[OMEGA_TENSOR_MAX_RANK] = {false}; |
| 484 | OmegaTensorInfo v = *in; |
| 485 | for (uint32_t d = 0; d < in->rank; d++) { |
| 486 | if (perm[d] >= in->rank || seen[perm[d]]) return OMEGA_TENSOR_ERR_AXIS; |
| 487 | seen[perm[d]] = true; |
| 488 | v.shape[d] = in->shape[perm[d]]; |
| 489 | v.strides[d] = in->strides[perm[d]]; /* MUT:PERMUTE_STRIDES */ |
| 490 | } |
| 491 | return register_view(ctx, t, s, &v, out); |
| 492 | } |
| 493 | |
| 494 | int omega_tensor_transpose(OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensor *out) { |
| 495 | TensorSlot *x; |
| 496 | int rc = tensor_get(ctx, t, &x, NULL); |
| 497 | if (rc) return rc; |
| 498 | uint32_t r = x->info.rank; |
| 499 | if (r < 2) return OMEGA_TENSOR_ERR_RANK; |
| 500 | uint64_t zeros[8] = {0}, out_buf[24] = {0}; |
| 501 | const uint64_t meta[4] = { r, 0, 0, 0 }; |
| 502 | tensor_plan_op(zeros, zeros, out_buf, meta); |
| 503 | uint32_t perm[OMEGA_TENSOR_MAX_RANK]; |
| 504 | for (uint32_t d = 0; d < r; d++) perm[d] = (uint32_t)out_buf[d]; |
| 505 | return omega_tensor_permute(ctx, t, perm, out); |
| 506 | } |
| 507 | |
| 508 | int omega_tensor_slice(OmegaTensorCtx *ctx, OmegaTensor t, const uint64_t *start, |
| 509 | const uint64_t *stop, const uint64_t *step, OmegaTensor *out) { |
| 510 | TensorSlot *x; |
| 511 | StorageSlot *s; |
| 512 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 513 | int rc = tensor_get(ctx, t, &x, &s); |
| 514 | if (rc) return rc; |
| 515 | const OmegaTensorInfo *in = &x->info; |
| 516 | if (in->rank == 0) return OMEGA_TENSOR_ERR_RANK; |
| 517 | if (!start || !stop) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 518 | OmegaTensorInfo v = *in; |
| 519 | uint64_t n = 1; |
| 520 | for (uint32_t d = 0; d < in->rank; d++) { |
| 521 | uint64_t st = step ? step[d] : 1; |
| 522 | if (st == 0) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 523 | if (stop[d] > in->shape[d]) return OMEGA_TENSOR_ERR_BOUNDS; |
| 524 | if (start[d] >= stop[d]) return OMEGA_TENSOR_ERR_SHAPE; |
| 525 | v.shape[d] = (stop[d] - start[d] - 1) / st + 1; /* ceil, no overflow */ |
| 526 | uint64_t so; |
| 527 | if (__builtin_mul_overflow(start[d], in->strides[d], &so) || /* MUT:SLICE_OFFSET */ |
| 528 | __builtin_add_overflow(v.offset, so, &v.offset)) |
| 529 | return OMEGA_TENSOR_ERR_BOUNDS; |
| 530 | /* A single-element axis never uses its stride; 0 avoids overflow. */ |
| 531 | if (v.shape[d] == 1) v.strides[d] = 0; |
| 532 | else if (__builtin_mul_overflow(in->strides[d], st, &v.strides[d])) return OMEGA_TENSOR_ERR_BOUNDS; |
| 533 | n *= v.shape[d]; |
| 534 | } |
| 535 | v.elements = n; |
| 536 | return register_view(ctx, t, s, &v, out); |
| 537 | } |
| 538 | |
| 539 | static int require_row_major(const OmegaTensorInfo *in) { |
| 540 | uint64_t result; |
| 541 | if (omega2_tensor_is_row_major(&result, in->shape, in->rank, in->strides, in->rank) != OMEGA_OK) |
| 542 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 543 | return result ? OMEGA_TENSOR_OK : OMEGA_TENSOR_ERR_NOT_CONTIGUOUS; |
| 544 | } |
| 545 | |
| 546 | int omega_tensor_reshape(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, |
| 547 | const uint64_t *shape, OmegaTensor *out) { |
| 548 | TensorSlot *x; |
| 549 | StorageSlot *s; |
| 550 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 551 | int rc = tensor_get(ctx, t, &x, &s); |
| 552 | if (rc) return rc; |
| 553 | uint64_t n; |
| 554 | rc = shape_check(rank, shape, &n); |
| 555 | if (rc) return rc; |
| 556 | if (n != x->info.elements) return OMEGA_TENSOR_ERR_SHAPE; |
| 557 | rc = require_row_major(&x->info); |
| 558 | if (rc) return rc; |
| 559 | OmegaTensorInfo v = x->info; |
| 560 | v.rank = rank; |
| 561 | memset(v.shape, 0, sizeof(v.shape)); |
| 562 | memset(v.strides, 0, sizeof(v.strides)); |
| 563 | if (rank) memcpy(v.shape, shape, rank * sizeof(uint64_t)); |
| 564 | rc = dense_strides(rank, v.shape, v.strides); |
| 565 | if (rc) return rc; |
| 566 | return register_view(ctx, t, s, &v, out); |
| 567 | } |
| 568 | |
| 569 | int omega_tensor_broadcast_to(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, |
| 570 | const uint64_t *shape, OmegaTensor *out) { |
| 571 | TensorSlot *x; |
| 572 | StorageSlot *s; |
| 573 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 574 | int rc = tensor_get(ctx, t, &x, &s); |
| 575 | if (rc) return rc; |
| 576 | if (rank > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; |
| 577 | OmegaTensorInfo v; |
| 578 | rc = broadcast_info(&x->info, rank, shape, &v); |
| 579 | if (rc) return rc; |
| 580 | return register_view(ctx, t, s, &v, out); |
| 581 | } |
| 582 | |
| 583 | /* ---- ops ---------------------------------------------------------------- */ |
| 584 | |
| 585 | static int numeric_fail(OmegaTensorCtx *ctx, int code, OmegaTensor made) { |
| 586 | ctx->last_numeric = code; |
| 587 | omega_tensor_release(ctx, made); |
| 588 | return OMEGA_TENSOR_ERR_NUMERIC; |
| 589 | } |
| 590 | |
| 591 | int omega_tensor_contiguous(OmegaTensorCtx *ctx, OmegaTensor t, OmegaTensor *out) { |
| 592 | TensorSlot *x; |
| 593 | StorageSlot *s; |
| 594 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 595 | int rc = tensor_get(ctx, t, &x, &s); |
| 596 | if (rc) return rc; |
| 597 | OmegaTensorInfo in = x->info; /* copy: slot table may be reused below */ |
| 598 | void *buf; |
| 599 | rc = new_dense(ctx, in.dtype, in.rank, in.shape, out, &buf); |
| 600 | if (rc) return rc; |
| 601 | gather(s, &in, buf); |
| 602 | return OMEGA_TENSOR_OK; |
| 603 | } |
| 604 | |
| 605 | int omega_tensor_cast(OmegaTensorCtx *ctx, OmegaTensor t, OmegaDType to, OmegaTensor *out) { |
| 606 | TensorSlot *x; |
| 607 | StorageSlot *s; |
| 608 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 609 | if (!omega_dtype_size(to)) return OMEGA_TENSOR_ERR_DTYPE; |
| 610 | int rc = tensor_get(ctx, t, &x, &s); |
| 611 | if (rc) return rc; |
| 612 | OmegaTensorInfo in = x->info; |
| 613 | if (in.dtype == to) return omega_tensor_contiguous(ctx, t, out); |
| 614 | if (in.dtype != OMEGA_DT_F32 && to != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 615 | size_t n = (size_t)in.elements; |
| 616 | float *src = malloc(n * sizeof(float)), *dst = malloc(n * sizeof(float)); |
| 617 | if (!src || !dst) { free(src); free(dst); return OMEGA_TENSOR_ERR_CAPACITY; } |
| 618 | OmegaNumericOp op; |
| 619 | if (in.dtype == OMEGA_DT_F32) { |
| 620 | gather(s, &in, src); |
| 621 | op = to == OMEGA_DT_F16 ? OMEGA_NOP_F32_TO_F16 : OMEGA_NOP_F32_TO_BF16; |
| 622 | } else { |
| 623 | uint16_t *h = malloc(n * sizeof(uint16_t)); |
| 624 | if (!h) { free(src); free(dst); return OMEGA_TENSOR_ERR_CAPACITY; } |
| 625 | gather(s, &in, h); |
| 626 | uint64_t cdesc[21] = {0}; |
| 627 | cdesc[19] = n; cdesc[20] = 2; |
| 628 | tensor_copy_op((const uint8_t *)h, n * 2, (uint8_t *)src, n * 4, cdesc); |
| 629 | free(h); |
| 630 | op = in.dtype == OMEGA_DT_F16 ? OMEGA_NOP_F16_TO_F32 : OMEGA_NOP_BF16_TO_F32; |
| 631 | } |
| 632 | void *buf; |
| 633 | rc = new_dense(ctx, to, in.rank, in.shape, out, &buf); |
| 634 | if (rc) { free(src); free(dst); return rc; } |
| 635 | int nrc = ctx->real->elementwise(op, src, NULL, NULL, dst, n); |
| 636 | if (nrc) { free(src); free(dst); return numeric_fail(ctx, nrc, *out); } |
| 637 | if (to == OMEGA_DT_F32) { |
| 638 | memcpy(buf, dst, n * sizeof(float)); |
| 639 | } else { |
| 640 | uint64_t cdesc[21] = {0}; |
| 641 | cdesc[19] = n; cdesc[20] = 3; |
| 642 | tensor_copy_op((const uint8_t *)dst, n * 4, (uint8_t *)buf, n * 2, cdesc); |
| 643 | } |
| 644 | free(src); |
| 645 | free(dst); |
| 646 | return OMEGA_TENSOR_OK; |
| 647 | } |
| 648 | |
| 649 | static const OmegaNumericOp BINARY_MAP[OMEGA_TB_COUNT] = { |
| 650 | [OMEGA_TB_ADD] = OMEGA_NOP_FADD, [OMEGA_TB_SUB] = OMEGA_NOP_FSUB, |
| 651 | [OMEGA_TB_MUL] = OMEGA_NOP_FMUL, [OMEGA_TB_DIV] = OMEGA_NOP_DIV, |
| 652 | [OMEGA_TB_MIN] = OMEGA_NOP_FMNMX_MIN, [OMEGA_TB_MAX] = OMEGA_NOP_FMNMX_MAX, |
| 653 | [OMEGA_TB_SEL_GE] = OMEGA_NOP_FSETP_SEL, [OMEGA_TB_SEL_LT] = OMEGA_NOP_FSETP_LT_SEL, |
| 654 | [OMEGA_TB_SEL_LE] = OMEGA_NOP_FSETP_LE_SEL, [OMEGA_TB_SEL_GT] = OMEGA_NOP_FSETP_GT_SEL, |
| 655 | [OMEGA_TB_SEL_EQ] = OMEGA_NOP_FSETP_EQ_SEL, [OMEGA_TB_SEL_NE] = OMEGA_NOP_FSETP_NE_SEL, |
| 656 | [OMEGA_TB_SEL_NUM] = OMEGA_NOP_FSETP_NUM_SEL, [OMEGA_TB_SEL_NAN] = OMEGA_NOP_FSETP_NAN_SEL, |
| 657 | [OMEGA_TB_SEL_LTU] = OMEGA_NOP_FSETP_LTU_SEL, [OMEGA_TB_SEL_LEU] = OMEGA_NOP_FSETP_LEU_SEL, |
| 658 | [OMEGA_TB_SEL_GTU] = OMEGA_NOP_FSETP_GTU_SEL, [OMEGA_TB_SEL_GEU] = OMEGA_NOP_FSETP_GEU_SEL, |
| 659 | [OMEGA_TB_SEL_EQU] = OMEGA_NOP_FSETP_EQU_SEL, [OMEGA_TB_SEL_NEU] = OMEGA_NOP_FSETP_NEU_SEL, |
| 660 | /* CR-3 mask compare: the ordered E1 compare-select op whose predicate |
| 661 | * the realization's compare entry evaluates. */ |
| 662 | [OMEGA_TB_CMP_EQ] = OMEGA_NOP_FSETP_EQ_SEL, /* MUT:CMP_EQ_NAN_TRUE */ |
| 663 | [OMEGA_TB_CMP_NE] = OMEGA_NOP_FSETP_NE_SEL, [OMEGA_TB_CMP_LT] = OMEGA_NOP_FSETP_LT_SEL, |
| 664 | [OMEGA_TB_CMP_LE] = OMEGA_NOP_FSETP_LE_SEL, [OMEGA_TB_CMP_GT] = OMEGA_NOP_FSETP_GT_SEL, |
| 665 | [OMEGA_TB_CMP_GE] = OMEGA_NOP_FSETP_SEL, |
| 666 | }; |
| 667 | |
| 668 | static bool binary_is_cmp(OmegaTensorBinaryOp op) { |
| 669 | return op >= OMEGA_TB_CMP_EQ && op <= OMEGA_TB_CMP_GE; |
| 670 | } |
| 671 | |
| 672 | /* Gather 1..3 F32 operands, broadcast together (numpy rules), into dense |
| 673 | * malloc'd buffers in[0..arity). On success the caller frees in[]. Moves |
| 674 | * data only. */ |
| 675 | static int gather_broadcast(OmegaTensorCtx *ctx, unsigned arity, const OmegaTensor *ops, uint32_t *rank, |
| 676 | uint64_t *shape, float **in, size_t *count) { |
| 677 | TensorSlot *x[3] = {NULL, NULL, NULL}; |
| 678 | StorageSlot *s[3] = {NULL, NULL, NULL}; |
| 679 | for (unsigned i = 0; i < arity; i++) { |
| 680 | int rc = tensor_get(ctx, ops[i], &x[i], &s[i]); |
| 681 | if (rc) return rc; |
| 682 | } |
| 683 | for (unsigned i = 0; i < arity; i++) |
| 684 | if (x[i]->info.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 685 | uint32_t r = x[0]->info.rank; |
| 686 | if (r) memcpy(shape, x[0]->info.shape, r * sizeof(uint64_t)); |
| 687 | for (unsigned i = 1; i < arity; i++) { |
| 688 | int rc = omega_tensor_broadcast_shape(r, shape, x[i]->info.rank, x[i]->info.shape, &r, shape); |
| 689 | if (rc) return rc; |
| 690 | } |
| 691 | OmegaTensorInfo bi[3] = {0}; |
| 692 | for (unsigned i = 0; i < arity; i++) { |
| 693 | int rc = broadcast_info(&x[i]->info, r, shape, &bi[i]); |
| 694 | if (rc) return rc; |
| 695 | } |
| 696 | size_t n = (size_t)bi[0].elements; |
| 697 | for (unsigned i = 0; i < arity; i++) { |
| 698 | in[i] = malloc(n * sizeof(float)); |
| 699 | if (!in[i]) { for (unsigned j = 0; j < i; j++) { free(in[j]); in[j] = NULL; } return OMEGA_TENSOR_ERR_CAPACITY; } |
| 700 | gather(s[i], &bi[i], in[i]); |
| 701 | } |
| 702 | *rank = r; |
| 703 | *count = n; |
| 704 | return OMEGA_TENSOR_OK; |
| 705 | } |
| 706 | |
| 707 | /* CR-3 compare: two operands broadcast together, then one call of the |
| 708 | * realization's compare entry (+1.0 / +0.0 per element). */ |
| 709 | static int compare_n(OmegaTensorCtx *ctx, OmegaNumericOp sel_op, const OmegaTensor *ops, OmegaTensor *out) { |
| 710 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 711 | if (!ctx->real->compare) return OMEGA_TENSOR_ERR_REALIZATION; |
| 712 | uint32_t r; |
| 713 | uint64_t shape[OMEGA_TENSOR_MAX_RANK]; |
| 714 | float *in[3] = {NULL, NULL, NULL}; |
| 715 | size_t n; |
| 716 | int rc = gather_broadcast(ctx, 2, ops, &r, shape, in, &n); |
| 717 | if (rc) return rc; |
| 718 | void *buf; |
| 719 | rc = new_dense(ctx, OMEGA_DT_F32, r, shape, out, &buf); |
| 720 | if (!rc) { |
| 721 | int nrc = ctx->real->compare(sel_op, in[0], in[1], buf, n); |
| 722 | if (nrc) rc = numeric_fail(ctx, nrc, *out); |
| 723 | } |
| 724 | free(in[0]); |
| 725 | free(in[1]); |
| 726 | return rc; |
| 727 | } |
| 728 | |
| 729 | /* Elementwise over 1..3 F32 operands broadcast together. */ |
| 730 | static int elementwise_n(OmegaTensorCtx *ctx, OmegaNumericOp op, unsigned arity, const OmegaTensor *ops, |
| 731 | OmegaTensor *out) { |
| 732 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 733 | TensorSlot *x[3]; |
| 734 | StorageSlot *s[3]; |
| 735 | for (unsigned i = 0; i < arity; i++) { |
| 736 | int rc = tensor_get(ctx, ops[i], &x[i], &s[i]); |
| 737 | if (rc) return rc; |
| 738 | } |
| 739 | for (unsigned i = 0; i < arity; i++) |
| 740 | if (x[i]->info.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 741 | uint32_t r = x[0]->info.rank; |
| 742 | uint64_t shape[OMEGA_TENSOR_MAX_RANK]; |
| 743 | if (r) memcpy(shape, x[0]->info.shape, r * sizeof(uint64_t)); |
| 744 | for (unsigned i = 1; i < arity; i++) { |
| 745 | int rc = omega_tensor_broadcast_shape(r, shape, x[i]->info.rank, x[i]->info.shape, &r, shape); |
| 746 | if (rc) return rc; |
| 747 | } |
| 748 | OmegaTensorInfo bi[3]; |
| 749 | for (unsigned i = 0; i < arity; i++) { |
| 750 | int rc = broadcast_info(&x[i]->info, r, shape, &bi[i]); |
| 751 | if (rc) return rc; |
| 752 | } |
| 753 | size_t n = (size_t)bi[0].elements; |
| 754 | float *in[3] = {NULL, NULL, NULL}; |
| 755 | for (unsigned i = 0; i < arity; i++) { |
| 756 | in[i] = malloc(n * sizeof(float)); |
| 757 | if (!in[i]) { for (unsigned j = 0; j < i; j++) free(in[j]); return OMEGA_TENSOR_ERR_CAPACITY; } |
| 758 | gather(s[i], &bi[i], in[i]); |
| 759 | } |
| 760 | void *buf; |
| 761 | int rc = new_dense(ctx, OMEGA_DT_F32, r, shape, out, &buf); |
| 762 | if (!rc) { |
| 763 | int nrc = ctx->real->elementwise(op, in[0], in[1], in[2], buf, n); |
| 764 | if (nrc) rc = numeric_fail(ctx, nrc, *out); |
| 765 | } |
| 766 | for (unsigned i = 0; i < arity; i++) free(in[i]); |
| 767 | return rc; |
| 768 | } |
| 769 | /* NEG: sign-bit flip; any NaN becomes the canonical quiet NaN. */ |
| 770 | static uint32_t neg_bits(uint32_t u) { |
| 771 | if ((u & 0x7f800000U) == 0x7f800000U && (u & 0x007fffffU)) return 0x7fc00000U; /* MUT:NEG_NAN */ |
| 772 | return u ^ 0x80000000U; /* MUT:NEG_SUB */ |
| 773 | } |
| 774 | |
| 775 | |
| 776 | /* RELU (M20 cut ops): no E1 op exists, so the tensor layer defines it as a |
| 777 | * pure bit-level select on the FP32 pattern, with no float arithmetic and no |
| 778 | * realization call. Rule: any NaN (exponent all ones, mantissa nonzero, any |
| 779 | * sign or payload) -> the canonical E1 qNaN OMEGA_QNAN_BITS (omega_numeric.h:48, |
| 780 | * as E1 ops return it, e.g. omega_numeric.c:459); sign bit set (-0, negative |
| 781 | * normals and subnormals, -inf) -> +0.0; otherwise (+0, positive values, +inf) |
| 782 | * -> the input bits unchanged. */ |
| 783 | static uint32_t relu_bits(uint32_t u) { |
| 784 | if ((u & 0x7fffffffU) > OMEGA_INF_POS) return OMEGA_QNAN_BITS; /* MUT:RELU_NAN_PAYLOAD */ |
| 785 | if (u >> 31) return 0U; /* MUT:RELU_NEG_ZERO */ |
| 786 | return u; |
| 787 | } |
| 788 | |
| 789 | static void relu_dense(const float *src, float *dst, size_t n) { |
| 790 | for (size_t i = 0; i < n; i++) { |
| 791 | uint32_t u; |
| 792 | memcpy(&u, &src[i], sizeof u); |
| 793 | u = relu_bits(u); |
| 794 | memcpy(&dst[i], &u, sizeof u); |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | /* Unary ops: gather the operand through its own view descriptor (offset, |
| 799 | * shape, strides, including stride-0 broadcast axes) into a dense buffer, |
| 800 | * then one realization call. SQRT goes through the E1 elementwise op; the |
| 801 | * bounded-contract transcendentals and EXP / LOG through the realization's |
| 802 | * transc entry; RELU is the tensor-layer bit select above (no realization). */ |
| 803 | int omega_tensor_unary(OmegaTensorCtx *ctx, OmegaTensorUnaryOp op, OmegaTensor a, OmegaTensor *out) { |
| 804 | if (!ctx || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 805 | if ((unsigned)op >= OMEGA_TU_COUNT) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 806 | if (op != OMEGA_TU_SQRT && op != OMEGA_TU_RELU && op != OMEGA_TU_NEG && !ctx->real->transc) return OMEGA_TENSOR_ERR_REALIZATION; |
| 807 | TensorSlot *x; |
| 808 | StorageSlot *s; |
| 809 | int rc = tensor_get(ctx, a, &x, &s); |
| 810 | if (rc) return rc; |
| 811 | OmegaTensorInfo in = x->info; /* copy: slot table may be reused below */ |
| 812 | if (in.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 813 | size_t n = (size_t)in.elements; |
| 814 | float *src = malloc(n * sizeof(float)); |
| 815 | if (!src) return OMEGA_TENSOR_ERR_CAPACITY; |
| 816 | gather(s, &in, src); /* MUT:UNARY_VIEW_STRIDE MUT:GELU_VIEW_STRIDE */ |
| 817 | void *buf; |
| 818 | rc = new_dense(ctx, OMEGA_DT_F32, in.rank, in.shape, out, &buf); |
| 819 | if (!rc) { |
| 820 | int nrc = 0; |
| 821 | if (op == OMEGA_TU_RELU) relu_dense(src, buf, n); |
| 822 | else if (op == OMEGA_TU_NEG) { |
| 823 | uint32_t *ob = buf; |
| 824 | for (size_t i = 0; i < n; i++) ob[i] = neg_bits(omega_float_to_bits(src[i])); |
| 825 | } else { |
| 826 | nrc = op == OMEGA_TU_SQRT ? ctx->real->elementwise(OMEGA_NOP_SQRT, src, NULL, NULL, buf, n) |
| 827 | : ctx->real->transc(op, src, buf, n); |
| 828 | } |
| 829 | if (nrc) rc = numeric_fail(ctx, nrc, *out); |
| 830 | } |
| 831 | free(src); |
| 832 | return rc; |
| 833 | } |
| 834 | |
| 835 | /* Constant tensors: pure bit fill, no arithmetic. */ |
| 836 | int omega_tensor_full(OmegaTensorCtx *ctx, uint32_t rank, const uint64_t *shape, float value, |
| 837 | OmegaTensor *out) { |
| 838 | if (!ctx || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 839 | void *buf; |
| 840 | int rc = new_dense(ctx, OMEGA_DT_F32, rank, shape, out, &buf); |
| 841 | if (rc) return rc; |
| 842 | uint32_t u = omega_float_to_bits(value); /* MUT:FULL_CANON */ |
| 843 | size_t n = (size_t)ctx->ts[out->slot].info.elements; |
| 844 | uint64_t fdesc[21] = {0}; |
| 845 | uint8_t dummy = 0; |
| 846 | fdesc[17] = u; fdesc[19] = n; fdesc[20] = 4; |
| 847 | tensor_copy_op(&dummy, 1, (uint8_t *)buf, n * 4, fdesc); |
| 848 | return OMEGA_TENSOR_OK; |
| 849 | } |
| 850 | |
| 851 | int omega_tensor_zeros(OmegaTensorCtx *ctx, uint32_t rank, const uint64_t *shape, OmegaTensor *out) { |
| 852 | return omega_tensor_full(ctx, rank, shape, 0.0f, out); /* MUT:ZEROS_NEG0 */ |
| 853 | } |
| 854 | |
| 855 | int omega_tensor_ones(OmegaTensorCtx *ctx, uint32_t rank, const uint64_t *shape, OmegaTensor *out) { |
| 856 | return omega_tensor_full(ctx, rank, shape, 1.0f, out); |
| 857 | } |
| 858 | |
| 859 | int omega_tensor_binary(OmegaTensorCtx *ctx, OmegaTensorBinaryOp op, OmegaTensor a, OmegaTensor b, |
| 860 | OmegaTensor *out) { |
| 861 | if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 862 | if ((unsigned)op >= OMEGA_TB_COUNT) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 863 | OmegaTensor ops[2] = {a, b}; |
| 864 | if (binary_is_cmp(op)) return compare_n(ctx, BINARY_MAP[op], ops, out); |
| 865 | return elementwise_n(ctx, BINARY_MAP[op], 2, ops, out); |
| 866 | } |
| 867 | |
| 868 | int omega_tensor_fma(OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, OmegaTensor c, OmegaTensor *out) { |
| 869 | if (!ctx) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 870 | OmegaTensor ops[3] = {a, b, c}; |
| 871 | return elementwise_n(ctx, OMEGA_NOP_FFMA_V, 3, ops, out); |
| 872 | } |
| 873 | |
| 874 | /* CR-3 where: data movement only. Every cond element is checked against the |
| 875 | * two mask bit patterns before any tensor is made; then each output element |
| 876 | * is a 4-byte copy of a[i] or b[i]. */ |
| 877 | int omega_tensor_where(OmegaTensorCtx *ctx, OmegaTensor cond, OmegaTensor a, OmegaTensor b, |
| 878 | OmegaTensor *out) { |
| 879 | if (!ctx || !out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 880 | OmegaTensor ops[3] = {cond, a, b}; |
| 881 | uint32_t r; |
| 882 | uint64_t shape[OMEGA_TENSOR_MAX_RANK]; |
| 883 | float *in[3] = {NULL, NULL, NULL}; |
| 884 | size_t n; |
| 885 | int rc = gather_broadcast(ctx, 3, ops, &r, shape, in, &n); |
| 886 | if (rc) return rc; |
| 887 | for (size_t i = 0; i < n && !rc; i++) { |
| 888 | uint32_t u = omega_float_to_bits(in[0][i]); |
| 889 | if (u != OMEGA_TENSOR_MASK_TRUE_BITS && u != OMEGA_TENSOR_MASK_FALSE_BITS) /* MUT:WHERE_ACCEPTS_HALF */ |
| 890 | rc = OMEGA_TENSOR_ERR_MASK; |
| 891 | } |
| 892 | void *buf = NULL; |
| 893 | if (!rc) rc = new_dense(ctx, OMEGA_DT_F32, r, shape, out, &buf); |
| 894 | if (!rc) { |
| 895 | uint8_t *o = buf; |
| 896 | for (size_t i = 0; i < n; i++) { |
| 897 | const float *src = omega_float_to_bits(in[0][i]) == OMEGA_TENSOR_MASK_TRUE_BITS ? &in[1][i] : &in[2][i]; |
| 898 | memcpy(o + i * sizeof(float), src, sizeof(float)); |
| 899 | } |
| 900 | } |
| 901 | for (unsigned i = 0; i < 3; i++) free(in[i]); |
| 902 | return rc; |
| 903 | } |
| 904 | |
| 905 | int omega_tensor_reduce(OmegaTensorCtx *ctx, OmegaTensorReduceOp op, OmegaTensor t, uint32_t axis, |
| 906 | bool keepdims, OmegaTensor *out) { |
| 907 | TensorSlot *x; |
| 908 | StorageSlot *s; |
| 909 | if (!out || (unsigned)op >= OMEGA_TR_COUNT) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 910 | int rc = tensor_get(ctx, t, &x, &s); |
| 911 | if (rc) return rc; |
| 912 | OmegaTensorInfo in = x->info; |
| 913 | if (in.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 914 | if (in.rank == 0) return OMEGA_TENSOR_ERR_RANK; |
| 915 | if (axis >= in.rank) return OMEGA_TENSOR_ERR_AXIS; |
| 916 | /* Move the axis last (descriptor only), gather rows densely. */ |
| 917 | OmegaTensorInfo moved = in; |
| 918 | size_t n = (size_t)in.shape[axis], rows = (size_t)(in.elements / in.shape[axis]); |
| 919 | uint32_t orank = keepdims ? in.rank : in.rank - 1; |
| 920 | uint64_t oshape[OMEGA_TENSOR_MAX_RANK] = {0}; |
| 921 | uint64_t out_desc[24] = {0}; |
| 922 | const uint64_t rmeta[4] = { in.rank, axis, keepdims ? 1 : 0, 1 }; |
| 923 | tensor_plan_op(in.shape, in.strides, out_desc, rmeta); |
| 924 | memcpy(moved.shape, out_desc, sizeof(moved.shape)); |
| 925 | memcpy(moved.strides, out_desc + 8, sizeof(moved.strides)); |
| 926 | memcpy(oshape, out_desc + 16, sizeof(oshape)); |
| 927 | float *dense = malloc((size_t)in.elements * sizeof(float)); |
| 928 | if (!dense) return OMEGA_TENSOR_ERR_CAPACITY; |
| 929 | gather(s, &moved, dense); |
| 930 | void *buf; |
| 931 | rc = new_dense(ctx, OMEGA_DT_F32, orank, oshape, out, &buf); |
| 932 | if (!rc) { |
| 933 | float *o = buf; |
| 934 | for (size_t r = 0; r < rows; r++) { |
| 935 | int nrc = ctx->real->reduce(op, dense + r * n, n, &o[r]); |
| 936 | if (nrc) { rc = numeric_fail(ctx, nrc, *out); break; } |
| 937 | } |
| 938 | } |
| 939 | free(dense); |
| 940 | return rc; |
| 941 | } |
| 942 | |
| 943 | /* Products per matmul block (elements): bounds the scratch of one block. */ |
| 944 | #define MATMUL_BLOCK_ELEMS ((uint64_t)1 << 20) |
| 945 | |
| 946 | int omega_tensor_matmul(OmegaTensorCtx *ctx, OmegaTensor a, OmegaTensor b, OmegaTensor *out) { |
| 947 | TensorSlot *xa, *xb; |
| 948 | StorageSlot *sa, *sb; |
| 949 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 950 | int rc = tensor_get(ctx, a, &xa, &sa); |
| 951 | if (!rc) rc = tensor_get(ctx, b, &xb, &sb); |
| 952 | if (rc) return rc; |
| 953 | OmegaTensorInfo ia = xa->info, ib = xb->info; |
| 954 | if (ia.dtype != OMEGA_DT_F32 || ib.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 955 | if (ia.rank < 2 || ib.rank < 2) return OMEGA_TENSOR_ERR_RANK; |
| 956 | uint64_t M = ia.shape[ia.rank - 2], K = ia.shape[ia.rank - 1]; |
| 957 | uint64_t K2 = ib.shape[ib.rank - 2], N = ib.shape[ib.rank - 1]; |
| 958 | if (K != K2) return OMEGA_TENSOR_ERR_SHAPE; |
| 959 | uint32_t br; |
| 960 | uint64_t bshape[OMEGA_TENSOR_MAX_RANK]; |
| 961 | rc = omega_tensor_broadcast_shape(ia.rank - 2, ia.shape, ib.rank - 2, ib.shape, &br, bshape); |
| 962 | if (rc) return rc; |
| 963 | if (br + 2 > OMEGA_TENSOR_MAX_RANK) return OMEGA_TENSOR_ERR_RANK; |
| 964 | uint64_t sha[OMEGA_TENSOR_MAX_RANK], shb[OMEGA_TENSOR_MAX_RANK], sho[OMEGA_TENSOR_MAX_RANK]; |
| 965 | memcpy(sha, bshape, br * sizeof(uint64_t)); |
| 966 | memcpy(shb, bshape, br * sizeof(uint64_t)); |
| 967 | memcpy(sho, bshape, br * sizeof(uint64_t)); |
| 968 | sha[br] = M; sha[br + 1] = K; |
| 969 | shb[br] = K; shb[br + 1] = N; |
| 970 | sho[br] = M; sho[br + 1] = N; |
| 971 | OmegaTensorInfo va, vb; |
| 972 | rc = broadcast_info(&ia, br + 2, sha, &va); |
| 973 | if (!rc) rc = broadcast_info(&ib, br + 2, shb, &vb); |
| 974 | if (rc) return rc; |
| 975 | /* B with its last two axes swapped, so each column is a dense row. */ |
| 976 | uint64_t t0 = vb.shape[br], t1 = vb.strides[br]; |
| 977 | vb.shape[br] = vb.shape[br + 1]; vb.strides[br] = vb.strides[br + 1]; |
| 978 | vb.shape[br + 1] = t0; vb.strides[br + 1] = t1; |
| 979 | uint64_t batches = va.elements / (M * K); |
| 980 | float *A = malloc((size_t)va.elements * sizeof(float)); |
| 981 | float *BT = malloc((size_t)vb.elements * sizeof(float)); |
| 982 | /* Outputs are done in blocks: the products of a whole block go through |
| 983 | * one elementwise FMUL call and one row reduction (reduce_rows, or one |
| 984 | * reduce per row), so a device realization needs a few launches per |
| 985 | * block instead of two per output. Same bits: FMUL is per element and |
| 986 | * every row is reduced in the declared order. */ |
| 987 | uint64_t outs = batches * M * N; |
| 988 | uint64_t blk = MATMUL_BLOCK_ELEMS / K; |
| 989 | if (blk == 0) blk = 1; |
| 990 | if (blk > outs) blk = outs; |
| 991 | float *pa = malloc((size_t)(blk * K) * sizeof(float)); |
| 992 | float *pb = malloc((size_t)(blk * K) * sizeof(float)); |
| 993 | float *prod = malloc((size_t)(blk * K) * sizeof(float)); |
| 994 | if (!A || !BT || !pa || !pb || !prod) { |
| 995 | free(A); free(BT); free(pa); free(pb); free(prod); |
| 996 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 997 | } |
| 998 | gather(sa, &va, A); |
| 999 | gather(sb, &vb, BT); |
| 1000 | void *buf; |
| 1001 | rc = new_dense(ctx, OMEGA_DT_F32, br + 2, sho, out, &buf); |
| 1002 | if (!rc) { |
| 1003 | float *o = buf; |
| 1004 | for (uint64_t o0 = 0; o0 < outs && !rc; o0 += blk) { |
| 1005 | uint64_t cnt = outs - o0 < blk ? outs - o0 : blk; |
| 1006 | uint64_t desc_a[21] = { M, N, K, o0, cnt, 0 }; |
| 1007 | uint64_t desc_b[21] = { M, N, K, o0, cnt, 1 }; |
| 1008 | desc_a[20] = 5; desc_b[20] = 5; |
| 1009 | tensor_copy_op((const uint8_t *)A, (size_t)va.elements * 4, |
| 1010 | (uint8_t *)pa, (size_t)(cnt * K) * 4, desc_a); |
| 1011 | tensor_copy_op((const uint8_t *)BT, (size_t)vb.elements * 4, |
| 1012 | (uint8_t *)pb, (size_t)(cnt * K) * 4, desc_b); |
| 1013 | int nrc = ctx->real->elementwise(OMEGA_NOP_FMUL, pa, pb, NULL, prod, (size_t)(cnt * K)); |
| 1014 | if (!nrc && ctx->real->reduce_rows) |
| 1015 | nrc = ctx->real->reduce_rows(OMEGA_TR_SUM, prod, (size_t)cnt, (size_t)K, o + o0); |
| 1016 | for (uint64_t q = 0; !nrc && !ctx->real->reduce_rows && q < cnt; q++) |
| 1017 | nrc = ctx->real->reduce(OMEGA_TR_SUM, prod + q * K, (size_t)K, &o[o0 + q]); |
| 1018 | if (nrc) rc = numeric_fail(ctx, nrc, *out); |
| 1019 | } |
| 1020 | } |
| 1021 | free(A); |
| 1022 | free(BT); |
| 1023 | free(pa); |
| 1024 | free(pb); |
| 1025 | free(prod); |
| 1026 | return rc; |
| 1027 | } |
| 1028 | |
| 1029 | void omega_tensor_live_counts(const OmegaTensorCtx *ctx, uint32_t *tensors, uint32_t *storages) { |
| 1030 | uint32_t t = 0, s = 0; |
| 1031 | for (uint32_t i = 0; ctx && i < ctx->cap; i++) { t += ctx->ts[i].live; s += ctx->st[i].live; } |
| 1032 | if (tensors) *tensors = t; |
| 1033 | if (storages) *storages = s; |
| 1034 | } |
| 1035 | |
| 1036 | /* ---- placement (CR-4): embed and concat ---------------------------------- */ |
| 1037 | /* Pure bit copies: gather the source in logical row-major order, then write |
| 1038 | * it through a destination descriptor into fresh zero-filled dense storage |
| 1039 | * (storage_alloc uses calloc: all-zero bits = +0.0 in F32/F16/BF16). */ |
| 1040 | |
| 1041 | /* Inverse of gather: element e of src (row-major) goes to the storage index |
| 1042 | * the descriptor `in` gives for logical index e. */ |
| 1043 | static void scatter(StorageSlot *s, const OmegaTensorInfo *in, const void *src) { |
| 1044 | size_t es = omega_dtype_size(in->dtype); |
| 1045 | uint64_t desc[21] = {0}; |
| 1046 | memcpy(desc, in->shape, sizeof(in->shape)); |
| 1047 | memcpy(desc + 8, in->strides, sizeof(in->strides)); |
| 1048 | desc[16] = in->rank; desc[17] = in->offset; desc[18] = es; desc[19] = in->elements; desc[20] = 1; |
| 1049 | tensor_copy_op((const uint8_t *)src, (size_t)in->elements * es, |
| 1050 | (uint8_t *)s->data, (size_t)s->elems * es, desc); |
| 1051 | } |
| 1052 | |
| 1053 | /* Gather part (s, in) and scatter it through dst_desc into out's storage. */ |
| 1054 | static int place(OmegaTensorCtx *ctx, const StorageSlot *s, const OmegaTensorInfo *in, OmegaTensor out, |
| 1055 | const OmegaTensorInfo *dst_desc) { |
| 1056 | StorageSlot *ds = &ctx->st[ctx->ts[out.slot].info.storage.slot]; |
| 1057 | int bounds_rc = bounds_check(dst_desc, ds->elems); /* defence in depth */ |
| 1058 | if (bounds_rc) return bounds_rc; |
| 1059 | void *tmp = malloc((size_t)in->elements * omega_dtype_size(in->dtype)); |
| 1060 | if (!tmp) return OMEGA_TENSOR_ERR_CAPACITY; |
| 1061 | gather(s, in, tmp); |
| 1062 | scatter(ds, dst_desc, tmp); |
| 1063 | free(tmp); |
| 1064 | return OMEGA_TENSOR_OK; |
| 1065 | } |
| 1066 | |
| 1067 | int omega_tensor_embed(OmegaTensorCtx *ctx, OmegaTensor src, uint32_t rank, const uint64_t *out_shape, |
| 1068 | const uint64_t *start, const uint64_t *step, OmegaTensor *out) { |
| 1069 | TensorSlot *x; |
| 1070 | StorageSlot *s; |
| 1071 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1072 | int rc = tensor_get(ctx, src, &x, &s); |
| 1073 | if (rc) return rc; |
| 1074 | OmegaTensorInfo in = x->info; /* copy: slot table may be reused below */ |
| 1075 | if (rank == 0 || rank != in.rank) return OMEGA_TENSOR_ERR_RANK; |
| 1076 | if (!out_shape || !start) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1077 | uint64_t n; |
| 1078 | rc = shape_check(rank, out_shape, &n); |
| 1079 | if (rc) return rc; |
| 1080 | uint64_t ds[OMEGA_TENSOR_MAX_RANK]; |
| 1081 | rc = dense_strides(rank, out_shape, ds); |
| 1082 | if (rc) return rc; |
| 1083 | OmegaTensorInfo v = in; /* destination descriptor over out's storage */ |
| 1084 | v.offset = 0; |
| 1085 | for (uint32_t d = 0; d < rank; d++) { |
| 1086 | uint64_t st = step ? step[d] : 1; |
| 1087 | if (st == 0) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1088 | uint64_t last, so; |
| 1089 | if (__builtin_mul_overflow(in.shape[d] - 1, st, &last) || |
| 1090 | __builtin_add_overflow(last, start[d], &last) || last >= out_shape[d]) |
| 1091 | return OMEGA_TENSOR_ERR_BOUNDS; |
| 1092 | if (__builtin_mul_overflow(start[d], ds[d], &so) || /* MUT:EMBED_START */ |
| 1093 | __builtin_add_overflow(v.offset, so, &v.offset)) |
| 1094 | return OMEGA_TENSOR_ERR_BOUNDS; |
| 1095 | if (in.shape[d] == 1) v.strides[d] = 0; /* never used; avoids overflow */ |
| 1096 | else if (__builtin_mul_overflow(ds[d], st, &v.strides[d])) /* MUT:EMBED_STEP */ |
| 1097 | return OMEGA_TENSOR_ERR_BOUNDS; |
| 1098 | } |
| 1099 | void *buf; |
| 1100 | rc = new_dense(ctx, in.dtype, rank, out_shape, out, &buf); |
| 1101 | if (rc) return rc; |
| 1102 | rc = place(ctx, s, &in, *out, &v); |
| 1103 | if (rc) omega_tensor_release(ctx, *out); |
| 1104 | return rc; |
| 1105 | } |
| 1106 | |
| 1107 | int omega_tensor_concat(OmegaTensorCtx *ctx, uint32_t n, const OmegaTensor *tensors, uint32_t axis, |
| 1108 | OmegaTensor *out) { |
| 1109 | if (!ctx || !out || !tensors || n == 0) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1110 | TensorSlot *x0; |
| 1111 | int rc = tensor_get(ctx, tensors[0], &x0, NULL); |
| 1112 | if (rc) return rc; |
| 1113 | OmegaTensorInfo first = x0->info; |
| 1114 | if (first.rank == 0) return OMEGA_TENSOR_ERR_RANK; |
| 1115 | if (axis >= first.rank) return OMEGA_TENSOR_ERR_AXIS; |
| 1116 | uint64_t shape[OMEGA_TENSOR_MAX_RANK]; |
| 1117 | memcpy(shape, first.shape, sizeof(shape)); |
| 1118 | shape[axis] = 0; |
| 1119 | for (uint32_t k = 0; k < n; k++) { /* validate everything before allocating */ |
| 1120 | TensorSlot *xk; |
| 1121 | rc = tensor_get(ctx, tensors[k], &xk, NULL); |
| 1122 | if (rc) return rc; |
| 1123 | const OmegaTensorInfo *ik = &xk->info; |
| 1124 | if (ik->dtype != first.dtype) return OMEGA_TENSOR_ERR_DTYPE; |
| 1125 | if (ik->rank != first.rank) return OMEGA_TENSOR_ERR_RANK; |
| 1126 | for (uint32_t d = 0; d < first.rank; d++) |
| 1127 | if (d != axis && ik->shape[d] != first.shape[d]) return OMEGA_TENSOR_ERR_SHAPE; |
| 1128 | if (__builtin_add_overflow(shape[axis], ik->shape[axis], &shape[axis]) || |
| 1129 | shape[axis] > OMEGA_TENSOR_MAX_ELEMS) |
| 1130 | return OMEGA_TENSOR_ERR_CAPACITY; |
| 1131 | } |
| 1132 | void *buf; |
| 1133 | rc = new_dense(ctx, first.dtype, first.rank, shape, out, &buf); /* MAX_ELEMS -> ERR_CAPACITY */ |
| 1134 | if (rc) return rc; |
| 1135 | uint64_t ds[OMEGA_TENSOR_MAX_RANK]; |
| 1136 | rc = dense_strides(first.rank, shape, ds); |
| 1137 | if (rc) { omega_tensor_release(ctx, *out); return rc; } |
| 1138 | uint64_t aoff = 0; |
| 1139 | for (uint32_t k = 0; k < n && !rc; k++) { |
| 1140 | TensorSlot *xk; |
| 1141 | StorageSlot *sk; |
| 1142 | rc = tensor_get(ctx, tensors[k], &xk, &sk); |
| 1143 | if (rc) break; |
| 1144 | OmegaTensorInfo ik = xk->info; |
| 1145 | OmegaTensorInfo v = ik; |
| 1146 | v.offset = aoff * ds[axis]; /* MUT:CONCAT_AXIS_OFFSET */ |
| 1147 | for (uint32_t d = 0; d < ik.rank; d++) v.strides[d] = ds[d]; |
| 1148 | rc = place(ctx, sk, &ik, *out, &v); |
| 1149 | aoff += ik.shape[axis]; |
| 1150 | } |
| 1151 | if (rc) omega_tensor_release(ctx, *out); |
| 1152 | return rc; |
| 1153 | } |
| 1154 | |
| 1155 | /* ---- multi-axis reduce and unbroadcast (CR-5) ------------------------------ */ |
| 1156 | |
| 1157 | /* Bit copy of t (any layout) into a new dense tensor of (rank, shape) holding |
| 1158 | * the same number of elements in the same logical row-major order. Used only |
| 1159 | * to drop or keep size-1 axes. No arithmetic. */ |
| 1160 | static int copy_as_shape(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, const uint64_t *shape, |
| 1161 | OmegaTensor *out) { |
| 1162 | TensorSlot *x; |
| 1163 | StorageSlot *s; |
| 1164 | int rc = tensor_get(ctx, t, &x, &s); |
| 1165 | if (rc) return rc; |
| 1166 | OmegaTensorInfo in = x->info; /* copy: slot table may be reused below */ |
| 1167 | uint64_t n; |
| 1168 | rc = shape_check(rank, shape, &n); |
| 1169 | if (rc) return rc; |
| 1170 | if (n != in.elements) return OMEGA_TENSOR_ERR_SHAPE; |
| 1171 | void *buf; |
| 1172 | rc = new_dense(ctx, in.dtype, rank, shape, out, &buf); |
| 1173 | if (rc) return rc; |
| 1174 | gather(s, &in, buf); |
| 1175 | return OMEGA_TENSOR_OK; |
| 1176 | } |
| 1177 | |
| 1178 | /* Single-axis reduce chain: step i reduces axis ax[i] with keepdims keep[i]. |
| 1179 | * The caller lists the axes in descending order. Every intermediate tensor is |
| 1180 | * released; t itself never is. n >= 1. */ |
| 1181 | static int reduce_chain(OmegaTensorCtx *ctx, OmegaTensorReduceOp op, OmegaTensor t, uint32_t n, |
| 1182 | const uint32_t *ax, const bool *keep, OmegaTensor *out) { |
| 1183 | OmegaTensor cur = t; |
| 1184 | for (uint32_t i = 0; i < n; i++) { |
| 1185 | OmegaTensor next; |
| 1186 | int rc = omega_tensor_reduce(ctx, op, cur, ax[i], keep[i], &next); |
| 1187 | if (i > 0) omega_tensor_release(ctx, cur); |
| 1188 | if (rc) return rc; |
| 1189 | cur = next; |
| 1190 | } |
| 1191 | *out = cur; |
| 1192 | return OMEGA_TENSOR_OK; |
| 1193 | } |
| 1194 | |
| 1195 | int omega_tensor_reduce_axes(OmegaTensorCtx *ctx, OmegaTensorReduceOp op, OmegaTensor t, |
| 1196 | uint32_t naxes, const uint32_t *axes, bool keepdims, OmegaTensor *out) { |
| 1197 | TensorSlot *x; |
| 1198 | if (!out || (unsigned)op >= OMEGA_TR_COUNT || (naxes && !axes)) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1199 | int rc = tensor_get(ctx, t, &x, NULL); |
| 1200 | if (rc) return rc; |
| 1201 | OmegaTensorInfo in = x->info; |
| 1202 | if (in.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 1203 | if (in.rank == 0) return OMEGA_TENSOR_ERR_RANK; |
| 1204 | if (naxes > in.rank) return OMEGA_TENSOR_ERR_AXIS; |
| 1205 | /* Mean over several axes would be a mean of means: refused (header). */ |
| 1206 | if (op == OMEGA_TR_MEAN && naxes > 1) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1207 | bool seen[OMEGA_TENSOR_MAX_RANK] = {false}; |
| 1208 | for (uint32_t i = 0; i < naxes; i++) { |
| 1209 | if (axes[i] >= in.rank || seen[axes[i]]) return OMEGA_TENSOR_ERR_AXIS; |
| 1210 | seen[axes[i]] = true; |
| 1211 | } |
| 1212 | if (naxes == 0) return omega_tensor_contiguous(ctx, t, out); |
| 1213 | uint32_t ax[OMEGA_TENSOR_MAX_RANK]; |
| 1214 | bool keep[OMEGA_TENSOR_MAX_RANK]; |
| 1215 | uint32_t n = 0; |
| 1216 | for (uint32_t d = in.rank; d-- > 0;) { /* MUT:REDUCE_AXES_DESCENDING */ |
| 1217 | if (!seen[d]) continue; |
| 1218 | ax[n] = d; |
| 1219 | keep[n] = keepdims; /* MUT:REDUCE_AXES_KEEPDIMS */ |
| 1220 | n++; |
| 1221 | } |
| 1222 | return reduce_chain(ctx, op, t, n, ax, keep, out); |
| 1223 | } |
| 1224 | |
| 1225 | int omega_tensor_sum_to_shape(OmegaTensorCtx *ctx, OmegaTensor t, uint32_t rank, |
| 1226 | const uint64_t *shape, OmegaTensor *out) { |
| 1227 | TensorSlot *x; |
| 1228 | if (!out) return OMEGA_TENSOR_ERR_BAD_ARGS; |
| 1229 | int rc = tensor_get(ctx, t, &x, NULL); |
| 1230 | if (rc) return rc; |
| 1231 | OmegaTensorInfo in = x->info; |
| 1232 | uint64_t elems; |
| 1233 | rc = shape_check(rank, shape, &elems); |
| 1234 | if (rc) return rc; |
| 1235 | if (in.dtype != OMEGA_DT_F32) return OMEGA_TENSOR_ERR_DTYPE; |
| 1236 | if (rank > in.rank) return OMEGA_TENSOR_ERR_SHAPE; |
| 1237 | uint32_t lead = in.rank - rank; |
| 1238 | /* Plan first (every check before any arithmetic), descending axis of t. */ |
| 1239 | uint32_t ax[OMEGA_TENSOR_MAX_RANK]; |
| 1240 | bool keep[OMEGA_TENSOR_MAX_RANK]; |
| 1241 | uint32_t n = 0; |
| 1242 | for (uint32_t d = in.rank; d-- > 0;) { |
| 1243 | if (d < lead) { /* leading axis: summed away, never kept */ |
| 1244 | if (in.shape[d] > 1) { ax[n] = d; keep[n] = false; n++; } |
| 1245 | continue; |
| 1246 | } |
| 1247 | uint64_t want = shape[d - lead]; |
| 1248 | if (want == in.shape[d]) continue; |
| 1249 | if (want != 1) return OMEGA_TENSOR_ERR_SHAPE; |
| 1250 | ax[n] = d; keep[n] = true; n++; /* MUT:SUM_TO_SHAPE_SIZE1 */ |
| 1251 | } |
| 1252 | if (n == 0) return copy_as_shape(ctx, t, rank, shape, out); |
| 1253 | OmegaTensor red; |
| 1254 | rc = reduce_chain(ctx, OMEGA_TR_SUM, t, n, ax, keep, &red); |
| 1255 | if (rc) return rc; |
| 1256 | rc = copy_as_shape(ctx, red, rank, shape, out); |
| 1257 | omega_tensor_release(ctx, red); |
| 1258 | return rc; |
| 1259 | } |