interplane.Get Omega
Read in your language

omega-mv

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

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / turing / ty_model.c

478 lines · 14581 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* Turing Yield context-table models. See ty_model.h. */
18#include "turing/ty_model.h"
19
20#include "sha256.h"
21
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25
26#define WHY(...) \
27 do { \
28 if (why && whylen) snprintf(why, whylen, __VA_ARGS__); \
29 } while (0)
30
31#define POS_IDX_BITS 20
32#define POS_RADIX_BITS 36 /* 16-bit crumb ordinal x 20-bit event index */
33
34void ty_model_free(ty_model *m) {
35 if (!m) return;
36 free(m->rows);
37 memset(m, 0, sizeof *m);
38}
39
40int ty_key_space(unsigned mask, unsigned K, uint64_t *space, unsigned *bits) {
41 if (mask & ~(unsigned)TY_F_ALL || K < 2 || K > TY_KMAX) return TY_E_ARG;
42 ty_u128 p = 1;
43 if (mask & TY_F_OP) p *= 16;
44 if (mask & TY_F_DEPTH) p *= TY_DEPTH_CLIP + 1;
45 if (mask & TY_F_PREV1) p *= K + 1;
46 if (mask & TY_F_PREV2) p *= K + 1;
47 if (mask & TY_F_PREV3) p *= K + 1;
48 if (mask & TY_F_PREV4) p *= K + 1;
49 if (mask & TY_F_PREV5) p *= K + 1;
50 if (mask & TY_F_POS) p *= (ty_u128)1 << POS_RADIX_BITS;
51 if (p > ((ty_u128)1 << 62)) return TY_E_RANGE;
52 uint64_t s = (uint64_t)p;
53 if (space) *space = s;
54 if (bits) *bits = s <= 1 ? 0u : 64u - (unsigned)__builtin_clzll(s - 1);
55 return TY_OK;
56}
57
58/* Walks a stream computing each event's context key. */
59typedef struct {
60 unsigned mask, K;
61 unsigned p1, p2, p3, p4, p5;
62} key_walk;
63
64static void kw_init(key_walk *w, unsigned mask, unsigned K) {
65 w->mask = mask;
66 w->K = K;
67 w->p1 = w->p2 = w->p3 = w->p4 = w->p5 = K;
68}
69
70static uint64_t kw_key(key_walk *w, const ty_ev *e) {
71 if (e->first) w->p1 = w->p2 = w->p3 = w->p4 = w->p5 = w->K; /* context resets per crumb */
72 uint64_t key = 0, mul = 1;
73 if (w->mask & TY_F_OP) {
74 key += (uint64_t)e->op * mul;
75 mul *= 16;
76 }
77 if (w->mask & TY_F_DEPTH) {
78 key += (uint64_t)e->depth * mul;
79 mul *= TY_DEPTH_CLIP + 1;
80 }
81 if (w->mask & TY_F_PREV1) {
82 key += (uint64_t)w->p1 * mul;
83 mul *= w->K + 1;
84 }
85 if (w->mask & TY_F_PREV2) {
86 key += (uint64_t)w->p2 * mul;
87 mul *= w->K + 1;
88 }
89 if (w->mask & TY_F_PREV3) {
90 key += (uint64_t)w->p3 * mul;
91 mul *= w->K + 1;
92 }
93 if (w->mask & TY_F_PREV4) {
94 key += (uint64_t)w->p4 * mul;
95 mul *= w->K + 1;
96 }
97 if (w->mask & TY_F_PREV5) {
98 key += (uint64_t)w->p5 * mul;
99 mul *= w->K + 1;
100 }
101 if (w->mask & TY_F_POS) {
102 uint64_t idx = e->idx >= (1u << POS_IDX_BITS) ? (1u << POS_IDX_BITS) - 1 : e->idx;
103 key += (((uint64_t)e->crumb << POS_IDX_BITS) | idx) * mul;
104 }
105 return key;
106}
107
108static void kw_advance(key_walk *w, const ty_ev *e) {
109 w->p5 = w->p4;
110 w->p4 = w->p3;
111 w->p3 = w->p2;
112 w->p2 = w->p1;
113 w->p1 = e->sym;
114}
115
116/* ------------------------------------------------------------ fit tables */
117
118typedef struct {
119 uint64_t key;
120 uint64_t c[TY_KMAX];
121} cnt_row;
122
123typedef struct {
124 uint64_t *keys;
125 uint32_t *slot; /* row index + 1; 0 = empty */
126 size_t cap;
127 cnt_row *rows;
128 size_t n, rcap;
129} cnt_map;
130
131static uint64_t mix64(uint64_t x) {
132 x ^= x >> 33;
133 x *= 0xff51afd7ed558ccdULL;
134 x ^= x >> 33;
135 x *= 0xc4ceb9fe1a85ec53ULL;
136 x ^= x >> 33;
137 return x;
138}
139
140static int cm_grow(cnt_map *h) {
141 size_t nc = h->cap ? h->cap * 2 : 1024;
142 uint64_t *k = calloc(nc, sizeof *k);
143 uint32_t *s = calloc(nc, sizeof *s);
144 if (!k || !s) {
145 free(k);
146 free(s);
147 return TY_E_IO;
148 }
149 for (size_t i = 0; i < h->cap; ++i) {
150 if (!h->slot[i]) continue;
151 size_t j = mix64(h->keys[i]) & (nc - 1);
152 while (s[j]) j = (j + 1) & (nc - 1);
153 k[j] = h->keys[i];
154 s[j] = h->slot[i];
155 }
156 free(h->keys);
157 free(h->slot);
158 h->keys = k;
159 h->slot = s;
160 h->cap = nc;
161 return TY_OK;
162}
163
164static cnt_row *cm_get(cnt_map *h, uint64_t key) {
165 if ((h->n + 1) * 2 > h->cap && cm_grow(h) != TY_OK) return NULL;
166 size_t j = mix64(key) & (h->cap - 1);
167 while (h->slot[j]) {
168 if (h->keys[j] == key) return &h->rows[h->slot[j] - 1];
169 j = (j + 1) & (h->cap - 1);
170 }
171 if (h->n == h->rcap) {
172 size_t nr = h->rcap ? h->rcap * 2 : 1024;
173 cnt_row *r = realloc(h->rows, nr * sizeof *r);
174 if (!r) return NULL;
175 h->rows = r;
176 h->rcap = nr;
177 }
178 if (h->n >= UINT32_MAX - 1) return NULL;
179 cnt_row *r = &h->rows[h->n++];
180 memset(r, 0, sizeof *r);
181 r->key = key;
182 h->keys[j] = key;
183 h->slot[j] = (uint32_t)h->n;
184 return r;
185}
186
187static void cm_free(cnt_map *h) {
188 free(h->keys);
189 free(h->slot);
190 free(h->rows);
191 memset(h, 0, sizeof *h);
192}
193
194static int cmp_row(const void *a, const void *b) {
195 uint64_t x = ((const ty_row *)a)->key, y = ((const ty_row *)b)->key;
196 return x < y ? -1 : x > y;
197}
198
199int ty_model_uniform(ty_model *m, unsigned K) {
200 if (!m || K < 2 || K > TY_KMAX) return TY_E_ARG;
201 memset(m, 0, sizeof *m);
202 uint64_t zero[TY_KMAX] = {0};
203 m->K = K;
204 return ty_quantize_kt(zero, K, m->def);
205}
206
207int ty_model_fit(ty_model *m, const ty_stream *const *streams, size_t ns, unsigned mask, unsigned K, int rule) {
208 if (!m || (ns && !streams) || (rule != TY_FIT_KEEP_ALL && rule != TY_FIT_MDL_PRUNE)) return TY_E_ARG;
209 unsigned kb;
210 int rc = ty_key_space(mask, K, NULL, &kb);
211 if (rc != TY_OK) return rc;
212 memset(m, 0, sizeof *m);
213 m->K = K;
214 m->mask = mask;
215 m->keybits = kb;
216 uint64_t tot[TY_KMAX] = {0};
217 cnt_map h;
218 memset(&h, 0, sizeof h);
219 for (size_t si = 0; si < ns; ++si) {
220 const ty_stream *s = streams[si];
221 key_walk w;
222 kw_init(&w, mask, K);
223 for (size_t t = 0; t < s->n; ++t) {
224 const ty_ev *e = &s->ev[t];
225 if (e->sym >= K) {
226 cm_free(&h);
227 return TY_E_RANGE;
228 }
229 uint64_t key = kw_key(&w, e);
230 tot[e->sym]++;
231 if (mask) {
232 cnt_row *r = cm_get(&h, key);
233 if (!r) {
234 cm_free(&h);
235 return TY_E_IO;
236 }
237 r->c[e->sym]++;
238 }
239 kw_advance(&w, e);
240 }
241 }
242 if ((rc = ty_quantize_kt(tot, K, m->def)) != TY_OK) {
243 cm_free(&h);
244 return rc;
245 }
246 m->rows = h.n ? malloc(h.n * sizeof *m->rows) : NULL;
247 if (h.n && !m->rows) {
248 cm_free(&h);
249 return TY_E_IO;
250 }
251 const int64_t row_cost_ub = (int64_t)(kb + (K - 1) * TY_QBITS) * TY_UB_PER_BIT;
252 for (size_t i = 0; i < h.n; ++i) {
253 ty_row r;
254 memset(&r, 0, sizeof r);
255 r.key = h.rows[i].key;
256 if ((rc = ty_quantize_kt(h.rows[i].c, K, r.q)) != TY_OK) break;
257 if (rule == TY_FIT_MDL_PRUNE) {
258 /* Keep the row only if, on the fit data, it saves more than it costs. */
259 int64_t save = 0;
260 for (unsigned x = 0; x < K; ++x) {
261 int64_t d = ty_ubits_q16(m->def[x]) - ty_ubits_q16(r.q[x]);
262 save += (int64_t)h.rows[i].c[x] * d; /* fit counts < 2^40, |d| < 2^25 */
263 }
264 if (save <= row_cost_ub) continue;
265 }
266 m->rows[m->nrows++] = r;
267 }
268 cm_free(&h);
269 if (rc != TY_OK) {
270 ty_model_free(m);
271 return rc;
272 }
273 if (m->nrows) qsort(m->rows, m->nrows, sizeof *m->rows, cmp_row);
274 return TY_OK;
275}
276
277/* ------------------------------------------------------------ bit code */
278
279typedef struct {
280 uint8_t *b;
281 size_t cap;
282 uint64_t bits;
283 int err;
284} bitw;
285
286static void bw_put(bitw *w, uint64_t v, unsigned n) {
287 for (unsigned i = n; i-- > 0;) {
288 size_t byte = (size_t)(w->bits >> 3);
289 if (byte >= w->cap) {
290 size_t nc = w->cap ? w->cap * 2 : 256;
291 uint8_t *p = realloc(w->b, nc);
292 if (!p) {
293 w->err = 1;
294 return;
295 }
296 memset(p + w->cap, 0, nc - w->cap);
297 w->b = p;
298 w->cap = nc;
299 }
300 if ((v >> i) & 1) w->b[byte] |= (uint8_t)(0x80u >> (w->bits & 7));
301 w->bits++;
302 }
303}
304
305typedef struct {
306 const uint8_t *b;
307 uint64_t nbits, pos;
308 int err;
309} bitr;
310
311static uint64_t br_get(bitr *r, unsigned n) {
312 uint64_t v = 0;
313 for (unsigned i = 0; i < n; ++i) {
314 if (r->pos >= r->nbits) {
315 r->err = 1;
316 return 0;
317 }
318 v = (v << 1) | ((r->b[r->pos >> 3] >> (7 - (r->pos & 7))) & 1u);
319 r->pos++;
320 }
321 return v;
322}
323
324static void put_row(bitw *w, const uint32_t *q, unsigned K) {
325 for (unsigned x = 0; x + 1 < K; ++x) bw_put(w, q[x], TY_QBITS);
326}
327
328int ty_model_encode(const ty_model *m, uint8_t **buf, size_t *nbytes, uint64_t *bits) {
329 if (!m || !buf || !nbytes || !bits || m->K < 2 || m->K > TY_KMAX) return TY_E_ARG;
330 if (m->nrows > UINT32_MAX) return TY_E_RANGE;
331 bitw w;
332 memset(&w, 0, sizeof w);
333 bw_put(&w, 0x54594D30u, 32); /* "TYM0" */
334 bw_put(&w, TY_MODEL_VERSION, 8);
335 bw_put(&w, m->K, 8);
336 bw_put(&w, m->mask, 8);
337 bw_put(&w, TY_QBITS, 8);
338 bw_put(&w, m->keybits, 8);
339 bw_put(&w, m->nrows, 32);
340 put_row(&w, m->def, m->K);
341 for (size_t i = 0; i < m->nrows; ++i) {
342 bw_put(&w, m->rows[i].key, m->keybits);
343 put_row(&w, m->rows[i].q, m->K);
344 }
345 if (w.err) {
346 free(w.b);
347 return TY_E_IO;
348 }
349 *buf = w.b;
350 *nbytes = (size_t)((w.bits + 7) / 8);
351 *bits = w.bits;
352 return TY_OK;
353}
354
355static int get_row(bitr *r, unsigned K, uint32_t *q) {
356 uint32_t s = 0;
357 for (unsigned x = 0; x + 1 < K; ++x) {
358 q[x] = (uint32_t)br_get(r, TY_QBITS);
359 if (q[x] == 0) return TY_E_PROFILE; /* below the floor */
360 s += q[x];
361 }
362 if (s >= TY_QONE) return TY_E_PROFILE; /* implied last entry would be < 1 */
363 q[K - 1] = TY_QONE - s;
364 return r->err ? TY_E_FORMAT : TY_OK;
365}
366
367int ty_model_decode(const uint8_t *buf, size_t nbytes, ty_model *m, uint64_t *bits, char *why, size_t whylen) {
368 if (!buf || !m) return TY_E_ARG;
369 memset(m, 0, sizeof *m);
370 bitr r = {buf, (uint64_t)nbytes * 8, 0, 0};
371 if (br_get(&r, 32) != 0x54594D30u || r.err) {
372 WHY("bad model magic");
373 return TY_E_FORMAT;
374 }
375 unsigned ver = (unsigned)br_get(&r, 8), K = (unsigned)br_get(&r, 8), mask = (unsigned)br_get(&r, 8);
376 unsigned qb = (unsigned)br_get(&r, 8), kb = (unsigned)br_get(&r, 8);
377 uint64_t nrows = br_get(&r, 32);
378 if (r.err) {
379 WHY("truncated header");
380 return TY_E_FORMAT;
381 }
382 if (ver != TY_MODEL_VERSION) {
383 WHY("model code version %u (profile encoder is version %u)", ver, TY_MODEL_VERSION);
384 return TY_E_PROFILE;
385 }
386 if (qb != TY_QBITS) {
387 WHY("quantization %u bits (profile pins %u)", qb, TY_QBITS);
388 return TY_E_PROFILE;
389 }
390 uint64_t space;
391 unsigned want_kb;
392 if (ty_key_space(mask, K, &space, &want_kb) != TY_OK || kb != want_kb) {
393 WHY("mask %u / K %u / key bits %u inconsistent", mask, K, kb);
394 return TY_E_FORMAT;
395 }
396 uint64_t need = TY_MODEL_HEADER_BITS + (uint64_t)(K - 1) * TY_QBITS +
397 nrows * ((uint64_t)kb + (uint64_t)(K - 1) * TY_QBITS);
398 if ((need + 7) / 8 != nbytes) {
399 WHY("code is %zu bytes, header implies %llu bits", nbytes, (unsigned long long)need);
400 return TY_E_FORMAT;
401 }
402 m->K = K;
403 m->mask = mask;
404 m->keybits = kb;
405 int rc = get_row(&r, K, m->def);
406 if (rc != TY_OK) {
407 WHY("default row: %s", ty_err_name(rc));
408 return rc;
409 }
410 m->rows = nrows ? malloc((size_t)nrows * sizeof *m->rows) : NULL;
411 if (nrows && !m->rows) return TY_E_IO;
412 for (uint64_t i = 0; i < nrows; ++i) {
413 ty_row *row = &m->rows[i];
414 memset(row, 0, sizeof *row);
415 row->key = br_get(&r, kb);
416 if (row->key >= space || (i > 0 && row->key <= m->rows[i - 1].key)) {
417 WHY("row %llu key out of range or not increasing", (unsigned long long)i);
418 ty_model_free(m);
419 return TY_E_FORMAT;
420 }
421 if ((rc = get_row(&r, K, row->q)) != TY_OK) {
422 WHY("row %llu: %s", (unsigned long long)i, ty_err_name(rc));
423 ty_model_free(m);
424 return rc;
425 }
426 m->nrows++;
427 }
428 while (r.pos < r.nbits) {
429 if (br_get(&r, 1) != 0) {
430 WHY("nonzero padding");
431 ty_model_free(m);
432 return TY_E_FORMAT;
433 }
434 }
435 if (bits) *bits = need;
436 return TY_OK;
437}
438
439static const ty_row *find_row(const ty_model *m, uint64_t key) {
440 size_t lo = 0, hi = m->nrows;
441 while (lo < hi) {
442 size_t mid = lo + (hi - lo) / 2;
443 if (m->rows[mid].key < key)
444 lo = mid + 1;
445 else
446 hi = mid;
447 }
448 return (lo < m->nrows && m->rows[lo].key == key) ? &m->rows[lo] : NULL;
449}
450
451int ty_model_score(const ty_model *m, const ty_stream *s, int64_t *ub, uint64_t *nsym) {
452 if (!m || !s || !ub) return TY_E_ARG;
453 key_walk w;
454 kw_init(&w, m->mask, m->K);
455 int64_t total = 0;
456 for (size_t t = 0; t < s->n; ++t) { /* file order; integer sum, order-free */
457 const ty_ev *e = &s->ev[t];
458 if (e->sym >= m->K) return TY_E_RANGE;
459 uint64_t key = kw_key(&w, e);
460 const ty_row *r = m->nrows ? find_row(m, key) : NULL;
461 uint32_t q = r ? r->q[e->sym] : m->def[e->sym];
462 int64_t b = ty_ubits_q16(q);
463 if (b < 0) return TY_E_ZERO_REALIZED;
464 if (ty_add(total, b, &total) != TY_OK) return TY_E_OVERFLOW;
465 kw_advance(&w, e);
466 }
467 *ub = total;
468 if (nsym) *nsym = s->n;
469 return TY_OK;
470}
471
472void ty_model_digest(const uint8_t *buf, size_t nbytes, uint8_t out[32]) {
473 sha256_ctx c;
474 sha256_init(&c);
475 sha256_update(&c, (const uint8_t *)TY_MODEL_DOMAIN, sizeof TY_MODEL_DOMAIN); /* includes 0x00 */
476 sha256_update(&c, buf, nbytes);
477 sha256_final(&c, out);
478}