interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / src / runtime / rx_costmodel.c

972 lines · 36666 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
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#include "runtime/rx_cm_sort.h"
17
18/*
19 * rx_costmodel.c -- Omega's empirical cost model. See rx_costmodel.h.
20 *
21 * Pure arithmetic over measurements the caller reports. No execution, no
22 * authority, no generation store.
23 */
24#include "runtime/rx_costmodel.h"
25#include "sha256.h"
26
27#include <math.h>
28#include <stdlib.h>
29#include <string.h>
30#include "runtime/rx_cm_math.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#ifndef CUDAPP_MIGRATION_PENDING_C_CM_FIT
40#define CUDAPP_MIGRATION_PENDING_C_CM_FIT 0
41#endif
42#ifndef CUDAPP_MIGRATION_PENDING_C_CM_STATS
43#define CUDAPP_MIGRATION_PENDING_C_CM_STATS 0
44#endif
45#ifndef CUDAPP_MIGRATION_PENDING_C_CM_FEATURES
46#define CUDAPP_MIGRATION_PENDING_C_CM_FEATURES 0
47#endif
48#ifndef CUDAPP_MIGRATION_PENDING_C_CM_QUANTILE
49#define CUDAPP_MIGRATION_PENDING_C_CM_QUANTILE 0
50#endif
51#ifndef CUDAPP_MIGRATION_PENDING_C_CM_DECISION
52#define CUDAPP_MIGRATION_PENDING_C_CM_DECISION 0
53#endif
54#ifndef CUDAPP_MIGRATION_PENDING_C_CM_PREDICTION
55#define CUDAPP_MIGRATION_PENDING_C_CM_PREDICTION 0
56#endif
57#ifndef CUDAPP_MIGRATION_PENDING_C_CM_CALIBRATION
58#define CUDAPP_MIGRATION_PENDING_C_CM_CALIBRATION 0
59#endif
60#ifndef CUDAPP_MIGRATION_PENDING_C_CM_BLOB
61#define CUDAPP_MIGRATION_PENDING_C_CM_BLOB 0
62#endif
63#ifndef CUDAPP_MIGRATION_PENDING_C_CM_DIGEST
64#define CUDAPP_MIGRATION_PENDING_C_CM_DIGEST 0
65#endif
66#ifndef CUDAPP_MIGRATION_PENDING_C_CM_ROUTE
67#define CUDAPP_MIGRATION_PENDING_C_CM_ROUTE 0
68#endif
69
70/* Host pointer validation stays here; scalar admission and wire offsets do not. */
71static uint64_t cm_route2(unsigned mode, uint64_t a, uint64_t b) {
72#if CUDAPP_MIGRATION_PENDING_C_CM_ROUTE
73 if (mode == 2) return a < b;
74 if (mode == 3) return a + b;
75 return a - b;
76#else
77 uint64_t data[16] = {a, b}, result;
78 if (omega_cm_route(&result, mode, data, 16) != OMEGA_OK) abort();
79 return result;
80#endif
81}
82
83#if CUDAPP_MIGRATION_PENDING_C_CM_FEATURES
84void rx_cm_default_policy(RxCmPolicy *p) {
85 p->ei_min = 0.08;
86 p->max_fail_p = 0.0; /* any wrong result excludes the arm */
87 p->fallback_arm = 0;
88 p->explore_frac = 0.05;
89 p->explore_allow_ps = 500000000ull; /* 0.5 ms to get started */
90}
91
92void rx_cm_init(RxCostModel *m, uint32_t n_arms) {
93 memset(m, 0, sizeof *m);
94 m->n_arms = n_arms > RX_CM_ARMS ? RX_CM_ARMS : n_arms;
95 m->lambda = 1e-3;
96 m->sd_scale = 1.0;
97 for (uint32_t c = 0; c < RX_CM_CELLS; c++)
98 for (uint32_t a = 0; a < RX_CM_ARMS; a++)
99 for (uint32_t i = 0, k = 0; i < RX_CM_D; i++)
100 for (uint32_t j = i; j < RX_CM_D; j++, k++)
101 m->cell[c][a].tri[k] = i == j ? m->lambda : 0.0;
102}
103
104uint32_t rx_cm_cell(const RxCmFeatures *f) {
105 /* An unknown semantic operation is not the last supported family.
106 * The restore-op-clamp mutant rewrites the next line. */
107 uint32_t op = f && f->op < RX_CM_OPS ? f->op : RX_CM_CELL_NONE; /* CM704:refuse-unsupported-op */
108 if (op >= RX_CM_OPS) return RX_CM_CELL_NONE;
109 uint32_t core = f->core < RX_CM_CORES ? f->core : RX_CM_CORE_OTHER;
110 uint32_t pr = f->pressure < RX_CM_PRESSURE ? f->pressure : RX_CM_PRESSURE - 1u;
111 return (op * RX_CM_CORES + core) * RX_CM_PRESSURE + pr;
112}
113
114void rx_cm_basis(const RxCmFeatures *f, double phi[RX_CM_D]) {
115 double lm = log2((double)(f->M ? f->M : 1));
116 double ln = log2((double)(f->N ? f->N : 1));
117 double ov = 0.0;
118 if (f->cache_bytes && f->state_bytes > f->cache_bytes)
119 ov = log2((double)f->state_bytes / (double)f->cache_bytes);
120 phi[0] = 1.0;
121 phi[1] = lm;
122 phi[2] = ln;
123 phi[3] = lm * ln;
124 phi[4] = ln * ln;
125 phi[5] = f->N <= 3 ? 1.0 : 0.0;
126 phi[6] = (f->N % 4u) != 0 ? 1.0 : 0.0;
127 phi[7] = ov;
128}
129#else
130void rx_cm_default_policy(RxCmPolicy *p) {
131 uint64_t words[64], result;
132 if (omega_cm_features(&result, 4, words, 64) != OMEGA_OK) {
133 memset(p, 0, sizeof *p);
134 return;
135 }
136 memcpy(&p->ei_min, words + 16, sizeof(double));
137 memcpy(&p->max_fail_p, words + 17, sizeof(double));
138 p->fallback_arm = (uint32_t)words[18];
139 memcpy(&p->explore_frac, words + 19, sizeof(double));
140 p->explore_allow_ps = words[20];
141}
142
143void rx_cm_init(RxCostModel *m, uint32_t n_arms) {
144 uint64_t words[64], result;
145 memset(m, 0, sizeof *m);
146 words[0] = n_arms;
147 if (omega_cm_features(&result, 3, words, 64) != OMEGA_OK) return;
148 m->n_arms = (uint32_t)result;
149 memcpy(&m->lambda, words + 16, sizeof(double));
150 memcpy(&m->sd_scale, words, sizeof(double));
151 for (uint32_t c = 0; c < RX_CM_CELLS; ++c)
152 for (uint32_t a = 0; a < RX_CM_ARMS; ++a)
153 memcpy(&m->cell[c][a], words + 16, sizeof(RxCmArmStats));
154}
155
156uint32_t rx_cm_cell(const RxCmFeatures *f) {
157 if (!f) return RX_CM_CELL_NONE;
158 uint64_t words[64], result;
159 words[0] = f->op; words[5] = f->core; words[6] = f->pressure;
160 if (omega_cm_features(&result, 0, words, 64) != OMEGA_OK) return RX_CM_CELL_NONE;
161 return (uint32_t)result;
162}
163
164static void cm_host_basis(const RxCmFeatures *f, double phi[RX_CM_D], uint64_t mode) {
165 uint64_t words[64], result;
166 words[1] = f->M; words[2] = f->N;
167 words[3] = f->state_bytes; words[4] = f->cache_bytes;
168 if (omega_cm_features(&result, mode, words, 64) != OMEGA_OK) {
169 for (uint32_t i = 0; i < RX_CM_D; ++i) phi[i] = NAN;
170 return;
171 }
172 memcpy(phi, words + 16, RX_CM_D * sizeof(double));
173}
174
175void rx_cm_basis(const RxCmFeatures *f, double phi[RX_CM_D]) { cm_host_basis(f, phi, 1); }
176#endif
177
178#if CUDAPP_MIGRATION_PENDING_C_CM_FIT
179/* Cholesky of the D x D matrix held as an upper triangle. 0 on success. */
180static int cholesky(const double *tri, double L[RX_CM_D][RX_CM_D]) {
181 double A[RX_CM_D][RX_CM_D];
182 for (uint32_t i = 0, k = 0; i < RX_CM_D; i++)
183 for (uint32_t j = i; j < RX_CM_D; j++, k++) A[i][j] = A[j][i] = tri[k];
184 memset(L, 0, sizeof(double) * RX_CM_D * RX_CM_D);
185 for (uint32_t j = 0; j < RX_CM_D; j++) {
186 double s = A[j][j];
187 for (uint32_t k = 0; k < j; k++) s -= L[j][k] * L[j][k];
188 if (!(s > 0.0)) return -1;
189 L[j][j] = sqrt(s);
190 for (uint32_t i = j + 1; i < RX_CM_D; i++) {
191 double t = A[i][j];
192 for (uint32_t k = 0; k < j; k++) t -= L[i][k] * L[j][k];
193 L[i][j] = t / L[j][j];
194 }
195 }
196 return 0;
197}
198
199static void forward(double L[RX_CM_D][RX_CM_D], const double *b, double *v) {
200 for (uint32_t i = 0; i < RX_CM_D; i++) {
201 double s = b[i];
202 for (uint32_t k = 0; k < i; k++) s -= L[i][k] * v[k];
203 v[i] = s / L[i][i];
204 }
205}
206
207static void backward(double L[RX_CM_D][RX_CM_D], const double *v, double *x) {
208 for (int i = (int)RX_CM_D - 1; i >= 0; i--) {
209 double s = v[i];
210 for (uint32_t k = (uint32_t)i + 1; k < RX_CM_D; k++) s -= L[k][i] * x[k];
211 x[i] = s / L[i][i];
212 }
213}
214
215/* Predictive t for one (cell, arm). Returns 0 if there is no data. */
216static int fit_predict(const RxCmArmStats *s, const double phi[RX_CM_D], double *mean,
217 double *sd, double *dof, uint64_t minimum) {
218 if (s->n == 0 || s->n < minimum) return 0;
219 double L[RX_CM_D][RX_CM_D], v[RX_CM_D], mu[RX_CM_D], w[RX_CM_D];
220 if (cholesky(s->tri, L) != 0) return 0;
221 forward(L, s->xty, v);
222 backward(L, v, mu);
223 double quad = 0.0; /* mu' Lambda mu = |L' mu|^2 = v . v */
224 for (uint32_t i = 0; i < RX_CM_D; i++) quad += v[i] * v[i];
225 double a = PRIOR_A + 0.5 * (double)s->n;
226 double b = PRIOR_B + 0.5 * (s->yty - quad);
227 if (b < PRIOR_B) b = PRIOR_B;
228 double sigma2 = b / a;
229 if (sigma2 < NOISE_FLOOR) sigma2 = NOISE_FLOOR;
230 forward(L, phi, w);
231 double lev = 0.0;
232 for (uint32_t i = 0; i < RX_CM_D; i++) lev += w[i] * w[i];
233 double m = 0.0;
234 for (uint32_t i = 0; i < RX_CM_D; i++) m += mu[i] * phi[i];
235 *mean = m;
236 *sd = sqrt(sigma2 * (1.0 + lev));
237 *dof = 2.0 * a;
238 return 1;
239}
240#else
241static int fit_predict(const RxCmArmStats *s, const double phi[RX_CM_D], double *mean,
242 double *sd, double *dof, uint64_t minimum) {
243 _Static_assert(sizeof(RxCmArmStats) == 48 * sizeof(uint64_t), "statistics transport layout");
244 uint64_t input[64], output[16], found;
245 memcpy(input, s, 46 * sizeof(uint64_t));
246 memcpy(input + 48, phi, RX_CM_D * sizeof(double));
247 input[56] = minimum;
248 if (omega_cm_fit(&found, input, 64, output, 16) != OMEGA_OK || found != 1) return 0;
249 memcpy(mean, output, sizeof *mean);
250 memcpy(sd, output + 1, sizeof *sd);
251 memcpy(dof, output + 2, sizeof *dof);
252 return 1;
253}
254#endif
255
256#if CUDAPP_MIGRATION_PENDING_C_CM_FEATURES
257static uint64_t failures_of(const RxCostModel *m, uint32_t arm) {
258 uint64_t f = 0;
259 for (uint32_t c = 0; c < RX_CM_CELLS; c++) f += m->cell[c][arm].failures;
260 return f;
261}
262
263static double fail_p(const RxCostModel *m, uint32_t arm) {
264 uint64_t t = 0, f = 0;
265 for (uint32_t c = 0; c < RX_CM_CELLS; c++) {
266 t += m->cell[c][arm].trials;
267 f += m->cell[c][arm].failures;
268 }
269 return ((double)f + FAIL_PRIOR) / ((double)t + 1.0);
270}
271#else
272static uint64_t failures_of(const RxCostModel *m, uint32_t arm) {
273 uint64_t words[64], result;
274 for (uint32_t c = 0; c < RX_CM_CELLS; ++c) words[c] = m->cell[c][arm].failures;
275 if (omega_cm_features(&result, 6, words, 64) != OMEGA_OK) return UINT64_MAX;
276 return result;
277}
278
279static double fail_p(const RxCostModel *m, uint32_t arm) {
280 uint64_t words[64], result;
281 double value;
282 for (uint32_t c = 0; c < RX_CM_CELLS; ++c) {
283 words[c] = m->cell[c][arm].failures; words[9 + c] = m->cell[c][arm].trials;
284 }
285 if (omega_cm_features(&result, 7, words, 64) != OMEGA_OK) return 1.0;
286 memcpy(&value, &result, sizeof value);
287 return value;
288}
289#endif
290
291/* Pressure cells hold a correction over the same core class at pressure 0:
292 * log2 cost under pressure = quiet prediction + a + b * (doublings past the
293 * private cache). Two numbers per arm, readable as "pressure costs this much,
294 * and this much more per doubling out of cache". */
295static void residual_basis(const RxCmFeatures *f, double phi[RX_CM_D]) {
296#if !CUDAPP_MIGRATION_PENDING_C_CM_FEATURES
297 cm_host_basis(f, phi, 2);
298#else
299 double full[RX_CM_D];
300 rx_cm_basis(f, full);
301 memset(phi, 0, sizeof(double) * RX_CM_D);
302 phi[0] = 1.0;
303 phi[1] = full[7];
304#endif
305}
306
307static int quiet_predict(const RxCostModel *m, const RxCmFeatures *f, uint32_t arm, double *mean,
308 double *sd, double *dof, uint64_t *n) {
309 RxCmFeatures g = *f;
310 g.pressure = 0;
311 uint32_t cell = rx_cm_cell(&g);
312 if (!cm_route2(2, cell, RX_CM_CELLS)) return 0;
313 const RxCmArmStats *b = &m->cell[cell][arm];
314 double phi[RX_CM_D];
315 rx_cm_basis(f, phi);
316 if (!fit_predict(b, phi, mean, sd, dof, RX_CM_MIN_OBS)) return 0;
317 *n = b->n;
318 return 1;
319}
320
321static uint32_t bucket(const RxCmFeatures *f) {
322#if !CUDAPP_MIGRATION_PENDING_C_CM_FEATURES
323 uint64_t words[64], result;
324 words[6] = f->pressure;
325 if (omega_cm_features(&result, 5, words, 64) != OMEGA_OK) return RX_CM_PRESSURE - 1;
326 return (uint32_t)result;
327#else
328 return f->pressure < RX_CM_PRESSURE ? f->pressure : RX_CM_PRESSURE - 1;
329#endif
330}
331
332int rx_cm_predict(const RxCostModel *m, const RxCmFeatures *f, uint32_t arm,
333 RxCmPrediction *out) {
334 if (!out) return RX_CM_ERR_ARG;
335 memset(out, 0, sizeof *out);
336 if (!m || !f) return RX_CM_ERR_ARG;
337 if (!cm_route2(2, arm, m->n_arms)) return RX_CM_ERR_ARG;
338 uint32_t cell = rx_cm_cell(f);
339 if (!cm_route2(2, cell, RX_CM_CELLS)) {
340 out->refused = 1;
341 return RX_CM_ERR_UNSUPPORTED;
342 }
343 double mean = 0, sd = 0, dof = 0;
344 uint64_t n = 0;
345 out->fail_p = fail_p(m, arm);
346 if (!quiet_predict(m, f, arm, &mean, &sd, &dof, &n)) return RX_CM_OK;
347#if CUDAPP_MIGRATION_PENDING_C_CM_PREDICTION
348 if (bucket(f) == 0) {
349 out->known = 1;
350 } else {
351 const RxCmArmStats *r = &m->cell[cell][arm];
352 double phi[RX_CM_D], rm = 0, rsd = 0, rdof = 0;
353 residual_basis(f, phi);
354 if (fit_predict(r, phi, &rm, &rsd, &rdof, RX_CM_RES_MIN_OBS)) {
355 mean += rm;
356 sd = sqrt(sd * sd + rsd * rsd);
357 if (rdof < dof) dof = rdof;
358 n = r->n;
359 out->known = 1;
360 } else {
361 /* Never seen under this pressure: the quiet prediction, with the
362 * prior on how far an unseen condition may move cost. */
363 sd = sqrt(sd * sd + RX_CM_UNSEEN_SHIFT * RX_CM_UNSEEN_SHIFT);
364 out->borrowed = 1;
365 }
366 }
367 out->n = (uint32_t)n;
368 out->mean_log2_ps = mean;
369 out->sd_log2 = sd * (m->sd_scale >= 1.0 ? m->sd_scale : 1.0);
370 out->dof = dof;
371 uint32_t core = f->core < RX_CM_CORES ? f->core : RX_CM_CORE_OTHER;
372 double mw = m->power_mw[core][arm];
373 if (mw > 0.0) out->energy_pj = exp2(mean) * mw * 1e-3; /* ps * mW = 1e-3 pJ */
374#else
375 uint64_t words[32], result;
376 memcpy(words, &mean, sizeof(double)); memcpy(words + 1, &sd, sizeof(double));
377 memcpy(words + 2, &dof, sizeof(double)); words[3] = n;
378 words[4] = bucket(f); words[5] = 0;
379 if (words[4] != 0) {
380 const RxCmArmStats *r = &m->cell[cell][arm];
381 double phi[RX_CM_D], rm = 0, rsd = 0, rdof = 0;
382 residual_basis(f, phi);
383 words[5] = (uint64_t)fit_predict(r, phi, &rm, &rsd, &rdof, RX_CM_RES_MIN_OBS);
384 memcpy(words + 6, &rm, sizeof(double)); memcpy(words + 7, &rsd, sizeof(double));
385 memcpy(words + 8, &rdof, sizeof(double)); words[9] = r->n;
386 }
387 memcpy(words + 10, &m->sd_scale, sizeof(double)); words[11] = f->core;
388 for (uint32_t c = 0; c < RX_CM_CORES; ++c)
389 memcpy(words + 12 + c, &m->power_mw[c][arm], sizeof(double));
390 if (omega_cm_prediction(&result, words, 32) != OMEGA_OK) return RX_CM_OK;
391 memcpy(&out->mean_log2_ps, words + 16, sizeof(double));
392 memcpy(&out->sd_log2, words + 17, sizeof(double));
393 memcpy(&out->dof, words + 18, sizeof(double));
394 out->n = (uint32_t)words[19]; out->known = (int)words[20]; out->borrowed = (int)words[21];
395 memcpy(&out->energy_pj, words + 22, sizeof(double));
396#endif
397 return RX_CM_OK;
398}
399
400int rx_cm_observe(RxCostModel *m, const RxCmFeatures *f, uint32_t arm, const RxCmObservation *o) {
401 if (!m || !f || !o) return RX_CM_ERR_ARG;
402 if (!cm_route2(2, arm, m->n_arms)) return RX_CM_ERR_ARG;
403 uint32_t cell = rx_cm_cell(f);
404 if (!cm_route2(2, cell, RX_CM_CELLS)) return RX_CM_ERR_UNSUPPORTED;
405 RxCmArmStats *s = &m->cell[cell][arm];
406#if !CUDAPP_MIGRATION_PENDING_C_CM_STATS
407 uint64_t words[64] = {0}, stage;
408 memcpy(words, s, sizeof *s);
409 words[56] = (uint64_t)(uint32_t)o->failed;
410 words[59] = o->ps_per_call;
411 if (omega_cm_stats(&stage, 0, words, 64) != OMEGA_OK) return RX_CM_ERR_ARG;
412 memcpy(s, words, sizeof *s);
413 if (stage == 1) return RX_CM_OK;
414 if (stage != 0) return RX_CM_ERR_ARG;
415 double phi[RX_CM_D];
416 if (bucket(f) == 0) {
417 rx_cm_basis(f, phi);
418 } else {
419 double qm, qsd, qdof;
420 uint64_t qn;
421 if (!quiet_predict(m, f, arm, &qm, &qsd, &qdof, &qn)) return RX_CM_SKIPPED;
422 residual_basis(f, phi);
423 words[57] = 1;
424 memcpy(words + 58, &qm, sizeof qm);
425 }
426 memcpy(words + 48, phi, sizeof phi);
427 if (omega_cm_stats(&stage, 1, words, 64) != OMEGA_OK || stage != 0) return RX_CM_ERR_ARG;
428 memcpy(s, words, sizeof *s);
429 return RX_CM_OK;
430#else
431 s->trials++;
432 if (o->failed) {
433 s->failures++;
434 return RX_CM_OK;
435 }
436 if (o->ps_per_call == 0) return RX_CM_ERR_ARG;
437 double phi[RX_CM_D];
438 double y = log2((double)o->ps_per_call);
439 if (bucket(f) == 0) {
440 rx_cm_basis(f, phi);
441 } else {
442 double qm, qsd, qdof;
443 uint64_t qn;
444 if (!quiet_predict(m, f, arm, &qm, &qsd, &qdof, &qn)) return RX_CM_SKIPPED;
445 residual_basis(f, phi);
446 y -= qm;
447 }
448 for (uint32_t i = 0, k = 0; i < RX_CM_D; i++) {
449 for (uint32_t j = i; j < RX_CM_D; j++, k++) s->tri[k] += phi[i] * phi[j];
450 s->xty[i] += phi[i] * y;
451 }
452 s->yty += y * y;
453 s->n++;
454 return RX_CM_OK;
455#endif
456}
457
458#if CUDAPP_MIGRATION_PENDING_C_CM_DECISION
459static double norm_cdf(double x) { return 0.5 * erfc(-x / sqrt(2.0)); }
460#endif
461
462/* Acklam's inverse normal. */
463#if CUDAPP_MIGRATION_PENDING_C_CM_QUANTILE
464static double norm_inv(double p) {
465 static const double a[] = { -3.969683028665376e+01, 2.209460984245205e+02,
466 -2.759285104469687e+02, 1.383577518672690e+02,
467 -3.066479806614716e+01, 2.506628277459239e+00 };
468 static const double b[] = { -5.447609879822406e+01, 1.615858368580409e+02,
469 -1.556989798598866e+02, 6.680131188771972e+01,
470 -1.328068155288572e+01 };
471 static const double c[] = { -7.784894002430293e-03, -3.223964580411365e-01,
472 -2.400758277161838e+00, -2.549732539343734e+00,
473 4.374664141464968e+00, 2.938163982698783e+00 };
474 static const double d[] = { 7.784695709041462e-03, 3.224671290700398e-01,
475 2.445134137142996e+00, 3.754408661907416e+00 };
476 if (p <= 0.0) return -INFINITY;
477 if (p >= 1.0) return INFINITY;
478 double q, r;
479 if (p < 0.02425) {
480 q = sqrt(-2 * log(p));
481 return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
482 ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
483 }
484 if (p > 1 - 0.02425) {
485 q = sqrt(-2 * log(1 - p));
486 return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
487 ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
488 }
489 q = p - 0.5;
490 r = q * q;
491 return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q /
492 (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
493}
494#endif
495
496double rx_cm_t_quantile(double q, double dof) {
497#if CUDAPP_MIGRATION_PENDING_C_CM_QUANTILE
498 double z = norm_inv(0.5 + 0.5 * q);
499 if (!(dof > 0.0)) return z;
500 double z3 = z * z * z, z5 = z3 * z * z;
501 return z + (z3 + z) / (4.0 * dof) + (5.0 * z5 + 16.0 * z3 + 3.0 * z) / (96.0 * dof * dof);
502#else
503 uint64_t qb, db, result;
504 double value;
505 memcpy(&qb, &q, sizeof qb);
506 memcpy(&db, &dof, sizeof db);
507 if (omega_cm_quantile(&result, qb, db) != OMEGA_OK) return NAN;
508 memcpy(&value, &result, sizeof value);
509 return value;
510#endif
511}
512
513#if CUDAPP_MIGRATION_PENDING_C_CM_DECISION
514static int explore_allowed(const RxCostModel *m, const RxCmPolicy *p) {
515 double cap = p->explore_frac * (double)m->work_ps + (double)p->explore_allow_ps;
516 return (double)m->explore_ps < cap;
517}
518
519/* E[max(0, X)] for X ~ N(d, s^2): the expected gain, in log2 units, of
520 * switching to a competitor whose advantage over the chosen arm is d. */
521static double expected_improvement(double d, double s) {
522 if (!(s > 0.0)) return d > 0.0 ? d : 0.0;
523 double u = d / s;
524 return s * exp(-0.5 * u * u) / sqrt(2.0 * M_PI) + d * norm_cdf(u);
525}
526
527void rx_cm_decide(const RxCostModel *m, const RxCmPolicy *p, const RxCmFeatures *f,
528 int allow_measure, RxCmDecision *out) {
529 memset(out, 0, sizeof *out);
530 if (m && f && rx_cm_cell(f) >= RX_CM_CELLS) {
531 uint32_t na = m->n_arms;
532 out->action = RX_CM_REFUSE;
533 out->why = RX_CM_WHY_UNSUPPORTED_OP;
534 out->arm = na;
535 out->measure[0] = na;
536 out->measure[1] = na;
537 for (uint32_t a = 0; a < RX_CM_ARMS; a++) out->pred[a].refused = 1;
538 return;
539 }
540 uint32_t fb = p->fallback_arm < m->n_arms ? p->fallback_arm : 0;
541 uint32_t elig = (f->eligible | (1u << fb)) & ((1u << m->n_arms) - 1u);
542 int have[RX_CM_ARMS] = { 0 };
543 int n_elig = 0;
544 for (uint32_t a = 0; a < m->n_arms; a++) {
545 rx_cm_predict(m, f, a, &out->pred[a]);
546 if (!(elig & (1u << a))) continue;
547 if (a != fb && failures_of(m, a) > 0 && out->pred[a].fail_p > p->max_fail_p) {
548 elig &= ~(1u << a);
549 continue;
550 }
551 n_elig++;
552 have[a] = out->pred[a].known || out->pred[a].borrowed;
553 }
554 out->action = RX_CM_FALLBACK;
555 out->arm = fb;
556 if (n_elig <= 1) {
557 out->why = RX_CM_WHY_NO_ELIGIBLE;
558 return;
559 }
560
561 /* Best by predicted latency among arms that meet the budgets; if none
562 * meets them, best overall and say so. */
563 int best = -1, best_fit = -1;
564 for (uint32_t a = 0; a < m->n_arms; a++) {
565 if (!have[a] || !(elig & (1u << a))) continue;
566 const RxCmPrediction *pr = &out->pred[a];
567 double hi = exp2(pr->mean_log2_ps + 1.2816 * pr->sd_log2);
568 int fits = (!f->latency_budget_ps || hi <= (double)f->latency_budget_ps) &&
569 (!f->energy_budget_pj || pr->energy_pj == 0.0 ||
570 pr->energy_pj <= (double)f->energy_budget_pj);
571 if (best < 0 || pr->mean_log2_ps < out->pred[best].mean_log2_ps) best = (int)a;
572 if (fits && (best_fit < 0 || pr->mean_log2_ps < out->pred[best_fit].mean_log2_ps))
573 best_fit = (int)a;
574 }
575 int over = 0;
576 if (best_fit >= 0) best = best_fit;
577 else if (best >= 0) over = 1;
578
579 /* Competitor: the eligible arm with the largest expected improvement
580 * over `best`. An arm with no prediction at all is always worth a look. */
581 int comp = -1, comp_unknown = 0;
582 double ei = 0.0, pc = 0.0;
583 for (uint32_t a = 0; a < m->n_arms; a++) {
584 if (!(elig & (1u << a)) || (int)a == best) continue;
585 double e, pa;
586 int unknown = !have[a] || best < 0;
587 if (unknown) {
588 e = INFINITY;
589 pa = 0.5;
590 } else {
591 const RxCmPrediction *x = &out->pred[a], *b = &out->pred[best];
592 double s = sqrt(x->sd_log2 * x->sd_log2 + b->sd_log2 * b->sd_log2);
593 double d = b->mean_log2_ps - x->mean_log2_ps;
594 e = expected_improvement(d, s);
595 pa = norm_cdf(d / (s > 0 ? s : 1e-9));
596 }
597 if (comp < 0 || e > ei) {
598 comp = (int)a;
599 ei = e;
600 pc = pa;
601 comp_unknown = unknown;
602 }
603 }
604 out->p_runner_up_better = pc;
605 out->expected_improvement = isinf(ei) ? -1.0 : ei;
606
607 uint32_t why = RX_CM_WHY_CONFIDENT;
608 if (best < 0 || comp_unknown) why = RX_CM_WHY_UNKNOWN_ARM;
609 else if (ei > p->ei_min) why = RX_CM_WHY_WORTH_MEASURING;
610
611 if (why != RX_CM_WHY_CONFIDENT && allow_measure && explore_allowed(m, p) && comp >= 0) {
612 out->action = RX_CM_MEASURE;
613 out->measure[0] = best >= 0 ? (uint32_t)best : fb;
614 out->measure[1] = (uint32_t)comp;
615 if (out->measure[0] == out->measure[1]) out->measure[1] = fb;
616 out->why = why;
617 out->arm = out->measure[0];
618 return;
619 }
620 if (best < 0) {
621 out->why = allow_measure && !explore_allowed(m, p) ? RX_CM_WHY_BUDGET_SPENT
622 : RX_CM_WHY_UNKNOWN_ARM;
623 return; /* fallback */
624 }
625 out->action = RX_CM_SELECT;
626 out->arm = (uint32_t)best;
627 if (over) out->why = RX_CM_WHY_OVER_BUDGET;
628 else if (why != RX_CM_WHY_CONFIDENT && allow_measure) out->why = RX_CM_WHY_BUDGET_SPENT;
629 else out->why = RX_CM_WHY_CONFIDENT;
630}
631#else
632static void cm_decision_output(const uint64_t words[128], RxCmDecision *out) {
633 out->action = (int)words[100]; out->arm = (uint32_t)words[101];
634 out->measure[0] = (uint32_t)words[102]; out->measure[1] = (uint32_t)words[103];
635 out->why = (uint32_t)words[104];
636 memcpy(&out->p_runner_up_better, words + 105, sizeof(double));
637 memcpy(&out->expected_improvement, words + 106, sizeof(double));
638}
639
640void rx_cm_decide(const RxCostModel *m, const RxCmPolicy *p, const RxCmFeatures *f,
641 int allow_measure, RxCmDecision *out) {
642 uint64_t words[128], stage;
643 memset(out, 0, sizeof *out);
644 words[80] = m->n_arms; words[81] = f->op;
645 if (omega_cm_decision(&stage, 0, words, 128) != OMEGA_OK) return;
646 if (stage == 0) {
647 for (uint32_t a = 0; a < RX_CM_ARMS; ++a) out->pred[a].refused = (int)words[9 * a + 8];
648 cm_decision_output(words, out);
649 return;
650 }
651 for (uint32_t a = 0; a < m->n_arms; ++a) {
652 RxCmPrediction *pr = &out->pred[a];
653 rx_cm_predict(m, f, a, pr);
654 uint64_t *w = words + 9 * a;
655 memcpy(w, &pr->mean_log2_ps, sizeof(double));
656 memcpy(w + 1, &pr->sd_log2, sizeof(double));
657 memcpy(w + 2, &pr->dof, sizeof(double));
658 w[3] = pr->n; w[4] = (uint64_t)(uint32_t)pr->known; w[5] = (uint64_t)(uint32_t)pr->borrowed;
659 memcpy(w + 6, &pr->energy_pj, sizeof(double));
660 memcpy(w + 7, &pr->fail_p, sizeof(double));
661 w[8] = (uint64_t)(uint32_t)pr->refused;
662 words[72 + a] = failures_of(m, a);
663 }
664 words[82] = f->eligible;
665 words[86] = f->latency_budget_ps; words[87] = f->energy_budget_pj;
666 words[88] = (uint64_t)(uint32_t)allow_measure;
667 memcpy(words + 89, &p->ei_min, sizeof(double));
668 memcpy(words + 90, &p->max_fail_p, sizeof(double));
669 words[91] = p->fallback_arm;
670 memcpy(words + 92, &p->explore_frac, sizeof(double));
671 words[93] = p->explore_allow_ps; words[94] = m->explore_ps; words[95] = m->work_ps;
672 if (omega_cm_decision(&stage, 1, words, 128) != OMEGA_OK) return;
673 cm_decision_output(words, out);
674}
675#endif
676
677
678#if CUDAPP_MIGRATION_PENDING_C_CM_CALIBRATION
679double rx_cm_calibrate(RxCostModel *m, const RxCmFeatures *f, const uint32_t *arm,
680 const uint64_t *ps, uint32_t n, double q) {
681 if (!m || !f || !arm || !ps || n == 0 || !(q > 0.0 && q < 1.0)) return 0.0;
682 double *r = malloc(sizeof(double) * n);
683 if (!r) return 0.0;
684 double saved = m->sd_scale;
685 m->sd_scale = 1.0;
686 uint32_t k = 0;
687 for (uint32_t i = 0; i < n; i++) {
688 RxCmPrediction p;
689 rx_cm_predict(m, &f[i], arm[i], &p);
690 if (!(p.known || p.borrowed) || ps[i] == 0 || !(p.sd_log2 > 0.0)) continue;
691 double z = fabs(log2((double)ps[i]) - p.mean_log2_ps) / p.sd_log2;
692 r[k++] = z / rx_cm_t_quantile(q, p.dof);
693 }
694 double scale = 0.0;
695 if (k >= 10) {
696 if (rx_cm_sort(r, k) != 0) { m->sd_scale = saved; free(r); return 0.0; }
697 uint32_t idx = (uint32_t)ceil(q * (double)k) - 1u;
698 scale = r[idx < k ? idx : k - 1];
699 if (scale < 1.0) scale = 1.0;
700 m->sd_scale = scale;
701 } else {
702 m->sd_scale = saved;
703 }
704 free(r);
705 return scale;
706}
707#else
708double rx_cm_calibrate(RxCostModel *m, const RxCmFeatures *f, const uint32_t *arm,
709 const uint64_t *ps, uint32_t n, double q) {
710 if (!m || !f || !arm || !ps) return 0.0;
711 uint64_t words[32], stage;
712 memcpy(words, &q, sizeof(double)); words[2] = n;
713 if (omega_cm_calibration(&stage, 0, words, 32) != OMEGA_OK || stage == 0) return 0.0;
714 double *r = malloc(sizeof(double) * n);
715 if (!r) return 0.0;
716 double saved = m->sd_scale, scale = 0;
717 memcpy(words + 1, &saved, sizeof(double));
718 memcpy(&m->sd_scale, words + 10, sizeof(double));
719 uint32_t k = 0;
720 for (uint32_t i = 0; i < n; ++i) {
721 RxCmPrediction p;
722 rx_cm_predict(m, &f[i], arm[i], &p);
723 words[3] = ps[i];
724 memcpy(words + 4, &p.mean_log2_ps, sizeof(double));
725 memcpy(words + 5, &p.sd_log2, sizeof(double));
726 memcpy(words + 6, &p.dof, sizeof(double));
727 words[7] = (uint64_t)(uint32_t)p.known; words[8] = (uint64_t)(uint32_t)p.borrowed;
728 if (omega_cm_calibration(&stage, 1, words, 32) != OMEGA_OK) {
729 m->sd_scale = saved; free(r); return 0.0;
730 }
731 if (stage != 0) memcpy(r + k++, words + 10, sizeof(double));
732 }
733 words[2] = k;
734 if (omega_cm_calibration(&stage, 2, words, 32) != OMEGA_OK) {
735 m->sd_scale = saved; free(r); return 0.0;
736 }
737 if (stage != 0) {
738 uint64_t index = words[10];
739 if (rx_cm_sort(r, k) != 0) { m->sd_scale = saved; free(r); return 0.0; }
740 memcpy(words + 9, r + index, sizeof(double));
741 if (omega_cm_calibration(&stage, 3, words, 32) != OMEGA_OK) {
742 m->sd_scale = saved; free(r); return 0.0;
743 }
744 memcpy(&scale, words + 10, sizeof(double));
745 }
746 memcpy(&m->sd_scale, words + 10, sizeof(double));
747 free(r);
748 return scale;
749}
750#endif
751
752void rx_cm_charge(RxCostModel *m, uint64_t work_ps, uint64_t explore_ps) {
753#if CUDAPP_MIGRATION_PENDING_C_CM_CALIBRATION
754 m->work_ps += work_ps;
755 m->explore_ps += explore_ps;
756#else
757 uint64_t words[32], result;
758 words[0] = m->work_ps; words[1] = m->explore_ps;
759 words[2] = work_ps; words[3] = explore_ps;
760 if (omega_cm_calibration(&result, 4, words, 32) != OMEGA_OK) return;
761 m->work_ps = words[0]; m->explore_ps = words[1];
762#endif
763}
764
765/* ---- canonical bytes ---- */
766
767#define MAGIC 0x4d43474fu /* "OGCM" little-endian */
768/* VERSION binds the feature basis and the cell layout. RX_CM_CELLS already
769 * includes RX_CM_OPS, so a new operation family changes the blob length and
770 * this header's cells field. Bump VERSION in that same change. Deserialize
771 * refuses a different version, basis size, cell count, arm cap or core count. */
772#define VERSION 1u
773
774typedef struct {
775 uint32_t magic, version, n_arms, d, cells, arms_cap, cores;
776 uint32_t reserved;
777 double lambda;
778} Header;
779_Static_assert(sizeof(Header) == 40, "cost model native blob header layout");
780
781#if !CUDAPP_MIGRATION_PENDING_C_CM_BLOB
782static uint64_t cm_blob_check(unsigned mode, uint64_t words[64]) {
783 uint64_t result;
784#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
785 words[63] = 1;
786#else
787 words[63] = 0;
788#endif
789 if (omega_cm_blob(&result, mode, words, 64)) abort();
790 return result;
791}
792#endif
793
794#if CUDAPP_MIGRATION_PENDING_C_CM_DIGEST
795#define cm_sha256 sha256_hash
796static int cm_digest_equal(const uint8_t a[32], const uint8_t b[32]) {
797 return memcmp(a, b, 32) == 0;
798}
799#else
800static uint64_t cm_digest_step(unsigned mode, uint64_t state[16], uint8_t data[128]) {
801 uint64_t result;
802 if (omega_cm_digest(&result, mode, state, 16, data, 128)) abort();
803 return result;
804}
805static void cm_sha256(const uint8_t *data, size_t n, uint8_t out[32]) {
806 uint64_t state[16];
807 uint8_t block[128];
808 if (cm_digest_step(0, state, block)) abort();
809#if CUDAPP_MIGRATION_PENDING_C_CM_ROUTE
810 size_t blocks = n / 64, tail = n % 64, offset = blocks * 64;
811#else
812 uint64_t plan[16] = {n}, result;
813 if (omega_cm_route(&result, 0, plan, 16) != OMEGA_OK || result != 1) abort();
814 size_t blocks = (size_t)plan[1], tail = (size_t)plan[2], offset = (size_t)plan[3];
815#endif
816 const uint8_t *cursor = data;
817 for (size_t i = 0; i < blocks; ++i, cursor += 64) {
818 memcpy(block, cursor, 64);
819 if (cm_digest_step(1, state, block)) abort();
820 }
821 state[9] = tail;
822 memcpy(block, data + offset, tail);
823 if (cm_digest_step(2, state, block)) abort();
824 memcpy(out, block, 32);
825}
826static int cm_digest_equal(const uint8_t a[32], const uint8_t b[32]) {
827 uint64_t state[16];
828 uint8_t data[128];
829 memcpy(data, a, 32);
830 memcpy(data + 32, b, 32);
831 return (int)cm_digest_step(3, state, data);
832}
833#endif
834
835static size_t body_size(void) {
836 const RxCostModel *m = 0;
837#if CUDAPP_MIGRATION_PENDING_C_CM_ROUTE
838 return sizeof m->cell + sizeof m->power_mw + sizeof m->verify_ns + sizeof m->synth_ns +
839 sizeof m->code_bytes + sizeof m->sd_scale;
840#else
841 uint64_t sizes[16] = {sizeof m->cell, sizeof m->power_mw, sizeof m->verify_ns,
842 sizeof m->synth_ns, sizeof m->code_bytes, sizeof m->sd_scale}, result;
843 if (omega_cm_route(&result, 1, sizes, 16) != OMEGA_OK) abort();
844 return (size_t)result;
845#endif
846}
847
848size_t rx_cm_blob_size(void) {
849#if CUDAPP_MIGRATION_PENDING_C_CM_ROUTE
850 return sizeof(Header) + body_size() + 32u;
851#else
852 uint64_t sizes[16] = {sizeof(Header), body_size(), 32}, result;
853 if (omega_cm_route(&result, 1, sizes, 16) != OMEGA_OK) abort();
854 return (size_t)result;
855#endif
856}
857
858static size_t pack(const RxCostModel *m, uint8_t *out) {
859 Header h;
860#if CUDAPP_MIGRATION_PENDING_C_CM_BLOB
861 memset(&h, 0, sizeof h);
862 h.magic = MAGIC;
863 h.version = VERSION;
864 h.n_arms = m->n_arms;
865 h.d = RX_CM_D;
866 h.cells = RX_CM_CELLS;
867 h.arms_cap = RX_CM_ARMS;
868 h.cores = RX_CM_CORES;
869 h.lambda = m->lambda;
870#else
871 uint64_t words[64];
872 words[0] = m->n_arms;
873 memcpy(words + 1, &m->lambda, sizeof m->lambda);
874 if (!cm_blob_check(0, words)) abort();
875 memcpy(&h, words + 16, sizeof h);
876#endif
877 uint8_t *p = out;
878 memcpy(p, &h, sizeof h);
879 p += sizeof h;
880 memcpy(p, m->cell, sizeof m->cell);
881 p += sizeof m->cell;
882 memcpy(p, m->power_mw, sizeof m->power_mw);
883 p += sizeof m->power_mw;
884 memcpy(p, m->verify_ns, sizeof m->verify_ns);
885 p += sizeof m->verify_ns;
886 memcpy(p, m->synth_ns, sizeof m->synth_ns);
887 p += sizeof m->synth_ns;
888 memcpy(p, m->code_bytes, sizeof m->code_bytes);
889 p += sizeof m->code_bytes;
890 memcpy(p, &m->sd_scale, sizeof m->sd_scale);
891 p += sizeof m->sd_scale;
892 return (size_t)(p - out);
893}
894
895int rx_cm_serialize(const RxCostModel *m, uint8_t *out, size_t cap, size_t *out_len) {
896 if (!m || !out) return RX_CM_ERR_ARG;
897#if CUDAPP_MIGRATION_PENDING_C_CM_BLOB
898 if (cap < rx_cm_blob_size()) return RX_CM_ERR_ARG;
899#else
900 uint64_t words[64];
901 words[0] = cap;
902 words[1] = rx_cm_blob_size();
903 if (!cm_blob_check(3, words)) return RX_CM_ERR_ARG;
904#endif
905 size_t n = pack(m, out);
906 cm_sha256(out, n, out + n);
907 if (out_len) *out_len = (size_t)cm_route2(3, n, 32);
908 return RX_CM_OK;
909}
910
911int rx_cm_deserialize(RxCostModel *m, const uint8_t *in, size_t len) {
912 if (!m || !in) return RX_CM_ERR_FORMAT;
913#if CUDAPP_MIGRATION_PENDING_C_CM_BLOB
914 if (len != rx_cm_blob_size()) return RX_CM_ERR_FORMAT;
915#else
916 uint64_t words[64];
917 words[0] = len;
918 words[1] = rx_cm_blob_size();
919 if (!cm_blob_check(4, words)) return RX_CM_ERR_FORMAT;
920#endif
921 uint8_t d[32];
922 size_t payload = (size_t)cm_route2(4, len, 32);
923 cm_sha256(in, payload, d);
924 if (!cm_digest_equal(d, in + payload)) return RX_CM_ERR_DIGEST;
925 Header h;
926 memcpy(&h, in, sizeof h);
927#if CUDAPP_MIGRATION_PENDING_C_CM_BLOB
928 if (h.magic != MAGIC || h.version != VERSION || h.d != RX_CM_D || h.cells != RX_CM_CELLS ||
929 h.arms_cap != RX_CM_ARMS || h.cores != RX_CM_CORES || h.n_arms == 0 ||
930 h.n_arms > RX_CM_ARMS)
931 return RX_CM_ERR_FORMAT;
932#else
933 memcpy(words + 16, &h, sizeof h);
934 uint64_t n_arms = cm_blob_check(1, words);
935 if (!n_arms) return RX_CM_ERR_FORMAT;
936#endif
937 RxCostModel t;
938 memset(&t, 0, sizeof t);
939#if CUDAPP_MIGRATION_PENDING_C_CM_BLOB
940 t.n_arms = h.n_arms;
941 t.lambda = h.lambda;
942#else
943 t.n_arms = (unsigned)n_arms;
944 memcpy(&t.lambda, words + 20, sizeof t.lambda);
945#endif
946 const uint8_t *p = in + sizeof h;
947 memcpy(t.cell, p, sizeof t.cell);
948 p += sizeof t.cell;
949 memcpy(t.power_mw, p, sizeof t.power_mw);
950 p += sizeof t.power_mw;
951 memcpy(t.verify_ns, p, sizeof t.verify_ns);
952 p += sizeof t.verify_ns;
953 memcpy(t.synth_ns, p, sizeof t.synth_ns);
954 p += sizeof t.synth_ns;
955 memcpy(t.code_bytes, p, sizeof t.code_bytes);
956 p += sizeof t.code_bytes;
957 memcpy(&t.sd_scale, p, sizeof t.sd_scale);
958#if CUDAPP_MIGRATION_PENDING_C_CM_BLOB
959 if (!(t.sd_scale >= 1.0 && t.sd_scale < 1e6)) return RX_CM_ERR_FORMAT;
960#else
961 memcpy(words, &t.sd_scale, sizeof t.sd_scale);
962 if (!cm_blob_check(2, words)) return RX_CM_ERR_FORMAT;
963#endif
964 *m = t;
965 return RX_CM_OK;
966}
967
968void rx_cm_digest(const RxCostModel *m, uint8_t out[32]) {
969 uint8_t buf[sizeof(Header) + sizeof(((RxCostModel *)0)->cell) + 4096];
970 size_t n = pack(m, buf);
971 cm_sha256(buf, n, out);
972}