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 / physics0 / learner_v2 / pd0_learner.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 | /* PD-0 learner v2 implementation. See pd0_learner.h. Copy of the seal-1 learner plus the |
| 18 | * rollout terms marked "v2". No generator knowledge, no file I/O, no level identity. */ |
| 19 | #include "pd0_learner.h" |
| 20 | #include "pd0_rng.h" |
| 21 | #include <math.h> |
| 22 | #include <stdio.h> |
| 23 | #include <stdlib.h> |
| 24 | #include <string.h> |
| 25 | |
| 26 | typedef struct { int64_t before[PD0_MAX_OBS], after[PD0_MAX_OBS]; uint8_t chan; int64_t value; uint8_t tag; uint32_t episode; uint8_t is_reset; uint32_t seq; } trans; |
| 27 | |
| 28 | struct pd0_learner { |
| 29 | pd0l_desc d; |
| 30 | uint64_t seed; |
| 31 | trans *t; uint32_t nt; |
| 32 | unsigned ni, nl; /* inputs (obs + channels), library size */ |
| 33 | uint8_t lib[PD0L_MAX_LIB][PD0_MAX_VARS + PD0_MAX_CHAN]; |
| 34 | int ncand; pd0l_candidate cand[PD0L_MAX_CAND]; |
| 35 | int has_prior; pd0_rel prior; /* v2 */ |
| 36 | uint32_t lo, hi, n_ep; /* v2.1: fit window [lo,hi) over t[]; episodes seen */ |
| 37 | int forget, has_old; pd0_rel old; pd0l_detect det; /* v2.1 */ |
| 38 | }; |
| 39 | |
| 40 | /* v2 hidden-state rule on rollouts: a model whose 20-step SELECT rollout error is large in absolute terms AND far above its |
| 41 | * own one-step error is missing state (a latent) rather than noise (noise raises both together). */ |
| 42 | #ifndef PD0L_ROLL_FLAG_ABS |
| 43 | #define PD0L_ROLL_FLAG_ABS 30000 /* micro: rollout NRMSE 0.03 */ |
| 44 | #endif |
| 45 | #ifndef PD0L_ROLL_FLAG_RATIO |
| 46 | #define PD0L_ROLL_FLAG_RATIO 4 /* rollout NRMSE over one-step NRMSE (one-step floored at 1000 micro) */ |
| 47 | #endif |
| 48 | |
| 49 | /* ---- vocabulary: every monomial of total degree <= 3 over the inputs (constant included) ---- */ |
| 50 | static unsigned build_library(unsigned ni, uint8_t lib[PD0L_MAX_LIB][PD0_MAX_VARS + PD0_MAX_CHAN]) |
| 51 | { |
| 52 | unsigned n = 0; uint8_t e[PD0_MAX_VARS + PD0_MAX_CHAN]; |
| 53 | for (unsigned a = 0; a <= ni; a++) for (unsigned b = a; b <= ni; b++) for (unsigned c = b; c <= ni; c++) { |
| 54 | memset(e, 0, sizeof e); if (a < ni) e[a]++; if (b < ni) e[b]++; if (c < ni) e[c]++; |
| 55 | int dup = 0; for (unsigned k = 0; k < n; k++) if (!memcmp(lib[k], e, ni)) { dup = 1; break; } |
| 56 | if (!dup && n < PD0L_MAX_LIB) memcpy(lib[n++], e, sizeof e); } |
| 57 | return n; |
| 58 | } |
| 59 | |
| 60 | pd0_learner *pd0_learner_new(const pd0l_desc *d, uint64_t seed) |
| 61 | { |
| 62 | if (!d || d->n_obs == 0 || d->n_obs > PD0_MAX_OBS || d->n_channels > PD0_MAX_CHAN) return NULL; |
| 63 | pd0_learner *L = calloc(1, sizeof *L); if (!L) return NULL; |
| 64 | L->t = malloc(sizeof(trans) * PD0L_MAX_TRANS); if (!L->t) { free(L); return NULL; } |
| 65 | L->d = *d; L->seed = seed; L->ni = d->n_obs + d->n_channels; L->nl = build_library(L->ni, L->lib); |
| 66 | return L; |
| 67 | } |
| 68 | void pd0_learner_free(pd0_learner *L) { if (L) { free(L->t); free(L); } } |
| 69 | |
| 70 | int pd0_learner_observe(pd0_learner *L, const pd0_rec *r, uint8_t tag) |
| 71 | { |
| 72 | if (tag != TAG_FIT && tag != TAG_SELECT) return -1; /* I10: nothing else may reach the learner */ |
| 73 | if (r->n_obs != L->d.n_obs || L->nt >= PD0L_MAX_TRANS) return -1; |
| 74 | if (r->kind == PD0_KIND_STEP && r->status != PD0_ST_OK && r->status != PD0_ST_EPISODE_END) return 0; /* spec rev 6: EPISODE_END carries an outcome; refused/out-of-bounds/budget steps do not */ |
| 75 | if (r->kind == PD0_KIND_RESET) L->n_ep++; |
| 76 | trans *t = &L->t[L->nt++]; memset(t, 0, sizeof *t); |
| 77 | t->seq = L->n_ep ? L->n_ep - 1 : 0; L->hi = L->nt; |
| 78 | memcpy(t->before, r->before, sizeof(int64_t) * r->n_obs); memcpy(t->after, r->after, sizeof(int64_t) * r->n_obs); |
| 79 | t->chan = r->channel; t->value = r->applied; t->tag = tag; t->episode = r->episode; t->is_reset = r->kind == PD0_KIND_RESET; |
| 80 | return 0; |
| 81 | } |
| 82 | uint32_t pd0_learner_n_transitions(const pd0_learner *L, uint8_t tag) { uint32_t n = 0; for (uint32_t i = 0; i < L->nt; i++) if (L->t[i].tag == tag && !L->t[i].is_reset) n++; return n; } |
| 83 | |
| 84 | /* ---- schedules ---- */ |
| 85 | static int64_t draw_in(pd0_rng *g, int64_t lo, int64_t hi) { int64_t u = pd0_rng_unit(g); return lo + pd0_mul(hi - lo, u); } |
| 86 | void pd0_learner_random_schedule(const pd0l_desc *d, uint64_t seed, const char *tag, uint32_t idx, int64_t *reset, pd0_step *steps, uint32_t n) |
| 87 | { |
| 88 | pd0_rng g; pd0_rng_stream(&g, seed ^ ((uint64_t)idx * 0x9E3779B97F4A7C15ull), tag); |
| 89 | for (int j = 0; j < d->n_obs; j++) reset[j] = draw_in(&g, d->reset_min[j], d->reset_max[j]); |
| 90 | for (uint32_t s = 0; s < n; s++) { |
| 91 | uint8_t ch = d->n_channels ? (uint8_t)(pd0_rng_next(&g) % d->n_channels) : PD0_CHAN_NONE; |
| 92 | steps[s].channel = ch; steps[s].value = ch == PD0_CHAN_NONE ? 0 : draw_in(&g, d->chan_min[ch], d->chan_max[ch]); } |
| 93 | } |
| 94 | void pd0_learner_explore(pd0_learner *L, uint32_t episode_index, int64_t *reset, pd0_step *steps, uint32_t n_steps) |
| 95 | { pd0_learner_random_schedule(&L->d, L->seed, "explore", episode_index, reset, steps, n_steps); } |
| 96 | |
| 97 | /* ---- prediction over a relation (integer evaluator shared with the checker: pd0_rel_step) ---- */ |
| 98 | void pd0_learner_rollout(const pd0_rel *rel, const int64_t *init, const pd0_step *steps, uint32_t n, int64_t *out) |
| 99 | { |
| 100 | int64_t st[PD0_MAX_VARS], nx[PD0_MAX_VARS]; uint8_t no = (uint8_t)(rel->n_vars - rel->n_latent); |
| 101 | memset(st, 0, sizeof st); for (int j = 0; j < no; j++) st[j] = init[j]; |
| 102 | for (uint32_t s = 0; s < n; s++) { pd0_rel_step(rel, st, steps[s].channel, steps[s].value, nx); |
| 103 | for (int j = 0; j < rel->n_vars; j++) { if (nx[j] > PD0L_ROLL_CLAMP) nx[j] = PD0L_ROLL_CLAMP; if (nx[j] < -PD0L_ROLL_CLAMP) nx[j] = -PD0L_ROLL_CLAMP; } /* v2: clamp so a diverging model cannot overflow */ |
| 104 | for (int j = 0; j < no; j++) out[s * no + j] = nx[j]; memcpy(st, nx, sizeof st); } |
| 105 | } |
| 106 | |
| 107 | typedef struct { double se[PD0_MAX_OBS], s[PD0_MAX_OBS], ss[PD0_MAX_OBS]; uint32_t n; } acc; |
| 108 | static void acc_add(acc *a, const int64_t *p, const int64_t *t, uint8_t no) { for (int j = 0; j < no; j++) { double e = (double)(p[j] - t[j]) / 1e6, v = (double)t[j] / 1e6; a->se[j] += e * e; a->s[j] += v; a->ss[j] += v * v; } a->n++; } |
| 109 | static int64_t acc_nrmse(const acc *a, uint8_t no) |
| 110 | { |
| 111 | double w = 0; if (!a->n) return 0; |
| 112 | for (int j = 0; j < no; j++) { double rmse = sqrt(a->se[j] / a->n), m = a->s[j] / a->n, var = a->ss[j] / a->n - m * m, sd = var > 0 ? sqrt(var) : 0, v = sd > 1e-9 ? rmse / sd : rmse; if (v > w) w = v; } |
| 113 | return w > 9e12 ? INT64_MAX : (int64_t)(w * 1e6); |
| 114 | } |
| 115 | /* one-step NRMSE on the records of one tag; latent carried along each episode (as the checker's T3 does) */ |
| 116 | static int64_t onestep_eval(const pd0_learner *L, const pd0_rel *rel, uint8_t tag, double *lag1) |
| 117 | { |
| 118 | uint8_t no = L->d.n_obs; acc a; memset(&a, 0, sizeof a); int64_t st[PD0_MAX_VARS], nx[PD0_MAX_VARS]; memset(st, 0, sizeof st); |
| 119 | double num[PD0_MAX_OBS] = { 0 }, den[PD0_MAX_OBS] = { 0 }, prev[PD0_MAX_OBS] = { 0 }; int have_prev = 0; |
| 120 | for (uint32_t i = L->lo; i < L->hi; i++) { const trans *t = &L->t[i]; if (t->tag != tag) continue; |
| 121 | if (t->is_reset) { memset(st, 0, sizeof st); have_prev = 0; continue; } |
| 122 | for (int v = 0; v < no; v++) st[v] = t->before[v]; |
| 123 | pd0_rel_step(rel, st, t->chan, t->value, nx); acc_add(&a, nx, t->after, no); |
| 124 | for (int v = 0; v < no; v++) { double res = (double)(t->after[v] - nx[v]) / 1e6; if (have_prev) num[v] += res * prev[v]; den[v] += res * res; prev[v] = res; } |
| 125 | have_prev = 1; memcpy(st, nx, sizeof st); } |
| 126 | if (lag1) for (int v = 0; v < no; v++) lag1[v] = den[v] > 0 ? num[v] / den[v] : 0; |
| 127 | return acc_nrmse(&a, no); |
| 128 | } |
| 129 | int64_t pd0_learner_onestep_nrmse(const pd0_learner *L, const pd0_rel *rel, uint8_t tag) { return onestep_eval(L, rel, tag, NULL); } |
| 130 | |
| 131 | /* ---- least squares machinery ---- */ |
| 132 | static double mono(const double *x, const uint8_t *e, unsigned ni) { double v = 1; for (unsigned i = 0; i < ni; i++) for (uint8_t k = 0; k < e[i]; k++) v *= x[i]; return v; } |
| 133 | static int solve(double *A, double *b, unsigned n) |
| 134 | { |
| 135 | for (unsigned i = 0; i < n; i++) { unsigned p = i; for (unsigned r = i + 1; r < n; r++) if (fabs(A[r * n + i]) > fabs(A[p * n + i])) p = r; |
| 136 | if (fabs(A[p * n + i]) < 1e-14) return -1; |
| 137 | if (p != i) { for (unsigned k = 0; k < n; k++) { double t = A[i * n + k]; A[i * n + k] = A[p * n + k]; A[p * n + k] = t; } double t = b[i]; b[i] = b[p]; b[p] = t; } |
| 138 | for (unsigned r = i + 1; r < n; r++) { double f = A[r * n + i] / A[i * n + i]; for (unsigned k = i; k < n; k++) A[r * n + k] -= f * A[i * n + k]; b[r] -= f * b[i]; } } |
| 139 | for (int i = (int)n - 1; i >= 0; i--) { double s = b[i]; for (unsigned k = (unsigned)i + 1; k < n; k++) s -= A[i * n + k] * b[k]; b[i] = s / A[i * n + i]; } |
| 140 | return 0; |
| 141 | } |
| 142 | typedef struct { const double *X; const double *y; uint32_t n; unsigned nl; } design; |
| 143 | /* fit the subset sel[0..m) by normal equations; returns RSS (INFINITY if singular) and coef */ |
| 144 | static double fit_subset(const design *D, const unsigned *sel, unsigned m, double *coef) |
| 145 | { |
| 146 | double A[PD0L_MAX_SEL * PD0L_MAX_SEL] = { 0 }, b[PD0L_MAX_SEL] = { 0 }; |
| 147 | for (uint32_t i = 0; i < D->n; i++) for (unsigned p = 0; p < m; p++) { double xp = D->X[i * D->nl + sel[p]]; b[p] += xp * D->y[i]; for (unsigned q = 0; q < m; q++) A[p * m + q] += xp * D->X[i * D->nl + sel[q]]; } |
| 148 | for (unsigned p = 0; p < m; p++) A[p * m + p] += 1e-12; |
| 149 | if (m && solve(A, b, m)) return INFINITY; |
| 150 | double rss = 0; for (uint32_t i = 0; i < D->n; i++) { double pr = 0; for (unsigned p = 0; p < m; p++) pr += b[p] * D->X[i * D->nl + sel[p]]; rss += (pr - D->y[i]) * (pr - D->y[i]); } |
| 151 | memcpy(coef, b, sizeof(double) * m); return rss; |
| 152 | } |
| 153 | /* description-length score in bits: residual code length (n * log2 of the rmse in micro units, |
| 154 | * floor 1 micro) plus the spec 6.2 description bits of the terms */ |
| 155 | static double term_bits(unsigned ni) { return 8.0 * ni + 24.0; } |
| 156 | static double resid_bits(double rss, uint32_t n) { double rmse_micro = n ? sqrt(rss / n) * 1e6 : 0; if (rmse_micro < 1) rmse_micro = 1; return n * log2(rmse_micro); } |
| 157 | /* v2: 20-step rollouts of rel from the reset observation of every SELECT episode; fills the NRMSE (same normalisation as the |
| 158 | * one-step figure), the residual code length, and the number of rollout steps scored. Latent starts at 0 (pd0_learner_rollout). */ |
| 159 | static int64_t roll_eval(const pd0_learner *L, const pd0_rel *rel, double *bits, uint32_t *n_scored) |
| 160 | { |
| 161 | uint8_t no = L->d.n_obs; acc a; memset(&a, 0, sizeof a); double se[PD0_MAX_OBS] = { 0 }; |
| 162 | pd0_step steps[PD0L_ROLL_H]; int64_t truth[PD0L_ROLL_H][PD0_MAX_OBS], out[PD0L_ROLL_H * PD0_MAX_OBS], init[PD0_MAX_OBS]; uint32_t ns = 0; int open = 0; |
| 163 | for (uint32_t i = L->lo; i <= L->hi; i++) { |
| 164 | const trans *t = i < L->hi ? &L->t[i] : NULL; |
| 165 | if (t && t->tag != TAG_SELECT) continue; |
| 166 | if (!t || t->is_reset) { /* close the open episode */ |
| 167 | if (open && ns) { pd0_learner_rollout(rel, init, steps, ns, out); |
| 168 | for (uint32_t s = 0; s < ns; s++) { acc_add(&a, &out[s * no], truth[s], no); for (int v = 0; v < no; v++) { double e = (double)(out[s * no + v] - truth[s][v]) / 1e6; se[v] += e * e; } } } |
| 169 | open = 0; ns = 0; if (!t) break; |
| 170 | memcpy(init, t->after, sizeof init); open = 1; continue; } |
| 171 | if (open && ns < PD0L_ROLL_H) { steps[ns].channel = t->chan; steps[ns].value = t->value; memcpy(truth[ns], t->after, sizeof truth[ns]); ns++; } |
| 172 | } |
| 173 | double rb = 0; for (int v = 0; v < no; v++) rb += resid_bits(se[v], a.n); |
| 174 | if (bits) *bits = rb; if (n_scored) *n_scored = a.n; |
| 175 | return acc_nrmse(&a, no); |
| 176 | } |
| 177 | |
| 178 | typedef struct { unsigned sel[PD0L_MAX_SEL]; unsigned m; double coef[PD0L_MAX_SEL]; double rss, mdl; } eqfit; |
| 179 | |
| 180 | /* forward selection with backward pruning for one target; fills best (MDL-optimal) and alt (the |
| 181 | * runner-up subset: one term fewer if it exists, else one term more). deterministic order. */ |
| 182 | static void select_terms(const design *D, unsigned ni, unsigned max_terms, eqfit *best, eqfit *alt) |
| 183 | { |
| 184 | eqfit path[PD0L_MAX_SEL + 1]; memset(path, 0, sizeof path); |
| 185 | path[0].m = 0; path[0].rss = fit_subset(D, path[0].sel, 0, path[0].coef); path[0].mdl = resid_bits(path[0].rss, D->n); |
| 186 | unsigned steps = 0; |
| 187 | for (unsigned round = 1; round <= max_terms; round++) { |
| 188 | const eqfit *prev = &path[round - 1]; double best_rss = INFINITY; unsigned bk = D->nl; double bc[PD0L_MAX_SEL]; |
| 189 | for (unsigned k = 0; k < D->nl; k++) { int used = 0; for (unsigned s = 0; s < prev->m; s++) if (prev->sel[s] == k) used = 1; if (used) continue; |
| 190 | unsigned cand[PD0L_MAX_SEL]; memcpy(cand, prev->sel, sizeof(unsigned) * prev->m); cand[prev->m] = k; double c[PD0L_MAX_SEL]; |
| 191 | double rss = fit_subset(D, cand, prev->m + 1, c); |
| 192 | if (rss < best_rss * (1 - 1e-12)) { best_rss = rss; bk = k; memcpy(bc, c, sizeof c); } } |
| 193 | if (bk == D->nl) break; |
| 194 | eqfit *e = &path[round]; *e = *prev; e->sel[e->m++] = bk; memcpy(e->coef, bc, sizeof bc); e->rss = best_rss; e->mdl = resid_bits(best_rss, D->n) + term_bits(ni) * e->m; steps = round; |
| 195 | } |
| 196 | unsigned bi = 0; for (unsigned r = 1; r <= steps; r++) if (path[r].mdl < path[bi].mdl - 1e-9) bi = r; |
| 197 | eqfit b = path[bi]; |
| 198 | /* backward pruning: drop any term whose removal does not worsen MDL */ |
| 199 | int changed = 1; |
| 200 | while (changed && b.m > 0) { changed = 0; |
| 201 | for (unsigned drop = 0; drop < b.m; drop++) { eqfit c = b; for (unsigned s = drop; s + 1 < c.m; s++) c.sel[s] = c.sel[s + 1]; c.m--; |
| 202 | c.rss = fit_subset(D, c.sel, c.m, c.coef); c.mdl = resid_bits(c.rss, D->n) + term_bits(ni) * c.m; |
| 203 | if (c.mdl <= b.mdl + 1e-9) { b = c; changed = 1; break; } } } |
| 204 | *best = b; |
| 205 | /* runner-up: one fewer (weakest by refit) if possible, else one more from the forward path */ |
| 206 | if (b.m > 0) { eqfit bestdrop; bestdrop.mdl = INFINITY; bestdrop.m = 0; |
| 207 | for (unsigned drop = 0; drop < b.m; drop++) { eqfit c = b; for (unsigned s = drop; s + 1 < c.m; s++) c.sel[s] = c.sel[s + 1]; c.m--; c.rss = fit_subset(D, c.sel, c.m, c.coef); c.mdl = resid_bits(c.rss, D->n) + term_bits(ni) * c.m; if (c.mdl < bestdrop.mdl) bestdrop = c; } |
| 208 | *alt = bestdrop; } |
| 209 | else if (steps >= 1) *alt = path[1]; |
| 210 | else *alt = b; |
| 211 | } |
| 212 | |
| 213 | static void quantise(const pd0_learner *L, const eqfit *f, uint8_t target, pd0_eq *q) |
| 214 | { |
| 215 | memset(q, 0, sizeof *q); q->target = target; unsigned m = 0; |
| 216 | for (unsigned s = 0; s < f->m; s++) { int64_t c = (int64_t)llround(f->coef[s] * 1e6); if (c == 0) continue; q->coef[m] = c; memcpy(q->expo[m], L->lib[f->sel[s]], L->ni); m++; } |
| 217 | q->n_terms = (uint16_t)m; |
| 218 | } |
| 219 | static void finish_candidate(const pd0_learner *L, pd0l_candidate *c) |
| 220 | { |
| 221 | c->rel.description_bits = pd0_rel_bits(&c->rel); c->bits = c->rel.description_bits; c->size = pd0_rel_size(&c->rel); |
| 222 | c->fit_nrmse_micro = onestep_eval(L, &c->rel, TAG_FIT, c->lag1_autocorr); |
| 223 | c->select_nrmse_micro = onestep_eval(L, &c->rel, TAG_SELECT, NULL); |
| 224 | /* MDL on SELECT with the integer evaluator: residual bits per variable + description bits */ |
| 225 | uint8_t no = L->d.n_obs; double rb = 0; uint32_t n = 0; double se[PD0_MAX_OBS] = { 0 }; int64_t st[PD0_MAX_VARS], nx[PD0_MAX_VARS]; memset(st, 0, sizeof st); |
| 226 | for (uint32_t i = L->lo; i < L->hi; i++) { const trans *t = &L->t[i]; if (t->tag != TAG_SELECT) continue; if (t->is_reset) { memset(st, 0, sizeof st); continue; } |
| 227 | for (int v = 0; v < no; v++) st[v] = t->before[v]; |
| 228 | pd0_rel_step(&c->rel, st, t->chan, t->value, nx); |
| 229 | for (int v = 0; v < no; v++) { double e = (double)(t->after[v] - nx[v]) / 1e6; se[v] += e * e; } n++; memcpy(st, nx, sizeof st); } |
| 230 | for (int v = 0; v < no; v++) rb += resid_bits(se[v], n); |
| 231 | c->mdl_bits = rb + c->bits; |
| 232 | /* v2: multi-step consistency on the same SELECT episodes: ranking score and hidden-state rollout rule */ |
| 233 | uint32_t nroll = 0; c->select_roll_nrmse_micro = roll_eval(L, &c->rel, &c->roll_bits, &nroll); c->rank_bits = c->mdl_bits + c->roll_bits; |
| 234 | int64_t one = c->select_nrmse_micro > 1000 ? c->select_nrmse_micro : 1000; |
| 235 | c->hidden_by_rollout = !c->is_null && nroll > 0 && c->select_roll_nrmse_micro > PD0L_ROLL_FLAG_ABS && c->select_roll_nrmse_micro > PD0L_ROLL_FLAG_RATIO * one; |
| 236 | c->hidden_state_suspected = c->hidden_by_rollout; for (int v = 0; v < no; v++) if (fabs(c->lag1_autocorr[v]) > 0.3 && c->fit_nrmse_micro > 5000) c->hidden_state_suspected = 1; |
| 237 | } |
| 238 | static int cand_cmp(const void *a, const void *b) { const pd0l_candidate *x = a, *y = b; if (x->rank_bits < y->rank_bits) return -1; if (x->rank_bits > y->rank_bits) return 1; return (int)x->size - (int)y->size; } |
| 239 | static int same_structure(const pd0_rel *a, const pd0_rel *b) { return pd0_rel_size(a) == pd0_rel_size(b) && pd0_rel_bits(a) == pd0_rel_bits(b) && memcmp(a->eq, b->eq, sizeof a->eq) == 0; } |
| 240 | |
| 241 | /* v2: the injected prior is a candidate like any other: scored on the same FIT/SELECT records, ranked by rank_bits. If every slot is |
| 242 | * taken it replaces the worst-ranked non-null fitted candidate, so a prior can never push the null out. */ |
| 243 | void pd0_learner_set_prior(pd0_learner *L, const pd0_rel *rel) { if (rel) { L->prior = *rel; L->has_prior = 1; } else L->has_prior = 0; } |
| 244 | static void add_extra(pd0_learner *L, const pd0_rel *rel, int is_prior, int is_old) |
| 245 | { |
| 246 | |
| 247 | pd0l_candidate p; memset(&p, 0, sizeof p); p.rel = *rel; p.is_prior = is_prior; p.is_old = is_old; finish_candidate(L, &p); |
| 248 | for (int k = 0; k < L->ncand; k++) if (same_structure(&L->cand[k].rel, &p.rel)) { L->cand[k].is_prior |= is_prior; L->cand[k].is_old |= is_old; return; } |
| 249 | if (L->ncand < PD0L_MAX_CAND) { L->cand[L->ncand++] = p; return; } |
| 250 | qsort(L->cand, (size_t)L->ncand, sizeof L->cand[0], cand_cmp); |
| 251 | for (int k = L->ncand - 1; k > 0; k--) if (!L->cand[k].is_null) { L->cand[k] = p; return; } |
| 252 | } |
| 253 | |
| 254 | static void add_prior(pd0_learner *L) { if (L->has_prior) add_extra(L, &L->prior, 1, 0); if (L->has_old) add_extra(L, &L->old, 0, 1); } |
| 255 | static int fit_core(pd0_learner *L) |
| 256 | { |
| 257 | uint8_t no = L->d.n_obs; unsigned ni = L->ni, nl = L->nl; L->ncand = 0; |
| 258 | uint32_t n = 0; for (uint32_t i = L->lo; i < L->hi; i++) if (L->t[i].tag == TAG_FIT && !L->t[i].is_reset) n++; |
| 259 | pd0l_candidate *nullc = &L->cand[L->ncand++]; memset(nullc, 0, sizeof *nullc); nullc->is_null = 1; |
| 260 | nullc->rel.n_vars = no; nullc->rel.n_channels = L->d.n_channels; nullc->rel.n_equations = 0; finish_candidate(L, nullc); |
| 261 | if (n < 8) { add_prior(L); qsort(L->cand, (size_t)L->ncand, sizeof L->cand[0], cand_cmp); return L->ncand; } |
| 262 | double *X = malloc(sizeof(double) * n * nl), *Y = malloc(sizeof(double) * n * no); if (!X || !Y) { free(X); free(Y); return L->ncand; } |
| 263 | uint32_t r = 0; |
| 264 | for (uint32_t i = L->lo; i < L->hi; i++) { const trans *t = &L->t[i]; if (t->tag != TAG_FIT || t->is_reset) continue; |
| 265 | double x[PD0_MAX_VARS + PD0_MAX_CHAN]; for (int j = 0; j < no; j++) x[j] = (double)t->before[j] / 1e6; for (int c = 0; c < L->d.n_channels; c++) x[no + c] = t->chan == c ? (double)t->value / 1e6 : 0; |
| 266 | for (unsigned k = 0; k < nl; k++) X[r * nl + k] = mono(x, L->lib[k], ni); |
| 267 | for (int j = 0; j < no; j++) Y[r * no + j] = (double)(t->after[j] - t->before[j]) / 1e6; |
| 268 | r++; } |
| 269 | double *y = malloc(sizeof(double) * n); eqfit best[PD0_MAX_OBS], alt[PD0_MAX_OBS]; |
| 270 | for (int tg = 0; tg < no; tg++) { for (uint32_t i = 0; i < n; i++) y[i] = Y[i * no + tg]; design D = { X, y, n, nl }; select_terms(&D, ni, PD0L_MAX_SEL, &best[tg], &alt[tg]); } |
| 271 | /* candidate 1: MDL-best per target; alternatives: swap one target's equation for its runner-up */ |
| 272 | pd0l_candidate tmp[PD0L_MAX_CAND]; int nt = 0; |
| 273 | for (int which = -1; which < (int)no && nt < PD0L_MAX_CAND - 1; which++) { |
| 274 | pd0l_candidate *c = &tmp[nt]; memset(c, 0, sizeof *c); c->rel.n_vars = no; c->rel.n_channels = L->d.n_channels; unsigned ne = 0; |
| 275 | for (int tg = 0; tg < no; tg++) { const eqfit *f = (tg == which) ? &alt[tg] : &best[tg]; pd0_eq q; quantise(L, f, (uint8_t)tg, &q); if (q.n_terms) c->rel.eq[ne++] = q; } |
| 276 | c->rel.n_equations = (uint8_t)ne; finish_candidate(L, c); |
| 277 | int dup = 0; for (int k = 0; k < nt; k++) if (same_structure(&tmp[k].rel, &c->rel)) dup = 1; if (!dup && (ne || which < 0)) nt++; } |
| 278 | for (int k = 0; k < nt && L->ncand < PD0L_MAX_CAND; k++) if (!same_structure(&tmp[k].rel, &nullc->rel)) L->cand[L->ncand++] = tmp[k]; |
| 279 | add_prior(L); |
| 280 | qsort(L->cand, (size_t)L->ncand, sizeof L->cand[0], cand_cmp); |
| 281 | free(X); free(Y); free(y); |
| 282 | return L->ncand; |
| 283 | } |
| 284 | |
| 285 | /* ---- v2.1: change detection and bounded forgetting (learner side only: sees nothing but its own FIT/SELECT records) ---- |
| 286 | * Reference model: fit_core over the first PD0L_DET_BASE_EP episodes (null rival included). Its one-step residual scale per |
| 287 | * observed variable is measured on the SELECT episodes of that block. Every later episode i gets z_i = mean over its steps and |
| 288 | * variables of (residual / scale)^2 (about 1 while nothing changes). CUSUM: S <- max(0, S + min(ln z_i, CLIP) - SLACK); |
| 289 | * alarm when S > H. The estimated change episode is the first episode of the run that ended in the alarm with a clearly bad z. */ |
| 290 | void pd0_learner_set_forgetting(pd0_learner *L, int on) { L->forget = on; } |
| 291 | const pd0l_detect *pd0_learner_detection(const pd0_learner *L) { return &L->det; } |
| 292 | static void ref_residuals(const pd0_learner *L, const pd0_rel *ref, uint32_t from, uint32_t to, double *se, uint32_t *cnt) |
| 293 | { |
| 294 | uint8_t no = L->d.n_obs; int64_t st[PD0_MAX_VARS], nx[PD0_MAX_VARS]; memset(st, 0, sizeof st); *cnt = 0; for (int v = 0; v < no; v++) se[v] = 0; |
| 295 | for (uint32_t i = from; i < to; i++) { const trans *t = &L->t[i]; if (t->is_reset) { memset(st, 0, sizeof st); continue; } |
| 296 | for (int v = 0; v < no; v++) st[v] = t->before[v]; |
| 297 | pd0_rel_step(ref, st, t->chan, t->value, nx); |
| 298 | for (int v = 0; v < no; v++) { double e = (double)(t->after[v] - nx[v]) / 1e6; se[v] += e * e; } (*cnt)++; memcpy(st, nx, sizeof st); } |
| 299 | } |
| 300 | static void detect_change(pd0_learner *L) |
| 301 | { |
| 302 | memset(&L->det, 0, sizeof L->det); L->det.enabled = 1; L->det.n_ep = L->n_ep; L->lo = 0; L->hi = L->nt; L->has_old = 0; |
| 303 | uint32_t B = PD0L_DET_BASE_EP; if (L->n_ep < B + 2) return; |
| 304 | uint32_t *es = malloc(sizeof *es * (L->n_ep + 1)); if (!es) return; uint32_t ne = 0; |
| 305 | for (uint32_t i = 0; i < L->nt; i++) if (L->t[i].is_reset && ne < L->n_ep) es[ne++] = i; |
| 306 | if (ne < B + 2) { free(es); return; } es[ne] = L->nt; |
| 307 | /* reference model on the reference block */ |
| 308 | pd0l_candidate saved[PD0L_MAX_CAND]; int nsaved = L->ncand, hp = L->has_prior; memcpy(saved, L->cand, sizeof saved); |
| 309 | L->has_prior = 0; L->hi = es[B]; fit_core(L); pd0_rel ref = L->cand[0].rel; |
| 310 | L->has_prior = hp; memcpy(L->cand, saved, sizeof saved); L->ncand = nsaved; L->hi = L->nt; |
| 311 | /* residual scale on the block's SELECT episodes */ |
| 312 | uint8_t no = L->d.n_obs; double s2[PD0_MAX_OBS] = { 0 }; uint32_t ns = 0; |
| 313 | for (uint32_t e = 0; e < B; e++) if (L->t[es[e]].tag == TAG_SELECT) { double se[PD0_MAX_OBS]; uint32_t c; ref_residuals(L, &ref, es[e], es[e + 1], se, &c); for (int v = 0; v < no; v++) s2[v] += se[v]; ns += c; } |
| 314 | if (!ns) { free(es); return; } |
| 315 | for (int v = 0; v < no; v++) { s2[v] /= ns; if (s2[v] < PD0L_DET_FLOOR * PD0L_DET_FLOOR) s2[v] = PD0L_DET_FLOOR * PD0L_DET_FLOOR; } |
| 316 | L->det.base_ep = B; |
| 317 | double S = 0, smax = 0; uint32_t run = B; int have_run = 0; |
| 318 | for (uint32_t e = B; e < ne && !L->det.alarm; e++) { double se[PD0_MAX_OBS]; uint32_t c; ref_residuals(L, &ref, es[e], es[e + 1], se, &c); if (c < 5) continue; |
| 319 | double z = 0; for (int v = 0; v < no; v++) z += se[v] / s2[v]; z /= (double)c * no; |
| 320 | double lz = z > 1e-12 ? log(z) : log(1e-12), x = (lz > PD0L_DET_CLIP ? PD0L_DET_CLIP : lz) - PD0L_DET_SLACK; |
| 321 | if (S <= 0 && x > 0) { run = e; have_run = 1; } S += x; if (S < 0) S = 0; if (S > smax) smax = S; |
| 322 | if (S > PD0L_DET_H && have_run) { L->det.alarm = 1; L->det.alarm_ep = e; L->det.change_ep = run; |
| 323 | for (uint32_t f = run; f <= e; f++) { double se2[PD0_MAX_OBS]; uint32_t c2; ref_residuals(L, &ref, es[f], es[f + 1], se2, &c2); double zz = 0; if (c2) { for (int v = 0; v < no; v++) zz += se2[v] / s2[v]; zz /= (double)c2 * no; } |
| 324 | if (c2 >= 5 && zz > 5.0) { L->det.change_ep = f; break; } } } } |
| 325 | L->det.cusum_max = smax; |
| 326 | if (L->det.alarm) { /* keep the model held before the change as a rival, then forget the older episodes */ |
| 327 | fit_core(L); const pd0l_candidate *b = &L->cand[0]; |
| 328 | if (!b->is_null) { L->old = b->rel; L->has_old = 1; L->det.old_kept = 1; } |
| 329 | L->lo = es[L->det.change_ep]; } |
| 330 | free(es); |
| 331 | } |
| 332 | int pd0_learner_fit(pd0_learner *L) |
| 333 | { |
| 334 | if (L->forget) detect_change(L); else { L->lo = 0; L->hi = L->nt; L->has_old = 0; } |
| 335 | return fit_core(L); |
| 336 | } |
| 337 | int pd0_learner_n_candidates(const pd0_learner *L) { return L->ncand; } |
| 338 | const pd0l_candidate *pd0_learner_candidate(const pd0_learner *L, int i) { return (i >= 0 && i < L->ncand) ? &L->cand[i] : NULL; } |
| 339 | |
| 340 | /* ---- correlation evidence (spec T2) ---- */ |
| 341 | static double pearson(const double *x, const double *y, uint32_t n) |
| 342 | { |
| 343 | double mx = 0, my = 0; for (uint32_t i = 0; i < n; i++) { mx += x[i]; my += y[i]; } mx /= n; my /= n; |
| 344 | double sxy = 0, sxx = 0, syy = 0; for (uint32_t i = 0; i < n; i++) { sxy += (x[i] - mx) * (y[i] - my); sxx += (x[i] - mx) * (x[i] - mx); syy += (y[i] - my) * (y[i] - my); } |
| 345 | return (sxx > 0 && syy > 0) ? sxy / sqrt(sxx * syy) : 0; |
| 346 | } |
| 347 | int pd0_learner_correlation(const pd0_learner *L, uint64_t shuffle_seed, uint32_t n_shuffles, pd0_corr *out) |
| 348 | { |
| 349 | uint8_t no = L->d.n_obs; uint32_t n = 0; for (uint32_t i = 0; i < L->nt; i++) if (!L->t[i].is_reset) n++; |
| 350 | if (n < 100) return -1; |
| 351 | double *x = malloc(sizeof(double) * n), *y = malloc(sizeof(double) * n), *yp = malloc(sizeof(double) * n); if (!x || !y || !yp) { free(x); free(y); free(yp); return -1; } |
| 352 | double best_r = 0; int ba = -1, bb = -1; uint32_t n_pairs = (uint32_t)no * no; |
| 353 | for (int a = -1; a < (int)no; a++) for (int b = 0; b < no; b++) { uint32_t k = 0; if (a == b) continue; /* spec rev 5: no self pairs */ |
| 354 | for (uint32_t i = 0; i < L->nt; i++) { const trans *t = &L->t[i]; if (t->is_reset) continue; x[k] = a < 0 ? (double)t->value : (double)t->before[a]; y[k] = (double)(t->after[b] - t->before[b]); k++; } |
| 355 | double r = pearson(x, y, n); if (fabs(r) > fabs(best_r)) { best_r = r; ba = a; bb = b; } } |
| 356 | if (bb < 0) { free(x); free(y); free(yp); return -1; } |
| 357 | uint32_t k = 0; for (uint32_t i = 0; i < L->nt; i++) { const trans *t = &L->t[i]; if (t->is_reset) continue; x[k] = ba < 0 ? (double)t->value : (double)t->before[ba]; y[k] = (double)(t->after[bb] - t->before[bb]); k++; } |
| 358 | pd0_rng g; pd0_rng_stream(&g, shuffle_seed, "perm"); uint32_t hits = 0; double r0 = fabs(best_r); |
| 359 | for (uint32_t s = 0; s < n_shuffles; s++) { memcpy(yp, y, sizeof(double) * n); for (uint32_t i = n - 1; i > 0; i--) { uint32_t j = (uint32_t)(pd0_rng_next(&g) % (i + 1)); double t = yp[i]; yp[i] = yp[j]; yp[j] = t; } if (fabs(pearson(x, yp, n)) >= r0) hits++; } |
| 360 | double p = (hits + 1.0) / (n_shuffles + 1.0) * n_pairs; if (p > 1) p = 1; |
| 361 | memset(out, 0, sizeof *out); out->var_a = ba < 0 ? PD0_CHAN_NONE : (uint8_t)ba; out->var_b = (uint8_t)bb; out->n = n; out->r_micro = (int64_t)(best_r * 1e6); out->p_micro = (int64_t)(p * 1e6); out->n_pairs = n_pairs; out->n_shuffles = n_shuffles; out->shuffle_seed = shuffle_seed; |
| 362 | free(x); free(y); free(yp); return 0; |
| 363 | } |
| 364 | |
| 365 | /* ---- planner stand-in (spec section 8 selection rule, without local refinement) ---- */ |
| 366 | int64_t pd0_learner_propose(const pd0_learner *L, const pd0_rel *hyps, int n_hyp, uint64_t planner_seed, uint32_t n_random, |
| 367 | const uint8_t (*forbidden)[PD0_HASH], uint32_t n_forbidden, pd0_exp *out) |
| 368 | { |
| 369 | uint8_t no = L->d.n_obs; uint32_t n = PD0_MAX_STEPS; if (n_hyp < 2 || n_hyp > PD0_MAX_HYP) return -1; |
| 370 | /* pooled residual sd of the hypotheses on SELECT (in units); floor 1e-4 */ |
| 371 | double r = 0; int cnt = 0; for (int h = 0; h < n_hyp; h++) { int64_t e = pd0_learner_onestep_nrmse(L, &hyps[h], TAG_SELECT); if (e > 0 && e < INT64_MAX) { r += (double)e / 1e6; cnt++; } } |
| 372 | r = cnt ? r / cnt : 0; if (r < 1e-4) r = 1e-4; |
| 373 | double bestD = -1; int64_t best_cost = INT64_MAX; pd0_exp best; memset(&best, 0, sizeof best); uint8_t best_hash[PD0_HASH] = { 0 }; |
| 374 | int64_t pred[PD0_MAX_HYP][PD0_MAX_STEPS * PD0_MAX_OBS]; |
| 375 | for (uint32_t idx = 0; idx < n_random; idx++) { |
| 376 | pd0_exp e; memset(&e, 0, sizeof e); e.n_obs = no; e.n_hyp = (uint8_t)n_hyp; e.n_steps = (uint8_t)n; |
| 377 | pd0_learner_random_schedule(&L->d, planner_seed, "plan", idx, e.reset, e.steps, n); |
| 378 | uint8_t h[PD0_HASH]; pd0_schedule_hash(no, e.reset, (uint8_t)n, e.steps, h); int bad = 0; |
| 379 | for (uint32_t f = 0; f < n_forbidden; f++) if (!memcmp(h, forbidden[f], PD0_HASH)) { bad = 1; break; } |
| 380 | if (bad) continue; |
| 381 | for (int hy = 0; hy < n_hyp; hy++) pd0_learner_rollout(&hyps[hy], e.reset, e.steps, n, pred[hy]); |
| 382 | /* safety: the candidate's own prediction must stay well inside the world box */ |
| 383 | for (uint32_t s = 0; s < n && !bad; s++) for (int j = 0; j < no; j++) if (llabs(pred[0][s * no + j]) > 8000000) { bad = 1; break; } |
| 384 | if (bad) continue; |
| 385 | double D = 0; for (int a = 0; a < n_hyp; a++) for (int b = a + 1; b < n_hyp; b++) for (uint32_t s = 0; s < n; s++) for (int j = 0; j < no; j++) { double d = fabs((double)(pred[a][s * no + j] - pred[b][s * no + j])) / 1e6 / r; if (d > D) D = d; } |
| 386 | int64_t cost = 0; for (uint32_t s = 0; s < n; s++) cost += llabs(e.steps[s].value); |
| 387 | int better = D > bestD + 1e-12 || (fabs(D - bestD) <= 1e-12 && (cost < best_cost || (cost == best_cost && memcmp(h, best_hash, PD0_HASH) < 0))); |
| 388 | if (better) { bestD = D; best_cost = cost; best = e; memcpy(best_hash, h, PD0_HASH); for (int hy = 0; hy < n_hyp; hy++) for (uint32_t s = 0; s < n; s++) for (int j = 0; j < no; j++) best.expected[hy][s][j] = pred[hy][s * no + j]; } |
| 389 | } |
| 390 | if (bestD < 3.0) return -1; /* NO_DISCRIMINATING_EXPERIMENT */ |
| 391 | best.divergence_micro = (int64_t)(bestD * 1e6); memcpy(best.schedule_hash, best_hash, PD0_HASH); *out = best; return best.divergence_micro; |
| 392 | } |
| 393 | |
| 394 | size_t pd0_learner_report(const pd0_learner *L, char *buf, size_t cap) |
| 395 | { |
| 396 | size_t n = 0; n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "{\"n_fit\":%u,\"n_select\":%u,\"candidates\":[", pd0_learner_n_transitions(L, TAG_FIT), pd0_learner_n_transitions(L, TAG_SELECT)); |
| 397 | for (int i = 0; i < L->ncand; i++) { const pd0l_candidate *c = &L->cand[i]; |
| 398 | n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "%s{\"rank\":%d,\"null\":%d,\"size\":%u,\"bits\":%u,\"fit_nrmse_micro\":%lld,\"select_nrmse_micro\":%lld,\"mdl_bits\":%.1f,\"hidden_state_suspected\":%d,\"select_roll_nrmse_micro\":%lld,\"rank_bits\":%.1f,\"prior\":%d,\"eq\":[", |
| 399 | i ? "," : "", i, c->is_null, c->size, c->bits, (long long)c->fit_nrmse_micro, (long long)c->select_nrmse_micro, c->mdl_bits, c->hidden_state_suspected, (long long)c->select_roll_nrmse_micro, c->rank_bits, c->is_prior); |
| 400 | for (int e = 0; e < c->rel.n_equations; e++) { const pd0_eq *q = &c->rel.eq[e]; n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "%s{\"target\":%u,\"terms\":[", e ? "," : "", q->target); |
| 401 | for (int t = 0; t < q->n_terms; t++) { n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "%s{\"coef\":%lld,\"expo\":[", t ? "," : "", (long long)q->coef[t]); |
| 402 | for (unsigned k = 0; k < (unsigned)(c->rel.n_vars + c->rel.n_channels); k++) n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "%s%u", k ? "," : "", q->expo[t][k]); |
| 403 | n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "]}"); } |
| 404 | n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "]}"); } |
| 405 | n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "]}"); } |
| 406 | n += (size_t)snprintf(buf + n, cap > n ? cap - n : 0, "]}"); |
| 407 | return n < cap ? n : cap - 1; |
| 408 | } |