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 / runtime / rx_costmodel.c

475 lines · 18756 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * rx_costmodel.c -- Omega's empirical cost model. See rx_costmodel.h.
19 *
20 * Pure arithmetic over measurements the caller reports. No execution, no
21 * authority, no generation store.
22 */
23#include "runtime/rx_costmodel.h"
24#include "omega_native.h"
25#include "omega_api_decl.h"
26#include "sha256.h"
27
28#include <math.h>
29#include <stdlib.h>
30#include <string.h>
31
32_Static_assert(RX_CM_CELL_NONE >= RX_CM_CELLS,
33 "unsupported-op sentinel must not be a cell index");
34
35#define PRIOR_A 1.0
36#define PRIOR_B 0.01 /* prior noise variance ~0.01 log2^2 (about 7%) */
37#define NOISE_FLOOR 0.0009 /* never claim better than ~2% sd per call */
38#define FAIL_PRIOR 0.05
39
40void rx_cm_default_policy(RxCmPolicy *p) {
41 p->ei_min = 0.08;
42 p->max_fail_p = 0.0; /* any wrong result excludes the arm */
43 p->fallback_arm = 0;
44 p->explore_frac = 0.05;
45 p->explore_allow_ps = 500000000ull; /* 0.5 ms to get started */
46}
47
48void rx_cm_init(RxCostModel *m, uint32_t n_arms) {
49 memset(m, 0, sizeof *m);
50 m->n_arms = n_arms > RX_CM_ARMS ? RX_CM_ARMS : n_arms;
51 m->lambda = 1e-3;
52 m->sd_scale = 1.0;
53 for (uint32_t c = 0; c < RX_CM_CELLS; c++)
54 for (uint32_t a = 0; a < RX_CM_ARMS; a++)
55 for (uint32_t i = 0, k = 0; i < RX_CM_D; i++)
56 for (uint32_t j = i; j < RX_CM_D; j++, k++)
57 m->cell[c][a].tri[k] = i == j ? m->lambda : 0.0;
58}
59
60uint32_t rx_cm_cell(const RxCmFeatures *f) {
61 /* An unknown semantic operation is not the last supported family.
62 * The restore-op-clamp mutant rewrites the next line. */
63 uint32_t op = f && f->op < RX_CM_OPS ? f->op : RX_CM_CELL_NONE; /* CM704:refuse-unsupported-op */
64 if (op >= RX_CM_OPS) return RX_CM_CELL_NONE;
65 uint32_t core = f->core < RX_CM_CORES ? f->core : RX_CM_CORE_OTHER;
66 uint32_t pr = f->pressure < RX_CM_PRESSURE ? f->pressure : RX_CM_PRESSURE - 1u;
67 return (op * RX_CM_CORES + core) * RX_CM_PRESSURE + pr;
68}
69
70void rx_cm_basis(const RxCmFeatures *f, double phi[RX_CM_D]) {
71 double lm = log2((double)(f->M ? f->M : 1));
72 double ln = log2((double)(f->N ? f->N : 1));
73 double ov = 0.0;
74 if (f->cache_bytes && f->state_bytes > f->cache_bytes)
75 ov = log2((double)f->state_bytes / (double)f->cache_bytes);
76 phi[0] = 1.0;
77 phi[1] = lm;
78 phi[2] = ln;
79 phi[3] = lm * ln;
80 phi[4] = ln * ln;
81 phi[5] = f->N <= 3 ? 1.0 : 0.0;
82 phi[6] = (f->N % 4u) != 0 ? 1.0 : 0.0;
83 phi[7] = ov;
84}
85
86/* Predictive t for one (cell, arm), executed in pure OM-2 (om/runtime/rx_costmodel_core.om).
87 * Returns 0 if there is no data or matrix is not positive definite. */
88static int fit_predict(const RxCmArmStats *s, const double phi[RX_CM_D], double *mean,
89 double *sd, double *dof) {
90 if (s->n == 0) return 0;
91 uint64_t tri_u[36], xty_u[8], phi_u[8], meta[2], dst[4] = { 0 }, ok = 0;
92 memcpy(tri_u, s->tri, sizeof tri_u);
93 memcpy(xty_u, s->xty, sizeof xty_u);
94 memcpy(phi_u, phi, sizeof phi_u);
95 meta[0] = s->n;
96 memcpy(&meta[1], &s->yty, sizeof(uint64_t));
97 if (omega2_rx_cm_fit_predict(&ok, tri_u, 36, xty_u, 8, phi_u, 8, meta, 2, dst, 4) != OMEGA_OK ||
98 ok == 0)
99 return 0;
100 memcpy(mean, &dst[0], sizeof(double));
101 memcpy(sd, &dst[1], sizeof(double));
102 memcpy(dof, &dst[2], sizeof(double));
103 return 1;
104}
105
106static uint64_t failures_of(const RxCostModel *m, uint32_t arm) {
107 uint64_t f = 0;
108 for (uint32_t c = 0; c < RX_CM_CELLS; c++) f += m->cell[c][arm].failures;
109 return f;
110}
111
112static double fail_p(const RxCostModel *m, uint32_t arm) {
113 uint64_t t = 0, f = 0;
114 for (uint32_t c = 0; c < RX_CM_CELLS; c++) {
115 t += m->cell[c][arm].trials;
116 f += m->cell[c][arm].failures;
117 }
118 return ((double)f + FAIL_PRIOR) / ((double)t + 1.0);
119}
120
121/* Pressure cells hold a correction over the same core class at pressure 0:
122 * log2 cost under pressure = quiet prediction + a + b * (doublings past the
123 * private cache). Two numbers per arm, readable as "pressure costs this much,
124 * and this much more per doubling out of cache". */
125static void residual_basis(const RxCmFeatures *f, double phi[RX_CM_D]) {
126 double full[RX_CM_D];
127 rx_cm_basis(f, full);
128 memset(phi, 0, sizeof(double) * RX_CM_D);
129 phi[0] = 1.0;
130 phi[1] = full[7];
131}
132
133static int quiet_predict(const RxCostModel *m, const RxCmFeatures *f, uint32_t arm, double *mean,
134 double *sd, double *dof, uint64_t *n) {
135 RxCmFeatures g = *f;
136 g.pressure = 0;
137 uint32_t cell = rx_cm_cell(&g);
138 if (cell >= RX_CM_CELLS) return 0;
139 const RxCmArmStats *b = &m->cell[cell][arm];
140 double phi[RX_CM_D];
141 rx_cm_basis(f, phi);
142 if (b->n < RX_CM_MIN_OBS || !fit_predict(b, phi, mean, sd, dof)) return 0;
143 *n = b->n;
144 return 1;
145}
146
147static uint32_t bucket(const RxCmFeatures *f) {
148 return f->pressure < RX_CM_PRESSURE ? f->pressure : RX_CM_PRESSURE - 1;
149}
150
151int rx_cm_predict(const RxCostModel *m, const RxCmFeatures *f, uint32_t arm,
152 RxCmPrediction *out) {
153 if (!out) return RX_CM_ERR_ARG;
154 memset(out, 0, sizeof *out);
155 if (!m || !f || arm >= m->n_arms) return RX_CM_ERR_ARG;
156 uint32_t cell = rx_cm_cell(f);
157 if (cell >= RX_CM_CELLS) {
158 out->refused = 1;
159 return RX_CM_ERR_UNSUPPORTED;
160 }
161 double mean = 0, sd = 0, dof = 0;
162 uint64_t n = 0;
163 out->fail_p = fail_p(m, arm);
164 if (!quiet_predict(m, f, arm, &mean, &sd, &dof, &n)) return RX_CM_OK;
165 if (bucket(f) == 0) {
166 out->known = 1;
167 } else {
168 const RxCmArmStats *r = &m->cell[cell][arm];
169 double phi[RX_CM_D], rm = 0, rsd = 0, rdof = 0;
170 residual_basis(f, phi);
171 if (r->n >= RX_CM_RES_MIN_OBS && fit_predict(r, phi, &rm, &rsd, &rdof)) {
172 mean += rm;
173 sd = sqrt(sd * sd + rsd * rsd);
174 if (rdof < dof) dof = rdof;
175 n = r->n;
176 out->known = 1;
177 } else {
178 /* Never seen under this pressure: the quiet prediction, with the
179 * prior on how far an unseen condition may move cost. */
180 sd = sqrt(sd * sd + RX_CM_UNSEEN_SHIFT * RX_CM_UNSEEN_SHIFT);
181 out->borrowed = 1;
182 }
183 }
184 out->n = (uint32_t)n;
185 out->mean_log2_ps = mean;
186 out->sd_log2 = sd * (m->sd_scale >= 1.0 ? m->sd_scale : 1.0);
187 out->dof = dof;
188 uint32_t core = f->core < RX_CM_CORES ? f->core : RX_CM_CORE_OTHER;
189 double mw = m->power_mw[core][arm];
190 if (mw > 0.0) out->energy_pj = exp2(mean) * mw * 1e-3; /* ps * mW = 1e-3 pJ */
191 return RX_CM_OK;
192}
193
194int rx_cm_observe(RxCostModel *m, const RxCmFeatures *f, uint32_t arm, const RxCmObservation *o) {
195 if (!m || !f || !o || arm >= m->n_arms) return RX_CM_ERR_ARG;
196 uint32_t cell = rx_cm_cell(f);
197 if (cell >= RX_CM_CELLS) return RX_CM_ERR_UNSUPPORTED;
198 RxCmArmStats *s = &m->cell[cell][arm];
199 s->trials++;
200 if (o->failed) {
201 s->failures++;
202 return RX_CM_OK;
203 }
204 if (o->ps_per_call == 0) return RX_CM_ERR_ARG;
205 double phi[RX_CM_D];
206 double y = log2((double)o->ps_per_call);
207 if (bucket(f) == 0) {
208 rx_cm_basis(f, phi);
209 } else {
210 double qm, qsd, qdof;
211 uint64_t qn;
212 if (!quiet_predict(m, f, arm, &qm, &qsd, &qdof, &qn)) return RX_CM_SKIPPED;
213 residual_basis(f, phi);
214 y -= qm;
215 }
216 {
217 uint64_t tri_u[36], xty_u[8], phi_u[8], y_bits = 0, res = 0;
218 memcpy(tri_u, s->tri, sizeof tri_u);
219 memcpy(xty_u, s->xty, sizeof xty_u);
220 memcpy(phi_u, phi, sizeof phi_u);
221 memcpy(&y_bits, &y, sizeof(uint64_t));
222 (void)omega2_rx_cm_rank1_update(&res, tri_u, 36, xty_u, 8, phi_u, 8, y_bits);
223 memcpy(s->tri, tri_u, sizeof tri_u);
224 memcpy(s->xty, xty_u, sizeof xty_u);
225 }
226 s->yty += y * y;
227 s->n++;
228 return RX_CM_OK;
229}
230
231static double norm_cdf(double x) { return 0.5 * erfc(-x / sqrt(2.0)); }
232
233/* Acklam's inverse normal. */
234static double norm_inv(double p) {
235 static const double a[] = { -3.969683028665376e+01, 2.209460984245205e+02,
236 -2.759285104469687e+02, 1.383577518672690e+02,
237 -3.066479806614716e+01, 2.506628277459239e+00 };
238 static const double b[] = { -5.447609879822406e+01, 1.615858368580409e+02,
239 -1.556989798598866e+02, 6.680131188771972e+01,
240 -1.328068155288572e+01 };
241 static const double c[] = { -7.784894002430293e-03, -3.223964580411365e-01,
242 -2.400758277161838e+00, -2.549732539343734e+00,
243 4.374664141464968e+00, 2.938163982698783e+00 };
244 static const double d[] = { 7.784695709041462e-03, 3.224671290700398e-01,
245 2.445134137142996e+00, 3.754408661907416e+00 };
246 if (p <= 0.0) return -INFINITY;
247 if (p >= 1.0) return INFINITY;
248 double q, r;
249 if (p < 0.02425) {
250 q = sqrt(-2 * log(p));
251 return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
252 ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
253 }
254 if (p > 1 - 0.02425) {
255 q = sqrt(-2 * log(1 - p));
256 return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
257 ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
258 }
259 q = p - 0.5;
260 r = q * q;
261 return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q /
262 (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
263}
264
265double rx_cm_t_quantile(double q, double dof) {
266 double z = norm_inv(0.5 + 0.5 * q);
267 if (!(dof > 0.0)) return z;
268 double z3 = z * z * z, z5 = z3 * z * z;
269 return z + (z3 + z) / (4.0 * dof) + (5.0 * z5 + 16.0 * z3 + 3.0 * z) / (96.0 * dof * dof);
270}
271
272static int explore_allowed(const RxCostModel *m, const RxCmPolicy *p) {
273 double cap = p->explore_frac * (double)m->work_ps + (double)p->explore_allow_ps;
274 return (double)m->explore_ps < cap;
275}
276
277/* E[max(0, X)] for X ~ N(d, s^2): the expected gain, in log2 units, of
278 * switching to a competitor whose advantage over the chosen arm is d. */
279static double expected_improvement(double d, double s) {
280 if (!(s > 0.0)) return d > 0.0 ? d : 0.0;
281 double u = d / s;
282 return s * exp(-0.5 * u * u) / sqrt(2.0 * M_PI) + d * norm_cdf(u);
283}
284
285void rx_cm_decide(const RxCostModel *m, const RxCmPolicy *p, const RxCmFeatures *f,
286 int allow_measure, RxCmDecision *out) {
287 memset(out, 0, sizeof *out);
288 if (m && f && rx_cm_cell(f) >= RX_CM_CELLS) {
289 uint32_t na = m->n_arms;
290 out->action = RX_CM_REFUSE;
291 out->why = RX_CM_WHY_UNSUPPORTED_OP;
292 out->arm = na;
293 out->measure[0] = na;
294 out->measure[1] = na;
295 for (uint32_t a = 0; a < RX_CM_ARMS; a++) out->pred[a].refused = 1;
296 return;
297 }
298 uint32_t fb = p->fallback_arm < m->n_arms ? p->fallback_arm : 0;
299 uint32_t elig = (f->eligible | (1u << fb)) & ((1u << m->n_arms) - 1u);
300 int have[RX_CM_ARMS] = { 0 };
301 int n_elig = 0;
302 for (uint32_t a = 0; a < m->n_arms; a++) {
303 rx_cm_predict(m, f, a, &out->pred[a]);
304 if (!(elig & (1u << a))) continue;
305 if (a != fb && failures_of(m, a) > 0 && out->pred[a].fail_p > p->max_fail_p) {
306 elig &= ~(1u << a);
307 continue;
308 }
309 n_elig++;
310 have[a] = out->pred[a].known || out->pred[a].borrowed;
311 }
312 out->action = RX_CM_FALLBACK;
313 out->arm = fb;
314 if (n_elig <= 1) {
315 out->why = RX_CM_WHY_NO_ELIGIBLE;
316 return;
317 }
318
319 /* Best by predicted latency among arms that meet the budgets; if none
320 * meets them, best overall and say so. */
321 int best = -1, best_fit = -1;
322 for (uint32_t a = 0; a < m->n_arms; a++) {
323 if (!have[a] || !(elig & (1u << a))) continue;
324 const RxCmPrediction *pr = &out->pred[a];
325 double hi = exp2(pr->mean_log2_ps + 1.2816 * pr->sd_log2);
326 int fits = (!f->latency_budget_ps || hi <= (double)f->latency_budget_ps) &&
327 (!f->energy_budget_pj || pr->energy_pj == 0.0 ||
328 pr->energy_pj <= (double)f->energy_budget_pj);
329 if (best < 0 || pr->mean_log2_ps < out->pred[best].mean_log2_ps) best = (int)a;
330 if (fits && (best_fit < 0 || pr->mean_log2_ps < out->pred[best_fit].mean_log2_ps))
331 best_fit = (int)a;
332 }
333 int over = 0;
334 if (best_fit >= 0) best = best_fit;
335 else if (best >= 0) over = 1;
336
337 /* Competitor: the eligible arm with the largest expected improvement
338 * over `best`. An arm with no prediction at all is always worth a look. */
339 int comp = -1, comp_unknown = 0;
340 double ei = 0.0, pc = 0.0;
341 for (uint32_t a = 0; a < m->n_arms; a++) {
342 if (!(elig & (1u << a)) || (int)a == best) continue;
343 double e, pa;
344 int unknown = !have[a] || best < 0;
345 if (unknown) {
346 e = INFINITY;
347 pa = 0.5;
348 } else {
349 const RxCmPrediction *x = &out->pred[a], *b = &out->pred[best];
350 double s = sqrt(x->sd_log2 * x->sd_log2 + b->sd_log2 * b->sd_log2);
351 double d = b->mean_log2_ps - x->mean_log2_ps;
352 e = expected_improvement(d, s);
353 pa = norm_cdf(d / (s > 0 ? s : 1e-9));
354 }
355 if (comp < 0 || e > ei) {
356 comp = (int)a;
357 ei = e;
358 pc = pa;
359 comp_unknown = unknown;
360 }
361 }
362 out->p_runner_up_better = pc;
363 out->expected_improvement = isinf(ei) ? -1.0 : ei;
364
365 uint32_t why = RX_CM_WHY_CONFIDENT;
366 if (best < 0 || comp_unknown) why = RX_CM_WHY_UNKNOWN_ARM;
367 else if (ei > p->ei_min) why = RX_CM_WHY_WORTH_MEASURING;
368
369 if (why != RX_CM_WHY_CONFIDENT && allow_measure && explore_allowed(m, p) && comp >= 0) {
370 out->action = RX_CM_MEASURE;
371 out->measure[0] = best >= 0 ? (uint32_t)best : fb;
372 out->measure[1] = (uint32_t)comp;
373 if (out->measure[0] == out->measure[1]) out->measure[1] = fb;
374 out->why = why;
375 out->arm = out->measure[0];
376 return;
377 }
378 if (best < 0) {
379 out->why = allow_measure && !explore_allowed(m, p) ? RX_CM_WHY_BUDGET_SPENT
380 : RX_CM_WHY_UNKNOWN_ARM;
381 return; /* fallback */
382 }
383 out->action = RX_CM_SELECT;
384 out->arm = (uint32_t)best;
385 if (over) out->why = RX_CM_WHY_OVER_BUDGET;
386 else if (why != RX_CM_WHY_CONFIDENT && allow_measure) out->why = RX_CM_WHY_BUDGET_SPENT;
387 else out->why = RX_CM_WHY_CONFIDENT;
388}
389
390static int cmp_double(const void *a, const void *b) {
391 double x = *(const double *)a, y = *(const double *)b;
392 return (x > y) - (x < y);
393}
394
395double rx_cm_calibrate(RxCostModel *m, const RxCmFeatures *f, const uint32_t *arm,
396 const uint64_t *ps, uint32_t n, double q) {
397 if (!m || !f || !arm || !ps || n == 0 || !(q > 0.0 && q < 1.0)) return 0.0;
398 double *r = malloc(sizeof(double) * n);
399 if (!r) return 0.0;
400 double saved = m->sd_scale;
401 m->sd_scale = 1.0;
402 uint32_t k = 0;
403 for (uint32_t i = 0; i < n; i++) {
404 RxCmPrediction p;
405 rx_cm_predict(m, &f[i], arm[i], &p);
406 if (!(p.known || p.borrowed) || ps[i] == 0 || !(p.sd_log2 > 0.0)) continue;
407 double z = fabs(log2((double)ps[i]) - p.mean_log2_ps) / p.sd_log2;
408 r[k++] = z / rx_cm_t_quantile(q, p.dof);
409 }
410 double scale = 0.0;
411 if (k >= 10) {
412 qsort(r, k, sizeof(double), cmp_double);
413 uint32_t idx = (uint32_t)ceil(q * (double)k) - 1u;
414 scale = r[idx < k ? idx : k - 1];
415 if (scale < 1.0) scale = 1.0;
416 m->sd_scale = scale;
417 } else {
418 m->sd_scale = saved;
419 }
420 free(r);
421 return scale;
422}
423
424void rx_cm_charge(RxCostModel *m, uint64_t work_ps, uint64_t explore_ps) {
425 m->work_ps += work_ps;
426 m->explore_ps += explore_ps;
427}
428
429/* ---- canonical bytes ---- */
430
431/* OGCM v1. The Omega codec reads the contiguous persisted fields and omits
432 * the two runtime counters. Changing the model dimensions requires a wire version. */
433enum { CM_WIRE_BYTES = 28080, CM_DIGEST_BYTES = 32 };
434_Static_assert(RX_CM_D == 8 && RX_CM_CELLS == 9 && RX_CM_ARMS == 8 && RX_CM_CORES == 3 &&
435 sizeof(RxCmArmStats) == 384 && sizeof(RxCostModel) == 28072 &&
436 offsetof(RxCostModel, n_arms) == 0 && offsetof(RxCostModel, lambda) == 8 &&
437 offsetof(RxCostModel, cell) == 16 && offsetof(RxCostModel, power_mw) == 27664 &&
438 offsetof(RxCostModel, verify_ns) == 27856 && offsetof(RxCostModel, synth_ns) == 27920 &&
439 offsetof(RxCostModel, code_bytes) == 27984 && offsetof(RxCostModel, sd_scale) == 28048 &&
440 offsetof(RxCostModel, explore_ps) == 28056 && offsetof(RxCostModel, work_ps) == 28064,
441 "OGCM v1 model layout");
442
443size_t rx_cm_blob_size(void) { return CM_WIRE_BYTES + CM_DIGEST_BYTES; }
444
445int rx_cm_serialize(const RxCostModel *m, uint8_t *out, size_t cap, size_t *out_len) {
446 if (!m || !out || cap < rx_cm_blob_size()) return RX_CM_ERR_ARG;
447 uintptr_t src = (uintptr_t)m, dest = (uintptr_t)out;
448 if (dest >= src ? dest - src < sizeof *m : src - dest < CM_WIRE_BYTES) {
449 uint8_t wire[CM_WIRE_BYTES];
450 rx_cm_pack_v1((const uint8_t *)m, wire);
451 memcpy(out, wire, sizeof wire);
452 } else {
453 rx_cm_pack_v1((const uint8_t *)m, out);
454 }
455 sha256_hash(out, CM_WIRE_BYTES, out + CM_WIRE_BYTES);
456 if (out_len) *out_len = rx_cm_blob_size();
457 return RX_CM_OK;
458}
459
460int rx_cm_deserialize(RxCostModel *m, const uint8_t *in, size_t len) {
461 if (!m || !in || len != rx_cm_blob_size()) return RX_CM_ERR_FORMAT;
462 uint8_t d[32];
463 sha256_hash(in, len - 32u, d);
464 if (memcmp(d, in + len - 32u, 32) != 0) return RX_CM_ERR_DIGEST;
465 RxCostModel t = {0};
466 if (!rx_cm_unpack_v1(in, (uint8_t *)&t)) return RX_CM_ERR_FORMAT;
467 *m = t;
468 return RX_CM_OK;
469}
470
471void rx_cm_digest(const RxCostModel *m, uint8_t out[32]) {
472 uint8_t buf[CM_WIRE_BYTES];
473 rx_cm_pack_v1((const uint8_t *)m, buf);
474 sha256_hash(buf, sizeof buf, out);
475}