Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/blob/main/src/runtime/rx_costmodel.h # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `CUDApp / src / runtime / rx_costmodel.h` 240 lines · 12591 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 17 /* 18 * rx_costmodel.h -- Omega's empirical cost model (OMEGA_EMPIRICAL_OPTIMIZER). 19 * 20 * Omega picks a realization for an operation from what it has measured, not 21 * from a fixed rule. This is a calculator only: 22 * 23 * features of a call -> predicted cost of every eligible realization, 24 * with how sure the prediction is 25 * -> SELECT one, or MEASURE two when unsure 26 * 27 * It never runs code, never holds or reads authority, never writes a 28 * generation. Whoever calls it executes the realizations and reports what 29 * they cost. A learned model becomes durable only as the `model` blob of a 30 * generation promoted through the R9 barrier by a subject that holds the 31 * promotion right; the Makefile checks that rx_costmodel.o references none 32 * of those operations. 33 * 34 * This is not authority learning. No feature is derived from a capability, 35 * and a realization is eligible only if the caller says it was verified. 36 * 37 * Numerical contract: non-contracting IEEE binary64, round-to-nearest, with 38 * each operation rounded separately. First-party Omega math is canonical. 39 * The retained C algorithm is built with -ffp-contract=off; results can differ 40 * from older implicitly contracted/glibc builds. Measured differences and the 41 * exact differential gate are documented in tests/runtime/HOST_POLICY.md. 42 * 43 * Predictor: one Bayesian linear regression (normal-inverse-gamma, ridge 44 * prior) per (cell, arm), on log2 picoseconds per call. A cell is 45 * (operation class, core class, pressure bucket). Pressure cells hold a 46 * two-number correction over the quiet cell of the same core class. The basis is small and 47 * readable: 1, log2 M, log2 N, their product, (log2 N)^2, N <= 3, 48 * N % 4 != 0, and how far the working set overflows the core's cache, in 49 * doublings. Each (cell, arm) keeps only sufficient statistics, so the model 50 * serializes to a fixed-size blob. 51 */ 52 #ifndef RX_COSTMODEL_H 53 #define RX_COSTMODEL_H 54 55 #include 56 #include 57 58 #define RX_CM_ARMS 8u 59 #define RX_CM_OPS 1u /* matvec only. A new family widens this, changes 60 * RX_CM_CELLS, and must bump the blob version. 61 * An id outside 0 .. RX_CM_OPS-1 is refused; 62 * it is not aliased onto the last family. */ 63 #define RX_CM_CORES 3u 64 #define RX_CM_PRESSURE 3u 65 #define RX_CM_CELLS (RX_CM_OPS * RX_CM_CORES * RX_CM_PRESSURE) 66 #define RX_CM_D 8u /* basis size */ 67 #define RX_CM_TRI (RX_CM_D * (RX_CM_D + 1u) / 2u) 68 #define RX_CM_MIN_OBS 12u /* own-cell observations before a cell is used alone */ 69 #define RX_CM_RES_MIN_OBS 4u /* observations before a pressure correction is used */ 70 #define RX_CM_UNSEEN_SHIFT 1.0 /* prior sd, log2: an unseen pressure may halve or double cost */ 71 72 #define RX_CM_OK 0 73 #define RX_CM_ERR_ARG -1 74 #define RX_CM_ERR_FORMAT -2 75 #define RX_CM_ERR_DIGEST -3 76 #define RX_CM_ERR_UNSUPPORTED -4 /* semantic operation id is not a modeled family */ 77 #define RX_CM_SKIPPED 1 /* observe: pressure data with no quiet model to correct */ 78 #define RX_CM_CELL_NONE UINT32_MAX /* not an index into RxCostModel.cell */ 79 enum { RX_CM_OP_MATVEC = 0 }; 80 enum { RX_CM_CORE_X925 = 0, RX_CM_CORE_A725 = 1, RX_CM_CORE_OTHER = 2 }; 81 82 /* What the caller knows about one call. Fields the matvec workload cannot 83 * vary are carried and recorded, never used to fit (see spec). */ 84 typedef struct { 85 uint32_t op; /* semantic operation class; only ids below RX_CM_OPS */ 86 uint32_t M, N; /* input shape; branch count is 0 for matvec */ 87 uint64_t state_bytes; /* working set: (M*N + N + M) * 8 */ 88 uint64_t cache_bytes; /* last private cache of this core class */ 89 uint32_t core; /* hardware state: core class */ 90 uint32_t pressure; /* resource pressure bucket, 0 = none */ 91 uint32_t thermal_c; /* thermal state, degrees C (recorded) */ 92 uint32_t current_arm; /* realization in use now */ 93 uint32_t eligible; /* bit per arm: verified and allowed here */ 94 uint32_t need_evidence; /* 1: only arms with a passing verdict (always 1 here) */ 95 uint32_t cognitive; /* cognitive requirement (recorded; 0 for matvec) */ 96 uint64_t latency_budget_ps; /* per call; 0 = none */ 97 uint64_t energy_budget_pj; /* per call; 0 = none */ 98 } RxCmFeatures; 99 100 /* One measurement the caller made. */ 101 typedef struct { 102 uint64_t ps_per_call; /* latency */ 103 int failed; /* wrong result, crash or verification refusal */ 104 } RxCmObservation; 105 106 typedef struct { 107 double mean_log2_ps; /* predicted log2 picoseconds per call */ 108 double sd_log2; /* predictive standard deviation, log2 units */ 109 double dof; /* degrees of freedom of the predictive t */ 110 uint32_t n; /* observations behind it */ 111 int known; /* its own cell has at least RX_CM_MIN_OBS observations */ 112 int borrowed; /* unseen pressure: the quiet prediction, widened */ 113 double energy_pj; /* predicted energy per call (0 if no power figure) */ 114 double fail_p; /* posterior mean failure probability */ 115 int refused; /* 1: this operation id is not modeled */ 116 } RxCmPrediction; 117 118 enum { RX_CM_SELECT = 1, RX_CM_MEASURE = 2, RX_CM_FALLBACK = 3, RX_CM_REFUSE = 4 }; 119 120 /* Why a MEASURE, FALLBACK or REFUSE was returned. */ 121 enum { 122 RX_CM_WHY_CONFIDENT = 0, 123 RX_CM_WHY_UNKNOWN_ARM, /* an eligible arm has too few observations here */ 124 RX_CM_WHY_WORTH_MEASURING, /* expected improvement from measuring exceeds ei_min */ 125 RX_CM_WHY_BUDGET_SPENT, /* would measure, but the exploration budget is spent */ 126 RX_CM_WHY_NO_ELIGIBLE, /* nothing but the fallback may run */ 127 RX_CM_WHY_OVER_BUDGET, /* no arm is predicted to meet the latency/energy budget */ 128 RX_CM_WHY_UNSUPPORTED_OP /* semantic operation id is not a modeled family */ 129 }; 130 131 typedef struct { 132 int action; 133 uint32_t arm; /* SELECT / FALLBACK: run this */ 134 uint32_t measure[2]; /* MEASURE: run both, keep the faster */ 135 uint32_t why; 136 double p_runner_up_better; /* P(competitor faster than the chosen arm) */ 137 double expected_improvement; /* E[max(0, log2 cost chosen - log2 cost competitor)] */ 138 RxCmPrediction pred[RX_CM_ARMS]; 139 } RxCmDecision; 140 141 typedef struct { 142 /* Measure only when the expected improvement of the likeliest competitor 143 * over the chosen arm exceeds this, in log2 units (0.08 is about 6%). 144 * Two arms predicted equal and tight are not worth a run; an arm the 145 * model knows little about, or two arms it cannot separate, are. */ 146 double ei_min; 147 double max_fail_p; /* an arm that has failed and is above this is not selected */ 148 uint32_t fallback_arm; /* known-good: always verified, never removed */ 149 /* Exploration budget: extra time spent measuring may not exceed 150 * explore_frac of the time spent on chosen work plus explore_allow_ps. */ 151 double explore_frac; 152 uint64_t explore_allow_ps; 153 } RxCmPolicy; 154 155 typedef struct { 156 double tri[RX_CM_TRI]; /* X'X + lambda I, upper triangle, row-major */ 157 double xty[RX_CM_D]; 158 double yty; 159 uint64_t n; 160 uint64_t trials, failures; /* failure probability: Beta(1 + f, 1 + t - f) */ 161 } RxCmArmStats; 162 163 typedef struct { 164 uint32_t n_arms; 165 double lambda; /* ridge prior precision */ 166 RxCmArmStats cell[RX_CM_CELLS][RX_CM_ARMS]; 167 double power_mw[RX_CM_CORES][RX_CM_ARMS]; /* measured power while running, 0 = unknown */ 168 uint64_t verify_ns[RX_CM_ARMS]; /* verification cost */ 169 uint64_t synth_ns[RX_CM_ARMS]; /* synthesis cost; recompute = synth + verify */ 170 uint64_t code_bytes[RX_CM_ARMS]; /* memory held by the realization */ 171 /* Calibration: predictive spread is multiplied by this. Set from residuals 172 * on validation work measured apart from training (rx_cm_calibrate). */ 173 double sd_scale; 174 /* Runtime only; not serialized. */ 175 uint64_t explore_ps, work_ps; 176 } RxCostModel; 177 178 void rx_cm_default_policy(RxCmPolicy *p); 179 void rx_cm_init(RxCostModel *m, uint32_t n_arms); 180 181 /* Fold one measurement in. RX_CM_OK on success; RX_CM_SKIPPED for a pressure 182 * measurement when there is no quiet model yet to correct. 183 * RX_CM_ERR_UNSUPPORTED when `f->op` is not a modeled family: no sufficient 184 * statistic, trial, failure, exploration counter or other model field changes. 185 * RX_CM_ERR_ARG for a null argument, an arm this model does not have, or a 186 * successful observation with zero latency. */ 187 int rx_cm_observe(RxCostModel *m, const RxCmFeatures *f, uint32_t arm, const RxCmObservation *o); 188 189 /* Predict one arm. Returns RX_CM_ERR_UNSUPPORTED and sets out->refused when 190 * the semantic operation is not a modeled family. That output is zeros aside 191 * from `refused`: no mean, spread, failure rate or ranking is borrowed from 192 * another operation. Returns RX_CM_ERR_ARG for a null argument or an arm this 193 * model does not have. Otherwise returns RX_CM_OK. 194 * A supported operation needs RX_CM_MIN_OBS quiet observations for the core 195 * class before out->known is set. Under pressure, adds the learned correction 196 * once it has RX_CM_RES_MIN_OBS observations; before that, widens by 197 * RX_CM_UNSEEN_SHIFT and marks it borrowed. */ 198 int rx_cm_predict(const RxCostModel *m, const RxCmFeatures *f, uint32_t arm, RxCmPrediction *out); 199 200 /* Decide. An unsupported semantic operation sets RX_CM_REFUSE and 201 * RX_CM_WHY_UNSUPPORTED_OP, leaves every prediction refused, and does not 202 * rank arms (`arm` and `measure[]` are set to n_arms, not a selection). 203 * `allow_measure` 0 freezes the model's behaviour for a supported operation: 204 * it never asks to measure and picks the best prediction. The fallback arm is 205 * chosen when no other eligible arm has any prediction at all. */ 206 void rx_cm_decide(const RxCostModel *m, const RxCmPolicy *p, const RxCmFeatures *f, 207 int allow_measure, RxCmDecision *out); 208 209 /* Split calibration. For n measurements taken apart from the training data, 210 * set sd_scale so that the central q interval covers a fraction q of them 211 * (never below 1). Returns the scale, or 0 if fewer than 10 were usable. */ 212 double rx_cm_calibrate(RxCostModel *m, const RxCmFeatures *f, const uint32_t *arm, 213 const uint64_t *ps, uint32_t n, double q); 214 215 /* Account for time spent: chosen work, and extra time spent measuring. */ 216 void rx_cm_charge(RxCostModel *m, uint64_t work_ps, uint64_t explore_ps); 217 218 /* Canonical bytes: header, the fixed-size body, SHA-256 of both. The size is 219 * rx_cm_blob_size(). Runtime counters are not included. */ 220 size_t rx_cm_blob_size(void); 221 int rx_cm_serialize(const RxCostModel *m, uint8_t *out, size_t cap, size_t *out_len); 222 int rx_cm_deserialize(RxCostModel *m, const uint8_t *in, size_t len); 223 void rx_cm_digest(const RxCostModel *m, uint8_t out[32]); 224 225 /* Basis for these features, exposed so tests can see exactly what is fit. */ 226 void rx_cm_basis(const RxCmFeatures *f, double phi[RX_CM_D]); 227 228 /* Cell index for these features. RX_CM_CELL_NONE if `f` is null or `f->op` 229 * is not one of the RX_CM_OPS modeled families. That sentinel is never a 230 * legal index of RxCostModel.cell. An unknown core class maps to 231 * RX_CM_CORE_OTHER. Pressure above the last bucket saturates into that 232 * bucket. Those two mappings are hardware and pressure buckets, not a 233 * catch-all operation family. */ 234 uint32_t rx_cm_cell(const RxCmFeatures *f); 235 236 /* Two-sided central interval half-width multiplier for coverage q with 237 * `dof` degrees of freedom (Student t, Cornish-Fisher approximation). */ 238 double rx_cm_t_quantile(double q, double dof); 239 240 #endif /* RX_COSTMODEL_H */