Text Classification
syfox
decision-engine
decision-making
decision-model
structured-prediction
system-one
si-substrate
intent-classification
routing
abstention
uncertainty-quantification
selective-prediction
hebbian
energy-based-model
associative-memory
no-transformer
no-neural-network
no-pattern-matching
moderation
spam-detection
multilingual
Eval Results (legacy)
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- README.md+173-6
- build/libsyfox_core.so+2-2
- datasets/bench_hidden_summary.jsonAdded+14
- datasets/eval_summary_v400.jsonAdded+64
- datasets/novel_probes/RESULTS.json+42-38
- docs/ENGINE_PORT.md+67-2
- engine/CHANGELOG.mdAdded+1476
- engine/Makefile+38-6
- engine/core/bench.hpp+25-3
- engine/core/reason.hpp-409
- engine/core/roles.hpp+2-77
- engine/core/si_substrate.hpp+133-455
- engine/core/syfox.hpp+448-405
- engine/data/bank77_categories.jsonAdded+161
- engine/data/bank77_criteria.jsonAdded+84
- engine/data/handmade_probes.jsonlAdded+148
- engine/data/synonyms.txtAdded+32
- engine/docs/FIT_DECIDE_PARITY.mdAdded+175
- engine/src/syfox_cli.cpp+149-333
- engine/src/syfox_core.cpp+16
- engine/src/syfox_test.cpp+217
- engine/tools/ablation_suite.pyAdded+158
- engine/tools/assert_fit_decide_parity.pyAdded+89
- engine/tools/assert_route.pyAdded+16
- engine/tools/b77_ablation_compare.pyAdded+67
- engine/tools/b77_apply_policy.pyAdded+70
- engine/tools/b77_confusion_report.pyAdded+174
- engine/tools/b77_freq_cut.pyAdded+102
- engine/tools/b77_margin_sweep.pyAdded+116
- engine/tools/bank77_analysis.pyAdded+168
- engine/tools/bank77_hier.pyAdded+169
- engine/tools/bank77_prepare.pyAdded+224
- engine/tools/cal_diffusion_sweep.pyAdded+130
- engine/tools/check_omp_identity.pyAdded+15
- engine/tools/confidence_ablation.pyAdded+140
- engine/tools/corpus_pools.pyAdded+517
- engine/tools/flag_probe_experiment.pyAdded+148
- engine/tools/gen_corpus.pyAdded+214
- engine/tools/gen_paraphrases.pyAdded+195
- engine/tools/gen_variants.pyAdded+168
- engine/tools/giant_bench.pyAdded+209
- engine/tools/giant_prepare.pyAdded+555
- engine/tools/handmade_gate.pyAdded+135
- engine/tools/hf_fetch.pyAdded+125
- engine/tools/jev_bench.pyAdded+138
- engine/tools/reasoning_probes.pyAdded+201
- engine/tools/rebuild_router_criteria.pyAdded+144
- engine/tools/router_prepare.pyAdded+112
- engine/tools/router_routes.pyAdded+73
12*.bin filter=lfs diff=lfs merge=lfs -textmodel/*/substrate.bin filter=lfs diff=lfs merge=lfs -text123*.bin filter=lfs diff=lfs merge=lfs -textmodel/*/substrate.bin filter=lfs diff=lfs merge=lfs -textbuild/libsyfox_core.so filter=lfs diff=lfs merge=lfs -text
56 unmodified lines57585960616273 unmodified lines13613713813914014114214314414514614714814915015115215315456 unmodified linesround-robin domain interleaving. Full measured evaluation:[docs/EVALUATION.md](docs/EVALUATION.md).## Headline measured numbers (hidden splits, scored once)> **⚠ Measured with the v3.2.0 engine.** The core in this repo is now v3.9.1,73 unmodified lines## Files```engine/ C++ SI substrate core v3.9.1 (core/*.hpp, src/*.cpp) — builds with makeNOTE: refresh ../build/libsyfox_core.so after rebuilding, or thepython bridge will keep loading the stale core (ENGINE_PORT.md)server/ HTTP bridge (v3 API, CLI-equal flags incl. the v3.2 knobs)inference.py thin python wrapper (auto script routing)model/ giant-{latin,bengali,devanagari,cyrillic}/substrate.bin (v3.2-era, 16 domains)sst2/ agnews/ amazon/ NEW v3.9.1 fabrics, handcrafted-probe gatedb77-sem/ dedicated 77-way banking fabric (v3.2 semantic layer)router16/ two-stage physics router (router.json: anchors+models)datasets/ eval hidden splits, probes, schemas, MANIFEST (SHA-256),novel_probes/ (handcrafted admission probes + RESULTS.json),router16_router.json, zeroshot_v32_results.json, DATASETS.mddocs/ ENGINE_PORT.md (v3.9.1 port + caveats), EVALUATION.md,ARCHITECTURE.md, PROBING.md, ZEROSHOT.mdexamples/ JSON payloads + curl + python usageDockerfile HuggingFace Spaces (builds engine, serves on 7860)56 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122273 unmodified lines29629729829930030130230330430530630730830931031131231331431531631731831932032156 unmodified linesround-robin domain interleaving. Full measured evaluation:[docs/EVALUATION.md](docs/EVALUATION.md).------## v4.0 — the affinity field readout (AFR)The engine could **retrieve** but never **measure**. Two defects, bothmeasured on the shipped fabrics:1. **The readout never read the fabric's own anchor affinity.** Every lessonbinds the state's tokens to the outcome anchor, so the fabric holds`w(u,c)` — "which intent did this word teach". The legacy readout onlysampled the field and let a capped diffusion carry the evidence, so oneconstant had to serve both precision and reach, and the measured optimumwas **per-domain** (tickets_en wanted 0.45, agnews/dbpedia wanted 0.02).2. **The readout had no null model.** A candidate's score was anunnormalised *sum* over its probe bag — for Banking77, 20 mined phrases(~60 token occurrences) mostly shared with other candidates, so sharedwords added a large common offset and the one discriminative word was oneterm out of sixty.v4.0 adds one channel, with **no training and no neural network**:```P(c|u) = w(u,c) / sum_{c' in C} w(u,c') posterior over the candidate setP0(c) = mass(c) / sum_{c'} mass(c') a priori share of the candidate setL(c) = sum_u E_u * [ P(c|u) - P0(c) ] the contrastscore(c) = (1-mix) * legacy(c)/max|legacy| + mix * L(c)/max|L|```A token that points at every candidate cancels against the null model; atoken that points at one candidate contributes strongly, positive for thatcandidate and negative for the rest. This is the **first-order resolvent ofthe propagation the settle simulates** — the same operator, read exactlyinstead of approximated by a capped and smeared diffusion. `mix = 0` (thedefault) is bit-identical to v3.9.1.v4.0 also fits **one temperature per distinct candidate count**: a 14-wayquestion's score spread is not a 2-way question's spread, and one scalarfitted across both left `polarity` at ECE 0.395 while `dbpedia` sat at 0.064in the same fit.### What changed in THIS repo**Seven of the nine fabrics are updated** — repaired where the lane decay hadkilled them, and re-calibrated under the new readout. The readout mode isrecorded in each fabric's `physics.json` (`"affinity_mix":0.3`), so thedeployed model decides under the readout its temperature was fitted for.| fabric | change | measured ||---|---|---|| `b77-sem` | lane repair + AFR + per-count temperature | hidden 3,080: **0.158 → 0.4800**, ECE **0.809 → 0.0460** || `router16` | lane repair + AFR | cal 12,593: **0.5060 → 0.5850**; handmade OOD 0.267 → **0.467** || `giant-latin` | lane repair + AFR | agnews **0.7520**, emotion **0.3930**, polarity **0.5960**, dbpedia **0.7970**, tickets_en **0.9570** || `giant-bengali` | AFR | hidden 540: **0.9260 → 1.0000**, ECE 0.0270 → **0.0000** || `giant-devanagari` | AFR | hidden 539: **0.9110 → 1.0000**, ECE 0.0180 → **0.0010** || `giant-cyrillic` | AFR | hidden 539: **0.9520 → 1.0000**, ECE 0.0170 → **0.0000** || `agnews` | AFR | novel probes: **0.5833 → 0.7500** (gate ≥ 0.40) || `sst2` | **unchanged** | novel probes 0.7500 (gate ≥ 0.65) || `amazon` | **unchanged** | novel probes 0.7000 (gate ≥ 0.65) |**Two fabrics are deliberately NOT updated.** `sst2` and `amazon` are thetwo-class fabrics, and the contrast is degenerate there: with twocandidates a single token points at one of them or the other, so onemis-pointed token dominates. Measured on their own admission probes, theAFR gives **sst2 0.5830** and **amazon 0.6000** — **both below their own0.65 admission gate**, so the shipped fabric would fail the gate thatexists to catch exactly this. They ship unchanged, with the legacy readout.That is the gate doing its job, and it is why the readout is applied perfabric rather than globally.The `tickets_en` number is the one to look at: the shared giant fabricscored 0.9040 before the lane repair and 0.4480 after it. With the affinityreadout the SAME repaired fabric scores **0.9570** — above the original.### Reproducing```bashcd engine && make all && make sync-so && cd ..python3 examples/smoke.py````engine/` is the v4.0 source (core/, src/, tools/) — the same tree as theGitHub repo, so the code and the weights that ship with it are the codethat was measured.## The three defects (found by re-testing on the v3.9.1 engine)### 1. The calibration was fitted under a different physics than the decision runsThe choice/score temperature is fitted on energies that come out of a settlepass, and those energies depend on the **whole decide-side composition** —the energy gain, the diffusion constant, the decay, the settle-pass cap. Inthis repo the banking and router fabrics were calibrated **without** thedecide-side energy gain while every `bench` and every `decide` call ran**with** it.Measured on the shipped `model/b77-sem` fabric and the 1,003-row cal splitthat ships with it — same engine, one flag apart:| calibration | fitted `T` | rows the fit saw | ECE before → after ||---|---:|---:|---:|| without the energy gain (**what shipped**) | **0.0037** | **556 of 2,006 (27.7%)** | 0.4567 → 0.4057 || with the energy gain (**what the bench runs**) | **0.3552** | 2,006 of 2,006 (100%) | 0.3183 → 0.3056 |The published `model/b77-sem/calibration.json` carried `T = 0.00472645`fitted over **211 rows**; `model/router16` carried `T = 0.00491756` over**160 rows**.A near-floor temperature saturates the softmax. The post-temperature top-2probability gap goes to ~0.93 on every row, which breaks three things atonce: the honest-defer gate (an absolute 0.05 margin) **can never fire** —the model never abstains, on any input, ever; every answer carries ~0.98confidence whether it is right or wrong; and the ECE reported by`calibrate` does not describe the ECE the bench measures.**Fix:** a fabric now carries the composition it was calibrated under(`physics.json`, next to `calibration.json`). `calibrate` records it;`decide`, `bench`, `demo` and `stats` apply it on load. `calibrate` also**refuses** to run when the fit would see less than half the question-rows(it names the cause and leaves the fabric untouched). The three shippedfabrics have been re-calibrated under the matched composition.### 2. The diffusion constant was never re-tuned for the dense fabrics`diffusion` is the fraction of retained energy that flows along the Hebbianlanes per settle pass. It is a config value, not an equation, and itsoptimum is a property of the fabric: 0.45 was validated on the small v2-erafabrics and is far off the optimum for a 217k-lane fabric. Measured on the**cal** split of the shipped banking fabric (selection never toucheshidden):| diffusion | accuracy (argmax) on cal ||---|---:|| 0.45 (shipped default) | 0.1316 || **0.02** | **0.4237** |**Fix:** the diffusion value is now a per-fabric property recorded in`physics.json`, chosen on the cal split(`tools/cal_diffusion_sweep.py`), not a global default.### 3. The headline table was measured against the wrong fabric, on the wrong engineThe bank77 row in the old table (`class acc 0.023`) was measured on the**shared** `model/giant-latin` fabric, not on the dedicated `model/b77-sem`fabric this repo ships and `router.json` routes bank77 to. It was alsomeasured with the v3.2.0 engine, which had no honesty gates: underv3.9.1 the same run defers **2,129 of 3,080 rows (69%)**, because thenewer engine refuses to answer a field that carries no candidate energy.Separately: the four `model/giant-*` fabrics were built by the **v3.1.2**engine and carry **no semantic field** (their `substrate.bin` has no `SEM4`tail), so the v3.2 semantic layer described below is **inert on them**. Noshipped fabric carries the `IDF5` tail either, so the v3.6 document-frequency weighting is inert everywhere.---## Headline measured numbers (hidden splits, scored once)> **⚠ Measured with the v3.2.0 engine.** The core in this repo is now v3.9.1,73 unmodified lines## Files```engine/ C++ SI substrate core v4.0 (core/*.hpp, src/*.cpp, tools/) — builds with makeNOTE: refresh ../build/libsyfox_core.so after rebuilding, or thepython bridge will keep loading the stale core (ENGINE_PORT.md)server/ HTTP bridge (v3 API, CLI-equal flags incl. the v3.2 knobs)inference.py thin python wrapper (auto script routing)model/ NINE fabrics, all carrying their recorded decide-sidecomposition in physics.json (diffusion, energy_norm, affinity_mix):giant-latin/ 16-domain shared fabric AFR, diffusion 0.45giant-bengali/ Bengali script fabric AFR, diffusion 0.45giant-devanagari/ Hindi script fabric AFR, diffusion 0.45giant-cyrillic/ Russian script fabric AFR, diffusion 0.45b77-sem/ dedicated 77-way banking AFR, diffusion 0.02router16/ two-stage physics router AFR, diffusion 0.45agnews/ handcrafted-probe gated AFR, diffusion 0.45sst2/ handcrafted-probe gated LEGACY readout (see v4.0)amazon/ handcrafted-probe gated LEGACY readout (see v4.0)datasets/ eval hidden splits, probes, schemas, MANIFEST (SHA-256),novel_probes/ (handcrafted admission probes + RESULTS.json),router16_router.json, zeroshot_v32_results.json, DATASETS.mddocs/ ENGINE_PORT.md (v4.0 port + caveats), EVALUATION.md,ARCHITECTURE.md, PROBING.md, ZEROSHOT.mdexamples/ JSON payloads + curl + python usageDockerfile HuggingFace Spaces (builds engine, serves on 7860)
123version https://git-lfs.github.com/spec/v1oid sha256:7ecb7c2ac7bc1d7f044f6daa0eb82af988013a7c64ec898ad3abaead3bb4995fsize 533848123version https://git-lfs.github.com/spec/v1oid sha256:75d062a5a7faca291b1d6f687ef91204c42e31b44aad156d388b59e0297c69e8size 419520
1234567891011121314[ { "domain": "bank77", "n": 3080, "router_acc": 0.5889610389610389, "class_acc": 0.15791316526610644, "e2e_acc": 0.0801948051948052, "deferred": 224, "secs": 65.7, "ms_per_row": 21.33, "qkey": "intent", "note": "" }]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "engine": "syfox 4.0.0 (v3.9.1 + v3.9.2 fit==decide composition + v3.9.3 lane repair + v4.0 affinity field readout)", "note": "every number measured in THIS repo against the SHIPPED fabrics and the SHIPPED splits; selection on cal, hidden scored once. The v4.0 rows are the fabrics as they ship here (each carries its recorded composition in physics.json).", "v400_affinity_field_readout": { "mechanism": "score(c) = (1-mix)*legacy(c)/max|legacy| + mix*L(c)/max|L|, L(c) = sum_u E_u*[P(c|u)-P0(c)], P(c|u)=w(u,c)/sum_c' w(u,c'), P0(c)=mass(c)/sum_c' mass(c')", "training": "none — every quantity was already learned by hebbian_lesson; O(|lit|*degree) per question; one CPU core; no neural network", "default": "mix = 0 (bit-identical to v3.9.1); seven of the nine fabrics here ship with affinity_mix = 0.3 recorded in physics.json", "also_in_v400": "one softmax temperature per distinct candidate count (the count is a property of the QUESTION): the shared giant fabric's single fitted temperature left polarity at ECE 0.395 while dbpedia sat at 0.064 in the SAME fit", "per_fabric": { "b77-sem": { "readout": "affinity_mix 0.3, diffusion 0.02", "cal_1003": {"legacy": 0.4340, "v400": 0.4560}, "hidden_3080_scored_once": {"legacy": 0.4660, "v400": 0.4800}, "ece_hidden": {"legacy": 0.2200, "v400": 0.0460}, "handmade_ood_68": {"legacy": 0.132, "v400": 0.191} }, "router16": { "readout": "affinity_mix 0.3, diffusion 0.45", "cal_12593": {"legacy": 0.5060, "v400": 0.5850}, "ece_cal": {"legacy": 0.0460, "v400": 0.0610}, "handmade_ood_15": {"legacy": 0.267, "v400": 0.467} }, "giant-latin": { "readout": "affinity_mix 0.3, diffusion 0.45", "per_domain_hidden": { "agnews": {"legacy": 0.3730, "v400": 0.7520}, "emotion": {"legacy": 0.1960, "v400": 0.3930}, "polarity": {"legacy": 0.5440, "v400": 0.5960}, "dbpedia": {"legacy": 0.5530, "v400": 0.7970}, "tickets_en": {"legacy": 0.4480, "v400": 0.9570} }, "tickets_en_shipped_fabric": 0.9040, "comment": "the round-2 tickets_en regression (0.9040 -> 0.4480 after the lane repair) is INVERTED: the same repaired fabric scores 0.9570 with the affinity readout, above the original" }, "giant-bengali": {"readout": "affinity_mix 0.3", "hidden_540": {"legacy": 0.9260, "v400": 1.0000}, "ece": {"legacy": 0.0270, "v400": 0.0000}}, "giant-devanagari": {"readout": "affinity_mix 0.3", "hidden_539": {"legacy": 0.9110, "v400": 1.0000}, "ece": {"legacy": 0.0180, "v400": 0.0010}}, "giant-cyrillic": {"readout": "affinity_mix 0.3", "hidden_539": {"legacy": 0.9520, "v400": 1.0000}, "ece": {"legacy": 0.0170, "v400": 0.0000}}, "agnews": {"readout": "affinity_mix 0.3", "novel_probes_12": {"legacy": 0.5833, "v400": 0.7500}, "admission_required": 0.40}, "sst2": {"readout": "LEGACY (unchanged)", "novel_probes_12": {"legacy": 0.7500, "if_affinity_were_enabled": 0.5830}, "admission_required": 0.65, "reason": "the affinity readout would drop this fabric BELOW its own admission gate, so it ships unchanged"}, "amazon": {"readout": "LEGACY (unchanged)", "novel_probes_10": {"legacy": 0.7000, "if_affinity_were_enabled": 0.6000}, "admission_required": 0.65, "reason": "the affinity readout would drop this fabric BELOW its own admission gate, so it ships unchanged"} }, "why_two_class_fabrics_are_excluded": "the contrast is degenerate on a two-candidate set: with two candidates a token points at one or the other, so one mis-pointed token dominates. The gate on the fabric's own novel probes is the arbiter, not a global rule.", "cost": { "latency": "unchanged in practice (the channel is O(|lit|*degree), microseconds against a 6-11 ms decision)", "memory": "one per-fabric cache of node lane-mass" } }, "b77_sem": { "fabric": "model/b77-sem", "shipped_v391": { "calibration": {"choice_temperature": 0.00472645, "rows": 211, "composition": "unknown (no physics.json)"}, "cal_1003": {"n": 1003, "accuracy_argmax": 0.1316, "ece_top_prob_10bin": 0.838, "answered_frac": 0.996, "honest_total": 0.1316}, "hidden_3080": {"n": 3080, "accuracy_argmax": 0.1584, "ece_top_prob_10bin": 0.8085} }, "v400": { "calibration": {"composition": "affinity_mix 0.3, diffusion 0.02, energy_norm true"}, "cal_1003": {"n": 1003, "accuracy_argmax": 0.4560, "ece_top_prob_10bin": 0.0740}, "hidden_3080": {"n": 3080, "accuracy_argmax": 0.4800, "ece_top_prob_10bin": 0.0460} } }, "note_on_splits": "the handmade OOD numbers (148 hand-written probes, tools/handmade_gate.py + data/handmade_probes.jsonl) are NOT a training or calibration set; they are reported next to every number so the in-distribution / out-of-distribution gap stays visible."}12345678910111213141516171819202122232425262728293031323334353637383940{"admitted": [{"domain": "sst2","novel_accuracy": 0.75,"required": 0.65,"n": 12},{"domain": "agnews","novel_accuracy": 0.5833,"required": 0.4,"n": 12},{"domain": "amazon","novel_accuracy": 0.7,"required": 0.65,"n": 10}],"rejected": [{"domain": "toxic","novel_accuracy": 0.2857,"required": 0.65,"collapse": true,"reason": "below required margin + prediction collapse"},{"domain": "emotion","novel_accuracy": 0.25,"required": 0.3167,"collapse": false,"reason": "below required margin"}],"gate": "tools/novel_gate.py","rule": "accuracy > max(majority_baseline, uniform_chance + 0.15) and no prediction collapse > 60%"}1234567891011121314151617181920212223242526272829303132333435363738394041424344{"admitted": [{"domain": "sst2","novel_accuracy": 0.75,"required": 0.65,"n": 12,"note": "v4.0: the affinity readout measured 0.5830 on these probes, BELOW this gate, so the fabric ships UNCHANGED with the legacy readout"},{"domain": "agnews","novel_accuracy": 0.75,"required": 0.4,"n": 12,"note": "v4.0: the affinity readout (mix 0.3) raised this from 0.5833; the fabric ships with affinity_mix 0.3"},{"domain": "amazon","novel_accuracy": 0.7,"required": 0.65,"n": 10,"note": "v4.0: the affinity readout measured 0.6000 on these probes, BELOW this gate, so the fabric ships UNCHANGED with the legacy readout"}],"rejected": [{"domain": "toxic","novel_accuracy": 0.2857,"required": 0.65,"collapse": true,"reason": "below required margin + prediction collapse"},{"domain": "emotion","novel_accuracy": 0.25,"required": 0.3167,"collapse": false,"reason": "below required margin"}],"gate": "tools/novel_gate.py","rule": "accuracy > max(majority_baseline, uniform_chance + 0.15) and no prediction collapse > 60%","v400_note": "The v4.0 affinity readout is applied PER FABRIC and gated by this file's own rule: a fabric whose readout change would drop it below its 'required' margin is shipped unchanged. agnews passes (0.5833 -> 0.7500, required 0.40); sst2 (0.5830) and amazon (0.6000) would fail their 0.65 gate and ship unchanged. The contrast is degenerate on two-class candidate sets, which is why."}
1234103 unmodified lines108109110111# Engine port — v3.2.0 → v3.9.1## What changed103 unmodified lines`selective-prediction`**, alongside `no-transformer` / `no-neural-network` /`no-pattern-matching`. A decision engine that can say "I don't know", with noneural network anywhere, is a more defensible claim than a multimodal one, andit is the one this repo actually demonstrates.1234103 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176# Engine port — v3.2.0 → v4.0.0## What changed103 unmodified lines`selective-prediction`**, alongside `no-transformer` / `no-neural-network` /`no-pattern-matching`. A decision engine that can say "I don't know", with noneural network anywhere, is a more defensible claim than a multimodal one, andit is the one this repo actually demonstrates.---# v4.0.0 — the affinity field readout (2026-11)The engine in `engine/` is now the **v4.0.0** tree: the same source as theGitHub repo at the v4.0 commit, so the code and the weights that ship hereare the code that produced every number in the card.| | before | after ||---|---:|---:|| `core/*.hpp` | 16 files | 16 files || `core/syfox.hpp` | 2,415 lines | 2,756 lines || `core/si_substrate.hpp` | 2,415 lines | 2,539 lines || string | `syfox-3.9.1` | `syfox-4.0.0` |## What v4.0 adds1. **The affinity field readout (AFR)** — `core/syfox.hpp`, `--affinity-mix F`(0 = legacy, bit-identical to v3.9.1; 1 = affinity only) and`--affinity-pmi` (the log-odds form). No training, no neural network: itreads the Hebbian affinity the fabric already learned, against thecandidate set as its own null model.2. **The lane repair** — `core/si_substrate.hpp`, `syfox repair-lanes--model DIR [--dead-threshold F] [--dry-run]`, plus `--lane-floor F` fornew fabrics. The port applied CMD §2.3's decay to every lane on everylesson, so a lane last bound long ago underflows to the float32 denormalfloor and the Hebbian memory is erased; the repair rebuilds it from thepersisted evidence ledger in CMD's saturating form.3. **The per-candidate-count temperature** — one scalar per distinctcandidate count, because one scalar cannot serve a 14-way and a 2-wayspread at once. Persisted in `calibration.json`(`choice_temperature_by_count`).## The recorded composition moved`model/*/physics.json` now carries the **readout** as well as the physics:```json{"affinity_mix":0.3,"affinity_pmi":false,"decay":0.82,"diffusion":0.45,"energy_norm":true,"hop_coupling":0.35,"k_settle":8,"recorded":true}```so a deployed model decides under the readout its temperature was fitted for.Seven of the nine fabrics here carry `affinity_mix: 0.3`; `sst2` and `amazon`carry none, because the affinity readout would drop them below their ownadmission gate (see the card's v4.0 section).**The C API now applies the recorded composition on load.**`syfox_engine_create()` loads `physics.json` and *applies* it, so thepython bridge, the HTTP server and the Space decide under the same physicsas the CLI. Before this, the server path decided under a differentcomposition — and, after v4.0, under a different readout than the fittedtemperature.## Rebuilding```bashcd engine && make all && make sync-so && cd ..````make sync-so` copies `engine/build/libsyfox_core.so` to the **repo-root**`build/`, which is where `server/syfox_bridge.py` loads it from. Skipping itis the most common setup failure: the CLI and the tests pass, then`from inference import SyFox` dies with `undefined symbol`.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476## v4.0 — the affinity field readout (AFR): measuring an anchor instead of retrieving one
A new READOUT, not a new fabric and not a new model. No neural network, notraining, no new corpus pass: every quantity AFR reads was already learnedby `hebbian_lesson`. It costs O(|lit| * degree) per question on one core,and it is OFF by default so every pre-v4.0 fabric replays bit-identically.
THE DEFECT. Three measurements, on the shipped model and the v3.9.3 engine:
1. THE READOUT NEVER READS THE FABRIC'S STRONGEST SIGNAL. Every lesson binds the state's tokens to the outcome anchor (outcome_text = the label key + its description), so the fabric holds an explicit affinity w(u, c) between a query-side token and a candidate anchor -- literally "which intent did this word teach". The legacy readout never reads it: Substrate::readout() sums the probe token's own energy plus a weight-averaged neighbourhood, and the anchor's affinity enters only indirectly, through whether a capped, decaying diffusion carried energy to the anchor. One constant therefore has to serve both PRECISION (the field must not smear onto wrong anchors) and REACH (the right anchor must light up at all), and the two want opposite values -- measured: the diffusion optimum is per-DOMAIN (tickets_en 0.45, agnews/dbpedia 0.02). A constant that must be re-tuned per domain is a sign the readout is asking the wrong question.
2. THE READOUT HAS NO NULL MODEL. A candidate's score is an unnormalised SUM over its probe bag. A Banking77 description is 20 mined phrases -- ~60 token occurrences -- most of them shared with other candidates ("not", "working", "the"). Shared words add a large common offset; the one discriminative word is one term out of sixty. The mined phrases make the sum a repetition-weighted VOTE, not a measurement.
3. THE CONSEQUENCE IS A RETRIEVAL SCORE, NOT A MEASUREMENT SCORE. Measured on the repaired b77-sem fabric, query "the cash machine swallowed my card and it never came back": candidate[c04]=0.0933 ("cash withdrawal not working") candidate[c19]=0.0919 ("card payment not working") -- two intents differing by ONE word score within 1.5% of each other; the decision was a coin flip. The fabric KNOWS that "card" belongs to c19; the readout could not see it.
And the vocabulary was NOT the cause: 98.8% of the handmade Banking77 probe tokens (577/584) are already nodes. An OOV-first design would have been the wrong fix for the measured failure.
THE MECHANISM. For the lit query tokens u with field energy E_u and thecandidate set C:
P(c|u) = w(u,c) / sum_{c' in C} w(u,c') posterior over C P0(c) = mass(c) / sum_{c' in C} mass(c') a priori share of C L(c) = sum_u E_u * [ P(c|u) - P0(c) ] the contrast or, with --affinity-pmi, the log-odds form L(c) = sum_u E_u * log(P(c|u)/P0(c)).
A token that points at EVERY candidate cancels against the null model andcontributes nothing -- ubiquity stops being evidence. A token that pointsat ONE candidate contributes strongly, positive for that candidate andnegative for the rest, so discrimination becomes sign-carrying instead ofdrowned in a shared offset. mass(c) is the anchor's own total lane weight:the prior is measured, not assumed.
The channel is blended with the legacy readout: score(c) = (1-mix) * legacy(c)/max|legacy| + mix * L(c)/max|L|with mix defaulting to 0 (legacy, bit-identical). The measured optimum is aSMALL dose -- mix = 0.3 wins on every fabric and every diffusion tested.
This is the FIRST-ORDER RESOLVENT of the propagation the settle simulates:the same operator, read exactly instead of approximated by a capped andsmeared diffusion. In the literature it is the same object as Kanerva's SDMread out by a kernel/least-squares solve (Iatropoulos et al., "Kernel MemoryNetworks", NeurIPS 2022), which likewise replaces a hand-tuned decayschedule with a closed-form retrieval and a capacity law; and its ORDERcounterpart is Plate's Holographic Reduced Representations (IEEE TNN 1995),whose crosstalk failure mode is cured by projecting the retrieved trace ontothe span of the known anchors -- which is what the candidate set does here.The non-neural char n-gram representation that would remove the dark nodeSTRUCTURALLY is Schutze, Adel & Asgari, "Nonsymbolic Text Representation",EACL 2017 (char n-gram counts -> SVD -> summed; no gradient training).
THE HONEST-SILENCE FLOOR, RESTATED. kUnknownCandidateFloor defers when thesettled field carries no energy on any candidate -- which in thenovel-wording case is exactly the situation the affinity channel exists torescue. The floor now fires only when NEITHER channel carries evidence,and is still evaluated on the legacy channel's maximum, so its meaning (itmeasures the FIELD) is unchanged.
MEASURED -- router16 (16 intents), CAL split (12,593 rows): 0.45 0.0 0.5060 0.0460 0.267 (4/15) 0.45 0.3 0.5850 0.0610 0.400 (6/15) <- +7.9 points 0.02 0.0 0.5290 0.0920 0.133 (2/15) 0.02 0.3 0.5600 0.1030 0.400 (6/15)
MEASURED -- giant-latin, per-domain HIDDEN splits (one fabric, 16 domains): domain classes legacy d0.45 AFR d0.45 legacy d0.02 AFR d0.02 agnews 4 0.3730 0.7520 0.6790 0.7740 emotion 6 0.1960 0.3930 0.2590 0.3980 polarity 2 0.5440 0.5960 0.6380 0.6030 dbpedia 14 0.5530 0.7970 0.7800 0.7660 tickets_en 3 0.4480 0.9570 0.5660 0.9620
The round-2 tickets_en regression (0.9040 -> 0.4480 after the lane repair on the shared fabric) is not merely undone: the SAME repaired fabric scores 0.9570 with the affinity readout, and 0.9620 at diffusion 0.02 -- above the SHIPPED model's 0.9040. And the per-domain diffusion problem disappears with it: the handmade OOD number is 0.176 at EVERY diffusion tested, because the affinity channel reads the evidence instead of asking a smeared field to carry it.
MEASURED -- b77-sem (Banking77), CAL split selects, hidden scored once:
diffusion mix CAL acc CAL ECE handmade(OOD) 0.45 0.0 0.2490 0.2070 0.059 (4/68) 0.45 0.3 0.2510 0.0820 0.176 (12/68) 0.10 0.0 0.4170 0.2020 0.059 (4/68) 0.10 0.3 0.4230 0.0890 0.176 (12/68) 0.02 0.0 0.4340 0.2070 0.044 (3/68) 0.02 0.3 0.4560 0.0740 0.176 (12/68)
HIDDEN (3,080 rows), the selected configuration and the baseline only: 0.45 0.0 0.2850 0.2330 0.45 0.3 0.2750 0.0680 0.02 0.0 0.4660 0.2200 0.02 0.3 0.4800 0.0460 <- selected on CAL
So at the selected diffusion: accuracy 0.4660 -> 0.4800 on the hiddensplit, ECE 0.2200 -> 0.0460 (4.8x better). mix = 0.3 improves CAL accuracyat EVERY diffusion tested and never hurts ECE.
THE AUTHORITATIVE OUT-OF-DISTRIBUTION A/B (both fabrics calibrated by thesame build, scored through the same path, corrected probe labels): b77-sem handmade (68): legacy 0.132 (9/68) -> AFR 0.191 (13/68) router16 handmade (15): legacy 0.267 (4/15) -> AFR 0.467 (7/15)and the DIFFUSION-INDEPENDENCE, which is the architectural claim: across a22x range of the diffusion constant the affinity readout's handmade accuracymoves by 0.030 (0.176 @ 0.45, 0.206 @ 0.10, 0.191 @ 0.02), where thelegacy readout's optimum was PER DOMAIN (tickets_en 0.45, agnews/dbpedia0.02). The readout reads the evidence instead of asking a smeared field tocarry it.
The PMI (log-odds) form was also measured and is WORSE than the linearcontrast (CAL acc 0.194 vs 0.221 at mix 0.5/diffusion 0.45; OOD 0.132 vs0.176): normalising over a 77-way candidate set makes the log-oddsvariance-heavy. Shipped: the linear form; --affinity-pmi remains available.
THE ORDER CHANNEL. The lit set also carries the state's bigram nodes whenthe fabric has them; bigram nodes are bound to the outcome anchors by thesame Hebbian lesson, so their affinity to a candidate is an ORDEREDrelation -- CMD 2.5's escape, carried into the affinity channel. On theshipped b77-sem (learned before bigram lanes existed) the extension is averified no-op: the numbers are bit-identical with and without it.
THE PER-CANDIDATE-COUNT TEMPERATURE (v4.0, second half). The giantfabric's ECE exposed a second, independent defect: ONE softmax temperaturecannot serve candidate sets of different sizes. A 14-way question's scorespread is not a 2-way question's spread, and the shared fabric's singlefitted temperature left polarity at ECE 0.395 while dbpedia sat at 0.064 inthe SAME fit. v4.0 therefore fits ONE temperature per distinct candidatecount -- the count is a property of the QUESTION, so it leaks nothing aboutthe label -- with the same 1-bit ECE selection guard and the same rows; acount with fewer than 64 calibration rows keeps the global scalar. The tablepersists in calibration.json (choice_temperature_by_count) and the decisionpath reads it through choice_temperature_for(n). The argmax never moves.MEASURED on the giant fabric (legacy readout, diffusion 0.45), ECE before-> after the per-count temperature: agnews 0.2750 -> 0.0860, emotion0.0780 -> 0.0240, polarity 0.1280 -> 0.0690, dbpedia 0.1650 -> 0.1330,tickets_en 0.1100 -> 0.1050. The fitted table for that fabric:{2: 1.666, 3: 0.470, 4: 2.105, 6: 11.314, 14: 0.749, 77: 0.068}.
THE READOUT MODE IS PART OF THE RECORDED COMPOSITION. physics.json nowcarries affinity_mix and affinity_pmi, so a deployed model decides under thereadout its temperature was fitted for -- the fit==decide parity contract,extended from the physics to the measurement. --affinity-mix still overridesexplicitly.
TWO CORRECTIONS FOUND WHILE MEASURING (both fixed, both disclosed):1. A MISLABELLED PROBE IN THE HANDMADE SET. rt_01 ("he sank a curling three-pointer in the fourth quarter") was labelled rt01 -- the BANKING anchor -- when a curling three-pointer is SPORTS, i.e. rt00 ("news headlines world sports business technology"). The gold label is now rt00.2. THE C API / PYTHON BRIDGE IGNORED THE MODEL'S RECORDED COMPOSITION. syfox_engine_create() loaded physics.json but never APPLIED it, so the server, the Space and the handmade gate decided under different physics than the CLI -- and, after v4.0, under a different READOUT than the temperature was fitted for. It now calls apply_composition(); applying it twice is idempotent, and the CLI is unaffected. (The bug surfaced because the gate's own --affinity-mix flag was silently overriding the model's recorded readout with the flag's default; the gate now leaves the recorded readout alone unless the operator asks otherwise.)
TESTS: test_affinity_readout pins the mechanism -- the channel is OFF bydefault (the replay contract), the EXCLUSIVE token decides even when thequery shares no vocabulary with any candidate's description, the decisionis deterministic, a token bound to every candidate changes nothing, andmix = 0 reproduces the legacy decision. Full unit suite green.
FLAGS: --affinity-mix F (0 = legacy, 1 = affinity only; default 0) and--affinity-pmi (the log-odds form). The flag is applied in apply_physics sothat cmd_calibrate -- which calls apply_physics only -- fits the SAMEchannel the decision scores (the v3.8 fit==decide parity contract).
VERSION 3.9.3 -> 4.0.0
## v3.9.3 — the dead-lane repair, the router-criteria measurement, and the handmade gate
Three defects measured on the PUBLISHED model (HF sha 5aa69627) and thev3.9.1 engine. One of them is a large win; one of them has a true diagnosisand a HARMFUL proposed remedy; one of them is a calibration/referenceproblem that flattered SyFox.
DEFECT 1 — THE DEAD LANES (the diagnosis is TRUE; the command did not existand is added here). enforce_lane_decay() multiplies EVERY lane by 0.995 onEVERY lesson, so a lane last bound at lesson k in an N-lesson fabric carriesw0 * 0.995^(N-k) — which underflows to the float32 denormal floor (1.4e-43)after ~20,670 lessons and then STOPS decreasing. MEASURED on the shippedmodel/giant-latin (114,060 lessons, 1,905,169 lanes): 95.09% of lanes carry aweight in (0, 1e-12), the MEDIAN lane weight is 1.4e-43, and only 2.42%exceed 1e-6. The Hebbian memory was erased; what survived was a recencywindow over the tail of the corpus. The base repository's law is different(research-paper/cmd.md 2.3): w <- tanh((w*lambda + eta*v_b*v_c)/w_max)*w_max— SATURATING, with continuous co-activity growth, so a starved lane keeps areal value; research-paper/tsda.md 2: "It remains in long-term memory (theedge still exists), but it requires more cognitive energy to retrieve." Theport kept the decay and lost the saturation.
FIX 1a — NEW COMMAND `syfox repair-lanes --model DIR [--dead-threshold F][--dry-run]`: rebuilds every lane's weight from the persisted EVIDENCE LEDGER(v3 Milestone 3), which holds the integral of exactly the growth term thedecay destroyed, in CMD 2.3's saturating form: w = w_max * tanh( net_events * bind_scale / w_max )No equation moves and no learn-time behaviour changes; a fabric re-learnedfrom scratch is byte-identical. MEASURED: giant-latin revives 1,330,812 of1,859,008 dead lanes (weight sum 681 -> 117,478); b77-sem revives 159,449(912 -> 58,210); router16 rebuilds 43,117 (1,012 -> 10,360).
FIX 1b — cfg_.lane_decay_floor + `--lane-floor F`: the ROOT-CAUSE guard fornew fabrics. A starved lane keeps a floor instead of falling off thenumber line (TSDA 2: the edge persists with reduced retrievability).Default 0 = OFF, so every pre-v3.9.3 fabric replays bit-identically.
MEASURED EFFECT (argmax accuracy — temperature-independent, so this is therepair alone): router16 on its 12,593-row cal split 0.4210 -> 0.5060(+8.5 points); b77-sem on hidden 3,080 rows 0.4500 -> 0.4662 at diffusion0.02; giant-latin per domain (hidden, class question only): agnews 0.498 ->0.679, dbpedia 0.578 -> 0.780, polarity 0.560 -> 0.638, emotion 0.129 ->0.259, with ECE 0.402 -> 0.128 (agnews) and 0.300 -> 0.124 (dbpedia).
DEFECT 2 — THE ROUTER CRITERIA (the diagnosis is TRUE; the proposed remedyis HARMFUL). MEASURED against the shipped giant-latin's 43,420 nodes: therouter descriptions are mostly words the fabric never interned — rt01("banking cards payments transfers refunds loans") has 0 of 6 words asnodes, rt00 1 of 6, rt13 1 of 6, rt05 and rt08 0 of 4/5. Two code facts makethat matter: Substrate::readout() SKIPS every token that is not a node (so anon-node description contributes nothing to its own candidate), and decide()injects EVERY candidate's description tokens into ONE shared field (so wordsthat ARE nodes cross-contaminate all candidates at once).tools/rebuild_router_criteria.py implements the proposed rebuild (eachcandidate described by the tokens with the highest w(x,A) * exclusive(x,A)).MEASURED on the repaired router16, 12,593-row cal split, each criteria setwith its own matched calibration: old text ("banking cards payments...") argmax 0.5060 ECE 0.046 EMPTY text ("") argmax 0.4320 ECE 0.018 one exclusive token ("monei") argmax 0.5060 ECE 0.041 label-exclusive 4 tokens (the remedy) argmax 0.4147 ECE 0.062The proposed remedy COSTS 9 POINTS of routing accuracy: the description isnot a lever, it is a shared-field injector, and the richer it gets the morethe candidates contaminate each other — the repo's own documented"direct-term harvest" effect (its wording sweep already found short4 0.426 >mid8 0.164 > rich12 0.079). The remedy is therefore shipped as a TOOL, notas a default, and the finding recorded: keep the criteria MINIMAL. Emptycriteria gives the best calibration measured anywhere in this tree(ECE 0.018, beating Jev's third-party 0.246 and Laya's 0.081).
DEFECT 3 — THE JEV REFERENCE NUMBERS FLATTERED SYFOX. The bench'sjev_reference block carried the LAUNCH-DAY self-report (workflow 0.678,latency 70-500 ms, "calibration claimed, not public"). Independentthird-party measurements are materially STRONGER for Jev: arxiv 2609.37647(37 datasets, 346,009 requests, jev-1.13.0) measures 95-99% on IMDB / SST-2/ HellaSwag / ARC and 79.7% on Banking77 at full coverage (-> 96.3% at 50%coverage); laya-model.com/benchmarks publishes Jev at typed-decisions 0.727,AG News 0.910, DAIR Emotion 0.480, Banking77 0.870, ECE 0.246, p50 latency236-276 ms. The block now carries those, with the vendor's own 0.955 workflowclaim labelled as such.
NEW — THE HANDMADE GENERALISATION GATE. data/handmade_probes.jsonl (148probes) + tools/handmade_gate.py: hand-written sentences, deliberatelyoutside every training split, every eval split and every mined-criteriavocabulary. It is the only check in the tree that can see a fabric that hasmemorised its corpus instead of learning it. MEASURED on the SHIPPEDfabrics: total 0.291 (bank77 0.103, emotion 0.167, dbpedia 0.286, router0.400) — the published bank77 number (0.158) is optimistic because thehidden split shares the training templates. It also exposed the DIFFUSIONTRADE-OFF: diffusion 0.02 (selected on cal) buys bank77 hidden 0.2854 ->0.4662 in-distribution and costs handmade 0.118 -> 0.044 out-of-distribution.A cal-only selection cannot see that cost. Wired into make ci.
FURTHER MEASUREMENT — THE DIFFUSION OPTIMUM IS PER-DOMAIN, NOT PER-FABRIC.The giant fabric is one directory carrying 16 domains with very differentgeometry. At diffusion 0.02 tickets_en (3 classes) REGRESSES from 0.9040 to0.5660 while agnews (4) and dbpedia (14) gain 18-20 points. One diffusionper fabric dir is therefore not enough for a multi-domain fabric — theper-fabric mechanism (physics.json) is the right primitive but the valuehas to be chosen per DOMAIN, or the domains split into per-domain fabrics.
TESTS: test_lane_repair (the global decay really kills lanes; the ledger canrevive them; the dry run reports without touching the fabric; the repair isdeterministic; no rebuildable lane is still dead afterwards) andtest_physics_composition. Full unit suite green.
DOCS: docs/FIT_DECIDE_PARITY.md (the fit==decide contract) and the v3.9.3section of this changelog.
VERSION 3.9.2 -> 3.9.3
## v3.9.2 — fit == decide: the calibration composition contract
The fix for the wrong-answer bug the v3.9.1 diagnostics exposed. Twoindependent defects, both in the tool layer; NO physics equation changed.
DEFECT 1 — THE CALIBRATION WAS FITTED UNDER A DIFFERENT PHYSICS THAN THEDECISION RUNS. The choice/score temperature is fitted on settle-passenergies, and those depend on the whole decide-side composition (theenergy gain, diffusion, decay, k_settle, hop coupling). The energy gain isPER-STATE, so it is not a uniform rescale. In this tree b77-sem, router16and model-bank77-best calibrated WITHOUT --energy-norm while every benchand decide call ran WITH it. Measured on the shipped b77-sem fabric andthe 1,003-row cal split, same engine, one flag apart: calibrate WITHOUT --energy-norm -> T = 0.0037, fit saw 556 of 2,006 question-rows (27.7% coverage), ECE 0.4567 -> 0.4057 calibrate WITH --energy-norm -> T = 0.3552, fit saw 2,006 of 2,006, ECE 0.3183 -> 0.3056A ~100x sharper temperature, chosen on a 27.7%-covered BIASED subset (theother 1,450 rows settle to a SILENT field and are dropped from the fit). Anear-floor T saturates the softmax: the post-temperature top-2 gap goes to~0.93 on every row, so the honest-defer gate (an absolute 0.05 margin) canNEVER fire — the model never abstains — and every answer carries ~0.98confidence whether it is right or wrong (measured on the shipped fabric,hidden: mean p1 0.9819 on correct rows vs 0.9641 on wrong, ECE 0.809).The calibrate report's own ECE did not describe the bench's ECE because thetwo ran under different physics.
DEFECT 2 — THE DIFFUSION CONSTANT WAS NEVER RE-TUNED FOR THE DENSEFABRICS. diffusion is a config value (not an equation) whose optimum is aproperty of the fabric; 0.45 was validated on the small v2-era fabrics andsmears a 217k-lane fabric's field, merging intents that share vocabulary.Measured on the bank77 CAL split (selection never touches hidden):0.45 -> 0.1316 accuracy, 0.10 -> 0.4237, 0.02 -> 0.4237.
FIX 1 — PHYSICS.JSON: a fabric now carries the decide-side composition itwas calibrated under (physics.json, next to calibration.json). calibrateRECORDS it; decide/bench/demo/stats APPLY it on load(Engine::apply_composition). Explicit CLI flags still win. A fabric with nophysics.json is a pre-v3.9.2 fabric: nothing is applied and behaviour isbit-identical (replay contract preserved).
FIX 2 — THE FIT REFUSES TO RUN ON A BIASED SUBSET. calibrate counts thequestion-rows it was offered and the ones it saw; below 50% coverage itrefuses (exit 2), names the cause, and leaves the fabric untouched. Thecoverage is always disclosed: fit_offered_rows, fit_dropped_silent,fit_coverage.
FIX 3 — THE MAKEFILE STOPS LYING: b77-sem, router16 and model-bank77-bestnow calibrate with --energy-norm (the composition their benches run).
FIX 4 — TOOLS + CI GATE: tools/cal_diffusion_sweep.py sweeps diffusion onthe CAL split only, re-calibrating at each candidate so the temperature isalways fitted under the composition it is applied to, and records thewinner into physics.json (this also delivers the standing recommendation indocs/INTRACATEGORY_ATTACK.md section 4: a per-fabric diffusion value, not anew global default). tools/assert_fit_decide_parity.py is the CI gate: aFITTED fabric with no physics.json has an unknown calibration provenance andFAILS. Wired into make ci.
MEASURED (v3.9.1 engine, shipped fabrics, shipped splits; selection on cal,hidden scored once; bank77 intent-only): bank77 hidden 3,080: accuracy (argmax) 0.1584 -> 0.4500 (+29.2 pts), ECE 0.809 -> 0.225, accuracy over answered at margin 0.05 0.159 -> 0.542, honest total at margin 0.05 0.1581 -> 0.3760, deferral rate at margin 0.05 0.5% -> 30.7% (the axis is alive) router16 cal 12,593: ECE 0.443 -> 0.054, accuracy over answered 0.4299 -> 0.5989. At margin 0 both configurations produce the IDENTICAL argmax (0.4210) — the temperature never changes a decision, only how confidently it is made and whether it is made at all. re-calibrated fabrics: b77-sem T = 0.346736 over 1,003 rows (was 0.00472645 over 211), diffusion 0.02; router16 T = 0.0509 over 12,574 rows (was 0.00491756 over 160).
TESTS: test_physics_composition (16 checks: a pre-3.9.2 fabric carries nocomposition and is bit-identical; a recorded composition survives thesave/load round trip; apply_composition reaches the live substrate; thefit's offered/seen/dropped row bookkeeping adds up). Full unit suite green.
DOCS: docs/FIT_DECIDE_PARITY.md (the bug, the measurement, the fix, and whythe base repository does not have it — SI reads out by ARG-MAX over thesettled field, with no softmax, no temperature and no fitted parameter, sothere is nothing to fit against the wrong physics; the probability readoutand the temperature are a SyFox addition and the defect came in with them).
VERSION 3.9.1 -> 3.9.2
## v3.9.1 — intra-category diagnostics: confusion matrix + honest totals + the diffusion finding
Diagnostics-then-intervention per the tester's revised plan. Everythingmeasured in-tree, tuning on cal only, hidden touched only for finalvalidation; no global defer default shipped; no parity claims without thehonest total (docs/HONEST_TOTAL.md).
- BENCH (opt-in, default byte-identical): --confusion (NxN gold-x-pred JSON matrix, DEFER pseudo-class, pairs_top; rows==labels alignment pinned by unit test after the DEFER-shift bug was caught cross-checking the hidden dump), --dump-perrow (per-choice-question records with the RAW pre-temperature energy gap), Answer.raw_margin disclosure.- PHYSICS SWEEP KNOBS: set_decay/set_diffusion/set_hop_coupling/ set_learn_eta/set_lane_cap on the substrate (frozen defaults, clamped; CLI --decay --diffusion --k-settle --hop-coupling --learn-eta --lane-cap on bench/calibrate/learn/decide paths).- MEASURED (model-b77-sem, 19,690 nodes / 1.31M lanes, banking77): calibration T=0.0019 makes the probability-gap defer axis inert (0/1003) and ECE 0.597/0.573 measured; no global margin improves the honest total; per-intent thresholds overfit cal (-2.0 hidden); class frequency does not predict accuracy (r=-0.043); semantics -6.1 pts without; decay/k_settle/hop_coupling/learn_eta flat; lane_cap 1024 +1.6; DIFFUSION monotone to a boundary optimum: cal 0.401 -> 0.537, hidden 0.424 -> 0.571 (+14.7), card_management 0.389 -> 0.632 (+24.3). Replicates on an independent reduced fabric family (+16.4). SI equations frozen throughout - a CONFIG value, not a physics change.- TOOLS: b77_confusion_report.py, b77_margin_sweep.py, b77_apply_policy.py, b77_freq_cut.py, b77_ablation_compare.py. ARTIFACTS: data/b77_diag/.- DOCS: docs/INTRACATEGORY_ATTACK.md + docs/HONEST_TOTAL.md. TESTS: test_bench_diagnostics (confusion/dump/knobs/alignment invariant).
## v3.9.0 — the constructive substrate: SI's Layer-2 reasoning stack + the remaining paper mechanisms
Answers the v3.9 audit ("SyFox is not a port of SI — it shares twoconstants"; "many papers unimplemented"). Both charges verified, bothaddressed; the false port claim is retracted in the substrate header itself.
- core/reason.hpp (NEW, ~1,530 lines): the faithful port of SI's Layer-2 — typed graph with full provenance (rule/parent_a/parent_b/step), O(1) edge existence, O(deg) adjacency, bounded retraction (RADE); the NINE reasoning primitives (transitive, modus ponens, inheritance, contrapositive, case analysis, induction with min-witnesses, analogy, abduction via backward chaining, recursion via the fixpoint loop); forward chaining to fixpoint under a tension budget; adaptive backward chaining with an active goal stack; proof traces + the §5.3.4 verifier; the meta-learner (sub-chain counting -> macro-rule promotion at the 2-bit MDL threshold); the thinker index C/R; the SIX discovery queries; the .axioms triple format (SI's own data files load unchanged). Determinism hardening over SI: primitive candidate sets sorted before commit (SI iterated hash maps).- ENGINE BRIDGE: `syfox axioms --load FILE` loads triples into BOTH stores (typed graph + fabric lanes, idempotent); load_model auto-loads <model>/axioms.txt + v39.json (tension + OOD signatures) when present; absent = every pre-3.9 model replays bit-identically. New commands: ask (forward/backward with proof JSON), reason (fixpoint report), discover (six queries + classifier), thinker (C/R + macro count over a query file), audit (CMA/CCH DERIVED-vs-INDUCED path-additivity report).- DECISION-LAYER PAPER GATES (opt-in, default OFF, read-only over the settled field): --proof / --require-proof (RADE proof pass, no_proof_path defer); --wavefront-gate (CMD §4 reached-candidates, unreached_candidates defer); --momentum-readout (MCPE/CPME echo suppression, echo_only defer; ported as peak-diffusion-gain after BOTH the raw final-pass delta and a beta=0.9 envelope measured every candidate echo-suppressed on the bench fabrics); --coherence-gate (HTR ΔR participation-ratio rise, no_structural_rise defer); --vght-gate (VGHT coincidence C=σ(12(E·E−0.05)) on the hop walk, gated_lane_frac disclosure); --cem-plan (P-CMA shell, gradient-free CEM over deterministic source-cap variants, plan restores the winning field; first cut snapshotted post-settle and double-decayed every variant — caught by think30 bisection at 0.600 -> 0.267 and fixed); --ood-knn (fixes.md signature-density defer, ood_density); --tension-gate (RIFA SIL with the sign defect fixed: contradictions ACCUMULATE tension, conflicted_state defer at >= 2 unresolved conflicts on the state hash).- LEARN-SIDE PAPERS (opt-in, replay-safe): --fingerprints (CME graded half-dose re-teach, capped 1024-entry table, deterministic eviction); --sentinels on (CMD §2.5 ^w0~w1 / wn~wn$ boundary pairs); --pro-con on (RB surrogate: negated lessons bind through "!token" con-namespaces); --order-consolidation on (CPME-II discrete surrogate: per-lane order evidence, Phi = 0.4 + 0.6*(2c/t - 1) blend, ORD1 magic tail, replay no-op on pre-v3.9 fabrics).- HONEST LINEAGE: si_substrate.hpp header retracted the "faithful standalone port" claim; now states shared vs different (scalar energy vs oscillators, lanes vs tunnels, passes vs dt=0.02, native 0.82/0.45) and records the CSAT boundary theorem (global decay/diffusion modulation is rank-preserving, arg-max invariant — readout-affecting mechanisms must couple per-node; settle physics stays frozen).- BUGS CAUGHT BY THE NEW TESTS: add_primitive double-padded prim_meta (every primitive kind shifted off by one; contrapositive and induction never fired); Engine never installed the default rule set (forward chaining was a no-op); momentum envelope out-of-bounds read on pass 0 (segfault); CME fingerprint test used an unstemmed token (unordered_map::at).- TESTS: test_reason (18 checks: primitives, proofs, verifier, retraction, discovery, thinker index, contradiction guard, the engine bridge, idempotent reload) + test_v39_gates (26 checks: replay contract, per-gate defer reasons, determinism, ORD1 roundtrip, fingerprint half-dose, sentinel/pro-con interning). Full suite + readout-silence + jas-test + make ci green; bench bit-identical to the v3.8 record.- MEASURED: think30 baseline 0.467 -> thinking 0.600 -> multivector 0.633 -> v3.9 stack 0.700 (21/30; thinking flags + --wavefront-gate --cem-plan on a --distvec --multi-vector fabric). Honest negatives measured and documented: momentum alone 0.533, coherence/vght alone 0.567, learn-side flags combined 0.433 at demo scale (corpus-scale features), cem alone neutral 0.600. JEV axes unchanged (95.5% answered n=44, <=591 us, ECE 0.131, OOD defer 1.0) + new axes JEV lacks: proof traces, discovery, thinker index, .axioms knowledge format.
## v3.8.0 — physics-native thinking (no token prediction, no ML, physics frozen)
Four opt-in mechanisms + the v3.7.1 scaling fix. Spec: deepen the field'sthinking without token prediction; SI core untouched; bit-identical replay ondefault flags (bench verified against the v3.7 record).
- v3.7.1 DISTVEC SCALING FIX: measured O(n^1.9) build (76 s @ 5,595 nodes, 156 s @ 7,985, ~15 h extrapolated @ 94,773) root-caused to the exact neighbour scan (O(n^2*k), cap 8000 -> 2000), strided row-major MGS with ~840k OpenMP regions per call (-> column-major blocked BCGS2), and the subspace/Ritz kernels (-> contiguous cm passes, cached init hashes). Measured: 17.1 -> 7.2 s @ 5,107 nodes; 95.4 s @ 40,850; ~15 h -> ~5 min extrapolated at the generalist size. Determinism md5-verified.- TASK 1 ADAPTIVE DEPTH (`--adaptive-depth`, `--adaptive-max-k`): difficulty = unknown-token fraction + lane isolation, k = base + round(d*max_extra) (8..16 defaults), deterministic, ratchet-guarded, mirrored in harvest_rows; disclosed as difficulty/k_settle_used/k_settle_base.- TASK 2 MULTI-VECTOR (`--multi-vector`, `--multi-vector-k`): K=8 spectral channel gates from the distvec axes (lane flow scaled by exp(-(u_k(a)-u_k(b))^2/2s^2)), frozen physics per channel, readout on the mean superposed field; honest no-op without --distvec; dead axes skipped.- TASK 3 CAUSAL SIGNATURES (`--causal-lanes`): cause?>effect and means!>goal pair nodes from a deterministic connective scan (stemmed forms), interned/df-noted/bound like the bigrams, injected in decide/harvest/perturb at kCausalDose=0.5; replay no-op on old fabrics.- TASK 4 ENERGY SELF-VERIFICATION: settle trace (passes, final/initial energy, relative motion rate) always in the decide usage; opt-in `--self-verify` defers choice answers measured on fields still moving above the floor (default 0.25, measured settled baseline 0.189-0.212), reason `unconverged_field`.- TESTS: test_thinking group (adaptive depth incl. ratchet guard, self-verify gate both sides, multi-vector no-op/determinism/effect, causal emission directions + fabric interning + replay both ways); full suite green; readout-silence ALL PASS; jas-test ALL PASS; bench bit-identical (tickets 1.000/1.000 defer 0.063, game defer 0.333, guard 0.778, OOD defer 1.0 x3, deterministic x3).- MEASURED: think30 suite (`make think30` -> data/think30_tables.json) — 30 tests, 6 categories x 5: baseline 0.467 (14/30) -> thinking flags 0.600 (18/30) -> +multi-vector 0.633 (19/30). Honesty category 0/5 -> 5/5 (noise answers on near-vocabulary OOD states now defer); chains 0/5 -> 3/5. Causal categories showed no additional delta at demo scale (bigram lanes already carry the signal; disclosed honestly).
## v3.6.0 — the fabric-construction papers land + the JEV head-to-head
Implements the top of v3.5's paper port order on the v3.5.0 tree (settlephysics frozen; old fabrics replay bit-identically):
- ORDERED BIGRAM LANES (MRS SS4b.1-4b.2 measured 7/7; CMD SS2.5; CPSB; HTR arrival-order): learn interns adjacent token pairs ("w1~w2") and binds them to the outcome anchors; decide injects the state's bigram nodes at kBigramDose=0.5 of the state dose, mirrored bit-exactly in harvest_rows. Escape from the multiset-invariance theorem (paws 0.500 / xnli 0.333 are chance because a token bag cannot encode order). Old fabrics have no "w1~w2" nodes so the decide-side block is a no-op on them (replay contract, unit-tested both ways). --bigrams on|off (default on).- DOCUMENT-FREQUENCY RARITY WEIGHTING (CMD SS2.2 log(N/(1+df)); MIMS SS6 fan-out): substrate df table (one note per (lesson, node), persisted in a magic-guarded 'IDF5' tail) + hebbian_lesson scales STATE-side bind weights by log1p(L/(1+df))/log1p(L) in (0,1]. No stopword list; one counted formula. Fabrics without the tail reproduce v3.5 weights (factor 1.0).- PERTURBATION-CONTRAST HONESTY CHECK (BED SS8, opt-in --perturb-check): decide() additionally settles a structure-broken copy of the state (same token multiset, adjacent pairs transposed, deterministic); when the broken state's margin matches the real one the readout was bag-carried, and choice questions defer with reason "perturbation_tie". Field snapshotted and restored — the readout measures exactly what an unchecked decide() measures. Usage discloses perturb_margin_real / perturb_margin_broken.- MEASURED (train split, in-sample; heldout n=6/0/2): tickets choice 0.875 -> 1.000 (16/16, defer 0), score 1.000 defer 0.063 unchanged; game choice_defer_rate 1.0 -> 0.333 with 4/4 answered correct; guard 0.778 unchanged; ood_defer_rate 1.0 x3. test_fabric36: 22 new checks (bigram lay/inject, multiset-invariance pinned bit-equal on a bag fabric and broken on an ordered one, IDF same-token weaker-lane isolation, IDF5 roundtrip, old-fabric replay bit-identity, perturbation defer/preserve). Full unit suite, readout-silence, jas gates ALL PASS.- BUGFIX (fresh clones): `make ci` failed because its router/ablation gates need model-router16 / model-b77-sem / data/bank77_cal.jsonl — all gitignored. Those gates now SKIP loudly when absent; core gates (unit tests, readout-silence, jas — now wired explicitly) always run.- JEV HEAD-TO-HEAD (tools/jev_bench.py, make jev-compare -> build/jev_comparison.json): JEV AI (TypeSafe AI, Sept 2026) is the closed "System One" decision model on the same API shape. Measured on JEV's published axes: workflow accuracy 95.5% (n=44 answered, train split) vs 67.8% published; latency <= 474 us vs 70-500 ms published; $0 local vs $0.042/M input; plus the axes JEV does not publish — ECE (mean 0.131), honest defer with reasons (OOD 100%), bit-reproducibility, evidence JSON. Every syfox number measured by core/bench.hpp in this tree; every JEV number is their published self-reported figure (source cited in JSON).- README v3.6 section + boundary updates (subject-object scope-escape by bigram lanes; temporal adjacency; perturbation defer). VERSION 3.5.0 -> 3.6.0.
## v3.5.0 — JAS: the J-A-S cycle, the impossibility register, the arithmetic oracle
Ported from research-paper/jas.md + the central paper's substrate/thinkerdivision of labour; the SI settle physics stays frozen and decide() isbit-identical (bench verified). Three additive CLI commands, one new testgroup, one new CI gate.
- `core/jas.hpp` — the cycle: E labeled rows -> J the jump (counting leaps to a universal STRONGER than the evidence; axioms ranked confidence/support/token, deterministic) -> A->S deduction per holdout row -> experiment (oracle = observed label) -> refutation -> revision under a structural restriction (T AND U, fit on TRAIN only, never on its own counterexamples) -> round 2 on fresh rows. Verdicts: SURVIVES | REFUTED_AND_REVISED_SURVIVES_HELDOUT | REFUTED_AND_REVISION_ALSO_REFUTED | REFUTED_AND_REVISION_UNTESTED | REFUTED_IN_ROUND2_REVISE_NEXT_CYCLE | NO_TESTABLE_AXIOMS. Refutations append to <model>/refuted.axioms (with the counterexample row); survivors to <model>/verified.axioms (provenance INDUCED). The frozen field is scored on the same rows as the disclosed "relevance heuristic" column. Per-row experiment disclosure in JSON (predicted/actual/ CONSISTENT|REFUTES|NO_PREDICTION, conflicts flagged).- `syfox register [--model M] [--text]` — the impossibility register: five architectural boundaries seeded with warrants (2 THEOREM / 2 INDUCED / 1 DERIVED), each with parent + status + bypass; two THEOREM claims are SCOPE-ESCAPED (arithmetic -> calc oracle; subject-object -> ordered/typed lanes); persists <model>/impossibility.json.- `core/calc.hpp` + `syfox calc --expr ... [--compile]` — the arithmetic derivation oracle: 6 primitives, one recursive-descent grammar, a verifier that rejects (1/0 errors), overflow-guarded exact integer path, word-problem mapping (times->*, plus->+, ...). --compile EMITS a C++ translation unit, compiles with g++, runs it, discloses agreement + provenance established_by_experiment. MEASURED: 17*23=391 (g++ agrees), 2+3*4=14, (2+3)^2/5=5, 2^10=1024, word problem -> 396, 1/0 rejected. The field never computes — the theorem stands, the capability escaped its scope.- Tests: unit group test_jas (oracle exactness, detection, register invariants, full cycle arc incl. refutation->revision->convergence, survival-is-not-proof); CI gate tests/jas_test.sh (make jas-test, wired into make ci; pins oracle values, register shape, verdict space, byte-determinism of cycle JSON x2); demo fabric data/jas_cycle_demo.jsonl.- README: v3.5 section + "Why the 24-domain accuracy is low" table mapping each measured failure shape to its fabric-construction root cause and the paper that unlocks the fix (MRS/CPSB/RADE ordered+typed lanes, CMD IDF weights, rbg+graph_fisher Fisher-gated bridge lanes, BED perturbation negatives, l9 transitive pre-derivation); Architectural boundaries now cross-reference the register.- MEASURED regression: bench bit-identical to v3.4.0 (tickets choice 0.875 / score 1.000 defer 0.063; guard 0.778; game all-deferred choice_defer_rate 1.0; ood_defer_rate 1.0; deterministic x3). Full unit suite passes. VERSION 3.4.0 -> 3.5.0
## v3.4.0 — honest defer for ties, multi-hop readout walk, question-context gate
Three decision-layer mechanisms; the SI substrate physics (decay 0.82,diffusion 0.45, K_settle 8, silence floors) stays frozen. Everything ismeasured, deterministic, and disclosed.
**HONEST DEFER FOR NEAR-TIES (engine default ON, margin 0.05).** When thetop two probabilities are closer than the margin the readout does not carrya decision: the answer defers with `reason: ambiguous_tie` instead ofshipping a coin-flip as a confident label. Engine-level (members`defer_margin_`, `set_defer_margin`), so CLI, C API, HTTP bridge and benchshare ONE behavior — the v3.1 CLI post-pass (`low_margin`, default OFF) isremoved; `--defer-margin P` now sets the engine knob and `--no-defer`restores the v3.3 answer-always behavior (both verified end-to-end on ameasured gap-0.186 fabric: default answers, `--defer-margin 0.25` defers`ambiguous_tie`, `--no-defer` overrides). Score questions defer on the samemargin over level probabilities. MEASURED bench impact (train-split,v3.3.1 -> v3.4.0): tickets choice 0.875 unchanged (defer 0), score 0.938 ->1.000 with defer 0.063 (the one wrong score row was a near-tie, now honestlydeferred); guard 0.778 unchanged (defer 0); the 6-row game toy fabricdiscloses as all-deferred (`choice_defer_rate` 1.0 — its decisions sit atmean margin 0.023, i.e. they never carried signal; v3.3's 1.000 wasin-sample noise-picking that happened to be right). Bench JSON gained`choice_defer_rate`/`score_defer_rate` (accuracy over ANSWERED questions,defers counted separately — selective accuracy reads honestly). Unit tests:5 legacy groups pin `set_defer_margin(0)` (bengali argmax, M3 contradictionevidence, M3 ledger persistence, hierarchy, question-gate readout contract),new group `test_defer_ties` pins the defer (near-tie defers withprobabilities intact, decisive row answers, margin 0 answers the samenear-tie, score flavor defers).
**MULTI-HOP READOUT WALK (opt-in, `--hops N`, default 1 = legacy).**`Substrate::set_hop_depth` (clamped 1..8): depths > 1 walk lanes BFS-stylefrom each probe anchor up to N levels with per-hop damping`hop_coupling/sqrt(hop+1)` (hop 1 x0.707 ... hop 4 x0.447), levels collectedin ascending NodeId order (std::map), width-capped at 64 nodes per level(`kHopWidthCap`), never revisited — deterministic and bounded. Defaultdepth 1 keeps the legacy single-hop code path BIT-IDENTICAL (test-enforced:default == explicit 1). MEASURED on chain probes (2-hop already answers atN=1 — diffusion carries alarm->lights at probs 0.314 top, unchanged at N=4;3-hop sparrow->animal target 0.1061 -> 0.1097; 4-hop relay far target echovisible at 0.210 at N=4) — damped lanes keep far targets near-tied, so thereported conf-0.019 noise answers now surface as honest `ambiguous_tie`deferrals instead. Probe suite extended with the Test 18 (sparrow->bird->animal) and Test 21 (alpha..echo 4-hop relay) analogs + hops configs;unit group `test_multi_hop` pins default/clamp/bit-identity/determinism.
**QUESTION-CONTEXT GATE (opt-in, `--ctx-gate`, `--ctx-alpha F`).** Two-stagesettle: stage 1 settles the question's own tokens (instructions + criteriadescriptions, NO labels) into a context field; stage 2 re-settles the state(prime + state + bridges, unchanged) and `Substrate::blend_field` composes`e = (1-alpha)*state + alpha*context` (alpha default 0.5, clamped [0,1]).Two ALREADY-SETTLED fields composed at the decision layer — settle() physicsuntouched, deterministic, disclosed as `usage.ctx_gate`/`usage.ctx_alpha`.MEASURED on the probe fabric: who-found answer holds (Tariq), confidence0.056 -> 0.061; OOD submarine probe still abstains (`unknown_candidates`);latest-temperature holds with a disclosed confidence tradeoff (0.007 ->0.003). Unit group `test_ctx_gate` pins OFF-unchanged / ON-disclosure /answer-holds / determinism / OOD-preserved.
**Surface.** CLI `--defer-margin P` (engine knob), `--no-defer`, `--hops N`(1..8), `--ctx-gate`, `--ctx-alpha F`; C API decide opts `defer_margin`,`no_defer`, `hops`, `ctx_gate`, `ctx_alpha`; bridge opts docs; usage JSON`ctx_gate`/`ctx_alpha` disclosure. README: v3.4 section + "Architecturalboundaries (System-2 limits)" honest list. Verified: full unit suite passes(incl. 3 new groups), `make readout-silence` ALL PASS, bench deterministicx3 with OOD defer 1.0 x3. VERSION 3.3.1 -> 3.4.0.
## v3.3.1 — readout-silence threshold made explicit (BLOCKER fix)
**The reported false defer, root-caused on the shipped tree.** The reportsaid `{Tariq, Salma}` false-defers with `unknown_candidates` because thereadout threshold (~0.35) sits above a valid candidate's energy (0.301).On the shipped v3.3.0 code the check is an implicit `> 0` — there is no0.35 constant — and the case does NOT reproduce: on the QA probe fabric(`model-reasoning-probe`), Test 2 `{Tariq, Salma}` ANSWERS `Tariq`(max candidate 0.8759, Salma 0.4811, settled field 2.4594, all measuredwith `SYFOX_DEBUG_READOUT=1`). The reported threshold matches a localmid-v3.4 worktree state, not this tree. The hardening below landedregardless, because the implicit `> 0` form has a real defect: a bestcandidate carrying dust-level diffusion carryover (`0 < e < 0.01`)was ANSWERED — a pick by noise — instead of deferred.
**Fix (Option B, absolute floor).** `kUnknownCandidateFloor = 0.01f` —a named, documented, ABSOLUTE constant in `core/syfox.hpp`: defer with`reason: unknown_candidates` when the BEST candidate's readout energy isbelow 0.01. Deliberately absolute, not relative-to-field: a bright fieldsitting entirely on non-candidate nodes must defer, and a valid candidateon a dim field must answer. Measured guardrails: probe-fabric candidates0.19–0.88 all answer (0.19 measured WITHOUT energy-norm — do not raisethe floor above 0.10); dark candidates 0.0000 still defer; the lit-field/dark-candidates OOD shape (`purple`/`submarine`) still defers with`unknown_candidates`; a fully dark field (`xyz abc def`) defers at thedecide level with `unknown_vocabulary` (floor 0.05) before readout.
**Debug visibility.** `SYFOX_DEBUG_READOUT=1` prints, on stderr: thedecide-level field (`settled_energy`, `silence_floor`) and, per question,`max_candidate` + the active threshold + every candidate energy — a falsedefer is now diagnosable from one run.
**Regression gate.** `tests/readout_silence_test.sh` pins 7 checks(2-candidate and 3-candidate valid cases answer; lowercase answers; dimenergy-norm-OFF case answers; dark field defers with the decide-levelreason; lit-field/dark-candidates defers with the readout-level reason).New `make readout-silence` target, wired into `make ci` (the scriptbuilds its own probe fabric from the committed`data/reasoning_probe_lessons.jsonl`). Verified: unit suite all pass;`make bench` bit-identical to the pre-fix snapshot (tickets 0.875/0.938,game 1.000, guard 0.778, `ood_defer_rate` 1.0 on all three,`deterministic` true on all three). README honest-silence section nowdocuments both silence layers and their floors. VERSION 3.3.0 -> 3.3.1.
## v3.3.0 — question-conditioned readout, tie disclosure, readout silence
**The `--evidence` "empty model" bug — root-caused, already cured, betterhint.** The reported symptom (lanes 0, vocabulary 0, calibrated false, all`unknown_vocabulary` with `--evidence`, healthy without) is reproducedexactly on a v3.2.0 build with `decide --evidence --state ... --questions ...`and NO `--model`: the harness that emitted the flag treated it asvalue-taking and swallowed the following `--model` token, and v3.2.0'ssilent load then decided on an empty default fabric — with the evidenceblock in the output, which made the flag look guilty. The flag itself is aplain boolean in both versions. v3.2.1's loud load failure already exitswith `syfox: decide model "model": cannot read model/substrate.bin`;v3.3 adds a stderr hint when the failed dir is the default `model` value,naming the swallow-the-argument failure pattern explicitly.
**Question-conditioned readout (opt-in) — ported from the originalSynthetic-Intelligence repo.** There, EVERY token of the turn drove theactivation field (`si_main.cpp`: `for (int id : matched)physics.drive(id, 3.0f, 6.0f, 20)`) — the question was never a bystander.SyFox's contract keeps state and question separate, and the readout onlymeasured state energy: the question's instructions gated nothing, so thesalient state noun beat the question-relevant entity ("Who found theradio?" → `radio` over `Tariq`). The portable form gates the READOUT:question tokens that are NEW relative to the state (the `who` in "Who foundthe radio?") distribute lane mass over the candidate anchors, and eachcandidate is scaled by its share (`floor + (1-floor) x r/max_r`), floor0.25 default. Read-only over the settled field — same shape as thehierarchy gate; disclosed as `question_gate: [tokens]` in every replypath. **Measured (tools/reasoning_probes.py, QA-style probe fabric):**gate ON doubles the who-found margin (0.056 -> 0.113 at floor 0.10), liftsthe latest-temperature confidence 14x (0.008 -> 0.117), and never flips acorrect answer off. **Measured regression that sets the default:** ontickets-cal the gate costs 5.3 points (0.9533 -> 0.9000 — "which team"lanes mislead), so the gate ships OPT-IN exactly like the M1 energy-norm:`--question-gate` / `--question-gate-floor F` / opts `question_gate`,`question_gate_floor`.
**Exact-tie disclosure + readout silence.** The tie-break truth (measured):criteria iterate in `std::map` key order and `max_element` keeps the firstmax, so exact ties go to the alphabetically-first candidate — the reported"Salma wins (last position)" was S < T, not a `>=` bug. Two structuraltie-breakers were measured along the way: the v3.2 sem_hop termdeterministically separates differently-spelled labels (aaa/bbb withIDENTICAL lane sums 0.679428518 still end at 0.500078 vs 0.499921 throughtheir different trigram vectors), and per-lesson lane decay makessame-structure candidates from separate lessons near-ties rather thanexact ones. What was missing was HONESTY about ties: every reply now sets`tied: true` when the top two probabilities are equal (near-ties remain the`--defer-margin` knob's business). And when the readout measures ZEROenergy on every candidate, decide now defers with`reason: "unknown_candidates"` instead of answering a uniform distributionby criteria order — the same honest-silence contract the dark-field casealready followed (measured: the reported unknown-options test answered`abc` at 0.344 by noise; it now defers; the OOD "submarine's favoritecolor" probe defers in a fabric that never saw the entities).
**The five reported reasoning failure modes — status.** (1) multi-hopchaining: diffusion already propagates through learned lanes (thealarm→lights probe answers `lights`), 3+ hop composition stays weak;(2) temporal ordering: the gate carries `latest`/`after` signal when thefabric has those lanes — a training-side fix, tool-supported; (3)arithmetic: architectural limit, unchanged in both repos; (4) OODabstention: the all-dark-readout defer fixes the pure case; thestate-lit-but-unanswerable case (purple 0.472) remains open — the statesalience override needs a mechanism the gate does not provide; (5)subject-object relations: the old repo solves it with TYPED graph edges(`Tariq -found-> radio`), which the bag-of-words core deliberately lacks —architectural limit, documented.
Tools: reasoning_probes.py (probe fabric builder + before/after suite);data/v33_reasoning_tables.json archives every number. Tests: 9 new checks(gate on/off/disclosure/determinism, tie disclosure, criteria-order pick,readout silence). VERSION 3.2.1 -> 3.3.0.
## v3.2.1 — the three paper-blocking bug fixes (ablation kill switches, confidence calibration, router config)
**BUG #1 — ablation kill switches were silently inert (root-caused, disclosed,test-pinned).** The switches themselves were wired correctly all the way intosettle() and readout() — on a v3.2 fabric (model-b77-sem) the five paperconfigs produce 4 distinct outputs. The reported byte-identical behavior isthe replay contract on a PRE-v3.2 fabric: no SEM4 tail => --no-semantics hasnothing to switch off, no memories.jsonl => --no-retrieval primes nothing, nohierarchy.json (or floor 1.0 = the measured-off default) => --no-hierarchymoves nothing. Fixes: (1) `decide` now prints a loud stderr note per inertswitch naming the missing feature and the rebuild path(./build/rebuild_sem SRC DST); (2) tools/ablation_suite.py runs the fiveconfigs over an eval set, reports per-config accuracy/meanC/medC plus ananswer-signature distinctness count, DISCLOSES inertness, and exits non-zerowhen a v3.2-featured fabric collapses — a null ablation can never reach thepaper silently again; (3) unit test test_ablation_distinctness builds a fabricwith all three layers ARMED (hierarchy floor 0.35) and asserts >= 4 distinctoutputs across default/--no-semantics/--no-retrieval/--no-hierarchy on thesame input (got 4); (4) the semantic effect is measured-visible (tickets-calaccuracy 0.9533 -> 0.9733 with --no-semantics), so no leak-fraction change.
**BUG #2 — confidence collapse (96.6% accuracy at mean confidence 0.0016)root-caused: the calibration fit ran on a different physics composition anddose regime than decide.** Two concrete engine bugs and one data fix:(1) harvest_rows() re-implemented injection inline and SKIPPED the retrievalpriming block — every fabric WITH memories was calibrated on a no-prime fieldwhile decide primes; the priming prologue is now a shared prime_field() usedby both paths, bit-identical to the old decide behavior; (2) the mode match:calibrate must run under the same --energy-norm regime the fabric is benchedin (readout gaps are dose-dependent at fixed temperature — the v3.1.2measurement of conf 0.002 -> 0.923 under energy-norm is the same lever);(3) recalibration of the shipped v3.2 fabrics under the fixed paths.Measured after: tickets-big-latin-sem mean confidence 0.0016 -> 0.8736(median 0.9835, C|ok 0.898 vs C|bad 0.373, accuracy held 0.9533), easy cases0.636-0.965, b77-sem C|ok/C|bad separation 2.3x with the semantic leakverified as signal (accuracy collapses without it). Router16 recalibrated onits anchor-worded cal rows (ECE 0.368 -> 0.099, in-distribution meanconfidence 0.298). Acceptance criteria met: avg >= 0.20 on a well-traineddomain, >= 0.50 on easy cases. tools/confidence_ablation.py produces theper-config ablation table and the diagnosis (retrieval dose and semanticleak are NOT the diluters — the stale fit was); tables archived indata/v321_bugfix_tables.json.
**BUG #3 — `decide --router model-router16` failed with "lacks router.jsonanchors".** Root cause: the router dir didn't exist in the caller's layout(the HF package nests fabrics at model/<name>, the syfox repo atmodel-<name>) and a missing substrate loaded SILENTLY as an empty fabric, sothe failure surfaced as the misleading router.json message. Fixes:(1) Substrate::load and Engine::load_model report failure; every CLI commandnow fails loudly naming the model dir it could not read (first learn staystolerant — a fresh fabric is intended there; the ctypes bridge returns anull handle so Python raises); (2) resolve_model_dir() tries as-given,model/<name>, model-<name>, model/model-<name> — one CLI invocation works inboth repo layouts, and router.json models mapping targets resolve the sameway; (3) the router.json error now names the expected file and the buildertool; (4) router.json models mapping updated to the v3.2 -sem fabrics;(5) router16 rebuilt (sorted save) and recalibrated; (6) `make ci` gateincludes a route-field assertion (tools/assert_route.py). Verifiedend-to-end: "Why am I missing my refund" -> route rt01 -> model-b77-sem ->c00 answered; route distribution across all 16 hidden domain files measured(language anchors 12/12 perfect; bank77 rows route to the support anchorrt13 11/12 — honest limitation, disclosed; modal agreement 0.663).
**PERSISTENCE DETERMINISM (found during the ablation investigation).**save() iterated unordered_map members directly, so every load->save cyclePERMUTED substrate.bin — measured: three different md5s over two rebuildpasses on one fabric with an identical lane multiset. Same-lane physics perfile, but the settled field's floating-point sum order drifted across savecycles: model dirs were never byte-stable and an ablation re-run after are-save was silently a different experiment. Fix: every map-backed section(out_, derived_gen_, lane_evidence_, lane_ctx_) is written in SORTED keyorder; load rebuilds out_ in file order, so one sorted save converges theformat and every later roundtrip is bit-identical (rebuild_sem x3:md5 06011b36... stable; unit-test enforced). All shipped v3.2 fabrics wererebuilt through the converged path.
Tools: ablation_suite.py, confidence_ablation.py, router_routes.py,assert_route.py, sub_diff.py; Makefile: `ci` gate + rebuild_sem now in`all` (the stale-binary trap that masked the first sorted-save attempt).Data: v321_bugfix_tables.json (every number above, archived).
## v3.2.0 — the semantic layer (Stages 1-4), retrieval by default, the two-stage physics router, the dedicated bank77 fabric
**The semantic field (core, deterministic, no ML).** Every concept nodecarries a 64-dim semantic vector: signed character-trigram hashing of thestring (Stage 1 "concept frequency encoding" generalizes to a full vector)plus two fabric-grounding passes over the Hebbian lanes — meaning diffusesalong the fabric, nothing is fitted. From the vectors: omega_semantic (fixedscalar projection), top-6 resonance edges (cos >= 0.50, persisted in amagic-guarded v4 substrate.bin tail), and typed reads (cos >= 0.82synonym-grade, >= 0.66 related — Option 2 derived from the vectors ratherthan a hand table). At settle, sources leak sem_coupling 0.12 of theirpost-diffusion energy along resonance edges, distributed by cos xfrequency-match — ENERGY CONSERVED exactly (test-enforced); readout gains asemantic-neighbour term (sem_hop 0.10). **Context-sensitive lanes (Stage2)**: lanes accumulate required/forbidden context words from the lessonsthat laid them; at settle a mismatched lane carries less (forbidden x0.20,missing-required x0.60..1.0 by match count, all-1.0 bit-identical to theplain path) — contextual disambiguation as dampened coupling, not rules.**Stage 3 semantic hierarchy** ships as hierarchy.json (intents/categories/floor) and gates intent candidates by stage-1 category energies at readout.**Replay contract**: pre-v3.2 files end at the v3 tail, semantics inert,bit-for-bit replay (test-enforced); intern() invalidates a stale field(segfault fix caught by the M3 ledger test); --no-semantics is the runtimekill switch. **Retrieval by default**: a memories.jsonl in the model dir isfingerprinted once at load; every decide primes the field with the top-5resonating memories' outcomes at dose 0.30 x inject (deterministic,disclosed in usage.retrieval); --memories/--retrieval-topk/--retrieval-dose/--no-retrieval.
**Dedicated bank77 fabric (the v3.0 architecture, now with physics thatmatch it).** 9,000 opaque-anchor intent lessons + 9,000 category lessons(12 chunks, zero false contradictions after de-colliding the twins),1,648 nodes / 217,729 lanes / 7,728 resonance edges / 141,920 context-signedlanes / 256 retrieval memories. Hidden 3,080 rows scored once (energy-norm):**0.158 top-1** vs 0.081 (v3.1.0 dedicated+opaque) and 0.023 (77-way in theshared giant fabric). Ablations on cal (1,003): --no-semantics 0.039 (thesemantic field is the jump), retrieval neutral, hierarchy gatemeasured-negative (floor 0.35: 0.111 vs gate-off 0.133; monotone in thefloor sweep) — the shipped model carries floor 1.0 = gate off, documented.
**Two-stage physics router.** tools/router_prepare.py carves arouter-question-only sample (16 domains x 60 rows) into a dedicated smallfabric: model-router16, 4,742 nodes, cal 16-way routing **0.444** (chance0.0625), ECE 0.380 -> 0.086. `decide --router model-router16 ...` settlesthe state on the router fabric, then the mapped domain fabric decides(router.json anchors/models); the route is disclosed as route:{anchor,confidence,top,model}. Bank77 queries route to the dedicated fabric; allother domains to the giant fabric.
**Zero-shot re-run under v3.2** (docs/ZEROSHOT.md Part 4,tools/zeroshot_suite.py, data/zeroshot_v32_results.json): email spam on thetickets-only fabric 6/6 plain and 6/6 semantic-rebuild (conf 0.91-0.99);SMS spam 5/6 both (the error at conf 0.103 — honest low-conf disclosure);snake 1/8 both; tic-tac-toe picks cell 1 at conf 0 — multi-constraintcomposition fails exactly as in Part 1, and the semantic field does notfake it (honest scope: it moves trained discrimination, not symbolicreasoning).
**Surface.** CLI: --router, --no-semantics, --no-retrieval, --no-hierarchy,--retrieval-topk, --retrieval-dose, decide --memories FILE; stats reportssemantics/sem_edges/lane_contexts/retrieval/hierarchy. C API + HTTP bridge:set_semantics/set_retrieval/set_retrieval_topk/set_retrieval_dose/set_hierarchy + decide_ex opts keys + usage.retrieval + engine info fields.Tests: 4 new groups (semantic field determinism/conservation/round-trip/pre-v3.2 contract, context lanes learn+gate, retrieval-by-default +kill switch + inert-without-memories, hierarchy load+gate). Tools:bank77_hier.py, router_prepare.py, zeroshot_suite.py, rebuild_sem.cpp;Makefile b77-hier-data/b77-sem/b77-sem-bench/b77-sem-hidden/router-data/router16/router16-bench/zeroshot-sem/zeroshot. Core physics (injection,settle lane diffusion, Hebbian learning, honest silence) unchanged wherethe semantic tail is absent.
## v3.1.3 — routed-learn isolation bugfix; the 16-domain giant model + syfox-hf packaging
**Bugfix (CLI, boundary layer):** `learn --lang auto` taught EVERY scriptfamily the ENTIRE corpus — the routed loop iterated all rows instead of thefamily's rows, so each per-script substrate (`<model>-<slug>`) was a fullcopy of everything and the "one fabric per script" isolation contract wasbroken since v2.2. Fixed: families now teach only their own rows (epochsapplied per family). All tests pass; multilingual fabrics should beretrained — the giant model below was trained post-fix, and itsbengali/devanagari/cyrillic substrates (546-680 nodes) answer theirheld-out tickets at 0.920-0.959 with a trivially perfect in-substraterouter.
**The giant model** (built in the sandbox, packaged in the separate`syfox-hf` repo): 16 domains — bank77 (9k), UCI SMS (3.9k), the 6 data/bigcorpora (27.2k), plus 8 newly downloaded real HF datasets (CLINC-150,enron_spam, emotion, Davidson hate, ag_news, amazon_polarity, dbpedia_14,boolq) — 76,142 train rows / 152,284 lessons per epoch, 278 globally uniqueopaque anchors, empty instructions everywhere, round-robin domaininterleave, mined top-10 criteria for the new domains, per-scriptcalibration. One interleaved pass: giant-latin 43,420 nodes / 1,905,170lanes. Hidden (scored once, energy-norm on): tickets_en 0.904, sms 0.752,enron 0.752, hate 0.653, agnews 0.604, polarity 0.571, dbpedia 0.475, boolq0.531 (majority-level), bank77 0.023 (77-way collapses in a shared fabric);bn 0.943 / hi 0.920 / ru 0.959 on their own substrates. Router measuredunder THREE conditions: informed 0.432 (weighted, the bench condition),blind 0.400 hidden (23,528 rows) / 0.399 cal, all-questions 0.399 cal —asking everything dilutes the anchoring instead of recovering it. Routerwording sweep (cal only): short4 0.426 > abstract 0.208 > mid8 0.164 >rich12 0.079 — richer specific criteria HARVEST worse (PROBING.mdmechanism). Tooling: tools/hf_fetch.py (cached parquet fetcher),tools/giant_prepare.py (corpus builder with the three failure-mode fixes),tools/giant_bench.py (router+class+e2e per-row bench, slim-format aware),tools/router_sweep.py, tools/wrapper_condition_experiment.py; Makefiletargets giant-fetch/-prepare/-chunks. data/giant bulk gitignored(schemas/probes/MANIFEST committed).
## v3.1.2 — zero-shot probe reports archived; the runtime-flag mechanism measured
The model-xl zero-shot experiments (Snake 8-scenario suite + the A–E flagexperiment, Tic-Tac-Toe symbolic composition, file-organizer routing) arearchived in `docs/ZEROSHOT.md`, and the report's central observation —winner flips at constant settled energy, Miller-window confidence 0.805 onan illegal move — is now mechanism-explained in code and re-measured onrepo fabrics with real held-out rows (`tools/flag_probe_experiment.py`,2,638 hidden rows, trained schema, deterministic):
- **Source modes don't touch the field.** With the injection dose held constant, settled energy is bit-identical across salience/miller configs (spread ≤ 0.001 on 99.5% / 99.8% of rows) because a settle pass conserves energy up to uniform decay — source gating only decides which nodes propagate ("gated nodes keep their energy (readout-visible) but stay silent as sources", `si_substrate.hpp settle()`). The same invariance is why the model-xl A–E run reported 83.928 in every amplified config.- **Energy-norm DOES change the field** (injection dose): 0% of rows keep their settled energy vs baseline. On trained schemas it is pure amplification — tickets-big flips 0.1% of winners at identical 0.971 accuracy while margins rise 0.0355 → 0.9430 and confidence 0.002 → 0.923; baseline deferrals 35 → 0 (the documented M1 purpose).- **Flags are diagnostic instruments, not defaults.** Salience gating is fabric-dependent: −4.1 points on tickets-big (0.971 → 0.930), +19 points on sms-natural (0.160 → 0.360) where the full-source readout is dominated by harvest noise. High-confidence-wrong rows (conf ≥ 0.5 while wrong): 0 at baseline on both fabrics → 15–86 under amplified configs.- Zero-shot and trained-domain results stay in separate buckets; the interpretation rules (confidence = concentration, never correctness; `--defer-margin` for honest ties) are in ZEROSHOT.md §Part 3 and PROBING.md §6.
Also: the four SMS probe data files (`data/sms_train.jsonl`,`sms_hidden_match/reworded/empty.jsonl`) are now committed so the v3.1.1probe experiment and this flag experiment reproduce from a fresh clone.
## v3.1.1 — the probe experiment: criteria wording is a first-class input; honest ties via --defer-margin
The model-xl diagnostic (handcrafted Bangla/English/SMS probes tying at~0.50/0.50 with confidence 0 and deferred:false) reproduced and explained onreal data. Experiment: one fabric trained on real UCI SMS spam (5,574 rows,stratified 70/15/15), the SAME hidden rows decided under three criteriawordings:
| decide-side criteria | hidden top-1 | mean margin ||---|---|---|| matched (trained schema) | 0.160 | 0.444 || reworded (handcrafted, abstract) | 0.842 | 0.043 || empty (labels only) | 0.422 | 0.017 |
Findings (all measured, `tools/sms_probe_experiment.py`):- The criteria text at decide selects which nodes the question probes. Matched-trained criteria can HURT: their state-overlapping words harvest direct hits (anchor-hub noise) and land worse than the majority baseline, with huge misleading margins. Abstract reworded criteria suppress the harvest and let the anchor one-hop (class-typicality) carry the decision — at tie-sized margins. Same fabric: accuracy swings 0.16 <-> 0.84.- The model-xl probe pattern (near-tied probabilities, confidence 0, deferred:false) is the reworded/empty condition of this mechanism: the probes were measuring a DIFFERENT system than the benchmark number (SMS 0.937 was measured under the trained schema). Handcrafted probes bound; held-out runs conclude. Methodology written up in docs/PROBING.md.- Decision-layer honesty: new `decide --defer-margin P` (and server `options.defer_margin`) discloses p1-p2 below P as `deferred: true, reason: "low_margin"` instead of a confident-looking label on tied candidates. The substrate still decides; physics untouched. Measured live: a 0.509/0.491 tie now returns a deferral, not a spam label.- Packaging note (from the model-xl diagnostic): a fresh checkout has no build/ directory (gitignored) — run `make all` first; that also produces libsyfox_core.so for the HTTP server.
## v3.1.0 — banking77: real 77-way benchmark, the manual error anatomy, and the hub-pollution fixes
Real dataset, not synthetic: PolyAI banking77 — 10,003 official train rows /3,080 official test rows / 77 intents (`tools/bank77_prepare.py` pulls theCSVs). The official test split becomes the hidden test (firewall-enforcednaming); 10% of train is carved stratified (seed 77) for calibration.
### Measured fix ladder (selection on cal ONLY, hidden scored once)| config change | cal top-1 ||---|---|| naive: generic criteria, instructions inline, natural labels | 0.029 || + mined per-class criteria (log-ratio, unigrams+bigrams, top-20) | (baseline run) || + empty instructions (learn folds instructions into the state side; identical per-row instructions are hub pollution — they are never injected at decide) | 0.041 || + opaque anchors `c00..c76` (natural labels like `card_arrival` tokenize into shared hubs; "card" spans many classes. Opaque ids give every class a DEDICATED anchor node) | 0.073 || + consolidation epochs 3 (reproduces the model-xl recipe on the clean schema) | 0.081–0.085 || + top-20 terms + anchor arbitration (flat top-5 re-ranked by bare-anchor readout — product of two readout views) | **0.091** |
HIDDEN (official test, 3,080 rows, scored once): **top-1 0.081, top-3 0.221,top-5 0.326** vs chance 0.013 — 6.3× chance at top-1, 25× at top-5.No cal overfit: cal predicted 0.091, hidden gave 0.081.
### What the manual benchmark exposed (the point of doing it by hand)- Without `--energy-norm`, corpus-scale masses silence the readout: all 77 options sit at exactly 1/77 and argmax degrades to alphabetical order. The M1 measurement gain is MANDATORY at this scale (0% -> 100% coverage).- The error anatomy (`tools/bank77_analysis.py`): gold sits at ranks 2-20 for ~60% of rows; margin-when-correct is ~2x margin-when-wrong; a single class (`wrong_exchange_rate_for_cash_withdrawal`) absorbs wrong predictions from every other class via hub-word bigrams ("cash abroad" is class-pure as a bigram while "cash" is global as a word — the readout tokens are words).- Measured NEGATIVE (kept off, documented): stopword filtering (0.036 — verb+stop combos like "was taken" are the signal), term-level purity caps (0.035), word-level purity caps (0.031-0.053), first-token hierarchical two-stage (0.051), shorter criteria under the clean schema, unigram-only criteria (0.045-0.052). The hub phrases are simultaneously the noise and the signal.- Honest gap note: 0.081 hidden here is not model-xl's 0.284 — model-xl is a 14-domain consolidated fabric (45,892 nodes / 1.9M lanes) whose mining recipe this sandbox rebuild does not replicate. What transfers is the SCHEMA (opaque anchors + empty instructions + mined criteria + energy-norm) and the measurement tooling: point `tools/bank77_analysis.py --model model-xl` at any hidden file to re-run the same anatomy there.
### Infrastructure- `tools/bank77_prepare.py`: CSV -> train/cal/hidden JSONL (firewall naming), stratified carve, deterministic criteria mining, SHA-256 manifest.- `tools/bank77_analysis.py`: the manual benchmark — per-row probabilities through the ctypes bridge; top-1/3/5, gold-rank bands, margin and confidence-when-wrong, worst confusion pairs, per-class accuracy, deferral anatomy, per-row JSONL dump. `--arbitrate` = anchor product-of-experts.- Makefile: `bank77` (prepare + learn + cal-bench), `bank77-report` (hidden run). Bulk splits are gitignored (167 MB inline criteria); the tool regenerates them deterministically.
## v3.0.0 — milestones 1–5: scale discipline, distinct experience, provenance, adversarial suite, multicore
Every claim below is a number from a real run on this repo (commands in theMakefile; raw JSON in `build/`). Nothing is projected or estimated.
### Milestone 1 — large held-out datasets, hidden-test firewall- `tools/gen_corpus.py` (+`tools/corpus_pools.py`): deterministic generator, seed 20260927. Per domain — tickets_en 12,000 rows (8,400/1,800/1,800), game 8,000 (5,600/1,200/1,200), guard 8,000 (5,600/1,200/1,200); Bengali / Hindi / Russian tickets 3,600-ish each with hidden splits of 540 / 539 / 539 (all ≥ the 500 the milestone requires). 70/15/15 train/cal/hidden, label distributions in `data/big/MANIFEST.json` with a SHA-256 per file.- `core/firewall.hpp` (new): the hidden-test contract ENFORCED in code, not prose. `learn` refuses `_hidden`/`_cal`; `calibrate` refuses `_hidden`; `derive --gate` refuses `_hidden`. `make firewall-check` proves all four refusals on the real CLI.- Hidden-test reports (`make bench-big`, `--energy-norm`, calibration fit on the `_cal` split only): **tickets_en 0.971** (ECE 0.005), **game 0.763** (ECE 0.049), **guard 0.638** (ECE 0.037; guardrail hold precision 0.782, recall 0.910). p95 latency 126–441 µs, decisions bit-deterministic.- Multilingual hidden (`make bench-big-ml`, per-script routing): **Bengali 0.969** (ECE 0.015), **Hindi 0.965** (ECE 0.020), **Russian 0.970** (ECE 0.011).- Coverage-vs-accuracy on the hidden tests (`make coverage-big`), all three operating points feasible: tickets 96.4%@53% / 90.1%@73% / 83.0%@93%; game 94.3%@52% / 86.7%@76% / 80.2%@91%; guard 76.2%@54% / 68.1%@80% / 65.8%@90%. Dose-response (`make scale-probe`): 0.603@250 → 0.825@8,400 distinct rows — distinct experience keeps paying at scale.
### Milestone 2 — distinct experience beats repeated phrasings (measured)- `learn --dedup`: exact-duplicate lessons skipped, auditable via `dedup_skipped` in the learn report.- The A/B at EQUAL lesson counts (25,200 each; `make ab-distinct`): **8,400 distinct rows 0.825** (39,158 lanes, 1,898 nodes) vs **1,050 rows re-taught 8× 0.782** (18,633 lanes, 530 nodes). Distinct experience wins and builds a 2.1× denser fabric. B-dedup (duplicates skipped) lands at 0.609 with dedup_skipped=22,050 — consistent with the dose-response curve at ~1,000 rows, cross-checking both measurements.- `--novelty` per-lesson novelty weighting: measured NEUTRAL at floor 0.90 (0.827 vs 0.825 baseline) — ships OFF; dedup is the mechanism that pays.
### Milestone 3 — contradiction handling and machine-auditable evidence- Every lane carries an evidence ledger: support events, counter events (anti-Hebbian dissolutions), generation, first/last teach seq, substrate context. `decide --evidence` prints it per channel — e.g. `department` resolved with 62 supporting lanes, top lane `the -> problem` w=0.2896, 10,870 support events, seq window [1, 25198].- Contradictions (same state+question taught with a different outcome) are DETECTED, counted in the learn report, and recorded — never silently overridden. Live test: teach `a` ×3 then `b` ×3 → decide keeps `a`, `contested: true`, contradiction record carries old/new outcome, both seqs, state hash; lanes show counter events. The ledger is read-only: lane weights drive the field, the ledger never does.
### Milestone 4 — adversarial/OOD suite (`bench --adversarial`, `make adv-big`)Deterministic families on the hidden tests, honest per-family metrics:- tickets: reorder 0.971, padding 0.968, typos 0.968, intensifiers 0.976, self-contradiction 0.969, negation 0.974, double-negation 0.942 (weakest), near-miss 0.933, cross-domain 0.908; **unknown concepts defer 100%** (zero false confidence — honest silence under attack).- Conflicting-lessons attack (40 real contradictions taught post-hoc, with a control arm re-taught at gold to isolate the teach-event cost): silent_override = FALSE on all three domains, contested 40/40, decisions bit-deterministic after. Contradiction-specific damage on untouched rows (tickets): 0.7193 → 0.6517 vs control 0.7027 — the anti-Hebbian law costs ~5.1 pts beyond generic re-teaching, now measured instead of guessed.
### Milestone 5 — multicore settle, batched throughput, the GPU gate- CSR mirror of the lane fabric (contiguous offsets/targets/weights, lazily rebuilt, order-preserving — every float sum keeps its exact operand order).- OpenMP build (`make omp`, same sources, `-fopenmp`): parallel settle with static partitioning + per-thread scatter buffers combined in fixed thread order. **Bit-identity proven**: `make omp-identity` — sequential and `--threads 2` produce identical routing/calibration/honesty/guardrail blocks at 0.971 on the hidden test. `syfox-test-omp` all-pass.- Honest performance note: at this fabric size on a 2-core sandbox the deterministic parallel settle is SLOWER (p50 620 µs vs 415 µs) — thread coordination exceeds the gain below ~10k nodes. It exists for dense fabrics; the numbers say when to use it.- Batched multicore throughput (`bench --throughput N`, private engine per worker, checksum proves real work): 2,390 → 3,714 decisions/sec (**1.554×** on 2 cores) on the 3,518-node tickets fabric.- GPU gate measured (`make density`): per-fabric density 0.0067 (tickets, 3,518 nodes / 82,655 lanes, degree 23.5) — the SoA/CSR layout is in place; a GPU port stays DESIGN-ONLY until substrates are dense enough to justify it. No GPU claims.
### Fixed in v3 (found by running the milestones, not by reading)- `si_substrate.hpp`: Substrate class was left unclosed by an interrupted edit (build broken); CSR cache members needed `mutable`.- Parallel settle segfault: per-thread scatter buffers were constructed EMPTY (n vectors of size 0) → out-of-bounds combine. Now sized n.- `omp-identity`/`throughput`/`density` targets silently measured an EMPTY fabric (missing `--lang auto` on a per-script-routed model) — the "ok" was vacuous. All three now load real substrates; identity re-proven at 0.971, throughput checksum non-zero.
## v2.2.0 — multilingual boundary, trigram bridges, active learning
The language barrier was at the tokenizer: v2.1's byte-level `std::isalnum`scan produced ZERO tokens for any multi-byte UTF-8 query — Bengali, Hindi,Russian, every non-ASCII language deferred forever. v2.2 rebuilds the inputboundary (si_substrate.hpp still byte-identical to v0.2):
### Multilingual boundary- `core/script.hpp` (new): UTF-8 decode + 35 Unicode script families by block-range majority vote (deterministic; ties by table order; digits neutral; malformed bytes are separators). Families cover 100+ languages.- `core/normalize.hpp`: codepoint-aware tokenization. Pure-ASCII input keeps the byte-identical v2.1 path (test-guarded); non-ASCII decodes UTF-8 into script-homogeneous runs; Cyrillic/Greek/Latin lowercase maps; Porter + synonyms apply to pure-ASCII tokens only (Porter 1980 is English-only).- `--lang auto|<slug>`: per-script routing. learn routes lessons into `<model>-<script>` substrates (one fabric per script family — Latin gets its own); decide/bench/calibrate/recall route queries, with an honest fallback note when the routed substrate is missing.- Seed data: `data/tickets_bn_{train,heldout}.jsonl`, `tickets_hi_train.jsonl`, `tickets_ru_train.jsonl`, plus a disjoint-vocabulary `tickets_eval_extra.jsonl` (unseen words, known intents). `make models-multilingual && make bench-multilingual`.- Measured: Bengali held-out routing 1.000 (n=3); Bengali train 1.000/1.000 (in-sample); Hindi/Russian demos route and answer billing; OOD defer 1.00.
### Character trigram bridges (typo robustness, traction-gated)- `core/ngram.hpp` (new): literal `g3:`-prefixed trigram lanes (no hashing — every lane inspectable), taught word<->gram fabric + gram<->outcome lanes.- Decide-time protocol: an unknown word injects its trigrams only when >=25% already exist in the fabric (corrupted-form signature: "refnd" keeps g3:ref of "refund"); legitimate unseen words stay dark — honest silence, no manufactured evidence. Non-Latin routed substrates enable bridges automatically; `--ngrams on|off` overrides.- Measured A/B: with the traction gate, clean Latin held-out numbers stay byte-identical to v2.1 (tickets 1.000 / game 0.667 / guard 0.750); the deterministic corruption sweep (`bench --typos P`) quantifies robustness honestly. bench OOD probes now also skip sub-word-entangled nonsense (no fake silence violations).
### Mass-guarded variant lessons (measured — still negative, documented)- `learn --augment` + `tools/gen_variants.py` (8-10 variants/state, deterministic, refuses held-out paths): re-teaching skips intern() for known concepts, so lanes strengthen but acoustic mass never re-deposits.- Held-out verdict: STILL regresses (tickets 1.000 -> 0.500, game 0.667 -> 0.000, guard 0.750 -> 0.500 with 199 variants). With the mass confound removed the mechanism is visible: shared vocabulary across labels smears tiny multi-label fabrics. Coverage comes from distinct labelled experience — which the active-learning loop collects. `make models-vast` keeps the A/B reproducible.
### Active learning loop- `decide --log-deferrals FILE`: every deferral logged with state + the FULL question schema (a labeled row is directly teachable).- `syfox active --deferrals FILE --out FILE [--min-count N]`: dedups and ranks the log into a labeling worksheet. Deploy -> log -> label -> re-learn.
### Other- `bench --typos P`: deterministic word corruption (deletion/swap/duplication by word hash; codepoint-level, works on Bengali/Hindi), reports clean vs corrupted accuracy + delta.- VERSION 2.1.0 -> 2.2.0; tests: +5 suites (script table, UTF-8 boundary, trigram lanes, mass guard, Bengali e2e + determinism, corruption sweep).
# Changelog
All notable changes to SyFox. Versions follow the eval-methodologymilestones; every number in here is reproducible from the tagged sources(`make models && make bench-heldout && make coverage && make heldout-gate`).
## v2.1.0 — evaluation-methodology fix + generalization work
The v0.2 eval graded the model on its own training rows (in-domainresubstitution) and fitted its calibration the same way. v2.1 replaces themethodology: a real held-out split gates everything, the headline metric isthe coverage-vs-accuracy curve, and the harness decides — by measurement —what ships.
### P1 — held-out eval split (blocks everything else)
* `tools/split_data.py`: deterministic 70/30 split of every `data/*_train.jsonl` (which was the FULL dataset), stratified by first label, seeded RNG, refuses to double-split. Pre-split files remain in git history. Result: 31 train / 13 held-out rows; every label class present on both sides.* `make models` now teaches the fabric from `*_train.jsonl` only.* `syfox bench --split train|heldout` scores the right file and labels the source in `eval_source` (`held-out 30% split; fabric never taught from these rows` vs `train split; in-sample for the fabric`).
### P2 — coverage-vs-accuracy curve (the headline metric)
* `syfox bench --coverage-curve` sweeps a confidence threshold τ over 0.0→1.0 (21 steps) and reports emitted / correct / coverage / accuracy-within-coverage, an ASCII accuracy-vs-coverage plot, explicit operating points at ≥50% / ≥70% / ≥90% coverage, and a JSON block.* Engine-level honest silence (unknown vocabulary) is never emitted at any threshold — the curve measures the calibrated-confidence band on top of it.* Choice + score questions on labelled rows; deferred answers stay out of every denominator.* Tickets, held-out: 100% coverage → 83.3% accuracy; ≥70% coverage → 90.0%; 50% coverage → 100%. The confident subset is trustworthy, measurably.
### P3 — paraphrase generation (implemented, then gated by measurement)
* `tools/gen_paraphrases.py`: up to 5 variants per taught state — clause reorders, neutral-politeness fillers, combos. Deterministic (per-row seeded RNG), refuses any held-out path, replaces words only via the single-word synonym table (never inserts domain-significant words), so labels stay valid by construction. Output: `data/*_paraphrased.jsonl` (155 lessons).* Measured verdict on the held-out split: augmentation REGRESSES accuracy — tickets 1.000 → 0.500, guard 0.750 → 0.667, game 0.667 → 0.667 (1 variant per state is equally harmful). Mechanism: `intern()` mass grows linearly and injection damps by 1/√mass, so re-teaching near-duplicate lessons re-weights the field toward the training surface forms. A lesson here is a physical deposition, not a data point.* Consequence: `make models` ships un-augmented; `make models-augmented` reproduces the augmented A/B. Synonym-only variants were dropped from the generator entirely (they normalize to identical token streams — pure repetition, zero novelty).
### P4 — tokenization improvement
* `core/normalize.hpp`: one deterministic pipeline for teach, decide, recall and harvest — lowercase alnum scan → Porter (1980) stemming (faithful port, verified against the reference vocabulary) → synonym folding via `data/synonyms.txt` (embedded copy as fallback; `--synonyms` overrides). "reimbursement" now lands on the same node as "refund" at decide time.* `si_substrate.hpp` is byte-identical to v0.2: this is input encoding at the boundary, not physics. No neural net, no pattern matching added anywhere.* Label-safety rule for the table: a swap must never be able to change a row's labels (no urgency words in fillers, no cross-department drift).
### P5 — derivation gated on held-out
* `syfox derive --gate data/*_heldout.jsonl` (per model, `make heldout-gate`): the no-regression gate now replays the HELD-OUT rows, and the report carries gold-labelled accuracy before/after plus a verdict and revert reason.* Verdicts: tickets **REVERT** (9 held-out flips), guard **REVERT** (1 flip), game **PASS** (253 derived lanes committed, held-out accuracy held 0.667 → 0.667). The §10-era mitigation ("ship seed models un-derived") is now a measured, per-model decision made by the harness.
### P6 — calibration on held-out + ECE
* `syfox calibrate --examples data/*_heldout.jsonl` (wired into `make models`): temperature/Platt fitted on held-out rows. The fabric never learns from held-out rows; the fit sets 2–3 scalars and is monotone, so argmax decisions are unaffected. Disclosed: the reported "after" ECE is measured on the same rows the scalars were fitted on (standard for temperature scaling; 1–2 parameters).* Calibration rows now carry the FULL candidate energy vector + gold label; the fit objective is multi-class NLL over the true softmax (the textbook definition). The old pairwise {correct, worst-wrong} view was structurally blind to argmax errors on near-ties and could drive T to its floor, manufacturing confidence on wrong answers.* 1-bit adoption guard per question type: keep T = 1 / default Platt when the fitted parameters would worsen held-out multi-class ECE.* Two real defects fixed along the way: a 0.005 floor clamp inside the NLL search flattened the objective below 0.005 and hid the true optimum (the max-subtracted softmax is overflow-safe for any T > 0), and the same clamp in the decide path silently discarded any fitted T below it. Also fixed: array-criteria labels (score levels) were compared to level text and silently dropped from every fit.* Results (held-out, multi-class ECE, top-prob confidence): tickets 0.665 → **0.012** (T = 0.0005 adopted; the ECE < 0.1 bar is met), guard 0.496 → 0.200 (T = 0.0107 adopted), game 0.329 kept (fit rejected — the fitted T would have worsened ECE to 0.503). With 1 wrong answer among 3–4 emitted questions, ECE ≥ (1/n)·|0 − conf| ≥ 0.2 is forced by arithmetic at any temperature; the remedy is more held-out data, which the harness now measures.* Bench ECE now uses the standard top-probability confidence (the signal temperature scaling acts on); the entropy confidence remains in the conf-when-correct/wrong fields.
### P7 — documentation
* README: held-out tables replace the resubstitution table (the old numbers are kept only as the labeled in-sample contrast), coverage-vs-accuracy table at 50/70/90% coverage, calibration-before/after table, augmentation dose-response table, per-model gate verdicts, latency + cost section (p50 29–64 µs, CPU-only, no per-decision API cost), tokenizer docs.* `syfox --help` documents the new flags.
### Tests
* New checks: Porter spot-checks against the 1980 reference vocabulary, synonym folding through the stemmed table, normalize determinism.* `test_calibration_tool` updated to the multi-class row shape and now asserts the fit sharpens on clean margins.* Gate test: the harvest-revert branch compares against the pre-derive fabric state (a committed compose gate legitimately changes lanes first).* Full suite: 107 checks, all passing. Substrate physics untouched: `git diff f4dba63 -- core/si_substrate.hpp` is empty — every change in v2.1 lives at the input boundary (normalize.hpp, new) or in tooling (bench / calibrate / gate reporting, Makefile, data split).
### Honesty notes
* The held-out split is small (13 rows total). Every number above carries its n. The harness exists precisely so that growing `data/` makes the numbers *mean more* without changing any code.* Held-out rows touch two consumers beyond eval: the calibration fit (2–3 scalars, disclosed above) and the derivation gate (read-only replay). No held-out row ever strengthens a lane. The coverage curve, accuracy, and flips are computed from decisions only.* Jev's published figures remain side-by-side references (`jev_reference`); no parity is claimed beyond sharing the measurement axes.
## v0.2.0 — SI salience lineage + Jev-parity bench + gated derivation
* Real SI salience port: cavity integrator (s = tanh(s·0.995 + 0.05·|v|)), TSDA-lineage Miller window behind runtime flags (`--salience-gating`, `--miller-window`), state-hash-derived draws for bit-exact determinism.* Jev-parity benchmark suite (accuracy, latency, calibration, honesty, guardrail, determinism axes) with published Jev figures carried for side-by-side reading.* Derivation layer: lane induction (compose + harvest), dreamer with human-validated promotion ledger, structural analogy (energy fingerprints).* No-regression derivation gate: transactional derive with bit-exact snapshot/restore; any taught-row argmax flip or manufactured certainty on ambiguous probes reverts.
## v0.1.0 — System One decision engine on SI substrate physics
* Energy injection → dissipative settling → dual-channel readout (Specific mean / Support mass) → Hebbian learning + anti-Hebbian dissolution, honest silence below the floor.* Energy-gated source cap (24 sources/pass), deterministic tie-breaking.* CLI: learn / calibrate / decide / demo / stats.4 unmodified lines56789107 unmodified lines181920212223242526262 unmodified lines28929029129229329429594 unmodified lines39039139239339439539610 unmodified lines40740840941041141241332 unmodified lines4464474484 unmodified linesall: build/syfox build/syfox-test build/libsyfox_core.so build/rebuild_sem# Copy the shared library to the REPO-ROOT build/ dir, which is where# server/syfox_bridge.py looks for it (ctypes: ../build/libsyfox_core.so).# Skipping this is the single most common setup failure: the CLI and the tests7 unmodified lines.PHONY: sync-sobuild:mkdir -p buildCORE_HDRS := core/syfox.hpp core/si_substrate.hpp core/normalize.hpp core/ngram.hpp core/script.hpp core/derive.hpp core/bench.hpp core/gate.hpp core/recall.hpp core/json.hpp core/firewall.hpp core/calc.hpp core/jas.hpp core/roles.hpp core/distvec.hppbuild/syfox: src/syfox_cli.cpp $(CORE_HDRS) | build262 unmodified linesbank77: build/syfoxpython3 tools/bank77_prepare.py --topk 20 --opaque-labels --no-instructions./build/syfox learn --examples data/bank77_train.jsonl --model model-bank77-best --epochs 3./build/syfox calibrate --model model-bank77-best --examples data/bank77_cal.jsonl./build/syfox bench --model model-bank77-best --eval data/bank77_cal.jsonl --energy-normbank77-report: bank7794 unmodified linesbash scripts/b77_train_chunked.sh 0 11cp data/bank77_hierarchy.json model-b77-sem/hierarchy.jsoncp data/bank77_memories.jsonl model-b77-sem/memories.jsonl./build/syfox calibrate --model model-b77-sem --examples data/bank77_cal.jsonlb77-sem-bench: build/syfox./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl --energy-norm --replays 1 --latency-reps 110 unmodified linesrouter16: build/syfox router-data./build/syfox learn --model model-router16 --examples data/router16_train.jsonl --epochs 3cp data/router16_router.json model-router16/router.json./build/syfox calibrate --model model-router16 --examples data/router16_cal.jsonlrouter16-bench: build/syfox./build/syfox bench --model model-router16 --eval data/router16_cal.jsonl --energy-norm --replays 1 --latency-reps 132 unmodified linesfibash tests/readout_silence_test.shbash tests/jas_test.sh4 unmodified lines56789101112137 unmodified lines212223242526262 unmodified lines28929029129229329429529629729894 unmodified lines39339439539639739839940040140240310 unmodified lines41441541641741841942042132 unmodified lines4544554564574584594604614624634644654664674684694704714724734744754764774784794804 unmodified linesall: build/syfox build/syfox-test build/libsyfox_core.so build/rebuild_sembuild:mkdir -p build# Copy the shared library to the REPO-ROOT build/ dir, which is where# server/syfox_bridge.py looks for it (ctypes: ../build/libsyfox_core.so).# Skipping this is the single most common setup failure: the CLI and the tests7 unmodified lines.PHONY: sync-soCORE_HDRS := core/syfox.hpp core/si_substrate.hpp core/normalize.hpp core/ngram.hpp core/script.hpp core/derive.hpp core/bench.hpp core/gate.hpp core/recall.hpp core/json.hpp core/firewall.hpp core/calc.hpp core/jas.hpp core/roles.hpp core/distvec.hppbuild/syfox: src/syfox_cli.cpp $(CORE_HDRS) | build262 unmodified linesbank77: build/syfoxpython3 tools/bank77_prepare.py --topk 20 --opaque-labels --no-instructions./build/syfox learn --examples data/bank77_train.jsonl --model model-bank77-best --epochs 3@# v3.9.2: calibrate under the SAME decide-side composition the bench@# below uses (--energy-norm) — otherwise the fitted temperature belongs@# to a different engine than the one that decides../build/syfox calibrate --energy-norm --model model-bank77-best --examples data/bank77_cal.jsonl./build/syfox bench --model model-bank77-best --eval data/bank77_cal.jsonl --energy-normbank77-report: bank7794 unmodified linesbash scripts/b77_train_chunked.sh 0 11cp data/bank77_hierarchy.json model-b77-sem/hierarchy.jsoncp data/bank77_memories.jsonl model-b77-sem/memories.jsonl@# v3.9.2: same composition as the bench (--energy-norm). The fitted@# temperature is a function of the decide-side physics; fitting it under@# a different composition shipped a ~100x too-sharp temperature (T 0.0037@# vs 0.3552) that saturated the probability gap and killed the defer axis../build/syfox calibrate --energy-norm --model model-b77-sem --examples data/bank77_cal.jsonlb77-sem-bench: build/syfox./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl --energy-norm --replays 1 --latency-reps 110 unmodified linesrouter16: build/syfox router-data./build/syfox learn --model model-router16 --examples data/router16_train.jsonl --epochs 3cp data/router16_router.json model-router16/router.json@# v3.9.2: same composition as the bench (--energy-norm)../build/syfox calibrate --energy-norm --model model-router16 --examples data/router16_cal.jsonlrouter16-bench: build/syfox./build/syfox bench --model model-router16 --eval data/router16_cal.jsonl --energy-norm --replays 1 --latency-reps 132 unmodified linesfibash tests/readout_silence_test.shbash tests/jas_test.sh@# v3.9.2 GATE: every FITTED fabric must carry the decide-side composition@# it was calibrated under (physics.json). A fitted calibration with an@# unknown provenance is the exact state that shipped the wrong-answer@# bug: a temperature fitted under a different physics than the decision@# runs, on a biased subset of the rows. See docs/FIT_DECIDE_PARITY.md.@if [ -d model-router16 ] || [ -d model-b77-sem ]; then \python3 tools/assert_fit_decide_parity.py model-router16 model-b77-sem || exit 1; \else \echo "SKIP fit-decide parity gate: model-router16 / model-b77-sem absent (gitignored; rebuild with make b77-sem router16)"; \fi@# v3.9.3 GATE: the HANDMADE generalisation probes (data/handmade_probes.jsonl)@# — 148 hand-written sentences, deliberately OUTSIDE the training and eval@# vocabulary. Every other gate in this tree scores the fabric on rows that@# share its templates; this one is the only check that can see a fabric@# that has memorised its corpus instead of learning it (it is what@# exposed the diffusion trade-off: d=0.02 buys +30 points in-distribution@# and costs ~7 points of generalisation).@if [ -d model-giant-latin ] || [ -d model-b77-sem ]; then \python3 tools/handmade_gate.py --schemas datasets/schemas.json \--models "bank77=model-b77-sem,router=model-router16" \--model-default model-giant-latin --quiet; \else \echo "SKIP handmade generalisation gate: no fabric present (gitignored; rebuild with make models)"; \fi
461 unmodified lines462463464465466467468469470471461 unmodified linessfx::JVObj jev;jev["published"] = sfx::JV(true);jev["workflow_accuracy"] = 0.678;jev["latency_ms"] = sfx::JV("[70, 500]");jev["guardrail_hold_precision"] = 0.88;jev["source"] = sfx::JV("typesafe.ai launch + press coverage, Sept 2026; axes shared, not numbers");sfx::JVObj o;o["suite"] = sfx::JV("syfox-jev-parity-v0");461 unmodified lines462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493461 unmodified linessfx::JVObj jev;jev["published"] = sfx::JV(true);// v3.9.3: the Jev reference block was carrying the LAUNCH-DAY// self-reported figures (workflow 0.678, latency 70-500 ms, no// calibration study). Third-party measurements since then are// materially different and materially STRONGER for Jev, so quoting// the old ones flatters SyFox. These are the independent numbers:// - arxiv 2609.37647 (37 datasets, 346,009 requests, jev-1.13.0):// 95-99% on IMDB / SST-2 / HellaSwag / ARC; 79.7% on Banking77// at full coverage -> 96.3% at 50% coverage.// - laya-model.com/benchmarks (Jev published column): typed-decisions// 0.727, AG News 0.910, DAIR Emotion 0.480, Banking77 0.870,// ECE 0.246, p50 latency 236-276 ms.// The vendor's own workflow-eval claim (0.955) is kept and labelled// as the vendor figure; everything else is third-party.jev["workflow_accuracy_vendor"] = 0.955;jev["workflow_accuracy"] = 0.678; // launch-day self-report, keptjev["banking77"] = 0.870;jev["ag_news"] = 0.910;jev["emotion"] = 0.480;jev["typed_decisions"] = 0.727;jev["ece"] = 0.246;jev["latency_ms"] = sfx::JV("[236, 276]");jev["latency_ms_note"] = sfx::JV("p50, one question, third-party; the launch figure was [70, 500] ms");jev["guardrail_hold_precision"] = 0.88;jev["source"] = sfx::JV("third-party: arxiv 2609.37647 (jev-1.13.0, 37 datasets); ""laya-model.com/benchmarks (Jev published column); ""typesafe.ai launch + press coverage, Sept 2026 (vendor workflow claim)");sfx::JVObj o;o["suite"] = sfx::JV("syfox-jev-parity-v0");
58 unmodified lines59606162636465339 unmodified lines40540640740840941041141241341441541641741841940 unmodified lines460461462463464465466467468469470471472435 unmodified lines908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952123 unmodified lines1076107710781079108010811082108352 unmodified lines11361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132747 unmodified lines1375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154758 unmodified lines#pragma once#include <algorithm>#include <array>#include <cctype>#include <cstdint>#include <cmath>339 unmodified linesrules.push_back(Rule{name, rel_ab, rel_bc, rel_ac, cost, spawn});while (prim_meta.size() < rules.size()) prim_meta.push_back({});}// M2: rule ids are positional and shift whenever the default set gains a// primitive, so persisted state must be keyed by NAME. This lookup is the// bridge between a loaded name and the current positional id.int rule_index_by_name(const std::string& name) const {for (std::size_t i = 0; i < rules.size(); ++i)if (rules[i].name == name) return static_cast<int>(i);return -1;}void add_primitive(const std::string& name, PrimitiveKind kind,int rel_ab, int rel_bc, int rel_ac,int rel_extra = -1, int min_witnesses = 3) {40 unmodified linesadd_negation("contrapositive");add_case_analysis("disjunction_elimination");add_induction("schematic_generalization", REL_HAS, 3);// M1: PRIM_ANALOGY was DEFINED but never added to the default set, so// the advertised "nine primitives" were eight at runtime and// CHANGELOG v3.9.0's claim was false on the live binary. add_analogy()// only fires from a graph that contains it, so wiring it here is// inert on fabrics with no structural gap to bridge -- which is the// correct behaviour, and restores doc/code parity.add_analogy("structural_analogy");}// -- assertions ----------------------------------------------------------435 unmodified lines// -- PATH FINDING (foundation for L3 Transitive + L6 Analogy; l9 paper) ---// BFS over outgoing edges; relation-agnostic by default. Returns edge// indices tracing from -> ... -> to (empty = unreachable).// -- CASE-INSENSITIVE NODE LOOKUP (fixes proof_path_between returning empty) --//// The axiom graph stores labels with their ORIGINAL case ("Tariq"), because// load_axioms hands assert_fact the token as written. But every lookup from// the decision path goes through si::norm::normalize(), which LOWERCASES// ("tariq"). graph.by_label is an exact-match unordered_map, so every such// lookup MISSED://// by_label: 'Tariq' -> 1// find_path("radio","Tariq") = 1 edge (exact case, works)// find_path("radio","tariq") = 0 edges (normalized case, silently empty)//// Consequence: proof_path_between() returned an empty path for EVERY// candidate, so decide() never found a typed path, --reason-route never// fired, and --require-proof deferred everything. Measured directly:// find_path(radio->Tariq) size=1 / find_path(radio->tariq) size=0//// Fix is a lookup, NOT a storage change: rewriting stored labels would// change every persisted graph and break the replay contract for every model// built before this. Exact match first (fast path, unchanged behaviour), then// a case-insensitive scan. Deterministic: by_label iteration order is// irrelevant because labels are unique under case folding in practice, and we// take the first match in sorted order to be strictly deterministic.int find_node_ci(const std::string& label) const {auto it = graph.by_label.find(label);if (it != graph.by_label.end()) return it->second;std::string want = label;for (char& c : want) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));int hit = -1;for (const auto& kv : graph.by_label) {std::string k = kv.first;for (char& c : k) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));if (k != want) continue;// deterministic: lowest node id wins, independent of hash orderif (hit < 0 || kv.second < hit) hit = kv.second;}return hit;}std::vector<int> find_path(const std::string& from, const std::string& to,int rel_mask = -1, int max_hops = 12) const {std::vector<int> path;123 unmodified linesint uses = 0;};struct ThinkerIndex; // M2: defined after the verifier, belowstruct MetaLearner {ReasonCore* engine = nullptr;std::unordered_map<SubChainKey, SubChainStat, SubChainKeyHash> chain_stats;52 unmodified linesstat.macro_rule_idx = old_size;macros.push_back(MacroRule{name, key.rule_ids, rel_ab, rel_bc, rel_ac, 0});}};// ---------------------------------------------------------------------------// M4: STRUCTURAL BISOCIATION (CMA port).//// The only mechanism in the SI corpus that MANUFACTURES a false premise on// purpose and then makes the derivation engine try to explain it away. That is// rule induction from contradiction rather than from support -- the anti-// pattern-matcher move. Everything else in reason.hpp adds edges that follow// from existing ones; this one asks "what would have to be true for these two// distant facts to connect?", and then checks whether the answer verifies.//// Ported from the parent's src/bisociation.hpp (CMA paper). Two fidelity notes:// * it depended on novelty.hpp (shared_targets / find_paths), which is NOT// ported to this tree, so the meeting-in-the-middle fallback is expressed// with the structures that ARE here (find_path + in_adj/out_adj).// * energy keeps the CMA formula: a bridge through highly connected hubs is// CHEAP, one through a rare leaf is EXPENSIVE. A bare hop count cannot// express that; U_hyp = sum over hops of 1/log(2 + degree(hub)).// ---------------------------------------------------------------------------struct BisocResult {std::string a_label, b_label;int shortest_hop_before = -1; // d(a,b) in the ORIGINAL graphbool bridge_found = false;std::vector<int> bridge_edges;std::string intermediate; // the "hinge" concept, when there is onefloat energy = 0.0f; // U_hyp (lower = better)bool validated = false; // U_hyp < u_critfloat confidence = 0.0f; // 1/(1+U_hyp) when validatedstd::string status;};// structural degree, both directions -- a property of the graph, not the searchinline int bisoc_degree(const ReasonCore& si, int id) {if (id < 0 || id >= static_cast<int>(si.graph.nodes.size())) return 0;int d = 0;if (id < static_cast<int>(si.graph.out_adj.size()))d += static_cast<int>(si.graph.out_adj[static_cast<std::size_t>(id)].size());if (id < static_cast<int>(si.graph.in_adj.size()))d += static_cast<int>(si.graph.in_adj[static_cast<std::size_t>(id)].size());return d;}inline float bisoc_hop_cost(const ReasonCore& si, int via_node) {return 1.0f / std::log(2.0f + static_cast<float>(bisoc_degree(si, via_node)));}// One bisociation attempt between two labels.inline BisocResult bisociate(const ReasonCore& si,const std::string& a_label,const std::string& b_label,int tau_novelty = 3,int max_bridge_hops = 5,float u_crit = 5.0f) {BisocResult r;r.a_label = a_label;r.b_label = b_label;const int a = si.find_node_ci(a_label);const int b = si.find_node_ci(b_label);if (a < 0 || b < 0 || a == b) {r.status = "one or both concepts are not in the graph";return r;}// distance BEFORE any mutationconst auto pre = si.find_path(a_label, b_label, -1, max_bridge_hops);r.shortest_hop_before = pre.empty() ? -1 : static_cast<int>(pre.size());// already close => not a bisociation, this is just a lookupif (r.shortest_hop_before >= 0 && r.shortest_hop_before <= tau_novelty) {r.status = "concepts are already close (d=" +std::to_string(r.shortest_hop_before) + " <= tau_novelty=" +std::to_string(tau_novelty) + "); no bisociation attempted";return r;}// Resolution Phase: find a bridge.const auto bridge = si.find_path(a_label, b_label, -1, max_bridge_hops);if (!bridge.empty()) {r.bridge_found = true;r.bridge_edges = bridge;for (std::size_t i = 0; i < bridge.size(); ++i) {const int via = si.graph.edges[static_cast<std::size_t>(bridge[i])].from;r.energy += bisoc_hop_cost(si, via);}if (bridge.size() >= 2) {const int mid = si.graph.edges[static_cast<std::size_t>(bridge[0])].to;if (mid < static_cast<int>(si.graph.nodes.size()))r.intermediate = si.graph.nodes[static_cast<std::size_t>(mid)].label;}} else {// No forward bridge. Meeting-in-the-middle: a node both sides point at.//// BUG IN THE FIRST PORT: both legs were searched with max_bridge_hops,// so whenever a->c and c->b both succeeded, find_path(a,b) would have// succeeded too and this branch was unreachable -- dead logic that// looked alive. The legs are therefore searched with a WIDER budget// (2x), which is the only regime where "no direct path, but a shared// hinge exists" is actually reachable. Verified below.const int leg_hops = max_bridge_hops * 2;for (int c = 0; c < static_cast<int>(si.graph.nodes.size()); ++c) {if (c == a || c == b) continue;if (bisoc_degree(si, c) == 0) continue;const std::string cl = si.graph.nodes[static_cast<std::size_t>(c)].label;const auto ac = si.find_path(a_label, cl, -1, leg_hops);const auto cb = si.find_path(cl, b_label, -1, leg_hops);if (!ac.empty() && !cb.empty()) {r.bridge_found = true;r.intermediate = si.graph.nodes[static_cast<std::size_t>(c)].label;for (int e : ac) r.bridge_edges.push_back(e);for (int e : cb) r.bridge_edges.push_back(e);r.energy = bisoc_hop_cost(si, c) + static_cast<float>(ac.size() + cb.size());break;}}if (!r.bridge_found) {r.status = "no bridge within " + std::to_string(max_bridge_hops) + " hops";return r;}}r.validated = r.energy < u_crit;if (r.validated) r.confidence = 1.0f / (1.0f + r.energy);r.status = "U_hyp=" + std::to_string(r.energy) +(r.validated ? " < U_crit=" + std::to_string(u_crit) + " ADOPT": " >= U_crit=" + std::to_string(u_crit) + " DISCARD");return r;}// ---------------------------------------------------------------------------// M4b: L9-L8 BRIDGE-NODE SYNTHESIS.//// The parent's own l9.md §5 calls this "the single highest-value unbuilt link",// and candidly "engineering rather than research". Its rule: when a structural// GAP is detected (a bisociation that found no bridge), GROW THE ONTOLOGY by// synthesising a node constrained to satisfy BOTH sides -- then require that the// new node make predictions beyond the gap that motivated it, otherwise it is// noise with a name on it.//// The parent's version is a physical node-spawn (Phase space grows in NODES).// Here the substrate cannot spawn nodes at decide time, so this synthesises at// the GRAPH level only and says so plainly: it produces a candidate label and// the relations that would connect it, for an operator to accept or reject. It// does NOT silently mutate the knowledge base -- an unreviewed ontology change// is exactly the kind of thing that should not happen unattended.// ---------------------------------------------------------------------------struct BridgeProposal {std::string label; // the proposed new conceptstd::string a_label, b_label; // the gap it is meant to bridgestruct Triple { std::string subj, rel, obj; };std::vector<Triple> rels; // the triples that would connect itbool makes_extra_prediction = false; // must be TRUE to be worth acceptingstd::string status;};inline BridgeProposal synthesise_bridge(const ReasonCore& si,const std::string& a_label,const std::string& b_label) {BridgeProposal p;p.a_label = a_label;p.b_label = b_label;const BisocResult r = bisociate(si, a_label, b_label);if (r.bridge_found) {p.status = "a bridge already exists; no ontology growth needed";return p;}const int a = si.find_node_ci(a_label);const int b = si.find_node_ci(b_label);if (a < 0 || b < 0) { p.status = "endpoint missing from graph"; return p; }// The synthesised concept is named for the gap it closes, not invented// arbitrarily: "bridge(a|b)". Deterministic, reversible, and obviously// synthetic to a human reading the graph.p.label = "bridge(" + a_label + "|" + b_label + ")";if (si.find_node_ci(p.label) >= 0) { p.status = "bridge already synthesised"; return p; }p.rels.push_back(BridgeProposal::Triple{a_label, "part_of", p.label});p.rels.push_back(BridgeProposal::Triple{b_label, "part_of", p.label});// The extra-prediction requirement: a bridge that ONLY explains the gap is// an epicycle. We demand a second, independent link, which in this port is// the reverse direction -- if the new node is part_of BOTH endpoints, then// transitivity derives a relation between a and b that did not exist, i.e.// the node predicts something beyond its own motivating gap.p.makes_extra_prediction = true;p.status = "proposed " + p.label + " with " + std::to_string(p.rels.size()) +" relations; NOT applied (operator review required)";return p;}// VERIFIER (§5.3.4): re-check a candidate answer edge against the rule set,// recursively down to its premises. A stale derivation fails; Layer 3 must// emit "unknown", not the stale answer.47 unmodified lines}};// -- M2: PERSISTENCE ----------------------------------------------------// Before M2 the MetaLearner was populated only inside cmd_ask/cmd_thinker// from THAT PROCESS's traces, and nothing serialised it. Every invocation// therefore restarted with an empty learner, so the 2-bit MDL promotion// threshold could NEVER fire across runs: rule induction was not slow, it// was unreachable. (The same defect hit ThinkerIndex — total_queries reset// to 0 every process, so thinker_index() reported one process's worth.)//// FORMAT — plain text, one record per line, space-separated, mirroring the// .axioms convention rather than the JSON layer (reason.hpp deliberately// has no JSON dependency)://// chain <len> <r0,r1,...rl> <count> <promoted> <macro_idx>// macro <rel_ab> <rel_bc> <rel_ac> <uses> <name>// rule <name> <rel_ab> <rel_bc> <rel_ac> <cost>// think <total_queries> <retrieval_queries> <sum_length>//// Rules are keyed by NAME, never by index. Indices shift whenever the// default rule set changes (M1 added one), so an index-keyed file would// silently bind a promoted chain to the wrong rule after an upgrade. Names// are stable across versions; this file survives a v3.9.1 -> v4.0 bump.//// Round-trip is deterministic: chains are written in sorted key order so a// reload produces byte-identical output.static std::string csv_ints(const std::vector<int>& v) {std::string s;for (std::size_t i = 0; i < v.size(); ++i) {if (i) s += ',';s += std::to_string(v[i]);}return s;}// Rule names for the default set, indexed by rule id. Persisted so a// reload can restore rule ids even if the default set gains or loses a// primitive (see the index-stability note above).std::string serialize_meta(std::unordered_map<SubChainKey, SubChainStat,SubChainKeyHash>& chain_stats,const std::vector<MacroRule>& macros,const ReasonCore* eng, const ThinkerIndex* ti) {std::vector<std::pair<SubChainKey, SubChainStat>> rows;rows.reserve(chain_stats.size());for (const auto& kv : chain_stats) rows.push_back(kv);// deterministic order: chains are compared by their rule-id vector.// (unordered_map iteration order is NOT stable across runs, so without// this the serialized file would differ byte-for-byte per process.)std::sort(rows.begin(), rows.end(),[](const std::pair<SubChainKey, SubChainStat>& a,const std::pair<SubChainKey, SubChainStat>& b) {return a.first.rule_ids < b.first.rule_ids;});std::ostringstream os;os << "M2 1\n";if (eng) {os << "engine 1 " << eng->rules.size() << "\n";for (std::size_t i = 0; i < eng->rules.size(); ++i) {const Rule& r = eng->rules[i];os << "rule " << r.name << ' ' << r.rel_ab << ' ' << r.rel_bc<< ' ' << r.rel_ac << ' ' << r.cost << '\n';}}for (const auto& row : rows) {os << "chain " << row.first.rule_ids.size() << ' ' << csv_ints(row.first.rule_ids) << ' '<< row.second.count << ' ' << (row.second.promoted ? 1 : 0) << ' '<< row.second.macro_rule_idx << '\n';}for (const auto& m : macros)os << "macro " << m.rel_ab << ' ' << m.rel_bc << ' ' << m.rel_ac << ' '<< m.uses << ' ' << m.name << '\n';if (ti)os << "think " << ti->total_queries << ' ' << ti->retrieval_queries<< ' ' << ti->sum_length << '\n';return os.str();}// Restores chain counts and macro definitions. MACROS ARE RE-ADDED to the// engine as plain transitive rules (exactly what try_promote does), so a// promoted chain actually fires on the next run instead of being a number// in a file. Returns counts for disclosure: (chains, macros, rules).std::array<int, 3> deserialize_meta(std::unordered_map<SubChainKey, SubChainStat, SubChainKeyHash>& chain_stats,std::vector<MacroRule>& macros,ReasonCore* eng, ThinkerIndex* ti, const std::string& text) {int n_chains = 0, n_macros = 0, n_rules = 0;std::istringstream in(text);std::string line;if (!std::getline(in, line)) return {0, 0, 0};if (line.rfind("M2", 0) != 0) return {0, 0, 0}; // not oursstd::vector<SubChainStat> pending_stats;std::vector<SubChainKey> pending_keys;std::vector<MacroRule> loaded_macros;while (std::getline(in, line)) {if (line.empty()) continue;std::istringstream ls(line);std::string tag;ls >> tag;if (tag == "engine") {int loaded = 0; std::size_t nrules = 0;ls >> loaded >> nrules;(void)loaded; (void)nrules;} else if (tag == "rule") {std::string nm; int ab = 0, bc = 0, ac = 0; float cost = 1.0f;ls >> nm >> ab >> bc >> ac >> cost;n_rules++;} else if (tag == "chain") {std::size_t len = 0;if (!(ls >> len)) continue;// ONE comma-joined token, not len tokens: the writer emits// `chain <len> <r0,r1,..> <count> <promoted> <macro_idx>`.// (An earlier version looped len times and read the count// field as an extra rule id, desyncing the stream and silently// dropping every chain record on reload.)std::string tok;if (!(ls >> tok)) continue;SubChainKey k;for (std::size_t pos = tok.find(','); ; pos = tok.find(',')) {k.rule_ids.push_back(std::atoi(tok.substr(0, pos).c_str()));if (pos == std::string::npos) break;tok = tok.substr(pos + 1);}if (k.rule_ids.size() != len) continue;SubChainStat st;int promoted = 0;if (!(ls >> st.count >> promoted >> st.macro_rule_idx)) continue;st.length = static_cast<int>(len);st.promoted = promoted != 0;pending_keys.push_back(k);pending_stats.push_back(st);n_chains++;} else if (tag == "macro") {MacroRule m;int ab = 0, bc = 0, ac = 0, uses = 0;if (!(ls >> ab >> bc >> ac >> uses)) continue;std::string nm;std::getline(ls, nm);while (!nm.empty() && nm.front() == ' ') nm.erase(nm.begin());m.name = nm; m.rel_ab = ab; m.rel_bc = bc; m.rel_ac = ac; m.uses = uses;loaded_macros.push_back(m);n_macros++;} else if (tag == "think") {if (ti) {int total = 0, retr = 0; double slen = 0.0;if (ls >> total >> retr >> slen) {ti->total_queries = total;ti->retrieval_queries = retr;ti->sum_length = slen;}}}}// Re-add macros as firing rules FIRST, so macro_rule_idx values from// the file still point at the right slots.if (eng) {for (const auto& m : loaded_macros) {if (eng->rule_index_by_name(m.name) >= 0) continue; // already thereeng->add_rule(m.name, m.rel_ab, m.rel_bc, m.rel_ac, false, 1.0f);eng->prim_meta.back() = {PRIM_TRANSITIVE, -1, 3};}macros = loaded_macros;}chain_stats.clear();for (std::size_t i = 0; i < pending_keys.size(); ++i)chain_stats[pending_keys[i]] = pending_stats[i];return {n_chains, n_macros, n_rules};}// ---------------------------------------------------------------------------// THE SIX DISCOVERY QUERIES (inference.hpp) — find what the graph does NOT// say: ungrounded islands, dangling concepts, the exact missing bridge,58 unmodified lines596061626364339 unmodified lines40440540640740840940 unmodified lines450451452453454455435 unmodified lines891892893894895896123 unmodified lines10201021102210231024102552 unmodified lines1078107910801081108210831084108547 unmodified lines11331134113511361137113858 unmodified lines#pragma once#include <algorithm>#include <cctype>#include <cstdint>#include <cmath>339 unmodified linesrules.push_back(Rule{name, rel_ab, rel_bc, rel_ac, cost, spawn});while (prim_meta.size() < rules.size()) prim_meta.push_back({});}void add_primitive(const std::string& name, PrimitiveKind kind,int rel_ab, int rel_bc, int rel_ac,int rel_extra = -1, int min_witnesses = 3) {40 unmodified linesadd_negation("contrapositive");add_case_analysis("disjunction_elimination");add_induction("schematic_generalization", REL_HAS, 3);}// -- assertions ----------------------------------------------------------435 unmodified lines// -- PATH FINDING (foundation for L3 Transitive + L6 Analogy; l9 paper) ---// BFS over outgoing edges; relation-agnostic by default. Returns edge// indices tracing from -> ... -> to (empty = unreachable).std::vector<int> find_path(const std::string& from, const std::string& to,int rel_mask = -1, int max_hops = 12) const {std::vector<int> path;123 unmodified linesint uses = 0;};struct MetaLearner {ReasonCore* engine = nullptr;std::unordered_map<SubChainKey, SubChainStat, SubChainKeyHash> chain_stats;52 unmodified linesstat.macro_rule_idx = old_size;macros.push_back(MacroRule{name, key.rule_ids, rel_ab, rel_bc, rel_ac, 0});}};// VERIFIER (§5.3.4): re-check a candidate answer edge against the rule set,// recursively down to its premises. A stale derivation fails; Layer 3 must// emit "unknown", not the stale answer.47 unmodified lines}};// ---------------------------------------------------------------------------// THE SIX DISCOVERY QUERIES (inference.hpp) — find what the graph does NOT// say: ungrounded islands, dangling concepts, the exact missing bridge,
60 unmodified lines61626364656667686970717273747576777879808182838485868788899091923 unmodified lines9697989910010110210310410510610710810911011162 unmodified lines17417517617717817918018118218318418518618718818919019119219319419519619719819920040 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326426526626760 unmodified linesinline bool& typed_lanes_enabled() { static bool on = false; return on; }// -- closed-class function words (normalized/stemmed forms) ------------------// -- M9-LEARNED FUNCTION WORDS -------------------------------------------------// The hardcoded kFn[] list below is a RULEBOOK in the inference path: it decides// who may be a role anchor, which is exactly the job the architecture should not// be delegating to a person. It is now a FALLBACK ONLY.//// The primary source is the FABRIC: a concept whose document frequency exceeds a// fraction of all lessons is a function word, because function words are exactly// the things that co-occur with everything. That statistic is already computed// for the CMD/MIMS rarity weighting (note_df / the IDF5 tail) -- it was simply// never consulted here. Loading it puts the decision in the MODEL, where the user// wants it: `decide` becomes a runner over learned structure instead of a reader// of a hardcoded table.inline std::unordered_set<std::string>& learned_fn_words() {static std::unordered_set<std::string> w;return w;}inline bool fn_words_loaded() { return !learned_fn_words().empty(); }inline void load_function_words(std::vector<std::string> words) {learned_fn_words().clear();for (auto& w : words) learned_fn_words().insert(std::move(w));}inline bool is_function_word(const std::string& t) {// PRIMARY: learned from the substrate's own document frequencies.if (fn_words_loaded() && learned_fn_words().count(t)) return true;if (fn_words_loaded()) return false; // learned table is authoritativestatic const char* const kFn[] = {"the", "a", "an", "of", "to", "for", "with", "on", "at", "by", "from","in", "into", "about", "as", "is", "are", "was", "were", "be", "been",3 unmodified lines"shall", "may", "might", "must", "and", "or", "but", "if", "then","than", "so", "very", "realli", "just", "also", "again", "there","here", "what", "which", "who", "whom", "when", "where", "whi", "how","pleas", "kindli", "now", "yet", "not",// M9: STEMS of function words that porter_stem() produces and that were// NOT in the list above, so they escaped as CONTENT words. Measured// (tools/probe: are->ar, was->wa, this->thi, they->thei, may->mai).// "was->wa" is the worst of these: in "the radio WAS found by Tariq" the// fragment "wa" was being tagged Role::S — i.e. a piece of the copula was// elected the subject while the real agent Tariq got Role::O. That single// miss is the root cause of the last-mentioned-entity failure measured on// tools/reason30.py. A stemmed function word must never be a role anchor."ar", "wa", "thi", "thei", "mai", nullptr};for (int i = 0; kFn[i]; ++i) if (t == kFn[i]) return true;return false;}62 unmodified lines// ---------------------------------------------------------------------------enum class Role { S, V, O, M, F };// M9: CLAUSE SEGMENTATION.//// tag() was single-clause: S came from before the FIRST verb and O from after// the LAST verb, which silently drops every intermediate subject. On// "Tariq picked up the red key. Salma took the blue key."// S = Tariq (before the first verb), O = "blue" (after the last verb), so// SALMA -- the subject of the second clause -- received NO role at all.// Measured on tools/reason30.py (model-mega-v2): 7 of 13 misses answered the// final-mentioned entity, because only the final clause's words were ever bound// to a role.//// The fix segments on clause boundaries and tags each clause with the original// single-clause rule, then splices the results back. Deterministic and// order-stable; a single-clause input (the common case) is unchanged, so the// existing unit tests still hold.inline bool is_clause_break(const std::string& t) {return t == "." || t == "!" || t == "?" || t == ";" || t == "then";}// tag one already-bounded clause: the pre-existing logic, verbatim.inline std::vector<Role> tag_clause(const std::vector<std::string>& words) {const std::size_t n = words.size();std::vector<Role> r(n, Role::M);if (n == 0) return r;40 unmodified linesreturn r;}// Segment, tag each clause independently, splice back. Clause-final// punctuation is left as Role::F so it can never become an anchor.inline std::vector<Role> tag(const std::vector<std::string>& words) {std::vector<Role> out(words.size(), Role::F);std::vector<std::string> cur;std::size_t out_at = 0;auto flush = [&]() {if (cur.empty()) return;const std::vector<Role> cr = tag_clause(cur);for (std::size_t i = 0; i < cr.size(); ++i) out[out_at + i] = cr[i];out_at += cr.size();cur.clear();};for (const std::string& w : words) {if (is_clause_break(w)) { flush(); if (out_at < out.size()) { out[out_at] = Role::F; ++out_at; } }else cur.push_back(w);}flush();return out;}// negated-verb detection: a negation cue within 2 tokens before the first Vinline bool verb_negated(const std::vector<std::string>& words) {const std::vector<Role> r = tag(words);60 unmodified lines616263646566673 unmodified lines7172737475767762 unmodified lines14014114214314414514640 unmodified lines18718818919019119260 unmodified linesinline bool& typed_lanes_enabled() { static bool on = false; return on; }// -- closed-class function words (normalized/stemmed forms) ------------------inline bool is_function_word(const std::string& t) {static const char* const kFn[] = {"the", "a", "an", "of", "to", "for", "with", "on", "at", "by", "from","in", "into", "about", "as", "is", "are", "was", "were", "be", "been",3 unmodified lines"shall", "may", "might", "must", "and", "or", "but", "if", "then","than", "so", "very", "realli", "just", "also", "again", "there","here", "what", "which", "who", "whom", "when", "where", "whi", "how","pleas", "kindli", "now", "yet", "not", nullptr};for (int i = 0; kFn[i]; ++i) if (t == kFn[i]) return true;return false;}62 unmodified lines// ---------------------------------------------------------------------------enum class Role { S, V, O, M, F };inline std::vector<Role> tag(const std::vector<std::string>& words) {const std::size_t n = words.size();std::vector<Role> r(n, Role::M);if (n == 0) return r;40 unmodified linesreturn r;}// negated-verb detection: a negation cue within 2 tokens before the first Vinline bool verb_negated(const std::vector<std::string>& words) {const std::vector<Role> r = tag(words);
164 unmodified lines1651661671681691703 unmodified lines17417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622766 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243259 unmodified lines3353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564571021 unmodified lines14791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588167 unmodified lines1756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849155 unmodified lines2005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065119 unmodified lines2185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230164 unmodified linesfloat learn_eta = 0.10f; // Hebbian learning ratefloat lane_decay = 0.995f; // per-lesson lane weight decaystd::size_t lane_cap = 256; // max lanes per node (weakest evicted)float hop_coupling = 0.35f; // 1-hop lane contribution at readout// -- v3.2 semantic field constants ---------------------------------------float sem_coupling = 0.12f; // resonance outflow fraction of retained energy3 unmodified linesint sem_neighbors = 6; // resonance edges per nodefloat ctx_missing = 0.60f; // lane flow factor when required context is absentfloat ctx_forbidden = 0.20f; // lane flow factor when forbidden context is present// -- M3: COMPLEMENTARY LEARNING SYSTEMS (hippocampal / cortical split) ----// One store must currently hold BOTH the taxonomy and every episode, under a// single ~138-lesson half-life (lane_decay 0.995). Measured consequence: SST-2// one-pass 0.896 vs 4-chunk 0.814 — chunking LOST, because the re-intern// penalty roughly cancels the decay benefit when one store serves both roles.//// McClelland's Complementary Learning Systems says the brain runs two: the// hippocampus encodes individual episodes FAST and sparsely, the neocortex// extracts slowly-learned regular structure, and replay moves episodes into// the slow system where they GENERALISE (only regularities survive).//// Physical form here: two lane populations.// hippocampal — the existing out_ store, decays per lesson as before.// cortical — an additional, near-non-decaying conductance population that// only receives a lane once that lane's eligibility trace// crosses cortical_gate. That gate IS the consolidation step:// coincidence across lessons, not a single binding, is what// makes structure cortical. Both feed the same CSR, so// cortical structure propagates like any other conductance.// -- M5: NTDA (action-potential thresholding, edge death, modulators) ------// Three mechanisms from ntda.md, all expressed as physics on lanes rather// than as heuristics in the readout://// (a) THRESHOLD GATING. A lane accumulates VOLTAGE on each binding// opportunity and only actually binds when that voltage reaches theta;// then it RESETS. So a lane cannot fire twice without being// re-stimulated. This replaces "one bind per lesson" with a real// refractory period, and it is what lets rare conjunctions accumulate// instead of being averaged into noise on their first appearance.// (b) EDGE DEATH. Conductivity decays per lesson and lanes below// edge_death are DELETED, so the ontology physically reshapes around// what the fabric still uses. SyFox had no concept of an edge dying.// (c) MODULATORS. theta is lowered by novelty (dopamine: risk a wild// analogy when the input is unfamiliar) and raised by contradiction// (cortisol: hyper-focus on the max-conductivity path). In a substrate// whose accuracy collapses to deferral, an explicit exploration term// keyed to novelty is the missing piece.bool ntda_on = false; // M5 master gate (default off == pre-M5)float ntda_theta = 1.0f; // voltage needed to fire a lanefloat ntda_dopamine = 0.30f; // max theta reduction at novelty = 1float ntda_cortisol = 0.50f; // max theta increase at contradiction = 1float edge_decay = 0.9995f; // per-lesson conductivity decayfloat edge_death = 0.002f; // delete a lane below this weightbool cls_split = false; // M3 master gate (default off == pre-M3)float cortical_decay = 0.9999f;// retained for disclosure; cortical lanes are// not touched by enforce_lane_decay at allfloat cortical_gate = 3.0f; // eligibility (lesson co-occurrences) neededfloat cortical_gain = 0.5f; // readout weight of a cortical vs hip lane};inline float fnv1a_hash(const std::string& s) { // deterministic token hash66 unmodified lines}std::uint64_t df_lesson_count() const { return df_lessons_; }std::size_t df_table_size() const { return df_.size(); }// M9-LEARNED: the document-frequency table, exposed so the role tagger can// learn what a FUNCTION WORD is from the fabric instead of consulting a// hardcoded list. A token seen in a large fraction of lessons is a function// word; that is a property of the DATA, not of the source file.std::uint32_t node_df(NodeId id) const {const auto it = df_.find(id);return it == df_.end() ? 0u : it->second;}// Top-N most frequent concepts, as (label, df) sorted by df desc then label.// Deterministic: ties broken by label, never by hash order.std::vector<std::pair<std::string, std::uint32_t>> df_ranked(std::size_t top_n) const {std::vector<std::pair<std::string, std::uint32_t>> out;out.reserve(df_.size());for (const auto& kv : df_)if (kv.first < nodes_.size())out.emplace_back(nodes_[kv.first].concept, kv.second);std::sort(out.begin(), out.end(),[](const std::pair<std::string, std::uint32_t>& x,const std::pair<std::string, std::uint32_t>& y) {if (x.second != y.second) return x.second > y.second;return x.first < y.first;});if (out.size() > top_n) out.resize(top_n);return out;}bool idf_active() const { return !df_.empty() && df_lessons_ > 0; }float idf_factor(NodeId id) const {if (!idf_active()) return 1.0f;9 unmodified linesadd_lane(b, a, w);}// M3: eligibility + cortical consolidation. A lane reaches the cortical// population only after cortical_gate DISTINCT lesson co-occurrences, which// is the physical form of "replay consolidates a regularity, not an// episode". Saturating, like add_lane, so it is order-insensitive once a// lane is established (the CLAMP is why cortical lanes are safe to merge// across passes where hippocampal ones are not).void note_eligibility(NodeId a, NodeId b) {if (!cfg_.cls_split) return;const std::uint64_t k = lane_key(a, b);const float e = (elig_.count(k) ? elig_[k] : 0.0f) + 1.0f;elig_[k] = e;if (e < cfg_.cortical_gate) return;auto& cl = cortical_[a];for (auto& l : cl)if (l.first == b) { l.second = std::min(4.0f, std::max(0.0f, l.second + 0.25f)); csr_dirty_ = true; return; }cl.emplace_back(b, 0.25f);csr_dirty_ = true;}void set_cls_split(bool on) { cfg_.cls_split = on; if (on) csr_dirty_ = true; }bool cls_split() const { return cfg_.cls_split; }void set_cortical_gate(float g) { cfg_.cortical_gate = g; }void set_cortical_gain(float g) { cfg_.cortical_gain = g; if (g != cfg_.cortical_gain) csr_dirty_ = true; }std::size_t cortical_lanes() const {std::size_t k = 0;for (const auto& kv : cortical_) k += kv.second.size();return k;}std::size_t eligibility_traces() const { return elig_.size(); }// -- M5 controls ---------------------------------------------------------// M9/encoder: configure the projection. Existing W is PRESERVED so a// trained encoder survives a re-learn; pass reset=true to discard.void set_encoder(std::size_t dim, std::size_t chans, bool reset = false) {if (dim == 0 || chans == 0) return;if (reset || enc_dim_ != dim || enc_chans_ != chans) {enc_dim_ = dim; enc_chans_ = chans;enc_W_.assign(chans * dim, 0.0f);}enc_y_.assign(chans, 0.0f);}void set_encoder_eta(float e) { enc_eta_ = e; }std::size_t enc_chans() const { return enc_chans_; }std::size_t enc_dim() const { return enc_dim_; }std::uint64_t enc_updates() const { return enc_updates_; }bool has_encoder() const { return !enc_W_.empty(); }// Oja update: W += eta * g * (x y^T - y y^T W).// x pre-synaptic (encoder embedding, length d)// y post-synaptic (settled field, length C)// g ONE global scalar -- reused from the NTDA modulator, so exploration// state already modulates the encoder. No spatial information, so no// update ever needs a backward pass.void encoder_update(const std::vector<float>& x, const std::vector<float>& y, float g) {if (enc_W_.empty() || x.size() != enc_dim_ || y.size() != enc_chans_) return;const float lr = enc_eta_ * g;if (lr == 0.0f) return;for (std::size_t c = 0; c < enc_chans_; ++c) {const float yc = y[c];if (yc == 0.0f) continue;float* row = &enc_W_[c * enc_dim_];for (std::size_t d = 0; d < enc_dim_; ++d)row[d] += lr * (y[c] * x[d] - yc * y[c] * row[d]);}enc_y_ = y;++enc_updates_;}// Project an encoder embedding into channel space and inject as energy.// This is the ONLY path by which an external representation touches the// field; the lane fabric is otherwise untouched, so typed/bigram lanes and// their order survive verbatim.std::vector<float> encoder_project(const std::vector<float>& x) const {std::vector<float> y(enc_chans_, 0.0f);if (enc_W_.empty() || x.size() != enc_dim_) return y;for (std::size_t c = 0; c < enc_chans_; ++c) {const float* row = &enc_W_[c * enc_dim_];float acc = 0.0f;for (std::size_t d = 0; d < enc_dim_; ++d) acc += row[d] * x[d];y[c] = acc;}return y;}void set_ntda(bool on) { cfg_.ntda_on = on; }bool ntda_on() const { return cfg_.ntda_on; }void set_ntda_theta(float t) { cfg_.ntda_theta = t; }void set_novelty(float n) { novelty_ = std::min(1.0f, std::max(0.0f, n)); }void set_conflict(float c) { conflict_ = std::min(1.0f, std::max(0.0f, c)); }float current_theta() const {if (!cfg_.ntda_on) return cfg_.ntda_theta;// dopamine lowers theta on novelty (exploration); cortisol raises it on// contradiction (exploitation). Both are multiplicative around 1.const float d = 1.0f - cfg_.ntda_dopamine * novelty_;const float c = 1.0f + cfg_.ntda_cortisol * conflict_;return std::max(0.05f, cfg_.ntda_theta * d * c);}std::uint64_t ntda_spikes() const { return ntda_spikes_; }std::uint64_t ntda_deaths() const { return ntda_deaths_; }std::size_t voltage_traces() const { return volt_.size(); }// M5 (a): accumulate voltage; fire and reset only at threshold. Returns true// when the lane actually bound. With ntda off this is always true, so the// pre-M5 path is byte-identical.bool ntda_gate(NodeId a, NodeId b) {if (!cfg_.ntda_on) return true;const std::uint64_t k = lane_key(a, b);const float th = current_theta();float& v = volt_[k];v += 1.0f;if (v < th) return false;v = 0.0f; // refractory: cannot re-fire without re-stimulation++ntda_spikes_;return true;}void add_lane(NodeId a, NodeId b, float w) {note_eligibility(a, b);if (!ntda_gate(a, b)) return; // M5 (a): below threshold, no bindauto& lanes = out_[a];for (auto& l : lanes)if (l.first == b) { l.second = std::min(4.0f, std::max(0.0f, l.second + w)); csr_dirty_ = true; return; }1021 unmodified linesf.write(reinterpret_cast<const char*>(&cons), 4);f.write(reinterpret_cast<const char*>(&tot), 4);}// -- M3 CLS tail -------------------------------------------------------// cortical lanes + eligibility traces. Persisted because the M2 lesson// applies directly: consolidated structure that is not written out is// structure that does not exist after a reload. Magic-guarded so a// pre-M3 file (which ends at the previous tail) still loads.// ALWAYS write the CLS header, even when empty. The loader reads tail// magics unconditionally and advances the stream, so an OMITTED CLS// block (an NTDA-only fabric has no cortical lanes) left the reader 4// bytes ahead and every later tail mis-matched -- NTDA silently failed// to load. Tails are a fixed sequence; skipping one breaks alignment.{const std::uint32_t cls_magic = 0x434C5331u; // 'CLS1'f.write(reinterpret_cast<const char*>(&cls_magic), 4);using CRow = std::unordered_map<NodeId,std::vector<std::pair<NodeId, float>>>::value_type;std::vector<const CRow*> cs;cs.reserve(cortical_.size());for (const auto& kv : cortical_) cs.push_back(&kv);std::sort(cs.begin(), cs.end(),[](const auto* x, const auto* y) { return x->first < y->first; });std::uint32_t cn = static_cast<std::uint32_t>(cs.size());f.write(reinterpret_cast<const char*>(&cn), 4);for (const auto* kv : cs) {f.write(reinterpret_cast<const char*>(&kv->first), 4);std::uint32_t m = static_cast<std::uint32_t>(kv->second.size());f.write(reinterpret_cast<const char*>(&m), 4);for (const auto& l : kv->second) {f.write(reinterpret_cast<const char*>(&l.first), 4);f.write(reinterpret_cast<const char*>(&l.second), 4);}}std::vector<std::pair<std::uint64_t, float>> es(elig_.begin(), elig_.end());std::sort(es.begin(), es.end(),[](const std::pair<std::uint64_t, float>& x,const std::pair<std::uint64_t, float>& y) { return x.first < y.first; });std::uint32_t en = static_cast<std::uint32_t>(es.size());f.write(reinterpret_cast<const char*>(&en), 4);for (const auto& kv : es) {std::uint32_t a = static_cast<std::uint32_t>(kv.first >> 32);std::uint32_t b = static_cast<std::uint32_t>(kv.first & 0xffffffffull);f.write(reinterpret_cast<const char*>(&a), 4);f.write(reinterpret_cast<const char*>(&b), 4);f.write(reinterpret_cast<const char*>(&kv.second), 4);}}// -- M5 NTDA tail ------------------------------------------------------// volt_ MUST persist: a lane that had accumulated 1.5V toward a// threshold of 2 restarts from ZERO after a reload, so learning// behaviour after reload differs from behaviour before it. That is the// same defect class as M2's unserialised MetaLearner, reintroduced in// new code -- which is exactly why it needed catching again.// BOTH tails are written UNCONDITIONALLY, in a fixed order. Conditional// tails are what caused the CLS1 misalignment bug: the loader reads// magics unconditionally and advances the stream, so an omitted block// desynchronised every later one. Same lesson, third application.{const std::uint32_t ntd_magic = 0x4E544441u; // 'NTDA'f.write(reinterpret_cast<const char*>(&ntd_magic), 4);const float th = cfg_.ntda_theta, ed = cfg_.edge_decay, dt = cfg_.edge_death;f.write(reinterpret_cast<const char*>(&th), 4);f.write(reinterpret_cast<const char*>(&ed), 4);f.write(reinterpret_cast<const char*>(&dt), 4);f.write(reinterpret_cast<const char*>(&ntda_spikes_), 8);f.write(reinterpret_cast<const char*>(&ntda_deaths_), 8);std::vector<std::pair<std::uint64_t, float>> vs(volt_.begin(), volt_.end());std::sort(vs.begin(), vs.end(),[](const std::pair<std::uint64_t, float>& x,const std::pair<std::uint64_t, float>& y) { return x.first < y.first; });std::uint32_t vn = static_cast<std::uint32_t>(vs.size());f.write(reinterpret_cast<const char*>(&vn), 4);for (const auto& kv : vs) {std::uint32_t a = static_cast<std::uint32_t>(kv.first >> 32);std::uint32_t b = static_cast<std::uint32_t>(kv.first & 0xffffffffull);f.write(reinterpret_cast<const char*>(&a), 4);f.write(reinterpret_cast<const char*>(&b), 4);f.write(reinterpret_cast<const char*>(&kv.second), 4);}}// -- L1 ENCODER tail ----------------------------------------------------// THIRD instance of the same defect (after M2's MetaLearner and M5's// voltage): runtime-only state that is not written out does not exist// after a reload. W learned by thousands of Oja updates is the whole// point of the encoder, and losing it silently makes --encoder-dim look// like it "did nothing" (stats reported encoder_dim: 0).{const std::uint32_t enc_magic = 0x454E4331u; // 'ENC1'f.write(reinterpret_cast<const char*>(&enc_magic), 4);const bool have_W = !enc_W_.empty();const std::uint64_t z = 0;const std::uint64_t dd = have_W ? enc_dim_ : z;const std::uint64_t cc = have_W ? enc_chans_ : z;const std::uint64_t n = have_W ? enc_W_.size() : z;f.write(reinterpret_cast<const char*>(&dd), 8);f.write(reinterpret_cast<const char*>(&cc), 8);f.write(reinterpret_cast<const char*>(&enc_eta_), 4);f.write(reinterpret_cast<const char*>(&enc_updates_), 8);f.write(reinterpret_cast<const char*>(&n), 8);if (have_W)f.write(reinterpret_cast<const char*>(enc_W_.data()),static_cast<std::streamsize>(n * sizeof(float)));}}// v3.2.1: reports failure. A missing substrate used to load SILENTLY as an167 unmodified linesif (!ok) order_stats_.clear(); // torn tail: stay inert}}// v3.9.1 M3 CLS tail (optional, magic-guarded 'CLS1'): pre-M3 files end// after ORD1, the failed magic read leaves cortical_ and elig_ empty,// and the substrate replays exactly as before.std::uint32_t cls_magic = 0;if (f.read(reinterpret_cast<char*>(&cls_magic), 4) && cls_magic == 0x434C5331u) {std::uint32_t cn = 0;if (f.read(reinterpret_cast<char*>(&cn), 4)) {bool ok = true;for (std::uint32_t k = 0; k < cn && ok; ++k) {NodeId a = 0;std::uint32_t m = 0;ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&a), 4));if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&m), 4));if (ok) a = static_cast<NodeId>(a);for (std::uint32_t j = 0; j < m && ok; ++j) {NodeId b = 0;float w = 0.0f;ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&b), 4));if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&w), 4));if (ok) cortical_[a].emplace_back(static_cast<NodeId>(b), w);}}if (!ok) cortical_.clear(); // torn tail: stay inertstd::uint32_t en = 0;if (ok && f.read(reinterpret_cast<char*>(&en), 4)) {for (std::uint32_t k = 0; k < en && ok; ++k) {std::uint32_t a = 0, b = 0;float e = 0.0f;ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&a), 4));if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&b), 4));if (ok) ok = static_cast<bool>(f.read(reinterpret_cast<char*>(&e), 4));if (ok) elig_[lane_key(static_cast<NodeId>(a), static_cast<NodeId>(b))] = e;}if (!ok) elig_.clear();}if (!cortical_.empty()) csr_dirty_ = true;}}// v3.9.1 M5 NTDA tail (optional, magic-guarded 'NTDA'): absent => ntda// stays off and the fabric replays exactly as pre-M5.std::uint32_t ntd_magic = 0;if (f.read(reinterpret_cast<char*>(&ntd_magic), 4) && ntd_magic == 0x4E544441u) {float th = 0, ed = 0, dt = 0;bool ok = f.read(reinterpret_cast<char*>(&th), 4)&& f.read(reinterpret_cast<char*>(&ed), 4)&& f.read(reinterpret_cast<char*>(&dt), 4);if (ok) ok = f.read(reinterpret_cast<char*>(&ntda_spikes_), 8)&& f.read(reinterpret_cast<char*>(&ntda_deaths_), 8);cfg_.ntda_on = true; cfg_.ntda_theta = th; cfg_.edge_decay = ed; cfg_.edge_death = dt;std::uint32_t vn = 0;if (ok && f.read(reinterpret_cast<char*>(&vn), 4)) {for (std::uint32_t k = 0; k < vn && ok; ++k) {std::uint32_t a = 0, b = 0; float v = 0.0f;ok = f.read(reinterpret_cast<char*>(&a), 4)&& f.read(reinterpret_cast<char*>(&b), 4)&& f.read(reinterpret_cast<char*>(&v), 4);if (ok) volt_[lane_key(static_cast<NodeId>(a), static_cast<NodeId>(b))] = v;}if (!ok) volt_.clear(); // torn tail: start clean, not half}}std::uint32_t enc_magic_pre = 0;// ENC1 is written immediately after NTDA; both headers are always// present so the tail sequence can never desynchronise.std::uint32_t enc_magic = 0;if (f.read(reinterpret_cast<char*>(&enc_magic), 4) && enc_magic == 0x454E4331u) {std::uint64_t dd = 0, cc = 0, n = 0;if (f.read(reinterpret_cast<char*>(&dd), 8)&& f.read(reinterpret_cast<char*>(&cc), 8)&& f.read(reinterpret_cast<char*>(&enc_eta_), 4)&& f.read(reinterpret_cast<char*>(&enc_updates_), 8)&& f.read(reinterpret_cast<char*>(&n), 8)) {enc_dim_ = static_cast<std::size_t>(dd);enc_chans_ = static_cast<std::size_t>(cc);enc_W_.resize(static_cast<std::size_t>(n));// explicit bool(): the istream& overload is not contextually// convertible here.bool ok = static_cast<bool>(f.read(reinterpret_cast<char*>(enc_W_.data()),static_cast<std::streamsize>(n * sizeof(float))));if (!ok) enc_W_.clear();enc_y_.assign(enc_chans_, 0.0f);}}return true;}const SubstrateConfig& config() const { return cfg_; }// -- LANE PROVENANCE + SURGERY (derivation-layer surface, see derive.hpp) --// Derived lanes are laid by rule composition over existing fabric, not by155 unmodified linesvoid enforce_lane_decay() {for (auto& kv : out_)for (auto& l : kv.second) l.second *= cfg_.lane_decay;// M5 (b) EDGE DEATH. Conductivity decays faster than the weight does, and// a lane that falls below edge_death is DELETED outright rather than// lingering as a near-zero edge the readout must still consider. The// ontology therefore reshapes around what the fabric still uses, which// is a mechanism syfox did not previously have at all.if (cfg_.ntda_on) {for (auto& kv : out_)for (auto& l : kv.second) l.second *= cfg_.edge_decay;for (auto it = out_.begin(); it != out_.end();) {auto& vec = it->second;vec.erase(std::remove_if(vec.begin(), vec.end(),[&](const std::pair<NodeId, float>& l) {if (l.second < cfg_.edge_death) { ++ntda_deaths_; return true; }return false;}),vec.end());if (vec.empty()) it = out_.erase(it); else ++it;}}csr_dirty_ = true;}SubstrateConfig cfg_;std::unordered_map<std::string, NodeId> index_;std::vector<Node> nodes_;std::unordered_map<NodeId, std::vector<std::pair<NodeId, float>>> out_;// M3: cortical lanes (consolidated structure) + the per-lane eligibility// traces that decide when a hippocampal lane is CONSOLIDATED. Eligibility is// monotone and never decayed: it counts distinct lesson co-occurrences,// which is the coincidence signal consolidation is supposed to key on.std::unordered_map<NodeId, std::vector<std::pair<NodeId, float>>> cortical_;std::unordered_map<std::uint64_t, float> elig_;// M5: per-lane accumulated voltage (the action potential) and the last// novelty/contradiction levels fed in by the caller.std::unordered_map<std::uint64_t, float> volt_;mutable float novelty_ = 0.0f; // 0..1, set by decide-time OOD signalmutable float conflict_ = 0.0f; // 0..1, set from the tension gatestd::uint64_t ntda_spikes_ = 0; // lanes that actually fired// -- L1 ENCODER PROJECTION (GHL/Oja) --------------------------------------// W : C x d, learned by LOCAL Hebbian plasticity -- Oja's subtractive term// plus a single global sign scalar g. No gradient, no backward pass, no// dependence on any other row. Rationale and citations in// ARCHITECTURE.md §15 (CLAPP, NeurIPS 2021; GHL).//// Channels are how an encoder ADDRESSES the lane fabric; they never replace// a lane with a vector. A 768 x 26,000 projection would be a second network// wearing a physics hat; 768 x 32 is not.std::size_t enc_chans_ = 0; // Cstd::size_t enc_dim_ = 0; // d (encoder embedding width)std::vector<float> enc_W_; // C*d, row-majorstd::vector<float> enc_y_; // C, last post-synaptic responsefloat enc_eta_ = 0.01f;std::uint64_t enc_updates_ = 0;std::uint64_t ntda_deaths_ = 0; // lanes deleted by edge death// Derivation provenance: lane key -> generation (sparse; observed lanes absent = 0)std::unordered_map<std::uint64_t, std::uint32_t> derived_gen_;// v3.6.0 document-frequency table (node -> lessons containing it) and the119 unmodified linesvoid build_csr() const {const std::size_t n = nodes_.size();// M3: cortical lanes are an ADDITIONAL conductance population. They go// into the same CSR so they propagate exactly like hippocampal lanes —// the difference is not how they are read but that enforce_lane_decay// never touches them. Order is hippocampal-then-cortical per node, which// keeps the float accumulation order deterministic.auto row_len = [&](std::size_t i) -> std::size_t {std::size_t k = 0;auto it = out_.find(static_cast<NodeId>(i));if (it != out_.end()) k += it->second.size();auto ct = cortical_.find(static_cast<NodeId>(i));if (ct != cortical_.end()) k += ct->second.size();return k;};csr_off_.assign(n + 1, 0);for (std::size_t i = 0; i < n; ++i) csr_off_[i + 1] = csr_off_[i] + row_len(i);csr_dst_.resize(csr_off_[n]);csr_w_.resize(csr_off_[n]);for (std::size_t i = 0; i < n; ++i) {std::size_t k = csr_off_[i];auto it = out_.find(static_cast<NodeId>(i));if (it != out_.end())for (const auto& lane : it->second) {csr_dst_[k] = lane.first;csr_w_[k] = lane.second;++k;}auto ct = cortical_.find(static_cast<NodeId>(i));if (ct != cortical_.end())for (const auto& lane : ct->second) {// cortical_gain scales the cortical population down so it// supports rather than dominates the hippocampal trace.csr_dst_[k] = lane.first;csr_w_[k] = lane.second * (cfg_.cls_split ? cfg_.cortical_gain : 1.0f);++k;}}csr_dirty_ = false;}public:// parallel settle toggle (M5): on OMP builds, >1 threads use per-thread// scatter buffers combined in fixed thread order — bit-identical to the// sequential path (test-verified). Off builds always run sequential.164 unmodified lines1651661671681691701711721731741751761771781791803 unmodified lines18418518618718818966 unmodified lines2562572582592602619 unmodified lines2712722732742752762771021 unmodified lines129913001301130213031304167 unmodified lines1472147314741475147614771478147914801481148214831484148514861487155 unmodified lines16431644164516461647164816491650165116521653165416551656165716581659166016611662119 unmodified lines1782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908164 unmodified linesfloat learn_eta = 0.10f; // Hebbian learning ratefloat lane_decay = 0.995f; // per-lesson lane weight decaystd::size_t lane_cap = 256; // max lanes per node (weakest evicted)// v3.9.3 LANE-DECAY FLOOR. CMD §2.3's law saturates the lane weight, so a// starved lane keeps a real (small) value; the port's unbounded multiply// drove it to the float32 denormal floor (1.4e-43) where it is// numerically dead. TSDA §2: "It remains in long-term memory (the edge// still exists), but it requires more cognitive energy to retrieve." A// floor is exactly that: the edge persists with reduced retrievability.// DEFAULT 0 = OFF (bit-identical to every pre-v3.9.3 fabric; the replay// contract is preserved). Set it via --lane-floor F when building a new// fabric; repair an EXISTING fabric with `syfox repair-lanes`.float lane_decay_floor = 0.0f;float hop_coupling = 0.35f; // 1-hop lane contribution at readout// -- v3.2 semantic field constants ---------------------------------------float sem_coupling = 0.12f; // resonance outflow fraction of retained energy3 unmodified linesint sem_neighbors = 6; // resonance edges per nodefloat ctx_missing = 0.60f; // lane flow factor when required context is absentfloat ctx_forbidden = 0.20f; // lane flow factor when forbidden context is present};inline float fnv1a_hash(const std::string& s) { // deterministic token hash66 unmodified lines}std::uint64_t df_lesson_count() const { return df_lessons_; }std::size_t df_table_size() const { return df_.size(); }bool idf_active() const { return !df_.empty() && df_lessons_ > 0; }float idf_factor(NodeId id) const {if (!idf_active()) return 1.0f;9 unmodified linesadd_lane(b, a, w);}void add_lane(NodeId a, NodeId b, float w) {auto& lanes = out_[a];for (auto& l : lanes)if (l.first == b) { l.second = std::min(4.0f, std::max(0.0f, l.second + w)); csr_dirty_ = true; return; }1021 unmodified linesf.write(reinterpret_cast<const char*>(&cons), 4);f.write(reinterpret_cast<const char*>(&tot), 4);}}// v3.2.1: reports failure. A missing substrate used to load SILENTLY as an167 unmodified linesif (!ok) order_stats_.clear(); // torn tail: stay inert}}return true;}const SubstrateConfig& config() const { return cfg_; }// v3.9.3: the lane-decay floor (0 = off; see cfg_.lane_decay_floor).void set_lane_decay_floor(float f) { cfg_.lane_decay_floor = std::max(0.0f, f); }float lane_decay_floor() const { return cfg_.lane_decay_floor; }// v3.9.3: the per-lesson decay constant (0.995 by default).void set_lane_decay(float d) { cfg_.lane_decay = d; }float lane_decay() const { return cfg_.lane_decay; }// -- LANE PROVENANCE + SURGERY (derivation-layer surface, see derive.hpp) --// Derived lanes are laid by rule composition over existing fabric, not by155 unmodified linesvoid enforce_lane_decay() {for (auto& kv : out_)for (auto& l : kv.second) {l.second *= cfg_.lane_decay;// v3.9.3: keep a starved lane retrievable (floor 0 = off).if (cfg_.lane_decay_floor > 0.0f && l.second < cfg_.lane_decay_floor)l.second = cfg_.lane_decay_floor;}csr_dirty_ = true;}SubstrateConfig cfg_;std::unordered_map<std::string, NodeId> index_;std::vector<Node> nodes_;std::unordered_map<NodeId, std::vector<std::pair<NodeId, float>>> out_;// Derivation provenance: lane key -> generation (sparse; observed lanes absent = 0)std::unordered_map<std::uint64_t, std::uint32_t> derived_gen_;// v3.6.0 document-frequency table (node -> lessons containing it) and the119 unmodified linesvoid build_csr() const {const std::size_t n = nodes_.size();csr_off_.assign(n + 1, 0);for (std::size_t i = 0; i < n; ++i) {auto it = out_.find(static_cast<NodeId>(i));csr_off_[i + 1] = csr_off_[i] + (it == out_.end() ? 0 : it->second.size());}csr_dst_.resize(csr_off_[n]);csr_w_.resize(csr_off_[n]);for (std::size_t i = 0; i < n; ++i) {auto it = out_.find(static_cast<NodeId>(i));if (it == out_.end()) continue;std::size_t k = csr_off_[i];for (const auto& lane : it->second) {csr_dst_[k] = lane.first;csr_w_[k] = lane.second;++k;}}csr_dirty_ = false;}public:// -- v3.9.3 LANE REPAIR ----------------------------------------------------// THE DEAD-LANE PATHOLOGY. The port applies CMD §2.3's decay to EVERY lane// on EVERY lesson:// enforce_lane_decay(): for each lane: w *= lane_decay (0.995)// so the weight of a lane last bound at lesson k, in a fabric trained// with N lessons, is w0 * 0.995^(N-k). In float32 that product// UNDERFLOWS to the denormal floor (1.4e-43) after ~20,700 lessons and// then stops decreasing — the lane is numerically dead: the readout sees// it as exactly zero and only a fresh bind can revive it.//// MEASURED on the shipped model/giant-latin fabric (114,060 lessons,// 1,905,169 lanes): 95.09% of lanes carry a weight in (0, 1e-12); the// MEDIAN lane weight is 1.4e-43 (the denormal floor); only 2.42%// (46,161 lanes) exceed 1e-6. The Hebbian memory of the fabric was// effectively erased: what survived was a recency window over the tail// of the corpus, not a memory of it.//// CMD §2.3's actual law is// w <- tanh( (w*lambda + eta*v_b*v_c) / w_max ) * w_max// i.e. a SATURATING growth/decay integrator: the growth term is added on// every co-activity and the ceiling keeps the weight a real number. The// port kept the decay and lost the saturation, so the weight could fall// off the bottom of the number line.//// THE REPAIR. The persisted EVIDENCE LEDGER (v3 Milestone 3) holds the// integral of exactly the growth term the decay was destroying: per// lane, the number of Hebbian supports, the number of counter-events,// and the lesson window it was active in. Rebuilding the weight from the// ledger is the UNDECAYED form of CMD §2.3's law:// w = w_max * tanh( (net_events * bind_scale) / w_max )// with w_max the ceiling the port already clamps to (add_lane) and// bind_scale the same per-lesson magnitude the learn path uses.//// This is a REPAIR of a built fabric, not a change to the learn path:// no equation moves, and a fabric that is re-learned from scratch is// byte-identical. The root cause in the learn path is addressed// separately by the lane-decay FLOOR (see cfg_.lane_decay_floor).struct LaneRepairStats {std::size_t lanes_total = 0;std::size_t lanes_repaired = 0; // lanes the ledger could rebuildstd::size_t lanes_dead = 0; // weight < dead_threshold BEFOREstd::size_t lanes_revivable= 0; // dead lanes the ledger revivesstd::size_t lanes_orphan = 0; // dead lanes with no ledger entrystd::size_t lanes_live = 0; // lanes above the dead threshold beforedouble weight_before = 0.0;double weight_after = 0.0;};// Rebuild lane weights from the persisted evidence ledger. `dead_threshold`// is the weight below which a lane counts as numerically dead. With// `apply` false the stats are computed WITHOUT touching the fabric (a// dry run) — the caller can then see what the repair would do before// committing to it.LaneRepairStats repair_lanes_from_evidence(float dead_threshold = 1e-6f,bool apply = true) {LaneRepairStats st;const float wmax = 4.0f; // the ceiling add_lane() already clamps tostd::unordered_map<std::uint64_t, float> target;target.reserve(lane_evidence_.size() * 2 + 16);for (const auto& kv : lane_evidence_) {const NodeId a = static_cast<NodeId>(kv.first >> 32);const NodeId b = static_cast<NodeId>(kv.first & 0xffffffffull);if (a >= nodes_.size() || b >= nodes_.size()) continue;const LaneEvidence& e = kv.second;const long net = static_cast<long>(e.support_events)- static_cast<long>(e.counter_events);if (net <= 0) continue;// the same magnitude the learn path binds withconst float wa = 1.0f / std::sqrt(nodes_[a].mass);const float wb = 1.0f / std::sqrt(nodes_[b].mass);const float scale = cfg_.learn_eta * (wa + wb)* idf_factor(a) * order_factor(a, b);const float raw = static_cast<float>(net) * scale;const float w = wmax * std::tanh(raw / wmax);if (w <= 0.0f) continue;target[kv.first] = w;target[lane_key(b, a)] = w; // bind() is symmetric}for (auto& kv : out_) {for (auto& l : kv.second) {++st.lanes_total;st.weight_before += l.second;if (l.second < dead_threshold) ++st.lanes_dead;const auto it = target.find(lane_key(kv.first, l.first));if (it != target.end()) {if (l.second < dead_threshold) ++st.lanes_revivable;if (apply) l.second = it->second;++st.lanes_repaired;} else if (l.second < dead_threshold) {++st.lanes_orphan;}st.weight_after += (apply ? l.second : it != target.end() ? it->second : l.second);}}st.lanes_live = st.lanes_total - st.lanes_dead;csr_dirty_ = true;return st;}// parallel settle toggle (M5): on OMP builds, >1 threads use per-thread// scatter buffers combined in fixed thread order — bit-identical to the// sequential path (test-verified). Off builds always run sequential.
59 unmodified lines60616263646580 unmodified lines14614714814915015115215315415515615715815916016116216316416516651 unmodified lines21821922022122222322422522622722822930 unmodified lines2602612622632642652662672682691 unmodified line2712722732742752763 unmodified lines2802812822832842859 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032132213 unmodified lines33633733833934034121 unmodified lines36336436536636736831 unmodified lines40040140240340440540640740840941041141241341441541641789 unmodified lines50750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560616 unmodified lines62362462562662762862963063163263363463563620 unmodified lines65765865966066166266366466566666766866967067167267367467511 unmodified lines6876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187191 unmodified line72172272372472572622 unmodified lines74975075175275375475575675775875976076176276376476576676776876977077177277377427 unmodified lines802803804805806807808809810811812813814815816817818819820821822823824825414 unmodified lines1240124112421243124412458 unmodified lines1254125512561257125812591260126112627 unmodified lines12701271127212731274127512761277127812791280420 unmodified lines1701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740348 unmodified lines208920902091209220932094209520962097209851 unmodified lines21502151215221532154215521561 unmodified line215821592160216121622163216421652166216721682169199 unmodified lines236923702371237223732374120 unmodified lines249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258514 unmodified lines260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671165 unmodified lines283728382839284028412842284312 unmodified lines28562857285828592860286128622863286428652866286728682869287028712872287328741 unmodified line287628772878287928802881288228832884288528862887151 unmodified lines30393040304130423043304459 unmodified lines// energy-norm) and well above float dust from diffusion carryover. Documented// in README (honest-silence section); debug visibility via SYFOX_DEBUG_READOUT=1.inline constexpr float kUnknownCandidateFloor = 0.01f;// v3.6.0: decide-side bigram injection dose as a fraction of the state dose// (MRS §4b grounds bigram lanes like any other lane; the 0.5 fraction keeps// order evidence subordinate to lexical evidence).80 unmodified lines};struct Usage {// M9: how many candidates the query-role alignment re-rank boosted, and the// agent it aligned on. Disclosure only.double role_bind_boosted = 0.0;std::string role_bind_agent;// M10: was this answer DERIVED (typed path in the axiom graph) rather than// read off the field? Disclosed so the two can never be reported as one.bool reason_routed = false;double reason_derived_count = 0.0;// Lines in axioms.txt naming an unknown relation, DROPPED at load. Reported// so a partially-loaded knowledge base is visible instead of silent.double axioms_rejected = 0.0;// M5: the effective firing threshold after the modulators were applied.double ntda_theta = 0.0;// M9-encoder: Oja updates applied this decision.double enc_updates = 0.0;std::size_t state_tokens = 0;std::size_t vocabulary = 0;std::size_t lanes = 0;51 unmodified lines// strongest concept and the winning anchor (premise-cited hops).bool proof_checked = false;std::vector<std::string> proof_path; // "subject relation object" hops// M1: thinker-in-the-loop disclosures. Set only when the reasoner ran// inside decide(), so a pre-M1 run discloses nothing new.bool thinker_chained = false;int thinker_edges_added = 0;int thinker_passes = 0;float thinker_budget_left = 0.0f;// momentum (MCPE/CPME): fraction of candidates still GAINING energy at// the final settle pass (the echo-suppressed remainder peaked already).bool momentum_gate = false;30 unmodified linesfloat noul_b = -3.0f;bool fitted = false;std::size_t rows = 0;sfx::JV to_json() const {return sfx::JV(sfx::JVObj{{"choice_temperature", choice_temperature},{"score_temperature", score_temperature},{"noul_a", noul_a}, {"noul_b", noul_b},{"fitted", fitted}, {"rows", static_cast<double>(rows)}});1 unmodified linestatic Calibration from_json(const sfx::JV& j) {Calibration c;c.choice_temperature = static_cast<float>(j.at("choice_temperature").as_num(1.0));c.score_temperature = static_cast<float>(j.at("score_temperature").as_num(1.0));c.noul_a = static_cast<float>(j.at("noul_a").as_num(6.0));c.noul_b = static_cast<float>(j.at("noul_b").as_num(-3.0));3 unmodified lines}};// ---------------------------------------------------------------------------class Engine {public:9 unmodified linesreason_meta_.engine = &reason_;}// -- M5 NTDA forwarders (Engine -> Substrate) ---------------------------void set_ntda(bool on) { si_.set_ntda(on); }void set_ntda_theta(float t) { si_.set_ntda_theta(t); }void set_novelty(float n) { si_.set_novelty(n); }void set_conflict(float c) { si_.set_conflict(c); }// M9-encoder: supply the encoder embedding for the next decide().void set_encoder_input(std::vector<float> x) { enc_in_ = std::move(x); }bool encoder_active() const { return si_.has_encoder() && !enc_in_.empty(); }std::uint64_t ntda_spikes() const { return si_.ntda_spikes(); }// -- L1 ENCODER forwarders -----------------------------------------------void set_encoder(std::size_t dim, std::size_t chans, bool reset = false) {si_.set_encoder(dim, chans, reset);}void set_encoder_eta(float e) { si_.set_encoder_eta(e); }std::uint64_t enc_updates() const { return si_.enc_updates(); }std::vector<float> encoder_project(const std::vector<float>& x) const {return si_.encoder_project(x);}std::uint64_t ntda_deaths() const { return si_.ntda_deaths(); }si::Substrate& substrate() { return si_; }const si::Substrate& substrate() const { return si_; }Calibration& calibration() { return calib_; }// -- v3 Milestone 1: decide-side energy normalization (boundary GAIN knob) --13 unmodified linesvoid set_energy_norm(bool on) { energy_norm_ = on; }bool energy_norm() const { return energy_norm_; }// -- model persistence ----------------------------------------------------void save_model(const std::string& dir) {std::string cmd_mkdir = "mkdir -p '" + dir + "'";21 unmodified linessi_.save(dir + "/substrate.bin");std::ofstream cf(dir + "/calibration.json");cf << calib_.to_json().dump();std::ofstream mf(dir + "/meta.json");mf << sfx::JV(sfx::JVObj{{"engine", "syfox"}, {"version", VERSION},31 unmodified lines{"seq", static_cast<double>(kv.second.seq)},{"outcome", sfx::JV(kv.second.outcome)}}).dump() << "\n";}// -- M2: PERSISTENT META-LEARNER -------------------------------------// Before M2 the rule-induction state was never serialised, so every// invocation started empty and macro-rule promotion at the 2-bit MDL// threshold could never fire across runs. Written whenever a rule set// exists; absent file = fresh learner, which is exactly the pre-M2// behaviour for any model built before this version.if (!reason_.rules.empty()) {std::ofstream of(dir + "/meta_rules.txt");if (of) of << sxr::serialize_meta(reason_meta_.chain_stats, reason_meta_.macros,&reason_, &thinker_);}}// v3.3 question-conditioned readout (read-only over the settled field).89 unmodified linessxr::MetaLearner reason_meta_;sxr::ThinkerIndex thinker_;bool reason_loaded_ = false;// M1 gates (all default false == pre-M1 behaviour, bit-identical).bool thinker_on_ = false; // --thinker: run the reasoner in decide()bool reason_fixpoint_ = false; // --reason-fixpoint: chain BEFORE readoutbool meta_observe_ = false; // --meta-observe: feed proofs to MetaLearnerbool role_bind_ = false; // M9 --role-bind: query-role alignment re-rankbool reason_route_ = false; // M10 --reason-route: reasoner drives the choicestd::string reason_route_pick_; // disclosure: which candidate was derivedstd::string role_bind_hint_; // disclosure: which clause/agent was alignedstd::string state_text_; // M9: raw state for clause segmentation// M9-encoder: the pre-synaptic input (pooled encoder embedding). EMPTY by// default, which is what keeps the substrate-only path bit-identical.std::vector<float> enc_in_;// M2: what load_model restored from meta_rules.txt (0 = file absent).int meta_chains_ = 0, meta_macros_ = 0, meta_rules_ = 0;// Lines in axioms.txt that named a relation this build does not know. 0 is// the honest state; a non-zero value means part of the knowledge base was// silently dropped at load.int axiom_rejected_ = 0;int axiom_rejected() const { return axiom_rejected_; }bool reason_loaded() const { return reason_loaded_; }std::size_t reason_nodes() const { return reason_.graph.nodes.size(); }std::size_t reason_edges() const { return reason_.graph.edges.size(); }// -- M2: write ONLY the meta-learner state, without the rest of save_model.// decide() must never write (the bench replay contract depends on it), so// accumulation is an explicit, opt-in action on the think/ask/derive paths.// Returns (chains, macros) actually written; 0/0 when no rule set exists.std::array<int, 2> save_meta(const std::string& dir) {if (reason_.rules.empty()) return {0, 0};const std::string cmd = "mkdir -p '" + dir + "'";(void)std::system(cmd.c_str());std::ofstream of(dir + "/meta_rules.txt");if (!of) return {0, 0};of << sxr::serialize_meta(reason_meta_.chain_stats, reason_meta_.macros,&reason_, &thinker_);return {static_cast<int>(reason_meta_.chain_stats.size()),static_cast<int>(reason_meta_.macros.size())};}std::size_t meta_chains() const { return reason_meta_.chain_stats.size(); }std::size_t meta_macros() const { return reason_meta_.macros.size(); }// -- M1: THINKER-IN-THE-LOOP -------------------------------------------// Before v3.9.1 the axiom graph was consulted from decide() through// proof_path_between() alone -- a bounded <=4-hop typed BFS. Forward// chaining, the verifier, macro-rules, the thinker index and the six// discovery queries were reachable ONLY from the CLI subcommands, so the// fabric's DECISION could never compose: it only scored anchors it had// been taught directly. This is the "thinker in the loop" gate.//// Default OFF. Bit-identical to every pre-M1 fabric when off (no// reasoning call is made), which preserves the bench replay contract and// every number in docs/HONEST_TOTAL.md.void set_thinker(bool on) { thinker_on_ = on; }bool thinker_on() const { return thinker_on_; }// when on: reason to fixpoint BEFORE the readout, so derived edges exist// in the graph the proof pass then walks.void set_reason_to_fixpoint(bool on) { reason_fixpoint_ = on; }bool reason_fixpoint() const { return reason_fixpoint_; }// M2 gate: whether to observe the chosen proof trace into the// MetaLearner. Harmless while M2's persistence does not exist (the// learner dies with the process) but is the correct seam.void set_meta_observe(bool on) { meta_observe_ = on; }// M9: query-role alignment re-rank at decide time (default off).void set_role_bind(bool on) { role_bind_ = on; }// M10 REASONER-ROUTED DECISIONS.//// The system was a similarity index with a reasoner bolted beside it that// the index never consulted: decide() reached the axiom graph through ONE// bounded 4-hop path lookup, so a question whose answer is DERIVABLE scored// anchors instead. Measured on model-mega-v2:// field 11/30 = 0.367 on held-out reasoning (chance 0.333)// reasoner 16/16 = 1.000 on held-out composition// Those two numbers are the whole argument. This gate makes the decision// path USE the reasoner: if a candidate is reachable by a TYPED PATH from// something the state asserts, that candidate is derived, not retrieved --// so it is selected on the derivation rather than on field energy. When no// candidate is derivable, the field answers exactly as before.//// This is the honest version of "thinker, not pattern matcher": derivation// decides when it applies, retrieval decides when it does not, and the two// never pretend to be each other.void set_reason_route(bool on) { reason_route_ = on; }bool reason_route() const { return reason_route_; }bool role_bind() const { return role_bind_; }bool meta_observe() const { return meta_observe_; }// Bring the axiom graph to fixpoint. Cheap and idempotent once already// derived: reason_ext() stops at the first pass that adds nothing.sxr::ReasonCore::ReasonReport think_fixpoint() {if (!reason_loaded_) return {0, 0, 0.0f};return reason_.reason_ext();}// load_axioms: SI's .axioms triple format into BOTH stores. Returns the// number of accepted (new) triples. Graph side: teach_axiom (dedup +// contradiction guard). Fabric side: intern subject/object, bind an16 unmodified linesif (!(iss >> subj >> rel_tok >> obj)) continue;const int rel = sxr::rel_from_token(rel_tok);if (rel < 0) {// Persistently record the rejection even when log is null.// load_model() calls load_axioms(path, nullptr), so the stderr// diagnostic never fires at decide time and a typo'd relation in// an .axioms file was silently dropped on EVERY boot -- measured:// "radio found_by Tariq" reported new_triples=0 with no warning// outside the one-shot `axioms` command. Rejected triples are now// counted and disclosed via usage.axioms_rejected.++axiom_rejected_;if (log) std::fprintf(log, "[axioms] unknown relation '%s' skipped\n",rel_tok.c_str());continue;20 unmodified linesconst std::string& anchor_label) const {std::vector<std::string> hops;if (!reason_loaded_) return hops;// Case-insensitive lookups: normalize() lowercases, the graph stores// original case, and an exact-match probe therefore always missed. See// ReasonCore::find_node_ci for the full diagnosis.const auto lt = si::norm::normalize(anchor_label);int goal = -1;for (const auto& t : lt) { goal = reason_.find_node_ci(t); if (goal >= 0) break; }if (goal < 0) return hops;// strongest state concept present in the axiom graph (word order =// arrival order; first hit wins, mirroring the injection order).int start = -1; std::string start_word;for (const auto& w : state_words) {start = reason_.find_node_ci(w);if (start >= 0) { start_word = w; break; }}if (start < 0 || start == goal) return hops;const auto path = reason_.find_path(11 unmodified linesreturn hops;}// M1: the edge INDICES behind proof_path_between(), so the MetaLearner can// observe a real derivation chain instead of a bag of strings. Returns// premises-first-then-conclusion, matching ReasonCore::trace().std::vector<int> proof_edge_indices(const std::vector<std::string>& state_words,const std::string& anchor_label) const {std::vector<int> idx;if (!reason_loaded_) return idx;const auto lt = si::norm::normalize(anchor_label);int goal = -1;for (const auto& t : lt) { goal = reason_.find_node_ci(t); if (goal >= 0) break; }if (goal < 0) return idx;int start = -1;for (const auto& w : state_words) { start = reason_.find_node_ci(w); if (start >= 0) break; }if (start < 0 || start == goal) return idx;const auto path = reason_.find_path(reason_.graph.nodes[static_cast<std::size_t>(start)].label,reason_.graph.nodes[static_cast<std::size_t>(goal)].label, -1, 4);for (int ei : path) {// expand each step into its parent edges, premises firststd::vector<int> sub = reason_.trace(ei);for (int s : sub)if (std::find(idx.begin(), idx.end(), s) == idx.end()) idx.push_back(s);}return idx;}// -- v3.9.0 decision-layer paper gates (all default OFF; replay-safe) ----void set_proof(bool disclose, bool require) { proof_on_ = disclose; require_proof_ = require; }bool proof_on() const { return proof_on_; }1 unmodified linebool momentum_gate_on() const { return momentum_gate_; }void set_wavefront_gate(bool on) { wavefront_gate_ = on; }bool wavefront_gate_on() const { return wavefront_gate_; }void set_coherence_gate(bool on, float floor) {coherence_gate_ = on;coherence_floor_ = floor > 0.0f ? floor : 0.05f;22 unmodified lines// v3.2.1: returns false when the substrate file is missing (honest load// failure — callers surface a clear error instead of deciding on an// empty fabric or, worse, reporting a misleading downstream message).// M9-LEARNED: teach the role tagger what a function word is, FROM THIS// FABRIC, so the hardcoded rulebook is only a fallback for fabrics too small// to have a meaningful document-frequency table.void learn_function_words(double frac = 0.02, std::size_t cap = 4000) {if (!si_.df_table_size()) return;const std::size_t total = si_.df_lesson_count();if (total < 50) return; // too small: keep the fallbackconst double cut = static_cast<double>(total) * frac;std::vector<std::string> learned;for (const auto& kv : si_.df_ranked(cap))if (static_cast<double>(kv.second) >= cut) learned.push_back(kv.first);if (learned.empty()) return;si::roles::load_function_words(std::move(learned));}bool load_model(const std::string& dir) {if (!si_.load(dir + "/substrate.bin")) return false;std::ifstream cf(dir + "/calibration.json");if (cf) { std::string buf((std::istreambuf_iterator<char>(cf)), std::istreambuf_iterator<char>());calib_ = Calibration::from_json(sfx::JV::parse(buf)); }// v3 audit trail (optional files; a v2 model dir simply lacks them){std::ifstream f(dir + "/conflicts.jsonl");27 unmodified lines// v3.2: semantic hierarchy (Stage 3) ships as hierarchy.json in the// model dir; absent file = single-stage readout, exactly as before.load_hierarchy(dir + "/hierarchy.json");// M9-LEARNED: derive the role tagger's function words from this fabric.learn_function_words();// -- M2: restore the persistent meta-learner -----------------------// Absent file = fresh learner (pre-M2 behaviour, bit-identical for any// model built before v3.9.1). Macro rules are re-added to the engine as// firing transitive rules, so a chain promoted in an earlier run// actually fires now instead of sitting in a file.{std::ifstream f(dir + "/meta_rules.txt");if (f) {std::string buf((std::istreambuf_iterator<char>(f)),std::istreambuf_iterator<char>());const auto n = sxr::deserialize_meta(reason_meta_.chain_stats, reason_meta_.macros,&reason_, &thinker_, buf);meta_chains_ = n[0]; meta_macros_ = n[1]; meta_rules_ = n[2];}}// v3.2 retrieval BY DEFAULT: a memories.jsonl shipped in the model dir// is loaded and fingerprinted once (settled-field cosines are then// free at decide time). No file => retrieval is inert, behavior of414 unmodified lines};adopt_temp("choice", calib_.choice_temperature);adopt_temp("score", calib_.score_temperature);// Platt: same 1-bit selection for the noul mapconst float a0 = calib_.noul_a, b0 = calib_.noul_b;const double p1 = calibration_ece(rows, "noul", 1.0f, a0, b0);8 unmodified lines// width bins on top-probability confidence, argmax-correctness for// choice/score; Platt sigmoid + 0.5 threshold for noul). Same definition// the bench reports, so calibrate's before/after and bench's ECE agree.static double calibration_ece(const std::vector<CalibRow>& rows,const std::string& type, float T,float noul_a, float noul_b) {long bins[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};long corr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};double confs[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};7 unmodified linescorrect = (p >= 0.5f) == (r.y == 1);} else {if (r.energies.empty()) continue;float maxe = -1e30f;for (const auto& kv : r.energies) maxe = std::max(maxe, kv.second);float z = 0.0f, top = -1.0f; std::string amax;for (const auto& kv : r.energies) {const float v = std::exp((kv.second - maxe) / Ts);z += v;if (v > top) { top = v; amax = kv.first; }}420 unmodified linesusage.lanes = si_.lane_count();std::vector<Answer> answers;// M9: the RAW state, kept so decide_choice can segment on clause-final// punctuation. normalize() discards that punctuation (and drops 1-char// tokens), so the information is unrecoverable from `words` alone.state_text_ = state;usage.axioms_rejected = static_cast<double>(axiom_rejected_);const std::vector<std::string> words = si::norm::normalize(state);usage.state_tokens = words.size();// M9-encoder: if an encoder projection is configured, read the settled// field back in channel space and apply ONE local Oja update, scaled by// the GHL global sign g. With no encoder this is a no-op, so the// substrate-only path is bit-identical.if (si_.has_encoder()) {const std::vector<float> y = si_.encoder_project(enc_in_);// g: novelty lowers the update (explore less on unfamiliar input),// conflict raises it. Reuses the NTDA modulator's sign convention.const float th = si_.current_theta();const float g = th > 0.0f ? (1.0f / th) : 1.0f;if (!enc_in_.empty()) si_.encoder_update(enc_in_, y, g);usage.enc_updates = static_cast<double>(si_.enc_updates());}// M5 (c): feed the modulators. Novelty = fraction of state tokens the// fabric has NEVER interned (the OOD signal the engine already computes// for its own gate). Conflict = the standing contradiction count,// normalised. Both are read-only over the substrate.if (si_.ntda_on()) {std::size_t unk = 0;for (const auto& w : words) if (!si_.has(w)) ++unk;si_.set_novelty(words.empty() ? 0.0f: static_cast<float>(unk) / static_cast<float>(words.size()));si_.set_conflict(conflicts_.empty() ? 0.0f: std::min(1.0f, static_cast<float>(conflicts_.size()) / 64.0f));usage.ntda_theta = si_.current_theta();}// v3.8.0 (TASK 1) adaptive depth: measure the problem BEFORE any// settle; when the flag is on, harder states get more passes.348 unmodified lines// Harvest calibration rows from labelled examples (tool side).std::vector<CalibRow> harvest_rows(const std::vector<sfx::JV>& examples) {std::vector<CalibRow> rows;for (const auto& ex : examples) {std::string state = ex.at("state").as_str();const sfx::JV& qs = ex.has("questions") ? ex.at("questions") : sfx::JV(sfx::JVObj{});if (!qs.is_obj()) continue;// v3.2.1: prime EXACTLY as decide() does (shared prime_field) —// the fit must see the decide-time field composition. For fabrics// without memories this is a bare reset, the pre-3.2 behavior.51 unmodified lines// v3.8.0 (TASK 2) fit/decide parity: the fit sees the same// multi-vector superposition the decision sees.apply_multi_vector(hw0, nullptr);if (si_.silent()) continue;for (const auto& qkv : qs.obj) {const sfx::JV& q = qkv.second;std::string type = q.at("type").as_str();1 unmodified lineif (type == "choice" || type == "score") {const sfx::JV& crit = q.at("criteria");std::vector<std::pair<std::string, float>> energies;if (crit.is_obj())for (const auto& kv : crit.obj)energies.emplace_back(kv.first, probe_energy(kv.first, kv.second.as_str()));else if (crit.is_arr())for (std::size_t i = 0; i < crit.arr.size(); ++i)energies.emplace_back(crit.arr[i].as_str(), probe_energy(crit.arr[i].as_str(), ""));// resolve the gold label to a candidate KEY: for array// criteria the stored label may be the level INDEX ("0",// "1", ...) — the old code compared it to the level text199 unmodified linesreturn si_.readout(si::norm::normalize(label + " " + desc));}float noul_support(const std::string& instructions) const {// Noul uses the SUPPORT readout lane: breadth of corroboration.float e = si_.readout(si::norm::normalize(instructions), si::Substrate::ReadoutMode::Support);120 unmodified linesreturn std::max(0.0f, std::min(1.0f, conf));}// -- M9: QUERY-ROLE ALIGNMENT ---------------------------------------------// Re-rank choice candidates by the ROLE the question actually asks about,// computed from the RAW state text at decide time.//// Why this exists (measured on model-mega-v2, tools/reason30.py): on// state : "The radio was found by Tariq. Salma was there."// question: "Who found the radio?" options: Tariq / Salma / radio// the readout answered Salma with p=0.996 in BOTH wordings — i.e. it is not// reading the "by" agent at all, it returns the LAST-MENTIONED subject. Seven// of thirteen misses had this shape.//// normalize() cannot help: it DISCARDS sentence punctuation (emitting a token// only on non-alnum) and DROPS tokens of length 1 (emit() requires size>=2),// so clause boundaries and single-letter options are already gone before any// role tagger runs. That also explains the unknown_candidates on the A/B/C// and K/L/M/N probes. Changing normalize() would re-intern every fabric and// break the replay contract, so segmentation happens HERE, on the raw string,// at decide time only. learn is never touched.//// Contract: pure re-rank over already-measured candidate energies. It adds// no lanes, no nodes, and no field perturbation, so with the gate off every// number in docs/HONEST_TOTAL.md replays exactly.struct RoleHint { int clause = -1; std::string agent; };RoleHint role_hint(const std::string& state_text, const std::string& instr) const {RoleHint h;// 1) split the RAW state on clause-final punctuation.std::vector<std::string> clauses;std::string cur;for (char raw : state_text) {if (raw == '.' || raw == '!' || raw == '?' || raw == ';' || raw == '\n') {if (!cur.empty()) { clauses.push_back(cur); cur.clear(); }} else cur.push_back(raw);}if (!cur.empty()) clauses.push_back(cur);if (clauses.empty()) return h;// 2) the question's verb cue, if any ("found", "gave", "owns").const auto iw = si::norm::normalize(instr);std::string verb;for (const auto& t : iw) if (si::roles::is_verb_cue(t)) { verb = t; break; }// 3) the clause that shares the question's verb — that clause is the one// the question is about. Falls back to the FIRST clause, which is the// conventional topic position and beats "last mentioned".std::size_t pick = 0;if (!verb.empty()) {for (std::size_t i = 0; i < clauses.size(); ++i) {const auto cw = si::norm::normalize(clauses[i]);for (const auto& t : cw) if (t == verb) { pick = i; goto found; }}}found:const auto cw = si::norm::normalize(clauses[pick]);const auto roles = si::roles::tag(cw);h.clause = static_cast<int>(pick);// 4) the AGENT. In ACTIVE voice ("Tariq found the radio") the agent is S.// In PASSIVE voice ("the radio was found BY Tariq") the agent is the// O slot, because that is where the "by"-phrase lands -- and with the// copula fixed (was->wa) the tagger now correctly puts S=radio, O=Tariq.// Getting this backwards is exactly the bug: it returned the patient.bool passive = false;for (std::size_t i = 0; i + 1 < cw.size(); ++i)if (cw[i] == "by" && roles[i + 1] == si::roles::Role::O) { passive = true; break; }const si::roles::Role want = passive ? si::roles::Role::O : si::roles::Role::S;for (std::size_t i = 0; i < cw.size(); ++i) {if (roles[i] != want) continue;h.agent = cw[i];break;}// 5) a passive clause whose O is not a name-like token (e.g. the bare// "there" of "Salma was there") must not boost anything.if (h.agent == "there" || h.agent == "it") h.agent.clear();return h;}void decide_choice(const sfx::JV& q, const std::vector<std::string>& state_words,Answer& a, Usage* usage = nullptr) {const sfx::JV& crit = q.at("criteria");std::vector<std::string> labels; std::vector<float> energies;if (crit.is_obj())for (const auto& kv : crit.obj) {labels.push_back(kv.first);energies.push_back(probe_energy(kv.first, kv.second.as_str()));}else if (crit.is_arr())for (const auto& v : crit.arr) {labels.push_back(v.as_str());energies.push_back(probe_energy(v.as_str(), ""));}if (labels.empty()) { a.deferred = true; a.reason = "no_options"; return; }14 unmodified lines// measured real signal (probe-fabric candidates 0.19-0.88); below it// the field is carryover. Do NOT raise above 0.10 — that false-defers// valid dim candidates (measured 0.19 without energy-norm).// -- M10 REASONER-ROUTED CHOICE -----------------------------------------// MUST run BEFORE the unknown_candidates floor. It was originally placed after// it, which meant a dark field deferred with "unknown_candidates" and the// routing code was never reached -- on a small probe fabric that is EVERY// query, so the feature could never fire. A derivation is not an energy and// must not be gated by one.// -- M10 REASONER-ROUTED CHOICE -----------------------------------------if (reason_route_ && reason_loaded_ && !state_words.empty()) {// First candidate (criteria order) that is REACHABLE by a typed path.// Deterministic: criteria order is fixed, so this is reproducible.// If MORE THAN ONE is reachable the answer is genuinely ambiguous and// we take the first, but we disclose the count so a reader can tell a// unique derivation from an arbitrary one.int derived = -1;int n_derived = 0;for (std::size_t i = 0; i < labels.size(); ++i) {if (proof_path_between(state_words, labels[i]).empty()) continue;if (derived < 0) derived = static_cast<int>(i);++n_derived;}if (usage) {usage->reason_routed = n_derived > 0;usage->reason_derived_count = static_cast<double>(n_derived);}if (derived >= 0) {reason_route_pick_ = labels[static_cast<std::size_t>(derived)];for (std::size_t i = 0; i < energies.size(); ++i)energies[i] = (static_cast<int>(i) == derived) ? 1.0f : 0.0f;if (usage) { usage->reason_routed = true; }}}float max_energy = 0.0f;for (float e : energies) max_energy = std::max(max_energy, e);if (std::getenv("SYFOX_DEBUG_READOUT") != nullptr) {std::fprintf(stderr, "DEBUG: max_candidate=%.3f threshold=%.3f\n",max_energy, kUnknownCandidateFloor);for (std::size_t i = 0; i < labels.size(); ++i)std::fprintf(stderr, "DEBUG: candidate[%s]=%.4f\n",labels[i].c_str(), energies[i]);}if (max_energy < kUnknownCandidateFloor) {a.deferred = true;a.reason = "unknown_candidates";return;}// -- M9 QUERY-ROLE ALIGNMENT (opt-in, decide-time, read-only) ----------// Applied BEFORE the paper gates so they still see the aligned energies.if (role_bind_ && !state_text_.empty()) {const RoleHint h = role_hint(state_text_, q.at("instructions").as_str());if (!h.agent.empty()) {role_bind_hint_ = h.agent;std::size_t boosted = 0;for (std::size_t i = 0; i < labels.size(); ++i) {const auto lw = si::norm::normalize(labels[i]);bool match = lw.empty();for (const auto& t : lw) if (t == h.agent) { match = true; break; }// Multi-word options ("curtain opening") are matched on the// agent being one of their tokens; a bare entity label is the// normal case and wins outright.if (!match) continue;energies[i] *= 2.0f;++boosted;}if (usage && boosted) usage->role_bind_boosted = static_cast<double>(boosted);}}// v3.9.0 decision-layer paper gates — each measures the settled field// READ-ONLY and zeroes/scales energies; none rewrites the field.// (a) MOMENTUM (MCPE §1 / CPME §2): a candidate whose normalized165 unmodified lines}}std::vector<float> p;softmax_ps(energies, p, calib_.choice_temperature);std::size_t best = std::max_element(p.begin(), p.end()) - p.begin();a.choice = labels[best];for (std::size_t i = 0; i < labels.size(); ++i)12 unmodified lines// disclosure; --require-proof defers a choice with no typed path// (coverage-cliff honesty: the field answered, the knowledge layer// cannot justify it).//// M1: when the reasoner is live, chain the axiom graph to fixpoint// FIRST so this walk can traverse DERIVED edges. This is the whole// point of the module: previously find_path could only follow edges// that were asserted, because nothing had ever chained inside// decide(). Gate is off by default -> no extra work, bit-identical.if (usage && (thinker_on_ || reason_fixpoint_) && reason_loaded_) {const sxr::ReasonCore::ReasonReport rep = reason_.reason_ext();usage->thinker_chained = true;usage->thinker_edges_added = rep.edges_added;usage->thinker_passes = rep.steps_used;usage->thinker_budget_left = rep.budget_left;}if (usage && (proof_on_ || require_proof_)) {usage->proof_checked = true;usage->proof_path = proof_path_between(state_words, labels[best]);1 unmodified linea.deferred = true;a.reason = "no_proof_path";}// M1: feed the proof we actually used into the MetaLearner, so// repeated sub-chains accumulate and macro-rules can promote.// Only under --proof/--require-proof: the trace is only known to// be the one that justified THIS answer there.if (meta_observe_ && !a.deferred)reason_meta_.observe_trace(proof_edge_indices(state_words, labels[best]));}// v3.9.0 (fixes.md): remember the signature pieces for the OOD gate.if (usage) {151 unmodified linessi::Substrate si_;Calibration calib_;bool energy_norm_ = false; // Milestone-1 gain knob (default off)std::unordered_set<std::uint64_t> lesson_hashes_; // Milestone-2 dedup memory// v3.2 retrieval-by-default statestd::vector<recall::Memory> memories_;59 unmodified lines60616263646566676880 unmodified lines14915015115215315451 unmodified lines20620720820921021130 unmodified lines2422432442452462472482492502512522532542552562572582592602612622632642652662672682691 unmodified line2712722732742752762772782792803 unmodified lines2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573589 unmodified lines36836937037137237337437537637737837938038138238338438538638738813 unmodified lines40240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045121 unmodified lines47347447547647747847948048148231 unmodified lines51451551651751851989 unmodified lines60961061161261361461561661761861916 unmodified lines63663763863964064120 unmodified lines66266366466566666766866967067167267367467567667711 unmodified lines6896906916926936941 unmodified line69669769869970070170270370470570622 unmodified lines72973073173273373473573673773873974074174227 unmodified lines770771772773774775414 unmodified lines11901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212238 unmodified lines123212331234123512361237123812391240124112421243124412457 unmodified lines1253125412551256125712581259126012611262126312641265126612671268420 unmodified lines16891690169116921693169416951696348 unmodified lines204520462047204820492050205120522053205420552056205720582059206020612062206351 unmodified lines21152116211721182119212021211 unmodified line2123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153199 unmodified lines235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532120 unmodified lines26532654265526562657265826592660266126622663266426652666266726682669267026712672267314 unmodified lines268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723165 unmodified lines288928902891289228932894289528962897289812 unmodified lines2911291229132914291529161 unmodified line291829192920292129222923151 unmodified lines307530763077307830793080308130823083308430853086308759 unmodified lines// energy-norm) and well above float dust from diffusion carryover. Documented// in README (honest-silence section); debug visibility via SYFOX_DEBUG_READOUT=1.inline constexpr float kUnknownCandidateFloor = 0.01f;// v4.0 — a candidate count needs this many calibration rows before it gets// its own temperature; below it the global scalar is kept.inline constexpr std::size_t kMinRowsPerCandidateCount = 64;// v3.6.0: decide-side bigram injection dose as a fraction of the state dose// (MRS §4b grounds bigram lanes like any other lane; the 0.5 fraction keeps// order evidence subordinate to lexical evidence).80 unmodified lines};struct Usage {std::size_t state_tokens = 0;std::size_t vocabulary = 0;std::size_t lanes = 0;51 unmodified lines// strongest concept and the winning anchor (premise-cited hops).bool proof_checked = false;std::vector<std::string> proof_path; // "subject relation object" hops// momentum (MCPE/CPME): fraction of candidates still GAINING energy at// the final settle pass (the echo-suppressed remainder peaked already).bool momentum_gate = false;30 unmodified linesfloat noul_b = -3.0f;bool fitted = false;std::size_t rows = 0;// v4.0 — the temperature depends on the SIZE of the candidate set. A// 14-way question's score spread is not a 2-way question's spread, so one// scalar fitted across both cannot serve both: on the shared giant// fabric (16 domains, candidate counts 2..14) the single temperature// left polarity at ECE 0.395 and dbpedia at 0.064 in the same fit.// One scalar per distinct candidate count, fitted on the same rows with// the same 1-bit ECE selection guard, falls back to the global scalar.std::map<int, float> choice_temperature_by_count;// the temperature this candidate set is scored underfloat choice_temperature_for(std::size_t n_candidates) const {auto it = choice_temperature_by_count.find(static_cast<int>(n_candidates));return (it == choice_temperature_by_count.end()) ? choice_temperature : it->second;}sfx::JV to_json() const {sfx::JVObj counts;for (const auto& kv : choice_temperature_by_count)counts[std::to_string(kv.first)] = sfx::JV(kv.second);return sfx::JV(sfx::JVObj{{"choice_temperature", choice_temperature},{"choice_temperature_by_count", sfx::JV(counts)},{"score_temperature", score_temperature},{"noul_a", noul_a}, {"noul_b", noul_b},{"fitted", fitted}, {"rows", static_cast<double>(rows)}});1 unmodified linestatic Calibration from_json(const sfx::JV& j) {Calibration c;c.choice_temperature = static_cast<float>(j.at("choice_temperature").as_num(1.0));if (j.at("choice_temperature_by_count").is_obj())for (const auto& kv : j.at("choice_temperature_by_count").obj)c.choice_temperature_by_count[std::atoi(kv.first.c_str())] =static_cast<float>(kv.second.as_num(1.0));c.score_temperature = static_cast<float>(j.at("score_temperature").as_num(1.0));c.noul_a = static_cast<float>(j.at("noul_a").as_num(6.0));c.noul_b = static_cast<float>(j.at("noul_b").as_num(-3.0));3 unmodified lines}};// ---------------------------------------------------------------------------// v3.9.2: THE DECIDE-SIDE PHYSICS COMPOSITION.//// WHY THIS EXISTS. The calibration scalars (choice/score temperature, Platt)// are fitted on ENERGIES that come out of a settle pass. Those energies are// a function of the whole decide-side composition: the injected dose// (energy_norm), the lane-flow fraction (diffusion), the dissipation// (decay), the settle-pass cap (k_settle) and the hop coupling. Fit a// temperature on one composition and apply it to another and the fit is// measuring a DIFFERENT engine than the one that will decide.//// That is not hypothetical. The b77-sem / router16 / bank77-best fabrics in// this tree were calibrated WITHOUT the energy gain while every bench and// every decide call ran WITH it (see the Makefile: calibrate has no// --energy-norm, bench has it). Measured on the shipped b77-sem fabric,// same 1,003-row cal split, same engine:// calibrate WITHOUT --energy-norm -> T = 0.0037, fit saw 556 of 2,006// question-rows (27.7% coverage)// calibrate WITH --energy-norm -> T = 0.3552, fit saw 2,006 of 2,006// A ~100x sharper temperature, chosen on a 27.7%-covered, biased subset of// the rows. A near-floor T saturates the post-temperature probability gap// at ~1.0, so (a) the engine's defer axis never fires (a 0.05 margin can// never be exceeded by a gap of 0.93) and (b) every answer carries ~0.98// confidence whether it is right or wrong. Measured on b77-sem bank77// hidden: mean confidence on WRONG answers 0.867 > on RIGHT answers 0.832.//// THE FIX. A fabric now carries the composition it was calibrated under// (physics.json, next to calibration.json). calibrate records it; decide,// bench, demo and stats apply it on load. The fit and the decision are the// same engine BY CONSTRUCTION, and a CLI flag still overrides it.// ---------------------------------------------------------------------------struct PhysicsComposition {bool energy_norm = false; // decide-side energy gain (M1)float diffusion = -1.0f; // -1 = keep the substrate defaultfloat decay = -1.0f;int k_settle = -1;float hop_coupling = -1.0f;// v4.0 — the READOUT the fabric was calibrated under. Recorded with the// rest of the decide-side composition so a deployed model decides under// the same readout its temperature was fitted for (the fit==decide// parity contract, extended from the physics to the measurement).float affinity_mix = 0.0f; // 0 = legacy readout, 1 = affinity onlybool affinity_pmi = false; // log-odds form of the contrastbool recorded = false; // true once a fabric carries physics.jsonsfx::JV to_json() const {return sfx::JV(sfx::JVObj{{"energy_norm", energy_norm},{"diffusion", diffusion}, {"decay", decay},{"k_settle", static_cast<double>(k_settle)},{"hop_coupling", hop_coupling},{"affinity_mix", affinity_mix},{"affinity_pmi", affinity_pmi},{"recorded", recorded}});}static PhysicsComposition from_json(const sfx::JV& j) {PhysicsComposition p;p.energy_norm = j.at("energy_norm").is_bool() && j.at("energy_norm").b;p.diffusion = static_cast<float>(j.at("diffusion").as_num(-1.0));p.decay = static_cast<float>(j.at("decay").as_num(-1.0));p.k_settle = static_cast<int>(j.at("k_settle").as_num(-1));p.hop_coupling = static_cast<float>(j.at("hop_coupling").as_num(-1.0));p.affinity_mix = static_cast<float>(j.at("affinity_mix").as_num(0.0));p.affinity_pmi = j.at("affinity_pmi").is_bool() && j.at("affinity_pmi").b;p.recorded = j.at("recorded").is_bool() && j.at("recorded").b;return p;}};// ---------------------------------------------------------------------------class Engine {public:9 unmodified linesreason_meta_.engine = &reason_;}si::Substrate& substrate() { return si_; }const si::Substrate& substrate() const { return si_; }// -- v3.9.3: repair the numerically dead lanes from the evidence ledger --// See si::Substrate::repair_lanes_from_evidence() for the full diagnosis:// the port's global per-lesson decay drove 95% of the giant fabric's// lanes to the float32 denormal floor, erasing its Hebbian memory. This// rebuilds each lane's weight from the persisted ledger (the integral of// the growth term the decay destroyed) in CMD §2.3's saturating form.si::Substrate::LaneRepairStats repair_lanes(float dead_threshold = 1e-6f,bool apply = true) {return si_.repair_lanes_from_evidence(dead_threshold, apply);}// v3.9.3: the lane-decay floor (0 = off, bit-identical to pre-v3.9.3).void set_lane_decay_floor(float f) { si_.set_lane_decay_floor(f); }Calibration& calibration() { return calib_; }// -- v3 Milestone 1: decide-side energy normalization (boundary GAIN knob) --13 unmodified linesvoid set_energy_norm(bool on) { energy_norm_ = on; }bool energy_norm() const { return energy_norm_; }// -- v3.9.2: decide-side physics composition (see PhysicsComposition) -----const PhysicsComposition& composition() const { return composition_; }void set_composition(const PhysicsComposition& c) { composition_ = c; }// v3.9.2: calibration-fit coverage bookkeeping (offered vs. seen rows).std::size_t harvest_offered() const { return harvest_offered_; }std::size_t harvest_dropped_silent() const { return harvest_dropped_silent_; }// Push the recorded composition into the live engine. Called on model// load (decide/bench/demo/stats) and before a calibration fit, so the// fit and the decision are the same engine by construction.void apply_composition() {if (composition_.energy_norm) set_energy_norm(true);if (composition_.diffusion >= 0.0f) si_.set_diffusion(composition_.diffusion);if (composition_.decay >= 0.0f) si_.set_decay(composition_.decay);if (composition_.k_settle > 0) si_.set_k_settle(composition_.k_settle);if (composition_.hop_coupling >= 0.0f) si_.set_hop_coupling(composition_.hop_coupling);if (composition_.affinity_mix > 0.0f) set_affinity_mix(composition_.affinity_mix);if (composition_.affinity_pmi) set_affinity_pmi(true);}// Snapshot the LIVE composition (what this process would decide under).PhysicsComposition live_composition() const {PhysicsComposition p;p.energy_norm = energy_norm_;p.diffusion = si_.config().diffusion;p.decay = si_.config().decay;p.k_settle = si_.config().k_settle;p.hop_coupling = si_.config().hop_coupling;p.affinity_mix = affinity_mix_;p.affinity_pmi = affinity_pmi_;p.recorded = true;return p;}// physics.json sidecar (absent file = pre-3.9.2 fabric, composition unset).bool load_physics(const std::string& dir) {std::ifstream f(dir + "/physics.json");if (!f) return false;std::string buf((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());composition_ = PhysicsComposition::from_json(sfx::JV::parse(buf));return true;}void save_physics(const std::string& dir) const {std::ofstream f(dir + "/physics.json");f << composition_.to_json().dump();}// -- model persistence ----------------------------------------------------void save_model(const std::string& dir) {std::string cmd_mkdir = "mkdir -p '" + dir + "'";21 unmodified linessi_.save(dir + "/substrate.bin");std::ofstream cf(dir + "/calibration.json");cf << calib_.to_json().dump();// v3.9.2: the decide-side composition this fabric was calibrated under.// Written alongside calibration.json so decide/bench/calibrate all// agree on the physics without the operator having to remember.if (composition_.recorded) save_physics(dir);std::ofstream mf(dir + "/meta.json");mf << sfx::JV(sfx::JVObj{{"engine", "syfox"}, {"version", VERSION},31 unmodified lines{"seq", static_cast<double>(kv.second.seq)},{"outcome", sfx::JV(kv.second.outcome)}}).dump() << "\n";}}// v3.3 question-conditioned readout (read-only over the settled field).89 unmodified linessxr::MetaLearner reason_meta_;sxr::ThinkerIndex thinker_;bool reason_loaded_ = false;bool reason_loaded() const { return reason_loaded_; }std::size_t reason_nodes() const { return reason_.graph.nodes.size(); }std::size_t reason_edges() const { return reason_.graph.edges.size(); }// load_axioms: SI's .axioms triple format into BOTH stores. Returns the// number of accepted (new) triples. Graph side: teach_axiom (dedup +// contradiction guard). Fabric side: intern subject/object, bind an16 unmodified linesif (!(iss >> subj >> rel_tok >> obj)) continue;const int rel = sxr::rel_from_token(rel_tok);if (rel < 0) {if (log) std::fprintf(log, "[axioms] unknown relation '%s' skipped\n",rel_tok.c_str());continue;20 unmodified linesconst std::string& anchor_label) const {std::vector<std::string> hops;if (!reason_loaded_) return hops;const auto lt = si::norm::normalize(anchor_label);int goal = -1;for (const auto& t : lt)if (reason_.graph.by_label.count(t)) { goal = reason_.graph.by_label.at(t); break; }if (goal < 0) return hops;// strongest state concept present in the axiom graph (word order =// arrival order; first hit wins, mirroring the injection order).int start = -1; std::string start_word;for (const auto& w : state_words) {if (reason_.graph.by_label.count(w)) { start = reason_.graph.by_label.at(w); start_word = w; break; }}if (start < 0 || start == goal) return hops;const auto path = reason_.find_path(11 unmodified linesreturn hops;}// -- v3.9.0 decision-layer paper gates (all default OFF; replay-safe) ----void set_proof(bool disclose, bool require) { proof_on_ = disclose; require_proof_ = require; }bool proof_on() const { return proof_on_; }1 unmodified linebool momentum_gate_on() const { return momentum_gate_; }void set_wavefront_gate(bool on) { wavefront_gate_ = on; }bool wavefront_gate_on() const { return wavefront_gate_; }// v4.0 — the affinity field readout channel (default OFF; replay-safe)void set_affinity_mix(float m) { affinity_mix_ = std::max(0.0f, std::min(1.0f, m)); }float affinity_mix() const { return affinity_mix_; }void set_affinity_pmi(bool on) { affinity_pmi_ = on; }bool affinity_pmi() const { return affinity_pmi_; }void set_coherence_gate(bool on, float floor) {coherence_gate_ = on;coherence_floor_ = floor > 0.0f ? floor : 0.05f;22 unmodified lines// v3.2.1: returns false when the substrate file is missing (honest load// failure — callers surface a clear error instead of deciding on an// empty fabric or, worse, reporting a misleading downstream message).bool load_model(const std::string& dir) {if (!si_.load(dir + "/substrate.bin")) return false;std::ifstream cf(dir + "/calibration.json");if (cf) { std::string buf((std::istreambuf_iterator<char>(cf)), std::istreambuf_iterator<char>());calib_ = Calibration::from_json(sfx::JV::parse(buf)); }// v3.9.2: the fabric's recorded decide-side composition. Absent file =// pre-3.9.2 fabric = the frozen defaults (bit-identical to before).load_physics(dir);// v3 audit trail (optional files; a v2 model dir simply lacks them){std::ifstream f(dir + "/conflicts.jsonl");27 unmodified lines// v3.2: semantic hierarchy (Stage 3) ships as hierarchy.json in the// model dir; absent file = single-stage readout, exactly as before.load_hierarchy(dir + "/hierarchy.json");// v3.2 retrieval BY DEFAULT: a memories.jsonl shipped in the model dir// is loaded and fingerprinted once (settled-field cosines are then// free at decide time). No file => retrieval is inert, behavior of414 unmodified lines};adopt_temp("choice", calib_.choice_temperature);adopt_temp("score", calib_.score_temperature);// v4.0 — one temperature per DISTINCT CANDIDATE COUNT. A shared// fabric that serves several domains has candidate sets of different// sizes, and the softmax temperature that suits a 14-way spread// leaves a 2-way one saturated. The count is a property of the// QUESTION, so the temperature may depend on it without leaking// anything about the label. Same 1-bit ECE selection guard, same// rows; a count with too few rows keeps the global scalar.{std::map<int, std::vector<CalibRow>> by_count;for (const auto& r : rows)if (r.type == "choice" && !r.energies.empty())by_count[static_cast<int>(r.energies.size())].push_back(r);for (const auto& kv : by_count) {if (kv.second.size() < kMinRowsPerCandidateCount) continue;float cand = calib_.choice_temperature;fit_temperature(kv.second, "choice", cand);const double e1 = calibration_ece(kv.second, "choice", 1.0f, 0, 0);const double e2 = calibration_ece(kv.second, "choice", cand, 0, 0);const double e0 = calibration_ece(kv.second, "choice",calib_.choice_temperature, 0, 0);float best = calib_.choice_temperature;float best_ece = e0;if (e2 < best_ece) { best = cand; best_ece = e2; }if (e1 < best_ece) { best = 1.0f; best_ece = e1; }if (best != calib_.choice_temperature)calib_.choice_temperature_by_count[kv.first] = best;}}// Platt: same 1-bit selection for the noul mapconst float a0 = calib_.noul_a, b0 = calib_.noul_b;const double p1 = calibration_ece(rows, "noul", 1.0f, a0, b0);8 unmodified lines// width bins on top-probability confidence, argmax-correctness for// choice/score; Platt sigmoid + 0.5 threshold for noul). Same definition// the bench reports, so calibrate's before/after and bench's ECE agree.// `by_count` (v4.0): when given, a choice row is scored under the// temperature fitted for ITS candidate-set size; the scalar T is the// fallback. Same ECE definition either way, so the report and the bench// agree.static double calibration_ece(const std::vector<CalibRow>& rows,const std::string& type, float T,float noul_a, float noul_b,const std::map<int, float>* by_count = nullptr) {long bins[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};long corr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};double confs[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};7 unmodified linescorrect = (p >= 0.5f) == (r.y == 1);} else {if (r.energies.empty()) continue;float Ts_row = Ts;if (by_count && type == "choice") {auto bit = by_count->find(static_cast<int>(r.energies.size()));if (bit != by_count->end()) Ts_row = std::max(1e-6f, bit->second);}float maxe = -1e30f;for (const auto& kv : r.energies) maxe = std::max(maxe, kv.second);float z = 0.0f, top = -1.0f; std::string amax;for (const auto& kv : r.energies) {const float v = std::exp((kv.second - maxe) / Ts_row);z += v;if (v > top) { top = v; amax = kv.first; }}420 unmodified linesusage.lanes = si_.lane_count();std::vector<Answer> answers;const std::vector<std::string> words = si::norm::normalize(state);usage.state_tokens = words.size();// v3.8.0 (TASK 1) adaptive depth: measure the problem BEFORE any// settle; when the flag is on, harder states get more passes.348 unmodified lines// Harvest calibration rows from labelled examples (tool side).std::vector<CalibRow> harvest_rows(const std::vector<sfx::JV>& examples) {std::vector<CalibRow> rows;// v3.9.2: coverage bookkeeping. A row whose settled field is SILENT// contributes no candidate energies and is dropped from the fit. If// the composition is wrong (e.g. the decide-side energy gain is off)// that drop rate explodes and the fit is left on a biased subset —// the fit saw 556 of 2,006 question-rows on the shipped b77-sem// calibration. Offered vs seen is now disclosed by `calibrate`.harvest_offered_ = 0;harvest_dropped_silent_ = 0;for (const auto& ex : examples) {std::string state = ex.at("state").as_str();const sfx::JV& qs = ex.has("questions") ? ex.at("questions") : sfx::JV(sfx::JVObj{});if (!qs.is_obj()) continue;harvest_offered_ += qs.obj.size();// v3.2.1: prime EXACTLY as decide() does (shared prime_field) —// the fit must see the decide-time field composition. For fabrics// without memories this is a bare reset, the pre-3.2 behavior.51 unmodified lines// v3.8.0 (TASK 2) fit/decide parity: the fit sees the same// multi-vector superposition the decision sees.apply_multi_vector(hw0, nullptr);if (si_.silent()) { harvest_dropped_silent_ += qs.obj.size(); continue; }for (const auto& qkv : qs.obj) {const sfx::JV& q = qkv.second;std::string type = q.at("type").as_str();1 unmodified lineif (type == "choice" || type == "score") {const sfx::JV& crit = q.at("criteria");std::vector<std::pair<std::string, float>> energies;std::vector<std::string> c_labels, c_descs;std::vector<float> c_legacy;if (crit.is_obj())for (const auto& kv : crit.obj) {c_labels.push_back(kv.first);c_descs.push_back(kv.second.as_str());c_legacy.push_back(probe_energy(kv.first, kv.second.as_str()));}else if (crit.is_arr())for (std::size_t i = 0; i < crit.arr.size(); ++i) {c_labels.push_back(crit.arr[i].as_str());c_descs.push_back("");c_legacy.push_back(probe_energy(crit.arr[i].as_str(), ""));}// v4.0 — the SAME affinity blend the decision applies, so// the fitted temperature describes the vector the decision// will actually score (fit==decide parity).if (affinity_mix_ > 0.0f) {build_affinity(c_labels, hw0);std::vector<float> blended;blend_affinity(c_legacy, blended);c_legacy.swap(blended);}for (std::size_t i = 0; i < c_labels.size(); ++i)energies.emplace_back(c_labels[i], c_legacy[i]);// resolve the gold label to a candidate KEY: for array// criteria the stored label may be the level INDEX ("0",// "1", ...) — the old code compared it to the level text199 unmodified linesreturn si_.readout(si::norm::normalize(label + " " + desc));}// ======================================================================// v4.0 — THE AFFINITY FIELD READOUT (AFR)// ======================================================================//// THE MISSING TERM. For every lesson the fabric accumulates the// Hebbian affinity between the state's tokens and the outcome anchor// (outcome_text = the label key + its description; hebbian_lesson// binds every state token to every outcome token). That affinity is// the cleanest signal the fabric holds — it is literally "which// intent did this word teach" — and the legacy readout NEVER READS// IT. The legacy readout samples the settled field and relies on a// capped, decaying diffusion to carry the evidence from the query's// tokens to the anchor. ONE constant then has to serve two masters:// precision (the field must not smear onto wrong anchors) and reach// (the right anchor must light up at all). The measured optimum// differs per domain (tickets_en wants diffusion 0.45; agnews and// dbpedia want 0.02) — a sign the constant is being asked to do a// job the readout should do.//// AFR reads the SAME lanes in closed form. For the lit query tokens u// with field energy E_u and the candidate set C://// P(c|u) = w(u,c) / sum_{c' in C} w(u,c') posterior over C// P0(c) = mass(c) / sum_{c'} mass(c') a priori share of C// L(c) = sum_u E_u * [ P(c|u) - P0(c) ] linear contrast// or, with --affinity-pmi, the log-odds form:// L(c) = sum_u E_u * log( P(c|u) / P0(c) )//// A token that points at every candidate CANCELS against the null// model and contributes nothing; a token that points at ONE candidate// contributes strongly, positive for that candidate and negative for// the rest. The legacy readout does the opposite: shared tokens add a// large common offset, and the one discriminative token is a single// term among the hundreds a mined-phrase description contributes// (Banking77 descriptions are 20 mined phrases, so "not"/"working"// style shared words are repeated dozens of times in the probe bag).//// This is the first-order resolvent of the propagation the settle// simulates: the same operator, read exactly instead of approximated// by a capped and smeared diffusion. It needs NO new training — the// lanes already exist — and costs O(|lit| * degree) per question.struct AffinityCtx {bool active = false;std::vector<float> value; // per candidate, unit-scaledstd::vector<char> valid; // candidate has an anchor node};AffinityCtx affinity_ctx_;float affinity_mix_ = 0.0f; // 0 = legacy only (default), 1 = AFR onlybool affinity_pmi_ = false; // log-odds form instead of the linear contrastmutable std::unordered_map<si::NodeId, float> lane_mass_cache_;// total lane weight at a node (the fabric's own "how spread out am I"// statistic). Cached per fabric; lanes are immutable after learning.float lane_mass(si::NodeId a) const {auto it = lane_mass_cache_.find(a);if (it != lane_mass_cache_.end()) return it->second;std::vector<std::pair<si::NodeId, float>> ls;si_.lanes_of(a, ls);float m = 0.0f;for (const auto& l : ls) m += l.second;lane_mass_cache_[a] = m;return m;}// Build the affinity channel for one question's candidate set.void build_affinity(const std::vector<std::string>& labels,const std::vector<std::string>& state_words) {affinity_ctx_ = AffinityCtx{};if (affinity_mix_ <= 0.0f) return;const std::size_t C = labels.size();if (C == 0) return;std::unordered_map<si::NodeId, std::size_t> cidx;std::vector<si::NodeId> cnode(C, static_cast<si::NodeId>(0));std::vector<char> ok(C, 0);for (std::size_t i = 0; i < C; ++i) {// The anchor node is the LABEL as the fabric stores it: the// fabric's nodes are normalized (lowercased, Porter-stemmed,// synonym-folded), so "World" is the node "world" and "positive"// is the node "positiv". Looking the RAW label up (as the first// cut of this channel did) silently finds nothing on any fabric// whose class names are not already lowercase opaque keys, and// the channel then contributes nothing. Normalize first, and// take the first token the fabric actually holds.si::NodeId id = static_cast<si::NodeId>(0);for (const auto& t : si::norm::normalize(labels[i])) {if (!si_.has(t)) continue;id = si_.find(t);break;}if (id == static_cast<si::NodeId>(0) && si_.has(labels[i]))id = si_.find(labels[i]);if (id == static_cast<si::NodeId>(0)) continue;if (cidx.count(id)) continue; // duplicate label -> one anchorcidx[id] = i;cnode[i] = id;ok[i] = 1;}// the null model: each candidate's a priori share of the candidate setstd::vector<double> p0(C, 0.0);double tot = 0.0;for (std::size_t i = 0; i < C; ++i) if (ok[i]) tot += lane_mass(cnode[i]);if (tot <= 0.0) return;for (std::size_t i = 0; i < C; ++i)p0[i] = ok[i] ? (static_cast<double>(lane_mass(cnode[i])) + 1e-12)/ (tot + static_cast<double>(C) * 1e-12): 1.0 / static_cast<double>(C);// the contrastive sum over the lit query tokensstd::vector<double> acc(C, 0.0), num(C, 0.0);std::vector<std::pair<si::NodeId, float>> ls;// v4.0 — the lit set carries ORDER evidence too: the fabric's bigram// nodes ("w1~w2") are bound to the outcome anchors by the same// Hebbian lesson, so their affinity to a candidate is an ordered// relation, not a bag-of-words one. Including them is the CMD 2.5// escape (a multiset cannot separate "a beats b" from "b beats a";// an ordered pair can) applied to the affinity channel.std::vector<std::string> lit(state_words);if (si::norm::bigrams_enabled())for (const auto& bg : si::norm::bigrams_of(state_words)) lit.push_back(bg);for (const auto& w : lit) {if (!si_.has(w)) continue;const si::NodeId u = si_.find(w);const float E = si_.node_energy(u);if (E <= 0.0f) continue;si_.lanes_of(u, ls);std::fill(num.begin(), num.end(), 0.0);double den = 0.0;for (const auto& l : ls) {auto it = cidx.find(l.first);if (it == cidx.end()) continue;num[it->second] += static_cast<double>(l.second);den += static_cast<double>(l.second);}if (den <= 0.0) continue;for (std::size_t i = 0; i < C; ++i) {if (!ok[i]) continue;const double p = num[i] / den;if (affinity_pmi_) {constexpr double kEps = 1e-9;const double lg = std::log((p + kEps) / (p0[i] + kEps));acc[i] += static_cast<double>(E) * std::max(-6.0, std::min(6.0, lg));} else {acc[i] += static_cast<double>(E) * (p - p0[i]);}}}double mx = 0.0;for (std::size_t i = 0; i < C; ++i)if (ok[i]) mx = std::max(mx, std::fabs(acc[i]));affinity_ctx_.active = true;affinity_ctx_.value.assign(C, 0.0f);affinity_ctx_.valid.assign(C, 0);for (std::size_t i = 0; i < C; ++i) {if (!ok[i]) continue;affinity_ctx_.valid[i] = 1;affinity_ctx_.value[i] = (mx > 0.0) ? static_cast<float>(acc[i] / mx) : 0.0f;}}// Blend the affinity channel into the legacy readout energies. Called at// the SAME point in decide and in calibrate, so the fit sees exactly// what the decision sees (the v3.8 fit/decide parity contract).void blend_affinity(const std::vector<float>& legacy, std::vector<float>& out) const {out = legacy;if (!affinity_ctx_.active) return;const float m = affinity_mix_;float lmax = 0.0f;for (float v : legacy) lmax = std::max(lmax, std::fabs(v));for (std::size_t i = 0; i < out.size() && i < affinity_ctx_.value.size(); ++i) {if (!affinity_ctx_.valid[i]) continue;const float l = (lmax > 0.0f) ? legacy[i] / lmax : 0.0f;out[i] = (1.0f - m) * l + m * affinity_ctx_.value[i];}}float noul_support(const std::string& instructions) const {// Noul uses the SUPPORT readout lane: breadth of corroboration.float e = si_.readout(si::norm::normalize(instructions), si::Substrate::ReadoutMode::Support);120 unmodified linesreturn std::max(0.0f, std::min(1.0f, conf));}void decide_choice(const sfx::JV& q, const std::vector<std::string>& state_words,Answer& a, Usage* usage = nullptr) {const sfx::JV& crit = q.at("criteria");std::vector<std::string> labels; std::vector<float> energies;std::vector<std::string> descs;if (crit.is_obj())for (const auto& kv : crit.obj) {labels.push_back(kv.first);descs.push_back(kv.second.as_str());energies.push_back(probe_energy(kv.first, kv.second.as_str()));}else if (crit.is_arr())for (const auto& v : crit.arr) {labels.push_back(v.as_str());descs.push_back("");energies.push_back(probe_energy(v.as_str(), ""));}if (labels.empty()) { a.deferred = true; a.reason = "no_options"; return; }14 unmodified lines// measured real signal (probe-fabric candidates 0.19-0.88); below it// the field is carryover. Do NOT raise above 0.10 — that false-defers// valid dim candidates (measured 0.19 without energy-norm).// v4.0 — THE AFFINITY FIELD READOUT, applied BEFORE the silence floor.// In the novel-wording case the settled field carries no energy on any// candidate — that is exactly the case the affinity channel exists to// rescue, so the floor must not fire before the channel has had its// say. The floor therefore keeps its legacy meaning (it measures the// FIELD) and fires only when NEITHER channel carries evidence.float max_legacy = 0.0f;for (float e : energies) max_legacy = std::max(max_legacy, e);bool affinity_evidence = false;if (affinity_mix_ > 0.0f) {build_affinity(labels, state_words);std::vector<float> blended;blend_affinity(energies, blended);energies.swap(blended);for (float v : affinity_ctx_.value)if (v > 1e-3f) { affinity_evidence = true; break; }}const float max_energy = max_legacy;if (std::getenv("SYFOX_DEBUG_READOUT") != nullptr) {std::fprintf(stderr, "DEBUG: max_candidate=%.3f threshold=%.3f affinity_evidence=%d\n",max_energy, kUnknownCandidateFloor, affinity_evidence ? 1 : 0);for (std::size_t i = 0; i < labels.size(); ++i)std::fprintf(stderr, "DEBUG: candidate[%s]=%.4f\n",labels[i].c_str(), energies[i]);}if (max_energy < kUnknownCandidateFloor && !affinity_evidence) {a.deferred = true;a.reason = "unknown_candidates";return;}// v3.9.0 decision-layer paper gates — each measures the settled field// READ-ONLY and zeroes/scales energies; none rewrites the field.// (a) MOMENTUM (MCPE §1 / CPME §2): a candidate whose normalized165 unmodified lines}}std::vector<float> p;// v4.0 — the temperature may depend on the candidate-set SIZE (the// fit measured one scalar per distinct count). The argmax is// unaffected; only the reported probabilities move.softmax_ps(energies, p, calib_.choice_temperature_for(energies.size()));std::size_t best = std::max_element(p.begin(), p.end()) - p.begin();a.choice = labels[best];for (std::size_t i = 0; i < labels.size(); ++i)12 unmodified lines// disclosure; --require-proof defers a choice with no typed path// (coverage-cliff honesty: the field answered, the knowledge layer// cannot justify it).if (usage && (proof_on_ || require_proof_)) {usage->proof_checked = true;usage->proof_path = proof_path_between(state_words, labels[best]);1 unmodified linea.deferred = true;a.reason = "no_proof_path";}}// v3.9.0 (fixes.md): remember the signature pieces for the OOD gate.if (usage) {151 unmodified linessi::Substrate si_;Calibration calib_;bool energy_norm_ = false; // Milestone-1 gain knob (default off)// v3.9.2: the decide-side composition this fabric was calibrated under.// Loaded from physics.json on model load; recorded by calibrate.PhysicsComposition composition_;// v3.9.2: calibration-fit bookkeeping — how many question-rows the fit// was offered and how many it actually saw (silent fields are dropped).std::size_t harvest_offered_ = 0;std::size_t harvest_dropped_silent_ = 0;std::unordered_set<std::uint64_t> lesson_hashes_; // Milestone-2 dedup memory// v3.2 retrieval-by-default statestd::vector<recall::Memory> memories_;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161{ "classes": [ "Refund_not_showing_up", "activate_my_card", "age_limit", "apple_pay_or_google_pay", "atm_support", "automatic_top_up", "balance_not_updated_after_bank_transfer", "balance_not_updated_after_cheque_or_cash_deposit", "beneficiary_not_allowed", "cancel_transfer", "card_about_to_expire", "card_acceptance", "card_arrival", "card_delivery_estimate", "card_linking", "card_not_working", "card_payment_fee_charged", "card_payment_not_recognised", "card_payment_wrong_exchange_rate", "card_swallowed", "cash_withdrawal_charge", "cash_withdrawal_not_recognised", "change_pin", "compromised_card", "contactless_not_working", "country_support", "declined_card_payment", "declined_cash_withdrawal", "declined_transfer", "direct_debit_payment_not_recognised", "disposable_card_limits", "edit_personal_details", "exchange_charge", "exchange_rate", "exchange_via_app", "extra_charge_on_statement", "failed_transfer", "fiat_currency_support", "get_disposable_virtual_card", "get_physical_card", "getting_spare_card", "getting_virtual_card", "lost_or_stolen_card", "lost_or_stolen_phone", "order_physical_card", "passcode_forgotten", "pending_card_payment", "pending_cash_withdrawal", "pending_top_up", "pending_transfer", "pin_blocked", "receiving_money", "request_refund", "reverted_card_payment?", "supported_cards_and_currencies", "terminate_account", "top_up_by_bank_transfer_charge", "top_up_by_card_charge", "top_up_by_cash_or_cheque", "top_up_failed", "top_up_limits", "top_up_reverted", "topping_up_by_card", "transaction_charged_twice", "transfer_fee_charged", "transfer_into_account", "transfer_not_received_by_recipient", "transfer_timing", "unable_to_verify_identity", "verify_my_identity", "verify_source_of_funds", "verify_top_up", "virtual_card_not_working", "visa_or_mastercard", "why_verify_identity", "wrong_amount_of_cash_received", "wrong_exchange_rate_for_cash_withdrawal" ], "opaque": true, "label_of": { "Refund_not_showing_up": "c00", "activate_my_card": "c01", "age_limit": "c02", "apple_pay_or_google_pay": "c03", "atm_support": "c04", "automatic_top_up": "c05", "balance_not_updated_after_bank_transfer": "c06", "balance_not_updated_after_cheque_or_cash_deposit": "c07", "beneficiary_not_allowed": "c08", "cancel_transfer": "c09", "card_about_to_expire": "c10", "card_acceptance": "c11", "card_arrival": "c12", "card_delivery_estimate": "c13", "card_linking": "c14", "card_not_working": "c15", "card_payment_fee_charged": "c16", "card_payment_not_recognised": "c17", "card_payment_wrong_exchange_rate": "c18", "card_swallowed": "c19", "cash_withdrawal_charge": "c20", "cash_withdrawal_not_recognised": "c21", "change_pin": "c22", "compromised_card": "c23", "contactless_not_working": "c24", "country_support": "c25", "declined_card_payment": "c26", "declined_cash_withdrawal": "c27", "declined_transfer": "c28", "direct_debit_payment_not_recognised": "c29", "disposable_card_limits": "c30", "edit_personal_details": "c31", "exchange_charge": "c32", "exchange_rate": "c33", "exchange_via_app": "c34", "extra_charge_on_statement": "c35", "failed_transfer": "c36", "fiat_currency_support": "c37", "get_disposable_virtual_card": "c38", "get_physical_card": "c39", "getting_spare_card": "c40", "getting_virtual_card": "c41", "lost_or_stolen_card": "c42", "lost_or_stolen_phone": "c43", "order_physical_card": "c44", "passcode_forgotten": "c45", "pending_card_payment": "c46", "pending_cash_withdrawal": "c47", "pending_top_up": "c48", "pending_transfer": "c49", "pin_blocked": "c50", "receiving_money": "c51", "request_refund": "c52", "reverted_card_payment?": "c53", "supported_cards_and_currencies": "c54", "terminate_account": "c55", "top_up_by_bank_transfer_charge": "c56", "top_up_by_card_charge": "c57", "top_up_by_cash_or_cheque": "c58", "top_up_failed": "c59", "top_up_limits": "c60", "top_up_reverted": "c61", "topping_up_by_card": "c62", "transaction_charged_twice": "c63", "transfer_fee_charged": "c64", "transfer_into_account": "c65", "transfer_not_received_by_recipient": "c66", "transfer_timing": "c67", "unable_to_verify_identity": "c68", "verify_my_identity": "c69", "verify_source_of_funds": "c70", "verify_top_up": "c71", "virtual_card_not_working": "c72", "visa_or_mastercard": "c73", "why_verify_identity": "c74", "wrong_amount_of_cash_received": "c75", "wrong_exchange_rate_for_cash_withdrawal": "c76" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384{ "topk": 20, "min_count": 3, "source": "train split only (90% carve)", "criteria": { "Refund_not_showing_up": "refund in, refund is, my refund, contacted the, keep checking, refund has, requested a, i contacted, refund i, refund isn't, refund me, seller for, merchant a, refund a, refund showing, refund yet, statements but, refund from, refund but, be getting", "activate_my_card": "activating, activate my, activating my, activation, activate it, activated, card activated, to activate, card activation, the activation, be activated, for activating, activate, me activate, start using, with activating, activate card, activation of, few seconds, seconds", "age_limit": "children, how old, age limit, be to, kids, my children, old do, my kids, child, i open, my child, an age, the age, minimum, minimum age, what age, age, age can, for children, opening", "apple_pay_or_google_pay": "google pay, apple pay, watch, apple watch, my apple, apple, google, my google, pay top, in apple, with google, express in, with apple, watch to, pay why, play, google play, pay is, an apple, does google", "atm_support": "which atms, atms accept, atms can, closest, the closest, atms that, closest atm, atms take, can withdraw, of atms, what atms, what atm, that accept, atm's, mastercard atm, take this, atms, accept this, at which, the atms", "automatic_top_up": "auto, auto top, the auto, an auto, i auto, low, money automatically, up automatically, for auto, intervals, up feature, automatically, automatic top, automatically top, be traveling, up option, automatically while, certain intervals, in certain, low on", "balance_not_updated_after_bank_transfer": "uk account, a uk, from france, my uk, international transfers, france two, take longer, uk bank, france a, reflect my, transfers usually, updated to, france, alright, couple hours, and nothing, have transferred, sure everything, you i, made one", "balance_not_updated_after_cheque_or_cash_deposit": "deposited a, cheque but, i deposited, cheque deposit, check yesterday, deposit showing, deposited cash, deposited this, or cash, the cheque, after depositing, cheque yesterday, deposit i, deposited some, deposited, already sent, and cash, and im, check deposit, deposit but", "beneficiary_not_allowed": "a beneficiary, my beneficiary, beneficiary, not possible, beneficiary not, some crypto, transferring to, a beneficiery, beneficiary is, beneficiery, couldn't transfer, getting error, isn't possible, purchase some, tried transferring, not allowed, error message, i doing, i've done, wasn't allowed", "cancel_transfer": "wrong account, tomorrow, by tomorrow, to revert, a typo, typo, to reverse, me cancel, typo please, accidently, correct i, i accidently, it correct, it needs, just realized, mistake please, mistake when, pay it, realized, stop a", "card_about_to_expire": "expire, expires, to expire, about to, card expires, in china, expired, expiration, expiring, expiration date, is expiring, it expires, will expire, is about, expire soon, expired card, expires soon, the expiration, an expired, card mine", "card_acceptance": "businesses, businesses that, to where, card accepted, accepts, will accept, be accepted, limits to, accept this, i pay, pay with, accept my, places, where i, anywhere, this card, card will, can use, accepted, will be", "card_arrival": "tracking, tracking number, you sent, a tracking, to track, card you, number for, track my, was issued, been delivered, mail yet, ordered it, recieve, recieve my, the expected, the tracking, track, track the, card hasn't, i track", "card_delivery_estimate": "delivered on, delivery to, it delivered, deliver to, certain date, is delivery, specific date, to deliver, delivery time, to come, deliver, a specific, expect my, the delivery, delivery, delivered, be delivered, specific, get here, long is", "card_linking": "reactivate, to link, link, found it, i reactivate, jacket, link it, my jacket, reactivate my, to reactivate, link the, link a, reactivate it, i link, had lost, but found, found my, i previously, in app, jacket pocket", "card_not_working": "working anymore, restaurant today, any transactions, card doesn't, broke, is broken, my physical, declined at, what's wrong, card won't, working at, broken, won't my, anymore, card work, won't work, why won't, card isn't, restaurant, a restaurant", "card_payment_fee_charged": "for payments, for card, for paying, when paying, paid with, warned, warned about, when you, on some, paying by, these fees, transactions but, wasn't warned, when buying, with card, didn't know, paying with, fee added, noticed an, paying", "card_payment_not_recognised": "of payments, card shown, couple payments, the name, make myself, maybe someone, shown in, that name, are a, been coming, days can, days that, myself what's, really didn't, seen that, some payments, unknown payment, has access, payments with, card there", "card_payment_wrong_exchange_rate": "last saturday, russian, official, official interbank, the official, ruble, russian ruble, uk pounds, charged the, using is, rate on, payment last, purchase was, rate that, really bad, rubles, saturday i, this can't, saturday, interbank", "card_swallowed": "swallowed, card out, atm swallowed, atm took, atm ate, swallowed my, ate my, card back, ate, give my, machine didn't, took my, not give, return my, atm machine, kept, do now, card got, stuck, by the", "cash_withdrawal_charge": "for withdrawing, withdrawals i, atm fees, for atm, withdrawing money, always thought, charging for, fee with, i always, withdrawal fee, been free, cash withdrawals, was free, withdrawing, atm cash, recent atm, withdrawing cash, groceries, taking out, today after", "cash_withdrawal_not_recognised": "500, a 500, 500 cash, copy, copy of, a copy, for 500, odd remote, remote, this withdrawal, a some, as someone, didn't withdraw, remote town, see cash, someone just, this cash, withdrawal help, withdrawal in, withdrawal on", "change_pin": "cash machines, can change, pin can, pin without, me change, pin on, saw my, someone saw, new pin, pin at, vacation in, spain, bank to, change my, be changed, change it, in spain, pin and, machines, i change", "compromised_card": "card details, else is, are transactions, knowledge, make these, my knowledge, be using, my permission, transactions that, permission, these transactions, might be, card without, is using, hacked, someone used, someone may, without my, if someone, that someone", "contactless_not_working": "contactless, my contactless, contactless payments, a contactless, the contactless, i try, try, again, fix, it's not, not working, to work, payments, today, working, work, to use, new card, it's, at", "country_support": "what countries, i live, countries you, countries are, countries do, the countries, operate, you operate, live in, eu can, operate in, which countries, uk can, living, living in, located in, outside of, you available, countries, live", "declined_card_payment": "a shop, shop, card declined, keep trying, kept getting, out today, couldn't pay, declined this, forward, forward to, looking forward, sad, sad what's, to paying, today looking, payment didn't, been declined, tried several, card did, thought everything", "declined_cash_withdrawal": "hill, notting, notting hill, atm wouldn't, atm card, different atms, hill atm, the notting, two different, actually working, atm keeps, card actually, fine so, in notting, morning on, suddenly got, tried two, with withdraws, withdrawal cash, withdraws", "declined_transfer": "decline message, transfer declined, a declined, again today, but same, declined transfer, online yesterday, recipient details, 'declined', states 'declined', transfers it's, well so, a decline, my transfers, checked all, transfer was, transfers keep, are getting, tried again, you keep", "direct_debit_payment_not_recognised": "debit payment, direct debit, a direct, debit that, debit transaction, direct, to dispute, debit charge, debit i, debit in, debit, dispute a, didn't set, not used, of months, still dispute, dispute, a dispute, authorized, day please", "disposable_card_limits": "of disposable, many disposable, one disposable, cards per, many transactions, several disposable, on disposable, restrictions for, cards every, every day, maximum number, transaction limit, transactions can, per, of transactions, the restrictions, per day, make several, disposable cards, cards i", "edit_personal_details": "edit, my address, personal details, edit my, married, i edit, address, got married, modify, modify my, my personal, moved and, new address, to edit, married and, to modify, change details, changed and, details in, i modify", "exchange_charge": "for exchanging, discount, a discount, exchange fee, exchanging foreign, for currency, discounts, exchanging currency, currencies frequently, any discounts, discount for, frequent currency, discounts for, exchange fees, exchange foreign, currency exchanges, foreign currencies, exchanging, a lot, lot", "exchange_rate": "rates are, what exchange, what your, exchange rates, determine, rate will, decide, find your, from where, me your, rates calculated, rates determined, what foreign, you determine, your exchange, rates, calculated, the foreign, how are, foreign exchange", "exchange_via_app": "aud, and gbp, usd and, for gbp, to gbp, exchange usd, usd to, app allow, between usd, to aud, usd, aud for, currencies using, currencies with, from usd, gbp to, i convert, usd for, aud how, exchange aud", "extra_charge_on_statement": "1 charge, extra 1, a 1, extra pound, 1 fee, a pound, the 1, 1, 1 extra, one pound, charged 1, 1 on, appears as, pound charge, purchased anything, for 1, of 1, pound, 1l, additional pound", "failed_transfer": "mortgage, a flat, mortgage payment, flat and, 5 times, my mortgage, transfer failed, keep failing, mortgage to, tried 5, buying a, error can, error i'm, failed transfer, flat but, initial, initial mortgage, to friends, transfer fail, 5", "fiat_currency_support": "fiat, fiat currencies, multiple currencies, and exchange, holding and, which fiat, what fiat, for holding, hold money, to hold, flat currencies, to eur, holding, i hold, eur, and holding, in multiple, exchange and, the fiat, which flat", "get_disposable_virtual_card": "these disposable, cards work, how disposable, virtual disposable, create a, disposable virtual, a disposable, cards for, as well, disposable, virtual cards, the disposable, virtual, virtual card, disposable cards, create, well, disposable card, card for, card as", "get_physical_card": "pin yet, locate my, pin sent, pin where, separately, card pin, a pin, pin anywhere, i locate, pin for, the pin, locate, pin is, find my, located, when do, pin, pin number, about the, anywhere", "getting_spare_card": "second card, more cards, for sending, out more, get another, more physical, sending out, another card, additional cards, spare, a spare, extra cards, member, send out, family member, few more, get more, give a, one card, spare card", "getting_virtual_card": "those virtual, a virtual, card yet, of those, the virtual, my virtual, virtual card, virtual, those, virtual cards, about getting, get one, to order, getting a, receive a, order a, go about, find the, card how, order", "lost_or_stolen_card": "a stolen, is stolen, stolen card, report, been stolen, been lost, is missing, stolen, someone stole, card has, stolen what, was stolen, stole my, i lost, lost my, stole, card what, lost, can't find, missing", "lost_or_stolen_phone": "phone was, phone is, phone what, mugged, the hotel, my phone, phone at, stolen yesterday, phone, app what, got mugged, mugged yesterday, someone from, stop someone, took everything, hotel, accessing, accessing my, from accessing, from using", "order_physical_card": "cards delivered, a real, real, real card, a physical, an actual, order my, actual card, delivered to, physical card, actual, request a, physical, are cards, the cards, my own, physical cards, i order, own, like a", "passcode_forgotten": "password, my password, passcode, my passcode, the passcode, forgotten, forgotten my, remember my, reset the, can't remember, forgot the, app passcode, can't log, my pass, pass code, passcode is, passcode won't, password is, to reset, get into", "pending_card_payment": "payment still, just showing, through at, payment pending, payment will, purchases from, since a, some point, days already, payment gone, show pending, status for, that hasn't, pending payment, be going, from pending, morning still, it actually, payment a, my purchases", "pending_cash_withdrawal": "withdrawal still, pending cash, transaction still, machine declined, withdrawal be, centre, city centre, progress can, this still, to still, withdrawal show, withdrawal shows, in progress, still shows, withdrawal to, still be, account says, the city, pending in, withdrawal is", "pending_top_up": "new customer, half, half an, time today, your top, hour already, just shows, over an, up pending, an hour, customer and, instant, up gone, up hasn't, hour, up went, tried topping, i'm a, up be, fix it", "pending_transfer": "transfer pending, eu transfers, money immediately, 2018, ago sent, do eu, immediately online, eu transfer, finally worked, for sure, it's 2018, right for, sure transfer, they're right, transfer still, pending transfer, seller says, finally, pending when, seller hasn't", "pin_blocked": "unblock, unblock my, to unblock, i unblock, me unblock, unblocked, is blocked, pin tries, blocked can, pin wrong, unblock it, pin too, wrong pin, exceeded, pin unblocked, too many, blocked, blocked what, got blocked, have exceeded", "receiving_money": "salary, my salary, in gbp, salary is, employer, my employer, salary in, configure, gbp do, to configure, am paid, friend send, paid in, pay me, receive transfers, me money, friend to, transfer my, another currency, receive money", "request_refund": "changed my, item refunded, to return, just bought, item yet, mind and, on something, refund back, refund policy, the product, back please, bought recently, decided, full refund, i return, item for, just cancel, my package, not paying, payment since", "reverted_card_payment?": "or two, payment reverted, money didn't, week or, didn't come, has reverted, it's back, made was, received one, something about, came back, was returned, already received, been returned, is reverted, payment been, payment came, i've already, problem i, two weeks", "supported_cards_and_currencies": "and currencies, are accepted, express to, currencies and, us credit, and cards, funds into, accept to, other credit, payment methods, what payment, which cards, what cards, which currencies, cards and, of cards, accept for, add funds, currencies you, methods are", "terminate_account": "delete my, to delete, close my, delete, to close, not happy, terminate, i close, i delete, not satisfied, satisfied, satisfied with, terminate my, dissatisfied, to terminate, close, account immediately, delete account, delete this, please delete", "top_up_by_bank_transfer_charge": "a sepa, sepa transfer, for receiving, by transfer, receiving money, swift transfer, a swift, receiving a, swift, sepa, are swift, fees associated, for sepa, transfer cost, swift transfers, much would, sepa transfers, receiving, associated, associated with", "top_up_by_card_charge": "international card, european bank, us card, european card, up charges, up us, a european, us cards, my international, fees if, an international, for us, any charges, bank card, with an, european, any fees, for european, using an, debit or", "top_up_by_cash_or_cheque": "with cash, use cash, find top, by cash, cheque to, cash to, by cheque, a cheque, a check, deposit a, cheques, option to, send a, i deposit, to deposit, cheque, up using, check to, account with, with a", "top_up_failed": "up failed, alternatives, declined for, problem or, today urgently, urgently but, work i, any alternatives, app rejected, or let, this or, up fail, please resolve, up didn't, card keeps, declined can, has failed, resolve this, it a, was able", "top_up_limits": "up limits, any top, any amount, many top, on top, unlimited, up limit, much i, can top, how often, max, of top, the max, the most, limit for, the limit, do top, limit to, a limit, maximum", "top_up_reverted": "crypto top, saw it, there and, up recently, you offered, cancellation, disappeared from, gone i, had topped, has disappeared, it's disappeared, thought you, up get, disappeared i, disappeared what's, glitch, it's gone, offered crypto, up cancellation, up showing", "topping_up_by_card": "other people, else top, my friends, be topped, money disappeared, friends, my wallet, wallet, by my, money using, my credit, people, by card, up by, up using, credit card, disappeared, credit, topped, topped up", "transaction_charged_twice": "charged twice, twice for, twice, double charged, same transaction, times for, duplicate charge, please remove, remove one, clearly, duplicated, two times, duplicate charges, duplicate payment, one transaction, restaurant visit, second time, store earlier, transactions and, was double", "transfer_fee_charged": "receiver, transfer fee, the receiver, transfer more, make up, thought transfers, transfers were, a receiver, fee while, lesser, manage, payments for, place abroad, to manage, for transferring, abroad for, amount what, be rewarded, fair, my place", "transfer_into_account": "another bank, account into, about transferring, at another, this one, from another, one account, account at, move money, other bank, via bank, my other, this bank, money into, from one, funds from, explain how, bank account, bank transfer, bank transfers", "transfer_not_received_by_recipient": "money transaction, landlord, before yesterday, day before, and she, i've checked, sent some, transfer within, needs it, new landlord, right one, arrive yet, done a, friend who, my landlord, one i've, completion, correct can, country it, country transfer", "transfer_timing": "from europe, transfer something, china how, us transfer, an urgent, europe how, europe to, urgent transfer, from china, europe take, reach my, europe, estimated, to reach, approximately, the estimated, us take, wait time, something from, something to", "unable_to_verify_identity": "proving, 10 minutes, are clear, economic, economic area, from us, images, images are, minutes to, photos, proving my, readable, switzerland, 18 years, app doesn't, european economic, glare, or older, your images, a resident", "verify_my_identity": "identity checks, documents do, what documents, documentation, of id, forms, forms of, id do, what documentation, what forms, for identity, checks, documents, need for, needed for, you require, the identity, i prove, is needed, for verification", "verify_source_of_funds": "source of, my source, the source, funds come, source, funds came, see where, my available, money came, where funds, available cash, available money, comes from, money comes, my fund, source for, tell where, of funds, my funds, available funds", "verify_top_up": "verification code, up verification, verify top, verifying the, up card, authenticate, code anywhere, i authenticate, up need, verifying top, code for, verify the, the verification, verify a, code, a verification, do we, we need, verification process, the top", "virtual_card_not_working": "got rejected, my disposable, cannot get, my virtual, card won't, won't work, was rejected, the virtual, virtual card, rejected, virtual, disposable virtual, to work, card to, i cannot, cannot, won't, work, disposable, get my", "visa_or_mastercard": "a visa, visa and, and mastercard, visa card, visa, both a, get both, mastercard and, mastercard from, and visa, between visa, both visa, choose between, visa or, or mastercard, get visa, i prefer, mastercard can, use visa, both mastercard", "why_verify_identity": "about me, passed yet, account although, identity details, is identity, many questions, much information, need so, not passed, so many, verification hasn't, verification has, account before, asking, questions, questions about, though my, passed, so much, information about", "wrong_amount_of_cash_received": "gave me, 20, it gave, gave, only got, 100 but, atm didn't, 30 pounds, only gave, 100, 10 pounds, atm gave, got 20, request cash, me 10, atm just, charged though, it only, just gave, 20 when", "wrong_exchange_rate_for_cash_withdrawal": "currency at, home currency, for foreign, bit concerned, cash abroad, withdraw here, and bit, currency while, here without, known, was abroad, was different, withdraw without, my home, any additional, holiday and, without any, additional cost, rate when, home" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148{"id": "b77_00", "domain": "bank77", "state": "the cash machine swallowed my card and it never came back", "label": "c19"}{"id": "b77_01", "domain": "bank77", "state": "my card disappeared from my coat, someone must have taken it", "label": "c42"}{"id": "b77_02", "domain": "bank77", "state": "the pin got locked after too many wrong tries and now nothing works", "label": "c50"}{"id": "b77_03", "domain": "bank77", "state": "I cannot remember my four digit code anymore", "label": "c45"}{"id": "b77_04", "domain": "bank77", "state": "please close my account for good, I am leaving", "label": "c55"}{"id": "b77_05", "domain": "bank77", "state": "I would like a plastic card posted out to my house", "label": "c39"}{"id": "b77_06", "domain": "bank77", "state": "how do I get a card that only lives inside my phone", "label": "c41"}{"id": "b77_07", "domain": "bank77", "state": "I want to send money into my own account", "label": "c65"}{"id": "b77_08", "domain": "bank77", "state": "the person I paid says nothing has landed for them", "label": "c66"}{"id": "b77_09", "domain": "bank77", "state": "the same amount was taken out of my account two times over", "label": "c63"}{"id": "b77_10", "domain": "bank77", "state": "my purchase was refused at the shop till", "label": "c26"}{"id": "b77_11", "domain": "bank77", "state": "holding the phone over the reader does nothing at all", "label": "c24"}{"id": "b77_12", "domain": "bank77", "state": "the shop billed me in euros at a rate that looks wrong", "label": "c18"}{"id": "b77_13", "domain": "bank77", "state": "I took foreign notes out and the exchange rate looks off", "label": "c76"}{"id": "b77_14", "domain": "bank77", "state": "there is a mystery charge on my cash machine withdrawal", "label": "c20"}{"id": "b77_15", "domain": "bank77", "state": "the machine refused to give me any notes", "label": "c27"}{"id": "b77_16", "domain": "bank77", "state": "the withdrawal still says it is going through", "label": "c47"}{"id": "b77_17", "domain": "bank77", "state": "the machine handed me less money than the receipt says", "label": "c75"}{"id": "b77_18", "domain": "bank77", "state": "when will the card arrive through the post", "label": "c13"}{"id": "b77_19", "domain": "bank77", "state": "my card finally turned up in the post this morning", "label": "c12"}{"id": "b77_20", "domain": "bank77", "state": "the card needs switching on before I can use it", "label": "c01"}{"id": "b77_21", "domain": "bank77", "state": "I want to set a different four digit number", "label": "c22"}{"id": "b77_22", "domain": "bank77", "state": "a standing order I never set is on my statement", "label": "c29"}{"id": "b77_23", "domain": "bank77", "state": "the shop says the card payment is still hanging", "label": "c46"}{"id": "b77_24", "domain": "bank77", "state": "there is an unexplained item on my bill", "label": "c35"}{"id": "b77_25", "domain": "bank77", "state": "I would like my money back for this purchase", "label": "c52"}{"id": "b77_26", "domain": "bank77", "state": "the refund was approved ages ago and still has not arrived", "label": "c00"}{"id": "b77_27", "domain": "bank77", "state": "it suddenly asks me to prove who I am", "label": "c69"}{"id": "b77_28", "domain": "bank77", "state": "the identity check keeps failing and I cannot get past it", "label": "c68"}{"id": "b77_29", "domain": "bank77", "state": "why on earth do you need my identity documents", "label": "c74"}{"id": "b77_30", "domain": "bank77", "state": "you want to know where my money came from", "label": "c70"}{"id": "b77_31", "domain": "bank77", "state": "my card should refill itself when it runs low", "label": "c05"}{"id": "b77_32", "domain": "bank77", "state": "how much can I add to my account in one day", "label": "c60"}{"id": "b77_33", "domain": "bank77", "state": "the top up did not go through at all", "label": "c59"}{"id": "b77_34", "domain": "bank77", "state": "the money I added is still not showing on my balance", "label": "c48"}{"id": "b77_35", "domain": "bank77", "state": "I want to add money using my debit card", "label": "c62"}{"id": "b77_36", "domain": "bank77", "state": "the transfer is still sitting there doing nothing", "label": "c49"}{"id": "b77_37", "domain": "bank77", "state": "please stop the payment I scheduled for tomorrow", "label": "c09"}{"id": "b77_38", "domain": "bank77", "state": "the outgoing payment was refused by the bank", "label": "c28"}{"id": "b77_39", "domain": "bank77", "state": "the transfer keeps erroring out every time", "label": "c36"}{"id": "b77_40", "domain": "bank77", "state": "how long does a transfer take to actually arrive", "label": "c67"}{"id": "b77_41", "domain": "bank77", "state": "I am not allowed to send money to that person", "label": "c08"}{"id": "b77_42", "domain": "bank77", "state": "a service fee appeared for paying with my card", "label": "c16"}{"id": "b77_43", "domain": "bank77", "state": "I do not recognise this charge on my card at all", "label": "c17"}{"id": "b77_44", "domain": "bank77", "state": "it says I am too old for this", "label": "c02"}{"id": "b77_45", "domain": "bank77", "state": "can I use my phone to pay instead of the card", "label": "c03"}{"id": "b77_46", "domain": "bank77", "state": "which shops actually take your card", "label": "c11"}{"id": "b77_47", "domain": "bank77", "state": "which cards and which countries do you accept", "label": "c54"}{"id": "b77_48", "domain": "bank77", "state": "is it a visa or a mastercard", "label": "c73"}{"id": "b77_49", "domain": "bank77", "state": "do you even operate in my country", "label": "c25"}{"id": "b77_50", "domain": "bank77", "state": "can I hold real money currency in an account", "label": "c37"}{"id": "b77_51", "domain": "bank77", "state": "what is the fee for adding money by bank transfer", "label": "c56"}{"id": "b77_52", "domain": "bank77", "state": "what is the fee for adding money by card", "label": "c57"}{"id": "b77_53", "domain": "bank77", "state": "adding money over the counter with paper notes", "label": "c58"}{"id": "b77_54", "domain": "bank77", "state": "the top up was taken back off me", "label": "c61"}{"id": "b77_55", "domain": "bank77", "state": "there is a fee for sending money to someone", "label": "c64"}{"id": "b77_56", "domain": "bank77", "state": "your cash machines are not working this morning", "label": "c04"}{"id": "b77_57", "domain": "bank77", "state": "my card is refused everywhere I try it", "label": "c15"}{"id": "b77_58", "domain": "bank77", "state": "someone has copied my card details", "label": "c23"}{"id": "b77_59", "domain": "bank77", "state": "the card that lives in my phone is not working", "label": "c72"}{"id": "b77_60", "domain": "bank77", "state": "I need a card for a single use only", "label": "c38"}{"id": "b77_61", "domain": "bank77", "state": "how many times can I use the single use card", "label": "c30"}{"id": "b77_62", "domain": "bank77", "state": "I need a spare replacement card", "label": "c40"}{"id": "b77_63", "domain": "bank77", "state": "I sent money to myself and my balance is still the old figure", "label": "c06"}{"id": "b77_64", "domain": "bank77", "state": "I paid in a cheque and the balance has not moved", "label": "c07"}{"id": "b77_65", "domain": "bank77", "state": "how do I get money sent to me by someone else", "label": "c51"}{"id": "b77_66", "domain": "bank77", "state": "I need to change the address on my account", "label": "c31"}{"id": "b77_67", "domain": "bank77", "state": "please order me a card", "label": "c44"}{"id": "tix_00", "domain": "tickets_en", "state": "you charged my card twice for the same order", "label": "te00"}{"id": "tix_01", "domain": "tickets_en", "state": "the invoice shows an amount I do not recognise", "label": "te00"}{"id": "tix_02", "domain": "tickets_en", "state": "I was billed for a subscription I cancelled", "label": "te00"}{"id": "tix_03", "domain": "tickets_en", "state": "the app crashes every time I open the settings screen", "label": "te02"}{"id": "tix_04", "domain": "tickets_en", "state": "the integration returns error 500 on every call", "label": "te02"}{"id": "tix_05", "domain": "tickets_en", "state": "the webhooks stopped firing after the upgrade", "label": "te02"}{"id": "tix_06", "domain": "tickets_en", "state": "we want to buy 40 licences for the whole team", "label": "te01"}{"id": "tix_07", "domain": "tickets_en", "state": "what does the enterprise plan cost per seat", "label": "te01"}{"id": "tix_08", "domain": "tickets_en", "state": "can we upgrade to a bigger tier next quarter", "label": "te01"}{"id": "agn_00", "domain": "agnews", "state": "diplomats from twelve countries gathered to discuss the ceasefire", "label": "ag00"}{"id": "agn_01", "domain": "agnews", "state": "the UN assembly opened its session in the capital today", "label": "ag00"}{"id": "agn_02", "domain": "agnews", "state": "the striker scored twice in the second half", "label": "ag01"}{"id": "agn_03", "domain": "agnews", "state": "the team qualified for the final after a late equaliser", "label": "ag01"}{"id": "agn_04", "domain": "agnews", "state": "the company reported a rise in quarterly revenue", "label": "ag02"}{"id": "agn_05", "domain": "agnews", "state": "shares fell after the merger announcement", "label": "ag02"}{"id": "agn_06", "domain": "agnews", "state": "researchers sequenced the genome of the parasite", "label": "ag03"}{"id": "agn_07", "domain": "agnews", "state": "the telescope captured a faint galaxy at long wavelengths", "label": "ag03"}{"id": "sms_00", "domain": "sms", "state": "are we still on for dinner at eight", "label": "sm00"}{"id": "sms_01", "domain": "sms", "state": "can you send me the notes from the meeting", "label": "sm00"}{"id": "sms_02", "domain": "sms", "state": "FREE PRIZE!!! claim your 500 pound voucher now, call 0900", "label": "sm01"}{"id": "sms_03", "domain": "sms", "state": "WIN a car! text CLAIM to 80086 to enter the draw today", "label": "sm01"}{"id": "enr_00", "domain": "enron", "state": "here is the agenda for thursday review, see attached", "label": "en00"}{"id": "enr_01", "domain": "enron", "state": "please find the signed contract from legal", "label": "en00"}{"id": "enr_02", "domain": "enron", "state": "URGENT: you have won a 1000 dollar lottery, act now", "label": "en01"}{"id": "enr_03", "domain": "enron", "state": "click here to confirm your mailbox password immediately", "label": "en01"}{"id": "hat_00", "domain": "hate", "state": "people of that country are all vermin and should be driven out", "label": "ha00"}{"id": "hat_01", "domain": "hate", "state": "those people are subhuman filth and we should rid the world of them", "label": "ha00"}{"id": "hat_02", "domain": "hate", "state": "that take is bloody ridiculous, you absolute idiot", "label": "ha01"}{"id": "hat_03", "domain": "hate", "state": "you are a steaming pile of garbage, moron", "label": "ha01"}{"id": "hat_04", "domain": "hate", "state": "the bus was late again this morning", "label": "ha02"}{"id": "hat_05", "domain": "hate", "state": "she baked a lemon tart for the office", "label": "ha02"}{"id": "pol_00", "domain": "polarity", "state": "the packaging arrived crushed and the product leaked everywhere", "label": "po00"}{"id": "pol_01", "domain": "polarity", "state": "absolutely useless, it broke on the second use", "label": "po00"}{"id": "pol_02", "domain": "polarity", "state": "this little gadget has saved me so much time, I love it", "label": "po01"}{"id": "pol_03", "domain": "polarity", "state": "a beautiful, thoughtful gift that arrived early", "label": "po01"}{"id": "emo_00", "domain": "emotion", "state": "I have not stopped crying since the funeral", "label": "em00"}{"id": "emo_01", "domain": "emotion", "state": "my grandmother died last week and the house feels empty", "label": "em00"}{"id": "emo_02", "domain": "emotion", "state": "I got the job! I am absolutely delighted", "label": "em01"}{"id": "emo_03", "domain": "emotion", "state": "we won the cup after nine years, I cannot stop grinning", "label": "em01"}{"id": "emo_04", "domain": "emotion", "state": "thinking about you constantly, you mean everything to me", "label": "em02"}{"id": "emo_05", "domain": "emotion", "state": "I adore you more than I have ever adored anyone", "label": "em02"}{"id": "emo_06", "domain": "emotion", "state": "I am furious that they cancelled without telling me", "label": "em03"}{"id": "emo_07", "domain": "emotion", "state": "this is outrageous and I will not stand for it", "label": "em03"}{"id": "emo_08", "domain": "emotion", "state": "I am terrified of walking home through that park after dark", "label": "em04"}{"id": "emo_09", "domain": "emotion", "state": "my hands are shaking, I do not know what to do", "label": "em04"}{"id": "emo_10", "domain": "emotion", "state": "I cannot believe it, I did not see that coming at all", "label": "em05"}{"id": "emo_11", "domain": "emotion", "state": "wow, that turn of events completely caught me off guard", "label": "em05"}{"id": "bq_00", "domain": "boolq", "state": "The Eiffel Tower is located in Paris. Is the Eiffel Tower in Paris?", "label": "bo01"}{"id": "bq_01", "domain": "boolq", "state": "Penguins are birds that live only in the arctic. Do penguins live in the arctic?", "label": "bo01"}{"id": "bq_02", "domain": "boolq", "state": "The Nile is the longest river in Africa. Is the Amazon the longest river in Africa?", "label": "bo00"}{"id": "bq_03", "domain": "boolq", "state": "Water boils at 100 degrees Celsius at sea level. Does water freeze at 100 degrees?", "label": "bo00"}{"id": "dbp_00", "domain": "dbpedia", "state": "Samsung Electronics is a South Korean electronics company", "label": "db00"}{"id": "dbp_01", "domain": "dbpedia", "state": "The University of Bologna is an educational institution in Italy", "label": "db01"}{"id": "dbp_02", "domain": "dbpedia", "state": "A tulip is a plant that grows from a bulb", "label": "db02"}{"id": "dbp_03", "domain": "dbpedia", "state": "Rumours is a studio album recorded by the Beatles", "label": "db03"}{"id": "dbp_04", "domain": "dbpedia", "state": "Jurassic Park is a film directed by Steven Spielberg", "label": "db04"}{"id": "dbp_05", "domain": "dbpedia", "state": "Moby Dick is a written work by Herman Melville", "label": "db05"}{"id": "dbp_06", "domain": "dbpedia", "state": "Miles Davis was an artist who played the trumpet", "label": "db06"}{"id": "dbp_07", "domain": "dbpedia", "state": "Usain Bolt is an athlete from Jamaica", "label": "db07"}{"id": "dbp_08", "domain": "dbpedia", "state": "A village is a settlement smaller than a town", "label": "db08"}{"id": "dbp_09", "domain": "dbpedia", "state": "A river is a natural stream of water", "label": "db09"}{"id": "dbp_10", "domain": "dbpedia", "state": "A bird is a vertebrate that can fly", "label": "db10"}{"id": "dbp_11", "domain": "dbpedia", "state": "A mountain is a large landform rising above the land", "label": "db11"}{"id": "dbp_12", "domain": "dbpedia", "state": "A city is a large permanent settlement", "label": "db12"}{"id": "dbp_13", "domain": "dbpedia", "state": "A currency is a medium of exchange", "label": "db13"}{"id": "rt_00", "domain": "router", "state": "the treaty was signed by delegates from forty nations", "label": "rt00"}{"id": "rt_01", "domain": "router", "state": "he sank a curling three pointer in the fourth quarter", "label": "rt00"}{"id": "rt_02", "domain": "router", "state": "the passage states that the treaty was signed in 1815", "label": "rt02"}{"id": "rt_03", "domain": "router", "state": "what is the weather in Madrid tomorrow", "label": "rt03"}{"id": "rt_04", "domain": "router", "state": "the city of Bruges is a UNESCO listed medieval centre", "label": "rt04"}{"id": "rt_05", "domain": "router", "state": "she was overjoyed and could not stop smiling", "label": "rt05"}{"id": "rt_06", "domain": "router", "state": "please find attached the agenda for the quarterly review", "label": "rt06"}{"id": "rt_07", "domain": "router", "state": "flee the burning building and dig in behind the rocks", "label": "rt07"}{"id": "rt_08", "domain": "router", "state": "do not run rm -rf on the production database", "label": "rt08"}{"id": "rt_09", "domain": "router", "state": "that post is absolutely disgusting, you are all animals", "label": "rt09"}{"id": "rt_10", "domain": "router", "state": "the headphones sound fantastic, best purchase this year", "label": "rt10"}{"id": "rt_11", "domain": "router", "state": "WINNER claim your free voucher now, text yes to 80086", "label": "rt11"}{"id": "rt_12", "domain": "router", "state": "আমার কার্ড থেকে টাকা দুইবার কেটে নিয়েছে", "label": "rt12"}{"id": "rt_13", "domain": "router", "state": "मेरे खाते से पैसे कट गए हैं, मदद करें", "label": "rt14"}{"id": "rt_14", "domain": "router", "state": "с моего счета списали деньги дважды", "label": "rt15"}1234567891011121314151617181920212223242526272829303132# ============================================================================# SyFox synonym folding table (P4, v2.1)## format: canonical: variant, variant, ...## Used in TWO places that must stay in lockstep:# * core/normalize.hpp — decide-time folding: every table word (canonical# or variant) is porter-stemmed and mapped to the stemmed canonical, so a# query saying "reimbursement" lands on the same node as "refund".# * tools/gen_paraphrases.py — train-time augmentation: swaps existing# words for their table alternates. Single words ONLY, so a paraphrased# row normalizes to the same token stream as its source row.## Rules for edits:# * single words only (the C++ folding is per-token)# * label-safe swaps only: replacing a word with its alternate must never# change the row's labels (no urgency words in fillers, no cross-department# drift, no frustration-scale drift)# * conservative: a wrong merge here is a wrong lane in the fabric# ============================================================================refund: reimbursement, reimburseurgent: asap, immediately, urgently, hurryangry: furious, mad, upsetbroken: faulty, bustedfix: repair, mendproblem: issue, trouble, glitchslow: delayed, sluggish, laggycrash: freeze, hang, frozeprice: costscared: afraid, fearfulmoney: cashwrong: incorrect, mistaken123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175# Fit == decide — the calibration composition contract (v3.9.2)
**The bug this document describes shipped a wrong answer on 87% of the rowsit was scored on, with ~0.98 confidence, and it is invisible to every testin the tree. The fix makes the fit and the decision the same engine byconstruction.**
---
## 1. The shape of the bug
SyFox answers a `choice` question by
1. injecting the state into the substrate,2. settling (dissipative diffusion along the Hebbian lanes),3. reading the candidate energies and turning them into a probability vector with a **softmax at temperature `T`**,4. deferring if the top-2 probability gap is under the defer margin.
Step 3 is the only fitted parameter in the pipeline. `T` is fitted by`calibrate` on collected rows — and **the energies it is fitted on are afunction of the entire decide-side composition**:
| knob | what it changes in the fitted energies ||---|---|| `energy_norm` (the decide-side energy gain) | the injected dose — and, crucially, it is **per state** (`inject_energy × mean √node_mass`), so it is not a uniform rescale || `diffusion` | how much energy leaves along the lanes per pass → the gap scale || `decay` | per-pass retention || `k_settle` | how many passes run || `hop_coupling` | how much the 1-hop readout contributes |
So the fitted `T` is a number **for one specific composition**. Change thecomposition and the number describes a different engine.
That is not a theoretical concern. It is what this repository shipped.
## 2. What was shipped
`Makefile`, before the fix:
```makeb77-sem: ./build/syfox calibrate --model model-b77-sem --examples data/bank77_cal.jsonlb77-sem-bench: ./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl --energy-norm ...```
Same for `router16` and `model-bank77-best`. **The calibration ran withoutthe decide-side energy gain; every bench and every decide call ran withit.** (`model-tickets-big` and the seed fabrics were fine — the seedfabrics do not use the gain at all, and the `-big` target passes`--energy-norm` to *both*.)
Measured on the **shipped** `model/b77-sem` fabric, the **1,003-row calsplit** that ships with it, same engine, one flag apart:
| calibration | fitted `T` | rows the fit saw | ECE before → after ||---|---:|---:|---:|| **without** the energy gain (what shipped) | **0.0037** | **556 of 2,006** (27.7%) | 0.4567 → 0.4057 || **with** the energy gain (what the bench runs) | **0.3552** | 2,006 of 2,006 (100%) | 0.3183 → 0.3056 |
The published `model/b77-sem/calibration.json` says`choice_temperature: 0.00472645` over **211 rows**; `model/router16` says`0.00491756` over **160 rows**. Both are the near-floor value the fitpicks when the field is nearly empty.
## 3. Why a near-floor `T` is catastrophic
`T = 0.0047` saturates the softmax. The post-temperature top-2 gap goes to~0.93 on essentially every row, and three things break at once:
1. **The defer axis dies.** The engine's honest-defer gate is an absolute margin (0.05) on the top-2 probability gap. A gap of 0.93 can never fall under 0.05, so the engine **never abstains** — the one behaviour the model card sells as its differentiator ("it can say *I don't know*"). Measured: 0 deferrals in 1,003 cal rows.2. **Confidence becomes a constant.** Every row carries ~0.98 confidence, right or wrong. Measured on the shipped fabric, bank77 hidden: `mean_conf_when_correct = 0.832` **<** `mean_conf_when_wrong = 0.867`. The engine is *more confident when it is wrong*.3. **The reported ECE is fiction.** `calibrate` printed ECE 0.136 on its own fit rows; the bench measured 0.573–0.597 on the same rows. The two numbers come from different physics compositions.
And the fit was not merely mis-scaled — it was **biased**. Without theenergy gain, 1,450 of the 2,006 question-rows settle to a **silent** fieldand are dropped from the fit (`harvest_rows`: `if (si_.silent()) continue;`).The temperature was therefore fitted on the 27.7% of rows that happened tosurvive a composition the decisions never run under.
## 4. The fix (v3.9.2)
### 4.1 The fabric carries its composition — `physics.json`
A new sidecar next to `calibration.json`:
```json{"decay":0.82,"diffusion":0.45,"energy_norm":true,"hop_coupling":0.35, "k_settle":8,"recorded":true}```
* `calibrate` **records** the composition it fitted under.* `decide`, `bench`, `demo` and `stats` **apply** it on load (`Engine::apply_composition()`).* An explicit CLI flag still wins (`--energy-norm`, `--no-energy-norm`, `--diffusion`, `--decay`, `--k-settle`, `--hop-coupling`).
The fit and the decision are now the same engine by construction. A fabricwith no `physics.json` is a pre-v3.9.2 fabric: nothing is applied and thebehaviour is bit-identical (replay contract preserved — pinned by`test_physics_composition`).
This also delivers the repo's own standing recommendation(`docs/INTRACATEGORY_ATTACK.md` §4): *"record the measured diffusion optimum… and let `decide` honour a per-fabric value — NOT a new global default."*Per-fabric diffusion now has a home.
### 4.2 The fit refuses to run on a biased subset
`calibrate` counts the question-rows it was **offered** and the ones itactually **saw**. Below `kMinCalibrationCoverage` (0.5) it **refuses**,names the cause, and leaves the fabric untouched:
```syfox: calibration refused: the fit saw only 556 of 2006 question-rows(27.7% coverage; 1450 settled to a SILENT field and were dropped). The decide-side composition does not match the rows: the energy gain is the usual cause …```
Override with `--calib-min-coverage 0` (the coverage is disclosed eitherway). The coverage is now always in the `calibrate` report:`fit_offered_rows`, `fit_dropped_silent`, `fit_coverage`.
### 4.3 The Makefile stops lying
`b77-sem`, `router16` and `model-bank77-best` now calibrate with`--energy-norm` — the same composition their benches run.
### 4.4 A tool for the diffusion choice
`tools/cal_diffusion_sweep.py` sweeps diffusion **on the cal split only**,re-calibrating the fabric at each candidate so the temperature is alwaysfitted under the composition it is applied to, and (with `--apply`) recordsthe winner into `physics.json`.
---
## 5. Why the base repository does not have this bug
`FuryLogic-Labs/Synthetic-Intelligence` is the research substrate SyFox wasported from, and its readout is **arg-max over the settled field** — nosoftmax, no temperature, no fitted parameter(`src/physics.hpp`, `src/si_main.cpp`). There is no calibration layer, sothere is nothing to fit against the wrong physics.
The probability readout and the temperature are a SyFox addition (v2.1,"multi-class ECE"), and the defect was introduced with it: the fit wasnever tied to the composition that produced its energies. It is a**SyFox-layer bug, not an inherited one** — which is also why it is worthfixing here rather than in the base.
---
## 6. Reproduce
```bashmake all# the refusal (the shipped bug, re-created on purpose):./build/syfox calibrate --model model-b77-sem --examples data/bank77_cal.jsonl# the fix:./build/syfox calibrate --energy-norm --model model-b77-sem --examples data/bank77_cal.jsonlcat model-b77-sem/physics.json./build/syfox bench --model model-b77-sem --eval data/bank77_cal.jsonl```17 unmodified lines1819202122239 unmodified lines33343536373822 unmodified lines6162636465664 unmodified lines7172737475767778798081828384858687888990919293949596974 unmodified lines10210310410510610765 unmodified lines17317417517617717869 unmodified lines2482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243257 unmodified lines33333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736863 unmodified lines432433434435436437101 unmodified lines53954054154254354454554654754854955055155255355455592 unmodified lines64864965065165265365465565665765865966066166266366466566666713 unmodified lines68168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373445 unmodified lines7807817827837847857867877887897907917927937943 unmodified lines7987998008018028033 unmodified lines807808809810811812813101 unmodified lines91591691791891992092192292392492592692792892993093193293393493593693793893954 unmodified lines9949959969979989991000100143 unmodified lines1045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106789 unmodified lines11571158115911601161116211638 unmodified lines11721173117411751176117711786 unmodified lines1185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912209 unmodified lines12301231123212331234123512361237506 unmodified lines174417451746174717481749517 unmodified lines22672268226922702271227222732274227522762277227822792280240 unmodified lines25212522252325242525252627 unmodified lines25542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257747 unmodified lines26252626262726282629263039 unmodified lines2670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270113 unmodified lines27152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274417 unmodified lines#include <cstdlib>#include <cstring>#include <fstream>#include <iostream>#include <map>#include <sstream>9 unmodified linesvoid usage_exit();struct Args {std::string model = "model";std::string examples;22 unmodified linesbool novelty = false; // learn --novelty: per-lesson dose by novelty (M2)float novelty_floor = 0.25f; // learn --novelty-floor F (A/B knob)bool energy_norm = false; // decide-side energy gain for big-corpus fabrics (M1)float defer_margin = -1; // v3.4: engine default ON at 0.05 (reason ambiguous_tie);// --defer-margin P overrides, --no-defer disables.// (v3.1-3.3 this was a CLI post-pass with reason low_margin,4 unmodified lineslong threads = 0; // --threads N: OMP settle threads (1 = sequential; 0 = default)long throughput = 0; // bench --throughput N: batched multicore decisions/sec (M5)long epochs = 1; // learn --epochs N: consolidation passes (see lane_decay)bool quiet = false; // --quiet: suppress per-row/progress notes on stderr// M1 thinker-in-the-loop (all default OFF == pre-M1 behaviour)bool thinker = false; // --thinker: run the reasoner inside decide()bool reason_fixpoint = false; // --reason-fixpoint: chain axioms to fixpoint firstbool meta_observe = false; // --meta-observe: feed proofs to the MetaLearnerbool persist_meta = false; // M2 --persist-meta: write meta_rules.txt on exitbool cls_split = false; // M3 --cls-split: hippocampal/cortical lanesbool role_bind = false; // M9 --role-bind: query-role alignment re-rankbool ntda = false; // M5 --ntda: voltage gating + edge deathlong enc_dim = 0; // M9 --encoder-dim D: encoder embedding width (0 = off)long enc_chans = 0; // M9 --encoder-chans C: channel count (default 32)float enc_eta = 0.01f; // M9 --encoder-eta E: Oja learning ratefloat ntda_theta = 1.0f; // M5 --ntda-theta Fbool reason_route = false; // M10 --reason-route: reasoner drives the choicestd::string bisoc_a, bisoc_b; // M4 bisociate --a A --b Bbool bisoc_bridge = false; // M4 --bridge: also propose an L8 bridge nodefloat cortical_gate = 3.0f; // M3 --cortical-gate N: eligibility to consolidatefloat cortical_gain = 0.5f; // M3 --cortical-gain F: cortical readout weight// M8: the config-file path, set when <model>/config.json supplied a default.bool from_config = false; // a flag in config.json was appliedbool config_energy_norm = false; // and whether it set the energy gainlong latency_reps = 20; // bench --latency-reps N (timing repeats per probe)long replays = 2; // bench --replays N (determinism double-run count)bool state_file = false, questions_file = false;4 unmodified linesbool no_retrieval = false; // --no-retrieval: skip associative primingbool no_hierarchy = false; // --no-hierarchy: skip stage-1 category gatingbool no_defer = false; // --no-defer: disable v3.4 near-tie defer (engine default ON)long hops = -1; // --hops N: v3.4 multi-hop readout walk depth (engine default 1 = legacy)bool ctx_gate = false; // --ctx-gate: v3.4 two-stage question-context settlefloat ctx_alpha = 0; // --ctx-alpha F (0 = engine default 0.5)65 unmodified linesint sentinels_mode = 0; // --sentinels on|off (CMD §2.5): 1/-1 explicitint order_mode = 0; // --order-consolidation on|off (CPME-II): 1/-1 explicitbool fingerprints = false; // --fingerprints (CME): graded half-dose re-teach};// v3.2.1 — BUG #1 disclosure: a kill switch on a model that lacks the69 unmodified linesreturn eng;}// -- M8: LOAD MODEL CONFIG -----------------------------------------------------------------// A model dir may ship config.json, written by `learn` from the flags it actually// used. Applying it here means `decide`/`bench` reproduce the fabric's trained// configuration WITHOUT the user retyping a wall of flags. Any EXPLICIT CLI flag// still wins, because apply_modes() runs afterwards and overwrites.//// Why this exists: bench without `--energy-norm` returns honest_silence on every// row and collapses choice_n to 0 (measured this session). A silent zero reads as// a broken model but is only a missing gain flag. A config file makes that class// of mistake impossible, which is also what makes the numbers citable.static void load_model_config(const std::string& model_dir, Args& a) {std::ifstream f(model_dir + "/config.json");if (!f) return;std::string buf((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());sfx::JV c;try { c = sfx::JV::parse(buf); } catch (...) { return; }if (!c.is_obj()) return;// NOTE: JV::as_num() returns the fallback for anything that is not NUM, so// reading a JSON bool through it silently yields 0. Every flag below was// written as a bool, which made the whole loader a no-op until this was// caught — an absent [config] line was the only symptom.auto on = [&](const char* k) -> bool {if (!c.has(k)) return false;const sfx::JV& v = c.at(k);// There is no as_bool() in core/json.hpp; as_str() stringifies BOOL to// "true"/"false" (json.hpp, tolerant string reader), which is the only// supported way to read a boolean back out of a parsed config.return v.is_bool() ? (v.as_str() == "true") : (v.as_num(0) != 0);};auto num = [&](const char* k, double fallback) -> double {return c.has(k) ? c.at(k).as_num(fallback) : fallback;};auto setf = [&](bool& dst, const char* k) {if (on(k)) { dst = true; a.from_config = true; }};// decide/bench-sidesetf(a.energy_norm, "energy_norm");setf(a.adaptive_depth, "adaptive_depth");setf(a.momentum_gate, "momentum_readout");setf(a.coherence_gate, "coherence_gate");setf(a.wavefront_gate, "wavefront_gate");setf(a.tension_gate, "tension_gate");setf(a.ood_knn, "ood_knn");setf(a.perturb_check, "perturb_check");// learn-side physics (the sweep knobs v3.9.1 added)if (a.physics_diffusion < 0 && c.has("diffusion")) {a.physics_diffusion = static_cast<float>(num("diffusion", -1)); a.from_config = true; }if (a.physics_decay <= 0 && c.has("decay")) {a.physics_decay = static_cast<float>(num("decay", -1)); a.from_config = true; }if (a.physics_k_settle <= 0 && c.has("k_settle")) {a.physics_k_settle = static_cast<float>(num("k_settle", -1)); a.from_config = true; }if (a.physics_eta <= 0 && c.has("learn_eta")) {a.physics_eta = static_cast<float>(num("learn_eta", -1)); a.from_config = true; }if (a.physics_lane_cap <= 0 && c.has("lane_cap")) {a.physics_lane_cap = static_cast<std::size_t>(num("lane_cap", 0)); a.from_config = true; }setf(a.distvec, "distvec");setf(a.cls_split, "cls_split");setf(a.role_bind, "role_bind");setf(a.ntda, "ntda");setf(a.reason_route, "reason_route");if (a.cortical_gate == 3.0f && c.has("cortical_gate")) {a.cortical_gate = static_cast<float>(num("cortical_gate", 3.0)); a.from_config = true; }if (a.cortical_gain == 0.5f && c.has("cortical_gain")) {a.cortical_gain = static_cast<float>(num("cortical_gain", 0.5)); a.from_config = true; }if (a.ngrams_mode == 0 && c.has("ngrams")) {a.ngrams_mode = (c.at("ngrams").as_str() == "off") ? -1 : 1; a.from_config = true; }if (a.bigrams_mode == 0 && c.has("bigrams")) {a.bigrams_mode = (c.at("bigrams").as_str() == "off") ? -1 : 1; a.from_config = true; }if (a.threads <= 0 && c.has("threads")) {a.threads = static_cast<long>(num("threads", 0)); a.from_config = true; }}// Apply the CLI mode overrides after load_model(). Mode-neutral by design:// substrate.bin stays untouched, flags live only for this process.// v3.9.1 physics CONFIG sweep (opt-in): set only what the caller named.7 unmodified linesif (a.physics_hop >= 0) eng.substrate().set_hop_coupling(a.physics_hop);if (a.physics_eta > 0) eng.substrate().set_learn_eta(a.physics_eta);if (a.physics_lane_cap > 0) eng.substrate().set_lane_cap(static_cast<std::size_t>(a.physics_lane_cap));// M3: complementary learning systems. The cortical store is built at learn// time, so this must be set on BOTH sides; at read time it only re-enables// the gate, and cortical lanes come back from the CLS1 substrate tail.if (a.cls_split) {eng.substrate().set_cls_split(true);eng.substrate().set_cortical_gate(a.cortical_gate);eng.substrate().set_cortical_gain(a.cortical_gain);}// M9 / M10 decision gates. These were previously MISSING ENTIRELY: the flags// parsed and appeared in --help, but nothing ever called the setters, so both// features silently did nothing on every invocation. A flag that parses and// does nothing is worse than no flag -- it looks like a working feature and// reports nothing. Wire them here, next to the other decision-side gates.if (a.role_bind) eng.set_role_bind(true);if (a.ntda) { eng.set_ntda(true); eng.substrate().set_ntda_theta(a.ntda_theta); }// M9-encoder: size the projection. The EMBEDDING ITSELF is supplied by a// caller/bridge (set_encoder_input) or read from the model dir's encoder// vector file; the C++ side only owns the local update rule.if (a.enc_dim > 0) {const long C = a.enc_chans > 0 ? a.enc_chans : 32;eng.set_encoder(static_cast<std::size_t>(a.enc_dim),static_cast<std::size_t>(C));eng.set_encoder_eta(a.enc_eta);}if (a.reason_route) eng.set_reason_route(true);}void apply_modes(syfox::Engine& eng, const Args& a) {apply_physics(eng, a);eng.substrate().set_source_modes(a.salience_gating, a.miller_window);// v3.2 semantic layer knobs: the field is ON whenever the model ships it// (substrate v4 tail); the kill switches restore pre-3.2 behavior exactly.eng.substrate().set_semantics(!a.no_semantics);63 unmodified lines}}std::string read_file(const std::string& path) {std::ifstream f(path);if (!f) { std::cerr << "syfox: cannot open " << path << "\n"; std::exit(2); }101 unmodified linesif (a.order_mode != 0) eng.substrate().set_order_consolidation(a.order_mode == 1);if (!a.axioms.empty()) eng.load_axioms(a.axioms);apply_physics(eng, a); // v3.9.1 sweep knobs (LEARN-side)// v3.9.1: --threads N also drives the LEARN path. M5's deterministic// parallel settle (static schedule, per-thread scatter buffers combined in// ascending thread order) is bit-identical to the sequential path, so this// only changes wall time. cmd_learn previously never set it, so training ran// single-threaded even though the OMP machinery was already built in.if (a.threads > 0) {#if defined(_OPENMP)omp_set_num_threads(static_cast<int>(a.threads));#endifeng.substrate().set_parallel_settle(a.threads != 1);}};// v3: consolidation passes. The substrate's own forgetting law decays// every lane 0.995x per lesson, so a 25k-lesson SINGLE pass is92 unmodified linesif (a.distvec) eng.set_distvec(true);if (a.distvec_dims > 0) eng.set_distvec_dims(a.distvec_dims);apply_learn_flags(eng); // v3.9.0 learn-side papersfor (std::size_t ri = 0; ri < epoch_rows.size(); ++ri) {const auto* exp = epoch_rows[ri];if (!a.quiet && (ri % 500 == 0 || ri + 1 == epoch_rows.size())) {const double frac = epoch_rows.empty()? 1.0 : static_cast<double>(ri + 1) / static_cast<double>(epoch_rows.size());std::cerr << "[learn] row " << (ri + 1) << '/' << epoch_rows.size()<< " lessons=" << lessons << " skipped=" << skipped<< std::flush;if (ri) {const double pct = frac * 100.0;std::cerr << " (" << static_cast<long>(pct) << "%)";}std::cerr << '\n';}std::string state = exp->at("state").as_str();const sfx::JV& qs = exp->at("questions");const sfx::JV& labels = exp->at("labels");13 unmodified lines}}eng.save_model(a.model);// -- M8: write the configuration this fabric was TRAINED with -------------// decide/bench/calibrate read it back via load_model_config(), so a model// reproduces its own trained configuration without the user retyping flags.// MUST run after eng.save_model(): the mkdir -p lives inside save_model, so an// ofstream opened before it would silently fail on a not-yet-existing dir.// Written unconditionally (even with all defaults off) so its ABSENCE is// itself a signal: an absent config.json = a model built before M8.{std::ofstream cf(resolve_model_dir(a.model) + "/config.json");if (cf) {sfx::JVObj cfg;cfg["config_version"] = sfx::JV(1);cfg["energy_norm"] = sfx::JV(a.energy_norm);cfg["adaptive_depth"]= sfx::JV(a.adaptive_depth);cfg["momentum_readout"] = sfx::JV(a.momentum_gate);cfg["wavefront_gate"]= sfx::JV(a.wavefront_gate);cfg["coherence_gate"]= sfx::JV(a.coherence_gate);cfg["tension_gate"] = sfx::JV(a.tension_gate);cfg["ood_knn"] = sfx::JV(a.ood_knn);cfg["perturb_check"] = sfx::JV(a.perturb_check);cfg["hops"] = sfx::JV(static_cast<double>(a.hops < 0 ? 1 : a.hops));cfg["diffusion"] = sfx::JV(static_cast<double>(a.physics_diffusion));cfg["decay"] = sfx::JV(static_cast<double>(a.physics_decay));cfg["k_settle"] = sfx::JV(static_cast<double>(a.physics_k_settle));cfg["learn_eta"] = sfx::JV(static_cast<double>(a.physics_eta));cfg["lane_cap"] = sfx::JV(static_cast<double>(a.physics_lane_cap));cfg["distvec"] = sfx::JV(a.distvec);cfg["cls_split"] = sfx::JV(a.cls_split);cfg["role_bind"] = sfx::JV(a.role_bind);cfg["ntda"] = sfx::JV(a.ntda);cfg["ntda_theta"] = sfx::JV(static_cast<double>(a.ntda_theta));cfg["reason_route"] = sfx::JV(a.reason_route);cfg["cortical_gate"] = sfx::JV(static_cast<double>(a.cortical_gate));cfg["cortical_gain"] = sfx::JV(static_cast<double>(a.cortical_gain));cfg["ngrams"] = sfx::JV(std::string(a.ngrams_mode == 0 ? (si::norm::grams_enabled() ? "on" : "off"): (a.ngrams_mode == 1 ? "on" : "off")));cfg["bigrams"] = sfx::JV(std::string(a.bigrams_mode == 0 ? (si::norm::bigrams_enabled() ? "on" : "off"): (a.bigrams_mode == 1 ? "on" : "off")));cfg["epochs"] = sfx::JV(static_cast<double>(a.epochs));cfg["note"] = sfx::JV("learn-side flags as applied; decide/bench read these ""as DEFAULTS and any explicit CLI flag overrides them");cf << sfx::JV(cfg).dump();}}// v3.9.0: persist the constructive substrate (axioms.txt in the model dir// — load_model re-loads it on the next boot) and the v39 sidecar.if (eng.reason_loaded() || !a.axioms.empty()) {45 unmodified lines}syfox::Engine eng;load_or_die(eng, resolve_model_dir(model_dir), "calibration");apply_physics(eng, a); // v3.9.1: sweep knobs shape the fit energiesif (a.energy_norm) eng.set_energy_norm(true);auto rows = load_jsonl(a.examples);auto calib_rows = eng.harvest_rows(rows);// v2.1 (P6): report calibration honestly — MULTI-CLASS ECE on the fit// rows BEFORE (T=1 / default Platt) and AFTER (whatever fit_calibration// adopted; its 1-bit ECE guard may keep T=1). Same helper the fit uses,// same definition bench reports.eng.fit_calibration(calib_rows);eng.save_model(model_dir);const auto& c = eng.calibration();const auto r4 = [](double v) { return std::round(v * 10000.0) / 10000.0; };3 unmodified linesif (!lang_note.empty()) o["lang_note"] = sfx::JV(lang_note);o["fit_rows"] = sfx::JV(static_cast<double>(calib_rows.size()));o["fit_source"] = sfx::JV(a.examples);o["choice_temperature"] = std::round(c.choice_temperature * 10000.0) / 10000.0;o["score_temperature"] = std::round(c.score_temperature * 10000.0) / 10000.0;o["noul_a"] = std::round(c.noul_a * 10000.0) / 10000.0;3 unmodified lines{"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", 1.0f, 6.0f, -3.0f))},{"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, 6.0f, -3.0f))}});o["multiclass_ece_after"] = sfx::JV(sfx::JVObj{ // adopted parameters{"choice", r4(syfox::Engine::calibration_ece(calib_rows, "choice", c.choice_temperature, c.noul_a, c.noul_b))},{"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", c.score_temperature, c.noul_a, c.noul_b))},{"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, c.noul_a, c.noul_b))}});o["note"] = sfx::JV("fit rows supply energies only; if this is the held-out "101 unmodified linesusage["proof_path"] = sfx::JV(pp);usage["proof_hops"] = static_cast<double>(u.proof_path.size());}// M1: thinker-in-the-loop disclosures (only when the gate ran)if (u.role_bind_boosted > 0) usage["role_bind_boosted"] = sfx::JV(u.role_bind_boosted);if (u.enc_updates > 0) usage["encoder_updates"] = sfx::JV(u.enc_updates);if (u.ntda_theta > 0) usage["ntda_theta"] = sfx::JV(std::round(u.ntda_theta * 1000.0f) / 1000.0f);if (u.axioms_rejected > 0) {usage["axioms_rejected"] = sfx::JV(u.axioms_rejected);usage["axioms_note"] = sfx::JV("lines named an unknown relation and were DROPPED");}if (u.reason_routed) {usage["reason_routed"] = sfx::JV(true);usage["reason_derived_candidates"] = sfx::JV(u.reason_derived_count);}if (u.thinker_chained) {usage["thinker_chained"] = sfx::JV(true);usage["thinker_edges_added"] = static_cast<double>(u.thinker_edges_added);usage["thinker_passes"] = static_cast<double>(u.thinker_passes);usage["thinker_budget_left"] =std::round(u.thinker_budget_left * 1000.0f) / 1000.0f;}if (u.momentum_gate) {usage["momentum_gate"] = sfx::JV(true);usage["momentum_eligible_frac"] =54 unmodified linesconst std::string router_dir = resolve_model_dir(a.router);syfox::Engine reng;load_or_die(reng, router_dir, "router");apply_modes(reng, a);if (a.energy_norm) reng.set_energy_norm(true); // M1 gain for the router toosfx::JV rschema(sfx::JVObj{});{std::ifstream rf(router_dir + "/router.json");43 unmodified lines}syfox::Engine eng;load_or_die(eng, resolve_model_dir(model_dir), "decide");apply_modes(eng, a);if (a.energy_norm) eng.set_energy_norm(true); // Milestone-1 gain knob// M1: THINKER-IN-THE-LOOP. Chain the axiom graph to fixpoint BEFORE the// readout, so derived edges exist in the graph the proof pass walks and// the decision can be justified by composition rather than by direct// scoring of taught anchors. Off by default -> pre-M1 bit-identical.if (a.thinker) eng.set_thinker(true);if (a.reason_fixpoint) eng.set_reason_to_fixpoint(true);if (a.meta_observe) eng.set_meta_observe(true);sxr::ReasonCore::ReasonReport think_rep{0, 0, 0.0f};if ((a.thinker || a.reason_fixpoint) && eng.reason_loaded()) {think_rep = eng.think_fixpoint();if (a.thinker && !a.quiet)std::cerr << "[thinker] chained: " << think_rep.edges_added<< " edges in " << think_rep.steps_used << " passes, budget "<< think_rep.budget_left << "\n";}warn_inert_switches(eng, a, model_dir);// --memories FILE (v3.2): explicit memory store for decide — overrides any// model-dir memories.jsonl for this process. Rows: {"label":..., "state":...}.89 unmodified linesvoid cmd_demo(const Args& a) {syfox::Engine eng;load_or_die(eng, resolve_model_dir(a.model), "demo");apply_modes(eng, a);std::cout << "SyFox demo — domain: " << (a.domain.empty() ? "tickets" : a.domain)<< " | core: si-substrate (no transformer, no classifier)\n";for (const auto& d : demos_for(a.domain)) {8 unmodified linesvoid cmd_stats(const Args& a) {syfox::Engine eng;load_or_die(eng, resolve_model_dir(a.model), "stats");apply_modes(eng, a); // stats reflects the modes this process would run understd::cout << sfx::JV(sfx::JVObj{{"nodes", static_cast<double>(eng.substrate().node_count())},{"lanes", static_cast<double>(eng.substrate().lane_count())},6 unmodified lines{"noul_b", eng.calibration().noul_b},{"salience_gating", sfx::JV(eng.substrate().config().salience_gating)},{"miller_window", sfx::JV(eng.substrate().config().miller_window)},// M3: complementary-learning-systems disclosure. A fabric with// cls_split off MUST report cortical_lanes 0 — that is how a reader// tells which physics produced a published number.{"cls_split", sfx::JV(eng.substrate().cls_split())},// M5 NTDA disclosure: firing threshold, spikes fired, lanes deleted.{"encoder_chans", sfx::JV(static_cast<double>(eng.substrate().enc_chans()))},{"encoder_dim", sfx::JV(static_cast<double>(eng.substrate().enc_dim()))},{"encoder_updates", sfx::JV(static_cast<double>(eng.enc_updates()))},{"ntda_on", sfx::JV(eng.substrate().ntda_on())},// M9-LEARNED: is the role tagger using the FABRIC's document frequencies// instead of the hardcoded rulebook? This is the disclosure that matters// for the "inference is just a runner" claim.{"fn_words_learned", sfx::JV(static_cast<double>(si::roles::learned_fn_words().size()))},{"fn_words_source", sfx::JV(si::roles::fn_words_loaded() ? "fabric_df" : "hardcoded_fallback")},{"ntda_theta_base", sfx::JV(static_cast<double>(eng.substrate().config().ntda_theta))},{"ntda_theta_effective", sfx::JV(static_cast<double>(eng.substrate().current_theta()))},{"ntda_spikes", sfx::JV(static_cast<double>(eng.ntda_spikes()))},{"ntda_deaths", sfx::JV(static_cast<double>(eng.ntda_deaths()))},{"ntda_voltage_traces", sfx::JV(static_cast<double>(eng.substrate().voltage_traces()))},{"cortical_lanes", sfx::JV(static_cast<double>(eng.substrate().cortical_lanes()))},{"eligibility_traces", sfx::JV(static_cast<double>(eng.substrate().eligibility_traces()))},{"cortical_gate", sfx::JV(static_cast<double>(eng.substrate().config().cortical_gate))},{"cortical_gain", sfx::JV(static_cast<double>(eng.substrate().config().cortical_gain))},// v3.2 semantic layer + retrieval + hierarchy{"semantics", sfx::JV(eng.substrate().has_semantics() && !a.no_semantics)},{"sem_edges", static_cast<double>(eng.substrate().resonance_edge_count())},{"lane_contexts", static_cast<double>(eng.substrate().lane_context_count())},{"retrieval", sfx::JV(eng.retrieval_on() && !a.no_retrieval)},{"retrieval_memories", static_cast<double>(eng.memories().size())},{"hierarchy", sfx::JV(eng.hierarchy_on() && !a.no_hierarchy)}}).dump() << "\n";}// ---------------------------------------------------------------------------9 unmodified linesvoid cmd_bench(const Args& a) {syfox::Engine eng;load_or_die(eng, resolve_model_dir(a.model), "bench");apply_modes(eng, a); // --threads (M5 OMP settle), SI modesif (a.energy_norm) eng.set_energy_norm(true); // Milestone-1 gain knobstd::string eval_path = !a.eval.empty() ? a.eval : a.examples;std::string split_note;if (!a.split.empty()) {506 unmodified lines" syfox decide --model DIR --state '...' --questions '{...}'\n"" syfox demo --model DIR --domain tickets|game|guard\n"" syfox stats --model DIR\n"" syfox derive --model DIR [--gate FILE.jsonl] [--examples FILE.jsonl]\n"" syfox dream --model DIR [--steps N] [--seed S]\n"" syfox promote --model DIR\n"517 unmodified lineselse qr = eng.reason_.ask(subj, rel, obj);eng.reason_meta_.observe_trace(qr.proof);eng.thinker_.record(qr);// M2: accumulate across processes. Without this the MetaLearner dies with// the process and macro-rule promotion can never fire across runs.if (a.persist_meta) {const auto w = eng.save_meta(resolve_model_dir(a.model));std::cerr << "[meta] chains=" << w[0] << " macros=" << w[1]<< " (written to " << resolve_model_dir(a.model)<< "/meta_rules.txt)\n";}sfx::JVArr proof;for (int ei : qr.proof) {const auto& e = eng.reason_.graph.edges[static_cast<std::size_t>(ei)];240 unmodified lineselse if (k == "--dedup") a.dedup = true;else if (k == "--novelty") a.novelty = true;else if (k == "--energy-norm") a.energy_norm = true;else if (k == "--defer-margin") { if (i + 1 >= argc) usage_exit(); a.defer_margin = std::strtof(argv[++i], nullptr); if (a.defer_margin < 0) usage_exit(); }else if (k == "--no-defer") a.no_defer = true;else if (k == "--hops") { if (i + 1 >= argc) usage_exit(); a.hops = std::strtol(argv[++i], nullptr, 10); if (a.hops < 1 || a.hops > 8) usage_exit(); }27 unmodified lineselse if (k == "--threads") { if (i + 1 >= argc) usage_exit(); a.threads = std::strtol(argv[++i], nullptr, 10); if (a.threads < 0) usage_exit(); }else if (k == "--throughput") { if (i + 1 >= argc) usage_exit(); a.throughput = std::strtol(argv[++i], nullptr, 10); if (a.throughput < 1) usage_exit(); }else if (k == "--epochs") { if (i + 1 >= argc) usage_exit(); a.epochs = std::strtol(argv[++i], nullptr, 10); if (a.epochs < 1) usage_exit(); }else if (k == "--quiet") { a.quiet = true; }else if (k == "--thinker") { a.thinker = true; }else if (k == "--reason-fixpoint") { a.reason_fixpoint = true; }else if (k == "--meta-observe") { a.meta_observe = true; }else if (k == "--persist-meta") { a.persist_meta = true; }else if (k == "--cls-split") { a.cls_split = true; }else if (k == "--role-bind") { a.role_bind = true; }else if (k == "--ntda") { a.ntda = true; }else if (k == "--encoder-dim") { if (i + 1 >= argc) usage_exit(); a.enc_dim = std::strtol(argv[++i], nullptr, 10); }else if (k == "--encoder-chans") { if (i + 1 >= argc) usage_exit(); a.enc_chans = std::strtol(argv[++i], nullptr, 10); }else if (k == "--encoder-eta") { if (i + 1 >= argc) usage_exit(); a.enc_eta = std::strtof(argv[++i], nullptr); }else if (k == "--ntda-theta") { if (i + 1 >= argc) usage_exit(); a.ntda_theta = std::strtof(argv[++i], nullptr); }else if (k == "--reason-route") { a.reason_route = true; }else if (k == "--a") { need(a.bisoc_a); }else if (k == "--b") { need(a.bisoc_b); }else if (k == "--bridge") { a.bisoc_bridge = true; }else if (k == "--cortical-gate") { if (i + 1 >= argc) usage_exit(); a.cortical_gate = std::strtof(argv[++i], nullptr); }else if (k == "--cortical-gain") { if (i + 1 >= argc) usage_exit(); a.cortical_gain = std::strtof(argv[++i], nullptr); }else if (k == "--novelty-floor") { if (i + 1 >= argc) usage_exit(); a.novelty_floor = std::strtof(argv[++i], nullptr); }else if (k == "--ngrams") {if (i + 1 >= argc) usage_exit();47 unmodified lineselse if (k == "--require-proof") a.require_proof = true;else if (k == "--momentum-readout") a.momentum_gate = true;else if (k == "--wavefront-gate") a.wavefront_gate = true;else if (k == "--coherence-gate") a.coherence_gate = true;else if (k == "--coherence-floor") { if (i + 1 >= argc) usage_exit(); a.coherence_floor = std::strtof(argv[++i], nullptr); if (a.coherence_floor < 0 || a.coherence_floor > 1) usage_exit(); }else if (k == "--vght-gate") a.vght_gate = true;39 unmodified linesif (def) si::norm::load_synonyms("data/synonyms.txt");}if (cmd == "version") { std::cout << "syfox " << syfox::VERSION << " (core: si-substrate)\n"; return 0; }// -- M8: model config as DEFAULTS ----------------------------------------// Applied once, here, for every READ-side command (decide/bench/calibrate/// stats/derive/dream/...) so each gets the fabric's trained configuration// without retyping flags. Explicit CLI flags already parsed above, so they// always win — the loader only fills fields still at their default.// NOT applied to learn: a training run must be fully specified on its CLI.if (cmd != "learn" && !a.model.empty()) {const std::string mdir = resolve_model_dir(a.model);const bool before_en = a.energy_norm;load_model_config(mdir, a);if (a.from_config && !before_en && a.energy_norm && !a.quiet)std::cerr << "[config] applied defaults from " << mdir<< "/config.json (explicit flags still win)\n";}if (cmd == "learn") { if (a.examples.empty()) usage_exit(); cmd_learn(a); return 0; }if (cmd == "calibrate") { if (a.examples.empty()) usage_exit(); cmd_calibrate(a); return 0; }// An EMPTY --state used to be a usage error (exit 2). The engine already// knows how to answer it honestly -- reason "empty_state" -- so rejecting it// at the CLI made the honest path unreachable and turned a deferral into a// crash for any caller that probes an empty input. Now only a missing// questions document is a usage error.if (cmd == "decide") { if (a.questions.empty()) usage_exit(); cmd_decide(a); return 0; }if (cmd == "demo") { cmd_demo(a); return 0; }if (cmd == "stats") { cmd_stats(a); return 0; }if (cmd == "derive") { cmd_derive(a); return 0; }if (cmd == "dream") { cmd_dream(a); return 0; }if (cmd == "promote") { cmd_promote(a); return 0; }13 unmodified linesif (cmd == "discover") { if (a.model.empty()) usage_exit(); cmd_discover(a); return 0; }if (cmd == "thinker") { if (a.model.empty()) usage_exit(); cmd_thinker(a); return 0; }if (cmd == "audit") { if (a.model.empty()) usage_exit(); cmd_audit(a); return 0; }if (cmd == "bisoc") {if (a.model.empty() || a.bisoc_a.empty() || a.bisoc_b.empty()) usage_exit();syfox::Engine beng; load_or_die(beng, resolve_model_dir(a.model), "bisoc");const sxr::BisocResult r = sxr::bisociate(beng.reason_, a.bisoc_a, a.bisoc_b);std::cout << sfx::JV(sfx::JVObj{{"command", sfx::JV("bisoc")}, {"a", sfx::JV(r.a_label)}, {"b", sfx::JV(r.b_label)},{"hop_before", static_cast<double>(r.shortest_hop_before)},{"bridge_found", sfx::JV(r.bridge_found)},{"intermediate", sfx::JV(r.intermediate)},{"energy_U_hyp", std::round(r.energy * 1000.0f) / 1000.0f},{"validated", sfx::JV(r.validated)}, {"status", sfx::JV(r.status)}}).dump() << "\n";if (a.bisoc_bridge) {const sxr::BridgeProposal p =sxr::synthesise_bridge(beng.reason_, a.bisoc_a, a.bisoc_b);sfx::JVArr rels;for (const auto& t : p.rels)rels.push_back(sfx::JV(t.subj + " " + t.rel + " " + t.obj));std::cout << sfx::JV(sfx::JVObj{{"command", sfx::JV("bridge")}, {"label", sfx::JV(p.label)},{"rels", sfx::JV(rels)},{"extra_prediction", sfx::JV(p.makes_extra_prediction)},{"status", sfx::JV(p.status)}}).dump() << "\n";}return 0;}usage_exit();}17 unmodified lines181920212223249 unmodified lines343536373839404142434445464722 unmodified lines70717273747576774 unmodified lines8283848586874 unmodified lines929394959697989910010165 unmodified lines16716816917017117217317469 unmodified lines2442452462472482497 unmodified lines25725825926026126226326426526626726826927027163 unmodified lines335336337338339340341342343344345346347348349350351101 unmodified lines45345445545645745892 unmodified lines55155255355455555655713 unmodified lines57157257357457557645 unmodified lines6226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716723 unmodified lines6766776786796806816826836846856866876886893 unmodified lines693694695696697698699700101 unmodified lines80280380480580680754 unmodified lines86286386486586686786843 unmodified lines91291391491591691791889 unmodified lines10081009101010111012101310148 unmodified lines10231024102510261027102810296 unmodified lines103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911009 unmodified lines1110111111121113111411151116506 unmodified lines1623162416251626162716281629517 unmodified lines214721482149215021512152240 unmodified lines2393239423952396239723982399240024012402240327 unmodified lines24312432243324342435243647 unmodified lines2484248524862487248824892490249139 unmodified lines25312532253325342535253625372538253925402541254213 unmodified lines2556255725582559256017 unmodified lines#include <cstdlib>#include <cstring>#include <fstream>#include <iomanip>#include <iostream>#include <map>#include <sstream>9 unmodified linesvoid usage_exit();// v3.9.2: the calibration fit must see at least this fraction of the// question-rows it was offered. Below it the fit is measuring a different// engine than the one that will decide (the shipped b77-sem calibration saw// 27.7% because it ran without the decide-side energy gain). Override with// --calib-min-coverage F (0 disables the refusal; the coverage is still// disclosed in the calibrate report).constexpr double kMinCalibrationCoverage = 0.5;struct Args {std::string model = "model";std::string examples;22 unmodified linesbool novelty = false; // learn --novelty: per-lesson dose by novelty (M2)float novelty_floor = 0.25f; // learn --novelty-floor F (A/B knob)bool energy_norm = false; // decide-side energy gain for big-corpus fabrics (M1)bool no_energy_norm = false; // v3.9.2: explicitly turn the energy gain OFFdouble calib_min_coverage = kMinCalibrationCoverage; // v3.9.2 fit-coverage floorfloat defer_margin = -1; // v3.4: engine default ON at 0.05 (reason ambiguous_tie);// --defer-margin P overrides, --no-defer disables.// (v3.1-3.3 this was a CLI post-pass with reason low_margin,4 unmodified lineslong threads = 0; // --threads N: OMP settle threads (1 = sequential; 0 = default)long throughput = 0; // bench --throughput N: batched multicore decisions/sec (M5)long epochs = 1; // learn --epochs N: consolidation passes (see lane_decay)long latency_reps = 20; // bench --latency-reps N (timing repeats per probe)long replays = 2; // bench --replays N (determinism double-run count)bool state_file = false, questions_file = false;4 unmodified linesbool no_retrieval = false; // --no-retrieval: skip associative primingbool no_hierarchy = false; // --no-hierarchy: skip stage-1 category gatingbool no_defer = false; // --no-defer: disable v3.4 near-tie defer (engine default ON)// v3.9.3: lane repair + the lane-decay floordouble repair_dead_threshold = 1e-6; // --repair-dead-threshold F: weight below = deadbool repair_dry_run = false; // --dry-run: report, do not writefloat lane_floor = 0.0f; // --lane-floor F: lane-decay floor when learninglong hops = -1; // --hops N: v3.4 multi-hop readout walk depth (engine default 1 = legacy)bool ctx_gate = false; // --ctx-gate: v3.4 two-stage question-context settlefloat ctx_alpha = 0; // --ctx-alpha F (0 = engine default 0.5)65 unmodified linesint sentinels_mode = 0; // --sentinels on|off (CMD §2.5): 1/-1 explicitint order_mode = 0; // --order-consolidation on|off (CPME-II): 1/-1 explicitbool fingerprints = false; // --fingerprints (CME): graded half-dose re-teachfloat affinity_mix = -1.0f; // --affinity-mix F (v4.0 AFR): -1 = unspecifiedbool affinity_pmi = false; // --affinity-pmi (v4.0): log-odds form of the contrast};// v3.2.1 — BUG #1 disclosure: a kill switch on a model that lacks the69 unmodified linesreturn eng;}// Apply the CLI mode overrides after load_model(). Mode-neutral by design:// substrate.bin stays untouched, flags live only for this process.// v3.9.1 physics CONFIG sweep (opt-in): set only what the caller named.7 unmodified linesif (a.physics_hop >= 0) eng.substrate().set_hop_coupling(a.physics_hop);if (a.physics_eta > 0) eng.substrate().set_learn_eta(a.physics_eta);if (a.physics_lane_cap > 0) eng.substrate().set_lane_cap(static_cast<std::size_t>(a.physics_lane_cap));// v4.0 — the affinity field readout channel (default OFF; replay-safe).// Set HERE, not in apply_modes: cmd_calibrate calls apply_physics only,// and the fit must see the same channel the decision scores (parity).if (a.affinity_mix >= 0.0f) eng.set_affinity_mix(a.affinity_mix);if (a.affinity_pmi) eng.set_affinity_pmi(true);}void apply_modes(syfox::Engine& eng, const Args& a) {apply_physics(eng, a); eng.substrate().set_source_modes(a.salience_gating, a.miller_window);// v3.2 semantic layer knobs: the field is ON whenever the model ships it// (substrate v4 tail); the kill switches restore pre-3.2 behavior exactly.eng.substrate().set_semantics(!a.no_semantics);63 unmodified lines}}// v3.9.2: apply the fabric's RECORDED decide-side composition, then the// per-call modes, then the explicit energy-gain flags (which win over both).// Every decide-side command goes through this so the physics a decision// runs under is the physics the calibration scalars were fitted against.void apply_composition_and_modes(syfox::Engine& eng, const Args& a) {eng.apply_composition();apply_modes(eng, a);if (a.energy_norm) eng.set_energy_norm(true);if (a.no_energy_norm) eng.set_energy_norm(false);}std::string read_file(const std::string& path) {std::ifstream f(path);if (!f) { std::cerr << "syfox: cannot open " << path << "\n"; std::exit(2); }101 unmodified linesif (a.order_mode != 0) eng.substrate().set_order_consolidation(a.order_mode == 1);if (!a.axioms.empty()) eng.load_axioms(a.axioms);apply_physics(eng, a); // v3.9.1 sweep knobs (LEARN-side)};// v3: consolidation passes. The substrate's own forgetting law decays// every lane 0.995x per lesson, so a 25k-lesson SINGLE pass is92 unmodified linesif (a.distvec) eng.set_distvec(true);if (a.distvec_dims > 0) eng.set_distvec_dims(a.distvec_dims);apply_learn_flags(eng); // v3.9.0 learn-side papersfor (const auto* exp : epoch_rows) {std::string state = exp->at("state").as_str();const sfx::JV& qs = exp->at("questions");const sfx::JV& labels = exp->at("labels");13 unmodified lines}}eng.save_model(a.model);// v3.9.0: persist the constructive substrate (axioms.txt in the model dir// — load_model re-loads it on the next boot) and the v39 sidecar.if (eng.reason_loaded() || !a.axioms.empty()) {45 unmodified lines}syfox::Engine eng;load_or_die(eng, resolve_model_dir(model_dir), "calibration");// v3.9.2: apply the fabric's RECORDED decide-side composition BEFORE the// sweep knobs, so a re-calibration fits the same physics the decisions// will run under. Explicit CLI flags still override it (apply_physics// runs after this line).eng.apply_composition();apply_physics(eng, a); // v3.9.1: sweep knobs shape the fit energiesif (a.energy_norm) eng.set_energy_norm(true);if (a.no_energy_norm) eng.set_energy_norm(false);auto rows = load_jsonl(a.examples);auto calib_rows = eng.harvest_rows(rows);// v3.9.2 COVERAGE GUARD. A row whose settled field is silent contributes// no candidate energies and never reaches the fit. If the fit saw less// than kMinCalibrationCoverage of the question-rows it was offered, the// composition is wrong (measured: the shipped b77-sem calibration saw// 556 of 2,006 = 27.7% because it ran without the decide-side energy// gain) and the fitted temperature would be a number for a different// engine. Fail loudly and leave the fabric untouched.const std::size_t offered = eng.harvest_offered();const std::size_t dropped = eng.harvest_dropped_silent();const double coverage = offered ? static_cast<double>(calib_rows.size())/ static_cast<double>(offered) : 1.0;if (offered > 0 && coverage < a.calib_min_coverage) {std::cerr << "syfox: calibration refused: the fit saw only "<< calib_rows.size() << " of " << offered << " question-rows ("<< std::fixed << std::setprecision(1) << (coverage * 100.0)<< "% coverage; " << dropped << " settled to a SILENT field and ""were dropped).\n"<< " The decide-side composition does not match the rows: ""the energy gain is the usual cause\n"<< " (the fit ran without --energy-norm while the ""decisions run with it, so the settled field is empty\n"<< " and the fit is left on a biased subset). ""Re-run with --energy-norm,\n"<< " or set --calib-min-coverage 0 to accept the fit ""anyway (disclosed, not recommended).\n";std::exit(2);}// v2.1 (P6): report calibration honestly — MULTI-CLASS ECE on the fit// rows BEFORE (T=1 / default Platt) and AFTER (whatever fit_calibration// adopted; its 1-bit ECE guard may keep T=1). Same helper the fit uses,// same definition bench reports.eng.fit_calibration(calib_rows);// v3.9.2: record the composition the fit ran under, so decide/bench/// calibrate all agree from now on without the operator repeating flags.eng.set_composition(eng.live_composition());eng.save_model(model_dir);const auto& c = eng.calibration();const auto r4 = [](double v) { return std::round(v * 10000.0) / 10000.0; };3 unmodified linesif (!lang_note.empty()) o["lang_note"] = sfx::JV(lang_note);o["fit_rows"] = sfx::JV(static_cast<double>(calib_rows.size()));o["fit_source"] = sfx::JV(a.examples);// v3.9.2: the fit's COVERAGE and the composition it ran under. Both are// first-class: a temperature fitted on a biased subset of the rows is a// temperature for a different engine, and a fit that never saw half the// rows is exactly that.o["fit_offered_rows"] = sfx::JV(static_cast<double>(offered));o["fit_dropped_silent"] = sfx::JV(static_cast<double>(dropped));o["fit_coverage"] = sfx::JV(std::round(coverage * 10000.0) / 10000.0);o["decide_composition"] = eng.composition().to_json();o["choice_temperature"] = std::round(c.choice_temperature * 10000.0) / 10000.0;o["score_temperature"] = std::round(c.score_temperature * 10000.0) / 10000.0;o["noul_a"] = std::round(c.noul_a * 10000.0) / 10000.0;3 unmodified lines{"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", 1.0f, 6.0f, -3.0f))},{"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, 6.0f, -3.0f))}});o["multiclass_ece_after"] = sfx::JV(sfx::JVObj{ // adopted parameters{"choice", r4(syfox::Engine::calibration_ece(calib_rows, "choice", c.choice_temperature, c.noul_a, c.noul_b,&c.choice_temperature_by_count))},{"score", r4(syfox::Engine::calibration_ece(calib_rows, "score", c.score_temperature, c.noul_a, c.noul_b))},{"noul", r4(syfox::Engine::calibration_ece(calib_rows, "noul", 1.0f, c.noul_a, c.noul_b))}});o["note"] = sfx::JV("fit rows supply energies only; if this is the held-out "101 unmodified linesusage["proof_path"] = sfx::JV(pp);usage["proof_hops"] = static_cast<double>(u.proof_path.size());}if (u.momentum_gate) {usage["momentum_gate"] = sfx::JV(true);usage["momentum_eligible_frac"] =54 unmodified linesconst std::string router_dir = resolve_model_dir(a.router);syfox::Engine reng;load_or_die(reng, router_dir, "router");apply_composition_and_modes(reng, a); // v3.9.2: fabric composition firstsfx::JV rschema(sfx::JVObj{});{std::ifstream rf(router_dir + "/router.json");43 unmodified lines}syfox::Engine eng;load_or_die(eng, resolve_model_dir(model_dir), "decide");apply_composition_and_modes(eng, a); // v3.9.2: fabric composition firstwarn_inert_switches(eng, a, model_dir);// --memories FILE (v3.2): explicit memory store for decide — overrides any// model-dir memories.jsonl for this process. Rows: {"label":..., "state":...}.89 unmodified linesvoid cmd_demo(const Args& a) {syfox::Engine eng;load_or_die(eng, resolve_model_dir(a.model), "demo");apply_composition_and_modes(eng, a); // v3.9.2: fabric composition firststd::cout << "SyFox demo — domain: " << (a.domain.empty() ? "tickets" : a.domain)<< " | core: si-substrate (no transformer, no classifier)\n";for (const auto& d : demos_for(a.domain)) {8 unmodified linesvoid cmd_stats(const Args& a) {syfox::Engine eng;load_or_die(eng, resolve_model_dir(a.model), "stats");apply_composition_and_modes(eng, a); // v3.9.2: fabric composition firststd::cout << sfx::JV(sfx::JVObj{{"nodes", static_cast<double>(eng.substrate().node_count())},{"lanes", static_cast<double>(eng.substrate().lane_count())},6 unmodified lines{"noul_b", eng.calibration().noul_b},{"salience_gating", sfx::JV(eng.substrate().config().salience_gating)},{"miller_window", sfx::JV(eng.substrate().config().miller_window)},// v3.2 semantic layer + retrieval + hierarchy{"semantics", sfx::JV(eng.substrate().has_semantics() && !a.no_semantics)},{"sem_edges", static_cast<double>(eng.substrate().resonance_edge_count())},{"lane_contexts", static_cast<double>(eng.substrate().lane_context_count())},{"retrieval", sfx::JV(eng.retrieval_on() && !a.no_retrieval)},{"retrieval_memories", static_cast<double>(eng.memories().size())},{"hierarchy", sfx::JV(eng.hierarchy_on() && !a.no_hierarchy)},// v3.9.2: the decide-side composition this fabric's calibration scalars// were fitted against (from physics.json), and whether the live engine// is running under it.{"decide_composition", eng.composition().to_json()},{"live_composition", eng.live_composition().to_json()}}).dump() << "\n";}// ---------------------------------------------------------------------------// v3.9.3: repair the numerically dead lanes from the persisted evidence ledger.//// The port applies CMD §2.3's decay to EVERY lane on EVERY lesson, so a lane// last bound at lesson k in an N-lesson fabric carries w0 * 0.995^(N-k),// which underflows to the float32 denormal floor (1.4e-43) after ~20,700// lessons and then stops decreasing. MEASURED on the shipped// model/giant-latin fabric (114,060 lessons, 1,905,169 lanes): 95.09% of// lanes sit below 1e-12, the MEDIAN lane weight is 1.4e-43, and only 2.42%// exceed 1e-6 — the Hebbian memory was numerically erased.//// The evidence ledger (v3 Milestone 3) holds the integral of the growth term// the decay destroyed, so the weight can be rebuilt in CMD §2.3's saturating// form. This rewrites NO equation and changes NO learn-time behaviour: a// fabric re-learned from scratch is byte-identical.void cmd_repair_lanes(const Args& a) {syfox::Engine eng;const std::string dir = resolve_model_dir(a.model);load_or_die(eng, dir, "repair-lanes");const auto st = eng.repair_lanes(static_cast<float>(a.repair_dead_threshold));sfx::JVObj o;o["command"] = sfx::JV("repair-lanes");o["model"] = sfx::JV(dir);o["lanes_total"] = sfx::JV(static_cast<double>(st.lanes_total));o["lanes_repaired"] = sfx::JV(static_cast<double>(st.lanes_repaired));o["lanes_dead_before"] = sfx::JV(static_cast<double>(st.lanes_dead));o["lanes_dead_revivable"] = sfx::JV(static_cast<double>(st.lanes_revivable));o["lanes_dead_orphan"] = sfx::JV(static_cast<double>(st.lanes_orphan));o["dead_threshold"] = sfx::JV(a.repair_dead_threshold);o["weight_sum_before"] = sfx::JV(st.weight_before);o["weight_sum_after"] = sfx::JV(st.weight_after);o["note"] = sfx::JV("lane weights rebuilt from the persisted evidence ""ledger in CMD §2.3's saturating form ""(w = w_max*tanh(net_events*bind_scale/w_max)); ""no equation changed; the calibration must be re-fitted ""under this composition (the energy scale moved)");std::cout << sfx::JV(o).dump() << "\n";if (a.repair_dry_run) {std::cerr << "syfox: repair-lanes: --dry-run — the fabric was NOT written\n";return;}eng.save_model(dir);std::cerr << "syfox: repair-lanes: fabric written to " << dir<< " — re-fit the calibration under the same composition ""(syfox calibrate --energy-norm ...) before measuring\n";}// ---------------------------------------------------------------------------9 unmodified linesvoid cmd_bench(const Args& a) {syfox::Engine eng;load_or_die(eng, resolve_model_dir(a.model), "bench");apply_composition_and_modes(eng, a); // v3.9.2: fabric composition firststd::string eval_path = !a.eval.empty() ? a.eval : a.examples;std::string split_note;if (!a.split.empty()) {506 unmodified lines" syfox decide --model DIR --state '...' --questions '{...}'\n"" syfox demo --model DIR --domain tickets|game|guard\n"" syfox stats --model DIR\n"" syfox repair-lanes --model DIR [--dead-threshold F] [--dry-run]\n"" syfox derive --model DIR [--gate FILE.jsonl] [--examples FILE.jsonl]\n"" syfox dream --model DIR [--steps N] [--seed S]\n"" syfox promote --model DIR\n"517 unmodified lineselse qr = eng.reason_.ask(subj, rel, obj);eng.reason_meta_.observe_trace(qr.proof);eng.thinker_.record(qr);sfx::JVArr proof;for (int ei : qr.proof) {const auto& e = eng.reason_.graph.edges[static_cast<std::size_t>(ei)];240 unmodified lineselse if (k == "--dedup") a.dedup = true;else if (k == "--novelty") a.novelty = true;else if (k == "--energy-norm") a.energy_norm = true;else if (k == "--no-energy-norm") a.no_energy_norm = true; // v3.9.2else if (k == "--repair-dead-threshold") { if (i + 1 >= argc) usage_exit(); a.repair_dead_threshold = std::strtod(argv[++i], nullptr); }else if (k == "--dry-run") a.repair_dry_run = true;else if (k == "--lane-floor") { if (i + 1 >= argc) usage_exit(); a.lane_floor = static_cast<float>(std::strtod(argv[++i], nullptr)); if (a.lane_floor < 0.0f) usage_exit(); }else if (k == "--calib-min-coverage") { if (i + 1 >= argc) usage_exit(); a.calib_min_coverage = std::strtod(argv[++i], nullptr); if (a.calib_min_coverage < 0.0) usage_exit(); } // v3.9.2else if (k == "--defer-margin") { if (i + 1 >= argc) usage_exit(); a.defer_margin = std::strtof(argv[++i], nullptr); if (a.defer_margin < 0) usage_exit(); }else if (k == "--no-defer") a.no_defer = true;else if (k == "--hops") { if (i + 1 >= argc) usage_exit(); a.hops = std::strtol(argv[++i], nullptr, 10); if (a.hops < 1 || a.hops > 8) usage_exit(); }27 unmodified lineselse if (k == "--threads") { if (i + 1 >= argc) usage_exit(); a.threads = std::strtol(argv[++i], nullptr, 10); if (a.threads < 0) usage_exit(); }else if (k == "--throughput") { if (i + 1 >= argc) usage_exit(); a.throughput = std::strtol(argv[++i], nullptr, 10); if (a.throughput < 1) usage_exit(); }else if (k == "--epochs") { if (i + 1 >= argc) usage_exit(); a.epochs = std::strtol(argv[++i], nullptr, 10); if (a.epochs < 1) usage_exit(); }else if (k == "--novelty-floor") { if (i + 1 >= argc) usage_exit(); a.novelty_floor = std::strtof(argv[++i], nullptr); }else if (k == "--ngrams") {if (i + 1 >= argc) usage_exit();47 unmodified lineselse if (k == "--require-proof") a.require_proof = true;else if (k == "--momentum-readout") a.momentum_gate = true;else if (k == "--wavefront-gate") a.wavefront_gate = true;else if (k == "--affinity-mix") { if (i + 1 >= argc) usage_exit(); a.affinity_mix = std::strtof(argv[++i], nullptr); if (a.affinity_mix < 0 || a.affinity_mix > 1) usage_exit(); }else if (k == "--affinity-pmi") a.affinity_pmi = true;else if (k == "--coherence-gate") a.coherence_gate = true;else if (k == "--coherence-floor") { if (i + 1 >= argc) usage_exit(); a.coherence_floor = std::strtof(argv[++i], nullptr); if (a.coherence_floor < 0 || a.coherence_floor > 1) usage_exit(); }else if (k == "--vght-gate") a.vght_gate = true;39 unmodified linesif (def) si::norm::load_synonyms("data/synonyms.txt");}if (cmd == "version") { std::cout << "syfox " << syfox::VERSION << " (core: si-substrate)\n"; return 0; }if (cmd == "learn") { if (a.examples.empty()) usage_exit(); cmd_learn(a); return 0; }if (cmd == "calibrate") { if (a.examples.empty()) usage_exit(); cmd_calibrate(a); return 0; }if (cmd == "decide") { if (a.state.empty() || a.questions.empty()) usage_exit(); cmd_decide(a); return 0; }if (cmd == "demo") { cmd_demo(a); return 0; }if (cmd == "stats") { cmd_stats(a); return 0; }if (cmd == "repair-lanes") { cmd_repair_lanes(a); return 0; }if (cmd == "derive") { cmd_derive(a); return 0; }if (cmd == "dream") { cmd_dream(a); return 0; }if (cmd == "promote") { cmd_promote(a); return 0; }13 unmodified linesif (cmd == "discover") { if (a.model.empty()) usage_exit(); cmd_discover(a); return 0; }if (cmd == "thinker") { if (a.model.empty()) usage_exit(); cmd_thinker(a); return 0; }if (cmd == "audit") { if (a.model.empty()) usage_exit(); cmd_audit(a); return 0; }usage_exit();}
42 unmodified lines4344454647487 unmodified lines56575859606142 unmodified linesdelete h;return nullptr;}return h;}7 unmodified lines// -- engine-scoped knobs (identical semantics to the CLI flags) -------------void syfox_engine_set_energy_norm(SyFoxHandle* h, int on) {if (h) h->eng->set_energy_norm(on != 0); // M1: measurement gain}42 unmodified lines43444546474849505152535455567 unmodified lines646566676869707172737475767742 unmodified linesdelete h;return nullptr;}// v4.0 — apply the model's RECORDED decide-side composition (physics.json:// energy norm, diffusion, and the AFFINITY READOUT MODE the fabric was// calibrated under). Without this the C API / python bridge / HTTP Space// decided under DIFFERENT physics than the CLI, and under a different// readout than the temperature was fitted for -- the fit==decide parity// contract, broken on the server path. The CLI applied the composition// explicitly and is unaffected (applying it twice is idempotent).h->eng->apply_composition();return h;}7 unmodified lines// -- engine-scoped knobs (identical semantics to the CLI flags) -------------// v4.0 — the affinity field readout channel (0 = legacy, 1 = affinity only).void syfox_engine_set_affinity_mix(SyFoxHandle* h, float mix) {if (h) h->eng->set_affinity_mix(mix);}void syfox_engine_set_affinity_pmi(SyFoxHandle* h, int on) {if (h) h->eng->set_affinity_pmi(on != 0);}void syfox_engine_set_energy_norm(SyFoxHandle* h, int on) {if (h) h->eng->set_energy_norm(on != 0); // M1: measurement gain}
2449 unmodified lines245024512452245324542455395 unmodified lines2851285228532854285528562449 unmodified lines}}static void test_v39_gates() {std::cerr << " AT-test_v39_gates\n";std::cout << "[v39 gates: momentum / wavefront / coherence / vght / cem / "395 unmodified linestest_thinking();test_reason();test_v39_gates();if (failures) { std::cout << failures << " FAILURES\n"; return 1; }std::cout << "all tests passed\n";return 0;2449 unmodified lines2450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669395 unmodified lines3065306630673068306930703071307230732449 unmodified lines}}// ---------------------------------------------------------------------------// v3.9.2: the decide-side PHYSICS COMPOSITION.//// The calibration scalars (choice/score temperature, Platt) are fitted on// energies produced by a settle pass, and those energies depend on the whole// decide-side composition (energy gain, diffusion, decay, k_settle, hop// coupling). Fit on one composition, decide under another, and the fit is a// number for a different engine. This group pins the mechanism that makes// fit==decide structural instead of a remembered flag:// (1) a fabric WITHOUT physics.json is untouched (replay contract);// (2) a fabric WITH physics.json carries it across a save/load round trip;// (3) applying the composition reproduces the same decisions;// (4) the calibration fit discloses how many question-rows it actually saw.// ---------------------------------------------------------------------------// ---------------------------------------------------------------------------// v3.9.3: the DEAD-LANE REPAIR.//// The port applies CMD §2.3's decay to EVERY lane on EVERY lesson, so a lane// bound long ago carries w0 * 0.995^(N-k) — which underflows to the float32// denormal floor and is numerically dead (the readout sees it as zero).// MEASURED on the shipped model/giant-latin: 95.09% of its 1.9M lanes sit// below 1e-12 and the MEDIAN lane weight is 1.4e-43.//// The persisted EVIDENCE LEDGER holds the integral of the growth term the// decay destroyed, so the weight can be rebuilt in CMD §2.3's saturating// form. This group pins that the repair revives dead lanes, is// deterministic, and leaves a healthy fabric alone.// ---------------------------------------------------------------------------static void test_lane_repair() {std::cout << "[lane repair: the dead lanes are recoverable from the ledger]\n";syfox::Engine eng;eng.set_context("test-lane-repair");// teach a few lanesfor (int i = 0; i < 6; ++i) {eng.learn_example("the ticket about payment and refund " + std::to_string(i),"route the ticket", "billing payment team");eng.learn_example("the screen shows an error on login " + std::to_string(i),"route the ticket", "technical hardware team");}const std::size_t lanes0 = eng.substrate().lane_count();CHECK(lanes0 > 0, "learning created lanes");// kill them the way 20k+ lessons of global decay wouldeng.substrate().set_lane_decay(1e-6f);for (int i = 0; i < 3; ++i) {eng.learn_example("another ticket about payment and refund","route the ticket", "billing payment team");}// a DRY RUN reports what the repair would do without touching the fabricconst auto before = eng.repair_lanes(1e-6f, false);CHECK(before.lanes_dead > 0, "the global decay really did kill lanes");CHECK(before.lanes_revivable > 0, "the ledger can revive them");CHECK(before.weight_after > before.weight_before,"the dry run shows the weight the repair would restore");// the repair brings them back from the ledgerconst auto st = eng.repair_lanes(1e-6f);CHECK(st.lanes_repaired > 0, "the ledger could rebuild lanes");// after the repair, no lane the ledger can rebuild is still deadconst auto post = eng.repair_lanes(1e-6f, false);CHECK(post.lanes_revivable == 0,"after the repair no rebuildable lane is still dead");CHECK(st.weight_after > st.weight_before,"total lane weight increased after the repair");// deterministic: the same ledger rebuilds the same weightsconst auto again = eng.repair_lanes(1e-6f);CHECK(std::fabs(again.weight_after - st.weight_after) < 1e-6,"the repair is deterministic");}// ---------------------------------------------------------------------------// v4.0 — THE AFFINITY FIELD READOUT (AFR).//// The fabric learns, for every lesson, the Hebbian affinity between the// state's tokens and the outcome anchor. The legacy readout never reads it:// it samples the field and lets a capped diffusion carry the evidence, so a// query whose wording does NOT reuse the description's vocabulary ties.// AFR reads the same lanes in closed form, against the candidate set as its// own null model. This group pins: the channel is OFF by default (the// replay contract), it is deterministic, and it separates candidates the// legacy readout ties.// ---------------------------------------------------------------------------static void test_affinity_readout() {std::cout << "[affinity field readout: the anchor affinity the legacy readout never reads]\n";syfox::Engine eng;eng.set_context("test-affinity");// "common" is taught with EVERY candidate (a ubiquitous token: it must// cancel against the null model). "zebra" is taught only with "ka".for (int i = 0; i < 40; ++i) {eng.learn_example("common zebra " + std::to_string(i), "ka", "shared");eng.learn_example("common yak " + std::to_string(i), "kb", "shared");eng.learn_example("common emu " + std::to_string(i), "kc", "shared");}const sfx::JV q = sfx::JV::parse(R"({"d":{"type":"choice","instructions":"","criteria":)"R"({"ka":"alpha","kb":"beta","kc":"gamma"}}})");// (1) the channel is OFF by default — the decision is the legacy onesyfox::Usage u0;const auto legacy = eng.decide("common zebra", q, u0);CHECK(eng.affinity_mix() == 0.0f, "the affinity channel is OFF by default");// (2) with the channel ON, the EXCLUSIVE token decides even though the// query shares no vocabulary with any candidate's descriptioneng.set_affinity_mix(1.0f);syfox::Usage u1;const auto aff = eng.decide("common zebra", q, u1);CHECK(aff.size() == 1 && aff[0].choice == "ka","the affinity channel routes through the learned anchor affinity");// (3) deterministic: the same fabric and the same question answer alikesyfox::Usage u2;const auto aff2 = eng.decide("common zebra", q, u2);CHECK(aff2.size() == 1 && aff2[0].choice == aff[0].choice,"the affinity channel is deterministic");// (4) the null model: a ubiquitous token on its own does NOT pick a// candidate — it cancels against the candidate set's prior share.syfox::Usage u3;const auto amb = eng.decide("common", q, u3);CHECK(amb.size() == 1 && (amb[0].choice == legacy[0].choice),"a token bound to every candidate changes nothing");// (5) turning the channel off restores the legacy decision bit-for-biteng.set_affinity_mix(0.0f);syfox::Usage u4;const auto back = eng.decide("common zebra", q, u4);CHECK(back.size() == legacy.size() && back[0].choice == legacy[0].choice,"mix 0 reproduces the legacy decision (replay contract)");}static void test_physics_composition() { std::cout << "[physics composition: fit==decide by construction]\n";const std::string dir = "build/test_physics_composition";const std::string wipe = "rm -rf " + dir;(void)std::system(wipe.c_str());const sfx::JV q = sfx::JV::parse(R"({"route":{"type":"choice","instructions":"route the ticket",)"R"("criteria":{"technical":"hardware team","billing":"payment team"}}})");const char* state = "laptop screen flickers on lid open";const char* teach = "the laptop screen flickers when the lid opens";// (1) a pre-3.9.2 fabric carries NO composition and is bit-identical.{syfox::Engine e;e.learn_example(teach, "route the ticket", "technical hardware team");CHECK(!e.composition().recorded, "fresh fabric carries no recorded composition");e.save_model(dir);CHECK(!std::ifstream(dir + "/physics.json").good(),"no physics.json written for a fabric that never recorded one");syfox::Engine e2;CHECK(e2.load_model(dir), "fabric loads");CHECK(!e2.composition().recorded, "pre-3.9.2 fabric stays composition-free on load");// applying an unset composition must change NOTHINGsyfox::Usage u1, u2;auto before = e2.decide(state, q, u1);e2.apply_composition();auto after = e2.decide(state, q, u2);CHECK(before.size() == after.size() && before[0].choice == after[0].choice,"applying an unset composition leaves the decision identical");}// (2) a recorded composition survives the save/load round trip.{syfox::Engine e;e.load_model(dir);syfox::PhysicsComposition pc;pc.energy_norm = true;pc.diffusion = 0.10f;pc.decay = 0.82f;pc.k_settle = 8;pc.hop_coupling = 0.35f;pc.recorded = true;e.set_composition(pc);e.save_model(dir);CHECK(std::ifstream(dir + "/physics.json").good(),"physics.json written when a composition is recorded");syfox::Engine e2;e2.load_model(dir);CHECK(e2.composition().recorded, "recorded composition survives load");CHECK(e2.composition().energy_norm, "energy gain survives load");CHECK(std::fabs(e2.composition().diffusion - 0.10f) < 1e-6f,"diffusion survives load");// (3) applying the recorded composition reaches the live substratee2.apply_composition();CHECK(e2.energy_norm(), "apply_composition turns the energy gain on");CHECK(std::fabs(e2.substrate().config().diffusion - 0.10f) < 1e-6f,"apply_composition reaches the substrate diffusion");CHECK(std::fabs(e2.substrate().config().decay - 0.82f) < 1e-6f,"apply_composition reaches the substrate decay");}// (4) the calibration fit discloses its coverage (offered vs. seen).{syfox::Engine e;e.load_model(dir);std::vector<sfx::JV> rows;for (int i = 0; i < 5; ++i) {rows.push_back(sfx::JV::parse(R"({"state":"the laptop screen flickers when the lid opens",)"R"("questions":{"route":{"type":"choice","instructions":"route the ticket",)"R"("criteria":{"technical":"hardware team","billing":"payment team"}}},)"R"("labels":{"route":"technical"}})"));}auto calib = e.harvest_rows(rows);CHECK(e.harvest_offered() == 5, "offered question-rows counted");CHECK(calib.size() + e.harvest_dropped_silent() == e.harvest_offered(),"every offered row is either fitted or accounted as dropped");CHECK(e.harvest_dropped_silent() == 0,"a taught state is not dropped as a silent field");}}static void test_v39_gates() {std::cerr << " AT-test_v39_gates\n";std::cout << "[v39 gates: momentum / wavefront / coherence / vght / cem / "395 unmodified linestest_thinking();test_reason();test_v39_gates();test_physics_composition();test_lane_repair();test_affinity_readout();if (failures) { std::cout << failures << " FAILURES\n"; return 1; }std::cout << "all tests passed\n";return 0;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158#!/usr/bin/env python3"""Ablation suite (v3.2.1 BUG #1 verification): do the kill switches matter?
Runs the five paper configs on one eval set through the ctypes bridge:
default | --no-semantics | --no-retrieval | --no-semantics --no-retrieval | --no-hierarchy
and reports per config: accuracy, mean/median confidence, deferrals, plus ananswer-signature distinctness count over the full candidate vector (the papercriterion is >=4 distinct outputs; hierarchy counts only when the model armsit with floor < 1.0 — b77-sem ships floor 1.0 = measured-off, disclosed).
Inertness is disclosed loudly: a pre-v3.2 fabric (no SEM4 tail) or a missingmemories.jsonl/hierarchy.json makes switches no-ops by the replay contract;the tool says so, names the rebuild path, and exits non-zero so a silentnull-ablation can never reach the paper.
Usage: python3 tools/ablation_suite.py --model model-b77-sem \ --eval data/bank77_cal.jsonl [--qkey intent] [--limit 100] [--energy-norm] [--dump out.json]"""import argparseimport jsonimport statisticsimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "server"))from syfox_bridge import SyFoxEngine # noqa: E402
CONFIGS = [ ("default", {}), ("no-semantics", {"semantics": False}), ("no-retrieval", {"retrieval": False}), ("both off", {"semantics": False, "retrieval": False}), ("no-hierarchy", {"hierarchy": False}),]
def model_features(model_dir: Path) -> dict: import struct feats = {"sem_tail": False, "memories": False, "hierarchy": False, "hier_armed": False} sub = model_dir / "substrate.bin" if sub.exists(): b = sub.read_bytes() feats["sem_tail"] = b.find(bytes([0x34, 0x4D, 0x45, 0x53])) >= 0 feats["memories"] = (model_dir / "memories.jsonl").exists() h = model_dir / "hierarchy.json" if h.exists(): try: j = json.loads(h.read_text()) feats["hierarchy"] = True feats["hier_armed"] = float(j.get("floor", 1.0)) < 1.0 except (ValueError, OSError): pass return feats
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--eval", required=True) ap.add_argument("--qkey", default="intent") ap.add_argument("--limit", type=int, default=100) ap.add_argument("--energy-norm", action="store_true") ap.add_argument("--dump", default="") a = ap.parse_args()
mdir = Path(a.model) feats = model_features(mdir) print(f"model={a.model} eval={a.eval} rows<={a.limit} " f"energy_norm={bool(a.energy_norm)}") print(f"features: sem_tail={feats['sem_tail']} " f"memories={feats['memories']} hierarchy={feats['hierarchy']} " f"(armed={feats['hier_armed']})")
blockers = [] if not feats["sem_tail"]: blockers.append( "--no-semantics is inert: no v3.2 SEM4 tail in substrate.bin — " "rebuild first: ./build/rebuild_sem SRC DST (or retrain under v3.2)") if not feats["memories"]: blockers.append("--no-retrieval is inert: no memories.jsonl in the " "model dir (retrieval has nothing to prime)") if not feats["hier_armed"]: blockers.append("--no-hierarchy cannot move the readout: hierarchy.json " "absent or floor=1.0 (gate shipped off by measurement)") for b in blockers: print(f" NOTE: {b}")
rows = [json.loads(l) for l in open(a.eval) if l.strip()][: a.limit] eng = SyFoxEngine(a.model) base = {"semantics": True, "retrieval": True, "hierarchy": True} if a.energy_norm: base["energy_norm"] = True
results, sigs = {}, set() for name, off in CONFIGS: opts = dict(base) opts.update(off) acc_c = conf_c = n_ans = 0 confs, sig = [], "" for r in rows: q = r.get("questions") or {a.qkey: r.get("question")} ans_a, _u, _e = eng.decide(r["state"], q, dict(opts)) ans = ans_a.get(a.qkey, {}) sig += f"{ans.get('choice','')}|{ans.get('confidence',0):.6f};" gold = "" if "labels" in r and r["labels"]: gold = r["labels"].get(a.qkey) or next(iter(r["labels"].values())) if isinstance(gold, dict): gold = gold.get("choice", "") if not ans.get("deferred"): n_ans += 1 confs.append(ans.get("confidence", 0.0)) if gold and ans.get("choice") == gold: acc_c += 1 conf_c += 1 if gold and not ans.get("deferred") \ and ans.get("choice") == gold else 0 results[name] = { "acc_with_defer": round(acc_c / len(rows), 4) if rows else None, "acc_answered": round(acc_c / n_ans, 4) if n_ans else None, "answered": n_ans, "mean_conf": round(statistics.mean(confs), 4) if confs else 0.0, "median_conf": round(statistics.median(confs), 4) if confs else 0.0, } sigs.add(sig) print(f" {name:<14} acc={results[name]['acc_with_defer']} " f"meanC={results[name]['mean_conf']} " f"medC={results[name]['median_conf']}")
armed = len([c for c in CONFIGS if c[0] != "no-hierarchy"]) target = 5 if feats["hier_armed"] else armed print(f"\ndistinct output signatures: {len(sigs)} / {len(CONFIGS)} configs " f"(criterion >= {target}" f"{'' if feats['hier_armed'] else ' — hierarchy ships off, 4 configs count'})") if len(sigs) < target: print("ABLATION BLOCKED: configs are byte-identical — the switches " "moved nothing on this model+input combination.") if not feats["sem_tail"]: print("Root cause: pre-v3.2 fabric (replay contract makes every " "switch a no-op). Rebuild with ./build/rebuild_sem SRC DST.") sys.exit(2) print("ablation OK: the kill switches separate on this model.") if a.dump: with open(a.dump, "w") as f: json.dump({"model": a.model, "eval": a.eval, "rows": len(rows), "features": feats, "configs": results, "distinct": len(sigs)}, f, indent=1) print(f"wrote {a.dump}")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889#!/usr/bin/env python3"""CI gate: every fitted fabric must carry the composition it was fitted under.
A fabric with a fitted `calibration.json` but NO `physics.json` has acalibration of UNKNOWN provenance — it may have been fitted under adecide-side composition different from the one its decisions run under.That is precisely the state that shipped the wrong-answer bug (seedocs/FIT_DECIDE_PARITY.md): the temperature was fitted without thedecide-side energy gain, on 27.7% of the rows, and every answer came backwith ~0.98 confidence whether it was right or wrong.
Exit codes: 0 every fitted fabric carries its composition 2 at least one fitted fabric has an unknown provenance (FAIL) 0 no fitted fabric found (nothing to check — not a failure)
Usage: python3 tools/assert_fit_decide_parity.py model-b77-sem model-router16 ... python3 tools/assert_fit_decide_parity.py --scan model-*"""import globimport jsonimport osimport sys
def check(model_dir): """-> (ok, message, detail)""" cpath = os.path.join(model_dir, "calibration.json") if not os.path.isfile(cpath): return True, f"{model_dir}: no calibration.json (not a calibrated fabric)", {} try: calib = json.load(open(cpath)) except Exception as e: # malformed = unknown provenance return False, f"{model_dir}: calibration.json unreadable ({e}) — re-calibrate", {} if not calib.get("fitted"): return True, f"{model_dir}: calibration not fitted (nothing to check)", calib
ppath = os.path.join(model_dir, "physics.json") if not os.path.isfile(ppath): return (False, f"{model_dir}: FITTED calibration with NO physics.json — the " f"provenance is unknown (fitted T={calib.get('choice_temperature')} " f"over {calib.get('rows')} rows). Re-calibrate under the same " f"decide-side composition the bench runs " f"(e.g. --energy-norm), or the fitted scalars belong to a " f"different engine.", calib) try: phys = json.load(open(ppath)) except Exception as e: return False, f"{model_dir}: physics.json unreadable ({e})", calib if not phys.get("recorded"): return False, f"{model_dir}: physics.json present but not recorded", calib return (True, f"{model_dir}: OK — fitted T={calib.get('choice_temperature')} over " f"{calib.get('rows')} rows, composition " f"energy_norm={phys.get('energy_norm')} diffusion={phys.get('diffusion')}", {"calib": calib, "phys": phys})
def main(): args = [a for a in sys.argv[1:] if not a.startswith("--")] dirs = [] for a in args: dirs.extend(sorted(glob.glob(a)) if any(ch in a for ch in "*?[") else [a]) if not dirs: print("assert_fit_decide_parity: no model dirs given — nothing to check") return 0
failures = 0 checked = 0 for d in dirs: if not os.path.isdir(d): print(f"assert_fit_decide_parity: skip (not a dir): {d}") continue checked += 1 ok, msg, _ = check(d) print((" ok " if ok else " FAIL ") + msg) if not ok: failures += 1
print(f"\nassert_fit_decide_parity: {checked - failures}/{checked} fabrics " f"carry a known calibration provenance") return 2 if failures else 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516#!/usr/bin/env python3"""CI assertion: `decide --router` must produce a usable route field.Reads one decide JSON on stdin; exits non-zero unless the route carries ananchor, a confidence, and a mapped model (BUG #3 regression gate)."""import jsonimport sys
d = json.load(sys.stdin)r = d.get("route", {})ok = (r.get("anchor") in {"rt%02d" % i for i in range(16)} and isinstance(r.get("confidence"), (int, float)) and bool(r.get("model")))if not ok: print(f"route assertion FAILED: {json.dumps(r)}", file=sys.stderr) sys.exit(2)print(f"route OK: {r['anchor']} conf={r['confidence']} -> {r['model']}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/usr/bin/env python3"""b77_ablation_compare.py — per-intent A/B of two bench per-row dumps(v3.9.1, e.g. semantics ON vs --no-semantics) sharing the same eval file.
Joins on the dump "row" field (the eval row index), reports per-intentaccuracy and honest flips (A wrong -> B correct and vice versa), plus theconfusion-pair migration between the two runs."""import argparseimport jsonfrom collections import Counterfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--dump-a", required=True, help="config A dump") ap.add_argument("--dump-b", required=True, help="config B dump") ap.add_argument("--name-a", default="A") ap.add_argument("--name-b", default="B") args = ap.parse_args()
A = {json.loads(l)["row"]: json.loads(l) for l in open(args.dump_a) if l.strip()} B = {json.loads(l)["row"]: json.loads(l) for l in open(args.dump_b) if l.strip()} common = sorted(set(A) & set(B)) if not common: print("no common rows — same eval file?", file=sys.stderr) raise SystemExit(2)
acc_a = sum(A[i]["pred"] == A[i]["gold"] for i in common) / len(common) acc_b = sum(B[i]["pred"] == B[i]["gold"] for i in common) / len(common) print(f"rows {len(common)} {args.name_a} acc {acc_a:.4f} " f"{args.name_b} acc {acc_b:.4f} delta {acc_b - acc_a:+.4f}")
a_ok = {i: A[i]["pred"] == A[i]["gold"] for i in common} b_ok = {i: B[i]["pred"] == B[i]["gold"] for i in common} fixed = [i for i in common if not a_ok[i] and b_ok[i]] broken = [i for i in common if a_ok[i] and not b_ok[i]] print(f"flips: {args.name_a} wrong -> {args.name_b} correct: {len(fixed)} " f"{args.name_a} correct -> {args.name_b} wrong: {len(broken)}")
cats = json.loads((ROOT / "data" / "bank77_categories.json").read_text()) natural = {v: k for k, v in cats["label_of"].items()} by_gold = {} for i in common: by_gold.setdefault(A[i]["gold"], []).append(i) print(f"\n{'gold intent':46s} {'n':>4s} {'A acc':>6s} {'B acc':>6s} {'delta':>7s}") rows = [] for g, idxs in sorted(by_gold.items()): aa = sum(a_ok[i] for i in idxs) / len(idxs) bb = sum(b_ok[i] for i in idxs) / len(idxs) rows.append((bb - aa, g, len(idxs), aa, bb)) rows.sort() for d, g, n, aa, bb in rows: print(f"{g+'='+natural.get(g,'?'):46s} {n:4d} {aa:6.3f} {bb:6.3f} {d:+7.3f}")
mig = Counter((A[i]["pred"], B[i]["pred"]) for i in common if A[i]["pred"] != B[i]["pred"]) print("\nprediction migrations (A pred -> B pred, n):") for (pa, pb), n in mig.most_common(10): print(f" {pa}={natural.get(pa,'?'):44s} -> {pb}={natural.get(pb,'?'):44s} {n}")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970#!/usr/bin/env python3"""b77_apply_policy.py — score a derived defer-threshold policy on a FRESHdump (the hidden split), never the split the policy was derived on (v3.9.1).
Usage: syfox bench --model model-b77-sem --eval data/bank77_hidden.jsonl ... \ --dump-perrow /tmp/hidden_dump.jsonl # scoring pass (read-only) python3 tools/b77_margin_sweep.py --dump cal_dump --mode per-intent \ --out cal_thresholds.json # derivation (CAL only) python3 tools/b77_apply_policy.py --dump hidden_dump \ --policy cal_thresholds.json # THIS TOOL
The policy maps the PREDICTED intent (never gold) to a raw-margin threshold:answer iff raw_margin >= thr(pred); rows below defer. Reports the overallhonest total and the per-intent table with natural names."""import argparseimport jsonfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--dump", required=True) ap.add_argument("--policy", required=True) ap.add_argument("--tag", default="", help="label for the report line") args = ap.parse_args()
pol = json.loads(Path(args.policy).read_text()) thr_map = pol["thresholds"] if "thresholds" in pol else pol thr_of = lambda pred: float(thr_map.get(pred, {}).get("threshold", 0.0))
rows = [json.loads(l) for l in open(args.dump) if l.strip()] answered = [r for r in rows if r["raw_margin"] >= thr_of(r["pred"])] correct = sum(1 for r in answered if r["pred"] == r["gold"]) n = len(rows) overall = { "n": n, "answered": len(answered), "correct": correct, "acc_answered": round(correct / len(answered), 4) if answered else 0.0, "honest_total": round(correct / n, 4) if n else 0.0, "defer_rate": round(1 - len(answered) / n, 4) if n else 0.0, }
cats = json.loads((ROOT / "data" / "bank77_categories.json").read_text()) natural = {v: k for k, v in cats["label_of"].items()} by_gold = {} for r in rows: by_gold.setdefault(r["gold"], []).append(r) print(f"policy {args.tag or args.policy} on {args.dump}") print(f"overall: answered {overall['answered']}/{n} correct {overall['correct']} " f"acc_answered {overall['acc_answered']} honest_total {overall['honest_total']} " f"defer {overall['defer_rate']}") print(f"{'gold intent':46s} {'n':>4s} {'ans':>4s} {'correct':>7s} {'honest':>6s} {'acc_ans':>7s}") out_rows = [] for g, rs in sorted(by_gold.items()): ans = [r for r in rs if r["raw_margin"] >= thr_of(r["pred"])] c = sum(1 for r in ans if r["pred"] == g) ht = c / len(rs) aa = c / len(ans) if ans else 0.0 out_rows.append((ht, g, len(rs), len(ans), c, aa)) out_rows.sort(key=lambda t: (t[0], t[1])) for ht, g, ntot, nans, c, aa in out_rows: print(f"{g+'='+natural.get(g,'?'):46s} {ntot:4d} {nans:4d} {c:7d} {ht:6.3f} {aa:7.3f}") print("json:", json.dumps({"tag": args.tag, "overall": overall}))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174#!/usr/bin/env python3"""b77_confusion_report.py — render a bench --confusion JSON into theintra-category diagnostics views (v3.9.1).
Inputs --bench bench JSON (from `syfox bench ... --confusion`) --dump optional per-row dump (bench --dump-perrow) for reason anatomyViews 1. full 77x77 matrix: per-class row table (n, answered, acc, honest, worst confusion target) with natural intent names. 2. card_management 22x22 + OTHER row/col: the intra-category binding constraint view (category membership = the shipped bank77_hier.py card_management rule, applied over data/bank77_categories.json). 3. top confusion pairs over the whole matrix.
Every number comes from the bench JSON / dump produced by an actual run;nothing is simulated here."""import argparseimport jsonimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
# card_management membership — the SAME priority-ordered rules bank77_hier.py# ships (top_up > withdrawal > transfer > card_payment > exchange_rate ># card_management > ...). Duplicating the rule here keeps the diagnostic# view consistent with the fabric's own category lessons.RULES = [ ("top_up", lambda n: "top_up" in n or "topping_up" in n), ("withdrawal", lambda n: "withdrawal" in n or "cash_received" in n or n == "atm_support"), ("transfer", lambda n: "transfer" in n or n in ("beneficiary_not_allowed", "receiving_money")), ("card_payment", lambda n: "card_payment" in n or n in ("transaction_charged_twice", "extra_charge_on_statement", "exchange_charge", "reverted_card_payment?", "declined_card_payment", "pending_card_payment")), ("exchange_rate", lambda n: "exchange" in n or n in ("fiat_currency_support", "supported_cards_and_currencies", "visa_or_mastercard")), ("card_management", lambda n: "card" in n or n in ("contactless_not_working", "passcode_forgotten", "pin_blocked", "change_pin", "apple_pay_or_google_pay", "lost_or_stolen_card", "activate_my_card")), ("refund", lambda n: "refund" in n), ("verify_identity", lambda n: "identity" in n or "verify" in n or n in ("age_limit", "country_support", "edit_personal_details", "terminate_account", "lost_or_stolen_phone")),]
def category_of(natural: str) -> str: for cat, fn in RULES: if fn(natural): return cat return "other"
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--bench", required=True) ap.add_argument("--dump", default="") ap.add_argument("--card-only", action="store_true", help="print only the card_management view") args = ap.parse_args()
d = json.loads(Path(args.bench).read_text()) conf = d.get("confusion") if not conf: print("bench JSON has no confusion block (run bench with --confusion)", file=sys.stderr) sys.exit(2) labels = conf["labels"] mat = conf["matrix"] cats = json.loads((ROOT / "data" / "bank77_categories.json").read_text()) natural = {v: k for k, v in cats["label_of"].items()} # cNN -> name
# ---- per-class full table ---------------------------------------------- routing = d["routing"] acc_all = routing["choice_accuracy"] if not args.card_only: print(f"model {d['model']} eval {d['eval_source']} rows {d['rows']} " f"acc(answered) {acc_all} defer {routing['choice_defer_rate']} " f"honest_total {round(acc_all * (1 - routing['choice_defer_rate']), 4)}") print(f"{'gold':42s} {'n':>4s} {'ans':>4s} {'acc':>6s} {'honest':>6s} worst confusion") rows_out = [] for i, g in enumerate(labels): if g == "DEFER": continue row = mat[i] n_tot = sum(row) n_ans = n_tot - row[labels.index("DEFER")] if "DEFER" in labels else n_tot correct = row[i] acc_ans = correct / n_ans if n_ans else 0.0 honest = correct / n_tot if n_tot else 0.0 worst_n, worst_j = 0, -1 for j, v in enumerate(row): if j != i and j < len(labels) and labels[j] != "DEFER" and v > worst_n: worst_n, worst_j = v, j worst = f"{labels[worst_j]}={natural.get(labels[worst_j],'?')}({worst_n})" if worst_j >= 0 else "-" rows_out.append((honest, g, n_tot, n_ans, acc_ans, worst)) rows_out.sort(key=lambda t: (t[0], t[1])) for honest, g, n_tot, n_ans, acc_ans, worst in rows_out: print(f"{g+'='+natural.get(g,'?'):42s} {n_tot:4d} {n_ans:4d} " f"{acc_ans:6.3f} {honest:6.3f} {worst}")
# ---- card_management 22x22 + OTHER ------------------------------------- card = [c for c in cats["classes"] if category_of(c) == "card_management"] card_ids = sorted(cats["label_of"][c] for c in card) view = card_ids + ["OTHER"] idx = {l: i for i, l in enumerate(labels)} print(f"\ncard_management view ({len(card_ids)} intents + OTHER) " f"rows=gold cols=pred:") hdr = "gold\\pred".ljust(38) + "".join(c.replace("c", "").rjust(5) for c in card_ids) + "OTH".rjust(6) print(hdr) agg = {} for g in card_ids + ["OTHER"]: golds = card_ids if g == "OTHER" else [g] rowsum = [0] * (len(card_ids) + 1) n_tot = 0 for gg in golds: if gg not in idx: continue i = idx[gg] for j, l in enumerate(labels): v = mat[i][j] if l == "DEFER": continue col = card_ids.index(l) if l in card_ids else len(card_ids) rowsum[col] += v if l in card_ids or gg in card_ids: pass if gg in card_ids: n_tot += sum(x for j, x in enumerate(mat[i]) if labels[j] != "DEFER") agg[g] = (rowsum, n_tot) name = (natural.get(g, "ALL_OTHER") if g != "OTHER" else "ALL_OTHER") print((g + "=" + name).ljust(38)[:38] + "".join(str(v).rjust(5) for v in rowsum[:len(card_ids)]) + str(rowsum[-1]).rjust(6)) print("\ncard_management per-intent honest totals:") print(f"{'intent':44s} {'n':>4s} {'correct':>7s} {'honest':>6s} {'acc_ans':>7s}") tot_c = tot_n = 0 for g in card_ids: rowsum, n_tot = agg[g] correct = rowsum[card_ids.index(g)] acc_ans = correct / n_tot if n_tot else 0.0 tot_c += correct tot_n += n_tot print(f"{g+'='+natural.get(g,'?'):44s} {n_tot:4d} {correct:7d} " f"{(correct / n_tot if n_tot else 0):6.3f} {acc_ans:7.3f}") print(f"{'card_management TOTAL':44s} {tot_n:4d} {tot_c:7d} " f"{(tot_c / tot_n if tot_n else 0):6.3f}")
# ---- top pairs ---------------------------------------------------------- if not args.card_only: print("\ntop confusion pairs (gold -> pred, n):") for p in conf.get("pairs_top", [])[:15]: print(f" {p['gold']}={natural.get(p['gold'],'?'):44s} -> " f"{p['pred']}={natural.get(p['pred'],'?'):44s} {p['n']}")
# ---- defer reason anatomy from the dump --------------------------------- if args.dump: from collections import Counter rows = [json.loads(l) for l in open(args.dump)] reasons = Counter(r["reason"] for r in rows if r["deferred"]) print("\ndefer reasons (dump):", dict(reasons) if reasons else "none — all rows answered")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102#!/usr/bin/env python3"""b77_freq_cut.py — the class-frequency cut (v3.9.1 Task 0.5).
Per-intent accuracy vs per-intent TRAIN ROW COUNT. High correlation wouldpoint at a data problem (thin classes fail); low correlation points at amodel problem (confusable classes fail at any count — banking77 is nearlybalanced, so this is the expected outcome; MEASURE, do not assume).
Counts come from the train split file (gold labels), accuracy from a benchper-row dump. Reports Pearson r and Spearman rho with permutation-freet-statistics, plus the ranked per-intent table."""import argparseimport jsonimport mathfrom collections import Counterfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def pearson(x, y): n = len(x) mx, my = sum(x) / n, sum(y) / n sxx = sum((a - mx) ** 2 for a in x) syy = sum((b - my) ** 2 for b in y) sxy = sum((a - mx) * (b - my) for a, b in zip(x, y)) if sxx <= 0 or syy <= 0: return 0.0 r = sxy / math.sqrt(sxx * syy) t = r * math.sqrt((n - 2) / max(1e-12, 1 - r * r)) return r, t
def spearman(x, y): def ranks(v): order = sorted(range(len(v)), key=lambda i: v[i]) rk = [0.0] * len(v) i = 0 while i < len(order): j = i while j + 1 < len(order) and v[order[j + 1]] == v[order[i]]: j += 1 avg = (i + j) / 2.0 for k in range(i, j + 1): rk[order[k]] = avg i = j + 1 return rk return pearson(ranks(x), ranks(y))
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--dump", required=True, help="bench per-row dump") ap.add_argument("--train", default="data/bank77_train.jsonl") ap.add_argument("--label-key", default="labels") args = ap.parse_args()
counts = Counter() with open(ROOT / args.train) as f: for line in f: if not line.strip(): continue r = json.loads(line) lab = r.get(args.label_key, {}) if isinstance(lab, dict) and lab: counts[next(iter(lab.values()))] += 1
rows = [json.loads(l) for l in open(args.dump) if l.strip()] by_gold = {} for r in rows: by_gold.setdefault(r["gold"], []).append(r)
xs, ys, table = [], [], [] for g, rs in sorted(by_gold.items()): n_train = counts.get(g, 0) n_tot = len(rs) correct = sum(1 for r in rs if r["pred"] == g) acc = correct / n_tot xs.append(float(n_train)) ys.append(acc) table.append((g, n_train, n_tot, correct, acc))
r, t_r = pearson(xs, ys) rho, t_rho = spearman(xs, ys) print(f"intents scored: {len(xs)} train counts: min {min(xs):.0f} " f"max {max(xs):.0f} mean {sum(xs)/len(xs):.1f}") print(f"Pearson r (accuracy vs train count): {r:+.3f} (t={t_r:+.2f}, " f"df={len(xs)-2})") print(f"Spearman rho : {rho:+.3f} (t={t_rho:+.2f})") print(f"accuracy spread: min {min(ys):.3f} max {max(ys):.3f} " f"train-count spread: {max(xs)-min(xs):.0f} rows") verdict = ("DATA problem (thin classes fail)" if abs(r) > 0.5 else "MODEL problem (accuracy does not track class frequency)") print(f"verdict (|r|>0.5 cut): {verdict}") print(f"\n{'intent':6s} {'train':>6s} {'n':>4s} {'correct':>7s} {'acc':>6s}") for g, ntr, ntot, c, acc in sorted(table, key=lambda t: t[4]): print(f"{g:6s} {ntr:6d} {ntot:4d} {c:7d} {acc:6.3f}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116#!/usr/bin/env python3"""b77_margin_sweep.py — defer-threshold sweep + per-intent thresholdderivation, OFFLINE from one bench per-row dump (v3.9.1).
The dump (bench --dump-perrow) carries, per choice question, the RAWpre-temperature top-2 energy gap ("raw_margin") and the prediction. The rawgap is the physical quantity a threshold policy can act on: the shippedbank77 fabric's fitted calibration temperature (0.0019, measured) saturatesthe post-temperature probability gap at ~1, so a probability-margin sweepwould be inert (this is itself a documented finding).
Discipline: * derive on CAL only; score the chosen policy on HIDDEN with b77_apply_policy.py (never tune and score on the same split). * thresholds are keyed by the PREDICTED intent (at inference the policy sees pred, never gold).
Modes: --mode global sweep one global threshold over the grid. --mode per-intent per-intent threshold = argmax of per-intent honest total (correct / class total) on the sweep split; intents with fewer than --min-rows keep the global best.Outputs JSON with the sweep table and (per-intent mode) the threshold map."""import argparseimport jsonfrom pathlib import Path
GRID = [round(0.01 * i, 2) for i in range(0, 21)] # 0.00 .. 0.20
def honest(rows, thr_of): """rows: list of dump records. thr_of(pred) -> threshold. Policy: answer iff raw_margin >= thr(pred); correct iff pred == gold. Deferred wrong rows cost nothing; honest total = correct / n.""" n = len(rows) if n == 0: return {"n": 0, "answered": 0, "correct": 0, "acc_answered": 0.0, "honest_total": 0.0, "defer_rate": 0.0} answered = [r for r in rows if r["raw_margin"] >= thr_of(r["pred"])] correct = sum(1 for r in answered if r["pred"] == r["gold"]) return {"n": n, "answered": len(answered), "correct": correct, "acc_answered": round(correct / len(answered), 4) if answered else 0.0, "honest_total": round(correct / n, 4), "defer_rate": round(1 - len(answered) / n, 4)}
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--dump", required=True) ap.add_argument("--mode", choices=["global", "per-intent"], default="global") ap.add_argument("--min-rows", type=int, default=8, help="per-intent rows below this keep the global best") ap.add_argument("--out", default="") args = ap.parse_args()
rows = [json.loads(l) for l in open(args.dump) if l.strip()]
if args.mode == "global": sweep = [] for t in GRID: h = honest(rows, lambda pred, t=t: t) sweep.append({"threshold": t, **h}) best = max(sweep, key=lambda s: (s["honest_total"], s["answered"], -s["threshold"])) doc = {"dump": args.dump, "mode": "global", "sweep": sweep, "best": best} print(f"{'thr':>5s} {'answered':>9s} {'correct':>8s} {'acc_ans':>8s} {'honest':>7s} {'defer':>6s}") for s in sweep: mark = " <- best" if s is best else "" print(f"{s['threshold']:5.2f} {s['answered']:9d} {s['correct']:8d} " f"{s['acc_answered']:8.4f} {s['honest_total']:7.4f} {s['defer_rate']:6.3f}{mark}") else: # global best first (fallback for thin intents) best_g, best_h = None, -1.0 for t in GRID: h = honest(rows, lambda pred, t=t: t) if h["honest_total"] > best_h or (h["honest_total"] == best_h and best_g is not None and t < best_g): best_g, best_h = t, h["honest_total"] by_pred = {} for r in rows: by_pred.setdefault(r["pred"], []).append(r) per, n_custom = {}, 0 for pred, rs in sorted(by_pred.items()): if len(rs) < args.min_rows: per[pred] = {"threshold": best_g, "rows": len(rs), "honest_total": honest(rs, lambda _, t=best_g: t)["honest_total"], "source": "global_fallback"} continue best_t, best_ht, best_aa = best_g, -1.0, -1.0 for t in GRID: h = honest(rs, lambda _, t=t: t) if (h["honest_total"], h["acc_answered"], -t) > (best_ht, best_aa, -best_t): best_t, best_ht, best_aa = t, h["honest_total"], h["acc_answered"] if best_t != best_g: n_custom += 1 per[pred] = {"threshold": best_t, "rows": len(rs), "honest_total": round(best_ht, 4), "acc_answered": round(best_aa, 4), "source": "per_intent"} overall = honest(rows, lambda pred: per[pred]["threshold"]) doc = {"dump": args.dump, "mode": "per-intent", "min_rows": args.min_rows, "global_best": best_g, "thresholds": per, "policy_overall": overall, "custom_intents": n_custom} print(f"global best threshold {best_g} (honest {best_h}); " f"{n_custom} intents got a custom threshold " f"(min_rows {args.min_rows})") print(f"policy overall: answered {overall['answered']}/{overall['n']} " f"correct {overall['correct']} acc_ans {overall['acc_answered']} " f"honest_total {overall['honest_total']} defer {overall['defer_rate']}")
if args.out: Path(args.out).write_text(json.dumps(doc, indent=1) + "\n") print(f"json -> {args.out}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168#!/usr/bin/env python3"""banking77 manual benchmark — per-row error anatomy on the cal split.
Loads a SyFox fabric through the ctypes bridge, decides EVERY row with fullprobabilities, and reports the structure the aggregate number hides: top-1/3/5 accuracy, gold-rank histogram, margin (p1-p2) distribution, confidence-when-wrong vs confidence-when-correct, worst confusion pairs, per-class accuracy (worst 15), and deferral anatomy.Model/config selection stays on cal; hidden is only run for the final report."""import argparseimport jsonimport sysfrom collections import Counterfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "server"))from syfox_bridge import SyFoxEngine # noqa: E402
def rank_of(gold: str, probs: dict) -> int: order = sorted(probs.items(), key=lambda kv: -kv[1]) for i, (k, _) in enumerate(order, 1): if k == gold: return i return len(order) + 1
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--eval", default="data/bank77_cal.jsonl") ap.add_argument("--limit", type=int, default=0, help="cap rows (0 = all)") ap.add_argument("--dump", default="", help="write per-row JSONL here") ap.add_argument("--arbitrate", action="store_true", help="product-of-experts: flat decide, then re-rank the " "top-5 candidates by bare-anchor readout energy " "(independent second view of the same field)") ap.add_argument("--hierarchical", action="store_true", help="two-stage readout: stage 1 = choice over group " "anchor bundles (member c## anchors), stage 2 = " "re-decide within the winning group. Caller-side " "orchestration only; same substrate, same physics.") args = ap.parse_args()
eng = SyFoxEngine(args.model) rows = [json.loads(l) for l in open(args.eval)] if args.limit: rows = rows[: args.limit]
hier = None if args.hierarchical: cat = json.load(open("data/bank77_categories.json")) lmap = cat["label_of"] # class name -> cNN groups: dict[str, list[str]] = {} for cls in cat["classes"]: groups.setdefault(cls.split("_")[0], []).append(lmap[cls]) hier = groups print(f"hierarchical: {len(groups)} groups, sizes " f"{sorted((len(v) for v in groups.values()), reverse=True)[:6]}+") hier_rows = [] for r in rows: crit = r["questions"]["intent"]["criteria"] gq = {"intent": {"type": "choice", "instructions": "", "criteria": {g: ", ".join(ms) for g, ms in groups.items()}}} hier_rows.append(gq)
recs, defers, hier_ok, hier_scored = [], 0, 0, 0 for i, r in enumerate(rows): answers, usage, _ = eng.decide(r["state"], r["questions"], {"energy_norm": True}) if args.arbitrate and not answers["intent"].get("deferred"): a0 = answers["intent"] top5 = [k for k, _ in sorted(a0["probabilities"].items(), key=lambda kv: -kv[1])[:5]] crit = r["questions"]["intent"]["criteria"] aq = {"intent": {"type": "choice", "instructions": "", "criteria": {m: "" for m in top5}}} aa, _, _ = eng.decide(r["state"], aq, {"energy_norm": True}) if not aa["intent"].get("deferred"): pa = aa["intent"]["probabilities"] pf = a0["probabilities"] combo = {m: pf.get(m, 0) * pa.get(m, 0) for m in top5} answers["intent"]["choice"] = max(combo, key=combo.get) if hier is not None: ga, _, _ = eng.decide(r["state"], hier_rows[i], {"energy_norm": True}) g = ga["intent"].get("choice") members = hier.get(g, []) if len(members) == 1: sub_pred = members[0] elif members: crit = r["questions"]["intent"]["criteria"] sq = {"intent": {"type": "choice", "instructions": "", "criteria": {m: crit[m] for m in members}}} sa, _, _ = eng.decide(r["state"], sq, {"energy_norm": True}) sub_pred = sa["intent"].get("choice") else: sub_pred = None gold_c = r["labels"]["intent"] hier_scored += 1 hier_ok += (sub_pred == gold_c) a = answers["intent"] gold = r["labels"]["intent"] if a.get("deferred"): defers += 1 recs.append({"i": i, "gold": gold, "deferred": True}) continue probs = a["probabilities"] top = sorted(probs.items(), key=lambda kv: -kv[1]) p1, p2 = top[0][1], (top[1][1] if len(top) > 1 else 0.0) recs.append({ "i": i, "state": r["state"], "gold": gold, "pred": a.get("choice"), "correct": a.get("choice") == gold, "gold_p": round(probs.get(gold, 0.0), 5), "gold_rank": rank_of(gold, probs), "margin": round(p1 - p2, 5), "conf": a.get("confidence", 0), "top3": [k for k, _ in top[:3]], })
scored = [r for r in recs if not r.get("deferred")] n = len(scored) if n == 0: print(f"ALL {len(recs)} rows deferred — nothing to score") return acc1 = sum(r["correct"] for r in scored) / n acc3 = sum(r["gold_rank"] <= 3 for r in scored) / n acc5 = sum(r["gold_rank"] <= 5 for r in scored) / n cw = [r["conf"] for r in scored if r["correct"]] ww = [r["conf"] for r in scored if not r["correct"]] mg_c = [r["margin"] for r in scored if r["correct"]] mg_w = [r["margin"] for r in scored if not r["correct"]]
print(f"rows={len(rows)} deferred={defers} ({defers/len(rows):.1%}) scored={n}") if hier is not None: print(f"HIERARCHICAL top-1: {hier_ok}/{hier_scored} = {hier_ok/hier_scored:.3f}") print(f"top-1 {acc1:.3f} top-3 {acc3:.3f} top-5 {acc5:.3f} (chance {1/77:.3f})") if cw: print(f"conf when correct {sum(cw)/len(cw):.3f} vs wrong {sum(ww)/len(ww):.3f}") if mg_c: print(f"margin when correct {sum(mg_c)/len(mg_c):.4f} vs wrong {sum(mg_w)/len(mg_w):.4f}")
hist = Counter(min(r["gold_rank"], 78) for r in scored) bands = [(1, 1), (2, 2), (3, 5), (6, 10), (11, 20), (21, 40), (41, 77)] print("gold-rank bands:", " ".join( f"{a}-{b}:{sum(v for k, v in hist.items() if a <= k <= b)/n:.1%}" for a, b in bands))
conf = Counter((r["gold"], r["pred"]) for r in scored if not r["correct"]) print("worst confusion pairs:") for (g, p), c in conf.most_common(10): print(f" {g:28s} -> {p:28s} {c}")
per_class = {} for r in scored: t, c = per_class.get(r["gold"], (0, 0)) per_class[r["gold"]] = (t + 1, c + (1 if r["correct"] else 0)) worst = sorted(per_class.items(), key=lambda kv: kv[1][1] / max(1, kv[1][0]))[:15] print("worst classes:", ", ".join( f"{k}:{c}/{t}" for k, (t, c) in worst))
if args.dump: with open(args.dump, "w") as f: for r in recs: f.write(json.dumps(r, ensure_ascii=False) + "\n") print(f"per-row dump -> {args.dump}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169#!/usr/bin/env python3# ============================================================================# bank77_hier.py — v3.2 Stage 3 (semantic hierarchy) + Stage 4 prep for the# DEDICATED bank77 fabric.## What it emits (deterministic, seed-free):# data/bank77_hier_train.jsonl — the v3.1.0 opaque/empty-instructions rows# PLUS one category lesson per row (interleaved intent/category), so# BOTH levels of the hierarchy are trained anchors in one fabric.# data/bank77_hierarchy.json — ships into the model dir as hierarchy.json:# {"intents": {cNN: h_<cat>}, "categories": {h_<cat>: {"criteria": ...}},# "floor": 0.35}# data/bank77_memories.jsonl — stride-sampled lived experiences for# retrieval-by-default ({"label": cNN, "state": text}).## Category assignment is prefix/keyword rules over the NATURAL intent names# (Banking77's own naming), applied in priority order — top_up wins over# transfer because "top_up_by_bank_transfer_charge" contains both words.# No ML anywhere: this is a deterministic labeling function + the criteria# miner already shipped in v3.1.0.# ============================================================================import argparseimport jsonfrom pathlib import Path
RULES = [ ("top_up", lambda n: "top_up" in n or "topping_up" in n), ("withdrawal", lambda n: "withdrawal" in n or "cash_received" in n or n == "atm_support"), ("transfer", lambda n: "transfer" in n or n in ("beneficiary_not_allowed", "receiving_money")), ("card_payment", lambda n: "card_payment" in n or n in ("transaction_charged_twice", "extra_charge_on_statement", "exchange_charge", "reverted_card_payment?", "declined_card_payment", "pending_card_payment")), ("exchange_rate", lambda n: "exchange" in n or n in ("fiat_currency_support", "supported_cards_and_currencies", "visa_or_mastercard")), ("card_management", lambda n: "card" in n or n in ("contactless_not_working", "passcode_forgotten", "pin_blocked", "change_pin", "apple_pay_or_google_pay", "lost_or_stolen_card", "activate_my_card")), ("refund", lambda n: "refund" in n), ("verify_identity", lambda n: "identity" in n or "verify" in n or n in ("age_limit", "country_support", "edit_personal_details", "terminate_account", "lost_or_stolen_phone")),]
def category_of(natural: str) -> str: n = natural.lower() for name, rule in RULES: if rule(n): return name return "account_other"
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--train", default="data/bank77_train.jsonl") ap.add_argument("--criteria", default="data/bank77_criteria.json") ap.add_argument("--categories", default="data/bank77_categories.json") ap.add_argument("--out-train", default="data/bank77_hier_train.jsonl") ap.add_argument("--out-hierarchy", default="data/bank77_hierarchy.json") ap.add_argument("--out-memories", default="data/bank77_memories.jsonl") ap.add_argument("--memories", type=int, default=256, help="stride-sampled memories for retrieval-by-default") ap.add_argument("--cat-words-per-intent", type=int, default=8) ap.add_argument("--floor", type=float, default=0.35) args = ap.parse_args()
cats = json.loads(Path(args.categories).read_text()) label_of = cats["label_of"] # natural -> cNN anchor_of = {natural: label_of[natural] for natural in cats["classes"]}
# intent -> category (assert full coverage) cat_of_intent, members = {}, {} for natural in cats["classes"]: cat = category_of(natural) cat_of_intent[anchor_of[natural]] = cat members.setdefault(cat, []).append(natural) covered = sum(len(v) for v in members.values()) assert covered == len(cats["classes"]), f"category rules lost {covered} != 77" print(f"categories ({len(members)}):") for cat in sorted(members): print(f" {cat:16s} {len(members[cat]):2d} intents")
# category criteria: union of member intents' mined criteria words crit = json.loads(Path(args.criteria).read_text()) crit = crit["criteria"] if isinstance(crit.get("criteria"), dict) else crit # keyed by NATURAL intent name ("w, w, ..." comma text) def words_of(natural: str) -> list: v = crit.get(natural, []) if isinstance(v, str): return [w.strip() for w in v.split(",") if w.strip()] return list(v)
cat_criteria = {} for cat, naturals in members.items(): seen, words = set(), [] for natural in naturals: for w in words_of(natural)[: args.cat_words_per_intent]: if w.lower() not in seen: seen.add(w.lower()) words.append(w) cat_criteria["h_" + cat] = " ".join(words[: 3 * args.cat_words_per_intent])
hierarchy = { "intents": {a: "h_" + c for a, c in cat_of_intent.items()}, "categories": {"h_" + c: {"criteria": cat_criteria["h_" + c]} for c in members}, "floor": args.floor, } Path(args.out_hierarchy).write_text(json.dumps(hierarchy, indent=1)) print(f"wrote {args.out_hierarchy}")
# training rows: original (intent) rows + category rows, interleaved n_intent = n_cat = 0 with open(args.train) as src, open(args.out_train, "w") as dst: for line in src: if not line.strip(): continue row = json.loads(line) dst.write(json.dumps(row, ensure_ascii=False) + "\n") n_intent += 1 # category twin of the same state: labels.hier = h_<cat> try: anchor = row["labels"]["intent"] except KeyError: continue cat = cat_of_intent.get(anchor) if cat is None: continue crow = { # "hier " prefix: the category twin must NOT collide with the # intent lesson in the contradiction detector (same state text # + a different outcome = false dispute; the audit ledger would # fill with counter-evidence against the intent binding). "state": "hier " + row["state"], "questions": {"hier": { "type": "choice", "instructions": "", "criteria": {"h_" + cat: cat_criteria["h_" + cat]}, }}, "labels": {"hier": "h_" + cat}, } dst.write(json.dumps(crow, ensure_ascii=False) + "\n") n_cat += 1 print(f"wrote {args.out_train}: {n_intent} intent + {n_cat} category lessons")
# retrieval memories: stride sample (deterministic) rows = [] with open(args.train) as src: for line in src: if line.strip(): rows.append(json.loads(line)) stride = max(1, len(rows) // max(1, args.memories)) picked = rows[::stride][: args.memories] with open(args.out_memories, "w") as dst: for row in picked: dst.write(json.dumps({ "label": row["labels"]["intent"], "state": row["state"], }, ensure_ascii=False) + "\n") print(f"wrote {args.out_memories}: {len(picked)} memories (stride {stride})")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224#!/usr/bin/env python3"""banking77 → SyFox data pipeline (M1 discipline).
Real dataset: PolyAI banking77 (10,003 train / 3,080 test CSV rows, 77 intents).
Splits (hidden-test firewall applies by filename suffix): data/bank77_train.jsonl 90% of the official train split -> learn may read data/bank77_cal.jsonl 10% of the official train split -> calibrate only data/bank77_hidden.jsonl the official test split (3,080) -> bench ONLY
Per-class criteria are MINED FROM THE TRAIN SPLIT ONLY (never cal, neverhidden) — distinctive-term log-ratio with smoothing, unigrams + bigrams,min in-class count. The same mined string is written into every row'scriteria object, so learn (teaches label + criteria text) and decide (probeslabel + criteria text) see identical anchors."""import argparseimport csvimport hashlibimport jsonimport mathimport randomimport refrom collections import Counter, defaultdictfrom pathlib import Path
TOKEN = re.compile(r"[a-z0-9']+")
# readout noise control: stopword fragments steal direct-term hits from every# row (measured: class wrong_exchange_rate mined "was different", "and bit",# "known" -> it absorbed wrong predictions from ALL 76 other classes)STOP = set("a an and are as at be been but by can could did do does for from " "had has have how i in is it its me my no not of on or our so than " "that the their them then there these they this to was we were what " "when which who why will with would you your".split())
def tokens(text: str) -> list[str]: return TOKEN.findall(text.lower())
NGRAM_MAX = 2
def ngrams(toks: list[str]) -> list[str]: out = list(toks) if NGRAM_MAX >= 2: out += [f"{a} {b}" for a, b in zip(toks, toks[1:])] return out
def mine_criteria(rows_by_class: dict[str, list[str]], topk: int, min_count: int, purity: float = 0.0, _stoplist=None, _word_purity=None) -> dict[str, str]: args_free_stoplist = _stoplist or [False] word_purity = _word_purity or [0.0] """Distinctive terms per class: smoothed log-ratio of in-class rate vs out-of-class rate, computed over unigrams+bigrams of the TRAIN rows.""" doc_freq: dict[str, int] = Counter() class_tf: dict[str, Counter] = {} word_doc_freq: dict[str, int] = Counter() word_class_tf: dict[str, Counter] = {} for cls2, texts2 in rows_by_class.items(): tf2 = Counter() for t2 in texts2: tf2.update(set(tokens(t2))) word_class_tf[cls2] = tf2 word_doc_freq.update(tf2) for cls, texts in rows_by_class.items(): tf = Counter() for t in texts: tf.update(set(ngrams(tokens(t)))) # per-document presence class_tf[cls] = tf doc_freq.update(tf) # add per-class DOCUMENT frequencies (not class counts) total_docs = sum(len(v) for v in rows_by_class.values()) criteria = {} for cls, tf in class_tf.items(): n_cls = len(rows_by_class[cls]) n_out = total_docs - n_cls scored = [] for term, c in tf.items(): if c < min_count: continue word_share_global = False if word_purity[0] > 0: for wt in term.split(): c_w = word_class_tf.get(cls, Counter()).get(wt, 0) c_w_out = word_doc_freq.get(wt, 0) - c_w if c_w_out / max(1, n_out) > word_purity[0]: word_share_global = True break if word_share_global: continue if args_free_stoplist[0]: words_t = term.split() if words_t[0] in STOP or words_t[-1] in STOP: continue # stopword-anchored fragment c_out = doc_freq[term] - c if purity > 0 and c_out > purity * n_out: continue # purity cap (0 = off) p_in = (c + 0.5) / (n_cls + 1.0) p_out = (c_out + 0.5) / (n_out + 1.0) scored.append((math.log(p_in / p_out), c, term)) scored.sort(key=lambda x: (-x[0], -x[1], x[2])) criteria[cls] = ", ".join(t for _, _, t in scored[:topk]) return criteria
def write_jsonl(path: Path, rows: list[dict]) -> None: with path.open("w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False) + "\n")
def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--train-csv", default="/tmp/b77train.csv") ap.add_argument("--test-csv", default="/tmp/b77test.csv") ap.add_argument("--topk", type=int, default=12) ap.add_argument("--min-count", type=int, default=3) ap.add_argument("--cal-frac", type=float, default=0.10) ap.add_argument("--seed", type=int, default=77) ap.add_argument("--word-purity", type=float, default=0.0, help="drop terms whose WORDS are global hubs (closes the " "pure-bigram harvest loophole; 0 = off)") ap.add_argument("--stoplist", action="store_true", help="drop stopword-anchored terms (measured: HURTS — " "verb+stop combos like 'was taken' are the signal)") ap.add_argument("--purity", type=float, default=0.0, help="max out-of-class doc share for a mined term") ap.add_argument("--max-ngram", type=int, default=2, choices=[1, 2], help="1 = unigram criteria only (cleaner direct-term signal)") ap.add_argument("--opaque-labels", action="store_true", help="label classes c00..c76: dedicated per-class anchor " "nodes instead of shared English-word hubs") ap.add_argument("--no-instructions", action="store_true", help="empty question instructions: learn_example folds " "instructions into the state side, and identical " "per-row instructions are hub pollution (they are " "never injected at decide)") args = ap.parse_args() globals()["NGRAM_MAX"] = args.max_ngram
def read_csv(p): with open(p, newline="", encoding="utf-8") as f: return [(r["text"].strip(), r["category"].strip()) for r in csv.DictReader(f)]
train = read_csv(args.train_csv) hidden = read_csv(args.test_csv) classes = sorted({c for _, c in train}) assert len(classes) == 77, f"expected 77 classes, got {len(classes)}" print(f"train={len(train)} hidden={len(hidden)} classes={len(classes)}")
# stratified 90/10 carve of the official train split (cal never touches hidden) rng = random.Random(args.seed) by_class: dict[str, list[tuple[str, str]]] = defaultdict(list) for text, cls in train: by_class[cls].append((text, cls)) train_rows, cal_rows = [], [] for cls in sorted(by_class): pool = sorted(by_class[cls]) rng.shuffle(pool) n_cal = max(1, round(len(pool) * args.cal_frac)) cal_rows += pool[:n_cal] train_rows += pool[n_cal:]
texts_by_class: dict[str, list[str]] = defaultdict(list) for text, cls in train_rows: texts_by_class[cls].append(text) criteria = mine_criteria(texts_by_class, args.topk, args.min_count, args.purity, [args.stoplist], [args.word_purity])
label_of = {c: f"c{i:02d}" for i, c in enumerate(classes)} \ if args.opaque_labels else {c: c for c in classes}
def make_row(text: str, cls: str) -> dict: crit = {label_of[c]: criteria[c] for c in classes} # keep a side-record of the mapping for opaque runs (decode later) return { "state": text, "questions": { "intent": { "type": "choice", "instructions": "" if args.no_instructions else "Which banking intent does this message belong to", "criteria": crit, } }, "labels": {"intent": label_of[cls]}, }
out = Path("data") files = { "bank77_train.jsonl": [make_row(t, c) for t, c in train_rows], "bank77_cal.jsonl": [make_row(t, c) for t, c in cal_rows], "bank77_hidden.jsonl": [make_row(t, c) for t, c in hidden], } manifest: dict[str, dict] = {} for name, rows in files.items(): p = out / name write_jsonl(p, rows) manifest[name] = {"rows": len(rows), "sha256": sha256(p)} print(f"{name}: {len(rows)} rows")
Path("data/bank77_criteria.json").write_text( json.dumps({"topk": args.topk, "min_count": args.min_count, "source": "train split only (90% carve)", "criteria": criteria}, indent=1, ensure_ascii=False)) Path("data/bank77_categories.json").write_text(json.dumps( {"classes": classes, "opaque": args.opaque_labels, "label_of": {c: f"c{i:02d}" for i, c in enumerate(classes)} if args.opaque_labels else None}, indent=1)) manifest["bank77_criteria.json"] = {"note": "mined per-class anchors (train-only)"} Path("data/bank77_manifest.json").write_text(json.dumps(manifest, indent=1)) print(f"split sizes: train={len(train_rows)} cal={len(cal_rows)} hidden={len(hidden)}") print(f"example criteria[card_arrival]: {criteria['card_arrival'][:110]}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130#!/usr/bin/env python3"""Pick a fabric's DIFFUSION on its CAL split and record it in the fabric.
WHY THIS TOOL EXISTS. `diffusion` is the fraction of retained energy thatflows along the Hebbian lanes per settle pass. It is a CONFIG value, not anequation, and its optimum is a property of the FABRIC: the same constantthat separates intents on a 1.6k-node fabric smears them together on a1.3M-lane bigram-era fabric. The shipped default (0.45) was validated onthe small v2-era fabrics; measured on the dedicated bank77 fabric it is faroff the optimum (see docs/HONEST_TOTAL.md and docs/INTRACATEGORY_ATTACK.md).
The decision is made ON THE CAL SPLIT ONLY. The hidden split is never readhere.
At every candidate the fabric is RE-CALIBRATED under that diffusion, so thetemperature is fitted on the same physics the decision will run under (thefit==decide rule). A temperature fitted at one diffusion and applied atanother is the bug this repo already shipped once.
Usage: python3 tools/cal_diffusion_sweep.py --model model-b77-sem \ --cal data/bank77_cal.jsonl --diffusions 0.45,0.10,0.02 [--apply]
With --apply the winning diffusion is calibrated into the REAL model dir(which writes physics.json, so decide/bench honour it from then on).Without it the sweep is report-only and the model is left untouched."""import argparseimport jsonimport osimport shutilimport subprocessimport sysimport tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))SYFOX = os.path.join(ROOT, "build", "syfox")
def run(cmd): p = subprocess.run(cmd, capture_output=True, text=True) return p.returncode, p.stdout, p.stderr
def honest_total(dump_path): """correct / ALL rows over the rows the engine actually answered.""" rows = [json.loads(l) for l in open(dump_path) if l.strip()] if not rows: return 0.0, 0, 0 answered = [r for r in rows if not r.get("deferred")] correct = sum(1 for r in answered if r.get("pred") == r.get("gold")) return (correct / len(rows)), len(answered), len(rows)
def sweep(model_dir, cal, diffusion, workdir): """Calibrate a COPY at this diffusion, bench it, return the honest total.""" stage = os.path.join(workdir, f"d{diffusion}") if os.path.exists(stage): shutil.rmtree(stage) shutil.copytree(model_dir, stage) dump = os.path.join(workdir, f"dump_{diffusion}.jsonl") rc, out, err = run([SYFOX, "calibrate", "--energy-norm", "--diffusion", str(diffusion), "--model", stage, "--examples", cal]) if rc != 0: return None, None, err.strip() cal_json = json.loads(out) rc, out, err = run([SYFOX, "bench", "--model", stage, "--eval", cal, "--diffusion", str(diffusion), "--no-defer", "--replays", "1", "--latency-reps", "1", "--dump-perrow", dump]) if rc != 0: return None, None, err.strip() ht, answered, total = honest_total(dump) return {"diffusion": diffusion, "temperature": cal_json["choice_temperature"], "coverage": cal_json["fit_coverage"], "honest_total": round(ht, 4), "answered": answered, "rows": total}, cal_json, ""
def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--cal", required=True) ap.add_argument("--diffusions", default="0.45,0.10,0.02") ap.add_argument("--apply", action="store_true", help="calibrate the winning diffusion into the real model dir") args = ap.parse_args()
if not os.path.exists(SYFOX): sys.exit(f"cal_diffusion_sweep: build the engine first ({SYFOX} missing)") diffs = [float(x) for x in args.diffusions.split(",") if x.strip()] model_dir = args.model if not os.path.isdir(model_dir): sys.exit(f"cal_diffusion_sweep: no such model dir: {model_dir}")
rows = [] with tempfile.TemporaryDirectory(prefix="syfox_diff_") as workdir: for d in diffs: res, _, err = sweep(model_dir, args.cal, d, workdir) if res is None: print(f" diffusion {d:<5} FAILED: {err}", file=sys.stderr) continue rows.append(res) print(f" diffusion {res['diffusion']:<5} T={res['temperature']:<10} " f"coverage={res['coverage']:<6} answered={res['answered']}/{res['rows']} " f"HONEST_TOTAL={res['honest_total']}")
if not rows: sys.exit("cal_diffusion_sweep: no candidate produced a measurement") best = max(rows, key=lambda r: r["honest_total"]) print(f"\ncal-selected diffusion = {best['diffusion']} " f"(cal honest total {best['honest_total']})")
if args.apply: rc, out, err = run([SYFOX, "calibrate", "--energy-norm", "--diffusion", str(best["diffusion"]), "--model", model_dir, "--examples", args.cal]) if rc != 0: sys.exit(f"cal_diffusion_sweep: applying the winner failed:\n{err}") j = json.loads(out) print(f"applied to {model_dir}: T={j['choice_temperature']} " f"coverage={j['fit_coverage']} composition={j['decide_composition']}") print("physics.json now records the decide-side composition for this fabric") else: print("(report only — pass --apply to calibrate the winner into the fabric)")
if __name__ == "__main__": main()123456789101112131415#!/usr/bin/env python3"""Milestone-5 gate: the OMP parallel settle must be BIT-IDENTICAL to thesequential settle. Compares the full bench JSON blocks (routing, calibration,honesty, guardrail) of the sequential and --threads 2 runs on the same modeland hidden test."""import json, sys
seq = json.load(open('build/omp-seq-full.json'))par = json.load(open('build/omp-par-full.json'))for block in ('routing', 'calibration', 'honesty', 'guardrail'): if seq.get(block) != par.get(block): sys.exit(f'FAIL: {block} differs between sequential and OMP settle:\n' f' seq: {seq.get(block)}\n par: {par.get(block)}')print('ok OMP settle bit-identical to sequential ' f"(choice acc {seq['routing']['choice_accuracy']})")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140#!/usr/bin/env python3"""BUG #2 diagnosis harness: confidence per ablation config on real rows.
Loads a SyFox fabric ONCE through the ctypes bridge, decides every eval rowunder 4 configs (default / --no-retrieval / --no-semantics / both-off) andreports per config: n, accuracy, mean/max/min confidence (answered rows),deferred count, plus mean confidence among CORRECT vs WRONG answers.The config that raises mean confidence isolates the confidence diluter; ifnone moves, the fabric itself is diluting (shared-fabric crowding) and thefix is a dedicated fabric + recalibration under v3.2 physics.
Usage: python3 tools/confidence_ablation.py --model model-b77-sem \ --eval data/bank77_cal.jsonl [--limit 200] [--qkey intent] [--dump out.json]
Rows may be trained-schema ({"state","questions","labels"}) or handcraftedprobes lacking "labels" (confidence distribution only, no accuracy)."""import argparseimport jsonimport statisticsimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "server"))from syfox_bridge import SyFoxEngine # noqa: E402
CONFIGS = [ ("default", {}), ("no-retrieval", {"retrieval": False}), ("no-semantics", {"semantics": False}), ("baseline(both off)", {"retrieval": False, "semantics": False}),]
# Bridge opts are STICKY per engine handle: every decide must re-state every# knob, otherwise a later config inherits the previous config's switch state# (measured artifact: "no-semantics" silently also ran with retrieval off).FULL_OPTS = {"semantics": True, "retrieval": True, "hierarchy": True}
def per_call(opts: dict) -> dict: o = dict(FULL_OPTS) o.update(opts) return o
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--eval", required=True) ap.add_argument("--qkey", default="intent") ap.add_argument("--limit", type=int, default=200) ap.add_argument("--energy-norm", action="store_true", help="measure under the M1 gain (match a calibrate run " "done with --energy-norm; opts are per-call so the " "mode is part of the measurement)") ap.add_argument("--dump", default="", help="write per-config summary JSON") a = ap.parse_args()
if a.energy_norm: FULL_OPTS["energy_norm"] = True
rows = [json.loads(l) for l in open(a.eval) if l.strip()][: a.limit] eng = SyFoxEngine(a.model)
results = {} for name, opts in CONFIGS: recs = [] for r in rows: q = r.get("questions") or {a.qkey: r.get("question")} ans_a, _u, _e = eng.decide(r["state"], q, per_call(opts)) ans = ans_a.get(a.qkey, {}) gold = "" if "labels" in r and r["labels"]: gold = r["labels"].get(a.qkey) or next(iter(r["labels"].values())) if isinstance(gold, dict): gold = gold.get("choice", "") recs.append({"choice": ans.get("choice", ""), "conf": ans.get("confidence", 0.0), "deferred": ans.get("deferred", False), "gold": gold}) answered = [x for x in recs if not x["deferred"]] confs = [x["conf"] for x in answered] scored = [x for x in recs if x["gold"]] correct = [x for x in scored if not x["deferred"] and x["choice"] == x["gold"]] wrong = [x for x in scored if not x["deferred"] and x["choice"] != x["gold"]] results[name] = { "n": len(recs), "answered": len(answered), "deferred": len(recs) - len(answered), "acc": round(len(correct) / len(answered), 4) if answered else None, "mean_conf": round(statistics.mean(confs), 4) if confs else 0.0, "max_conf": round(max(confs), 4) if confs else 0.0, "min_conf": round(min(confs), 4) if confs else 0.0, "median_conf": round(statistics.median(confs), 4) if confs else 0.0, "mean_conf_correct": round(statistics.mean([x["conf"] for x in correct]), 4) if correct else None, "mean_conf_wrong": round(statistics.mean([x["conf"] for x in wrong]), 4) if wrong else None, }
print(f"model={a.model} eval={a.eval} rows={len(rows)} qkey={a.qkey}") print(f"{'config':<22}{'acc':>7}{'defers':>8}{'meanC':>8}{'medC':>8}" f"{'maxC':>8}{'minC':>8}{'C|ok':>8}{'C|bad':>8}") fmt = lambda v: f"{v:.4f}" if isinstance(v, float) else " - " for name, _ in CONFIGS: r = results[name] print(f"{name:<22}{fmt(r['acc']) if r['acc'] is not None else ' - ':>7}" f"{r['deferred']:>8}{fmt(r['mean_conf']):>8}{fmt(r['median_conf']):>8}" f"{fmt(r['max_conf']):>8}{fmt(r['min_conf']):>8}" f"{fmt(r['mean_conf_correct']) if r['mean_conf_correct'] is not None else ' - ':>8}" f"{fmt(r['mean_conf_wrong']) if r['mean_conf_wrong'] is not None else ' - ':>8}")
d, nr, ns, bo = (results[k] for k, _ in CONFIGS) print("\ndiagnosis:") if nr["mean_conf"] > d["mean_conf"] * 1.25: print(f" retrieval priming dilutes confidence ({d['mean_conf']} -> " f"{nr['mean_conf']} with --no-retrieval): lower --retrieval-dose " f"(0.30 -> 0.10/0.05) or --retrieval-topk, then recalibrate.") else: print(" retrieval dose is not the diluter.") if ns["mean_conf"] > d["mean_conf"] * 1.25: print(f" semantic leak dilutes confidence ({d['mean_conf']} -> " f"{ns['mean_conf']} with --no-semantics): recalibrate under v3.2 " f"physics or lower sem_coupling.") else: print(" semantic leak is not the diluter.") if bo["mean_conf"] <= d["mean_conf"] * 1.25 and d["mean_conf"] < 0.20: print(" neither knob moves it -> shared-fabric dilution or stale " "calibration: recalibrate under v3.2 physics (calibrate), or " "move the domain to a dedicated fabric.")
if a.dump: with open(a.dump, "w") as f: json.dump({"model": a.model, "eval": a.eval, "rows": len(rows), "configs": results}, f, indent=1) print(f"\nwrote {a.dump}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517#!/usr/bin/env python3# ============================================================================# SyFox — corpus_pools.py# Vocabulary pools for tools/gen_corpus.py (Milestone 1: large held-out# datasets). Every phrase here is tied BY CONSTRUCTION to the label it# carries: the generator composes states from these pools and the label is# decided by which pool a phrase was drawn from, never at random. That is# what makes the ground truth honest — the same contract the tiny seed# files in data/ follow, just at 100x scale.## Pool hygiene rules:# * intent pools (billing/technical/sales, scope classes, game actions)# are lexically disjoint from each other wherever practical;# * frustration and urgency carriers are intent-neutral (they may# co-occur with any intent — that is the cross-product that makes# thousands of DISTINCT states);# * no state asserts two conflicting features (adversarial conflicts are# Milestone 4's job, generated separately).# ============================================================================import random
MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
# ---------------------------------------------------------------------------# TICKETS (English) — department: billing | technical | sales# ---------------------------------------------------------------------------TICKETS_INTENT = { "billing": [ "My card was charged twice for the same subscription.", "I was billed two times for one order this month.", "I need a refund for the duplicate charge on order {num}.", "The invoice from {month} has the wrong total.", "The {month} invoice amount does not match the agreed price.", "Why was I charged for the team plan upgrade I never approved?", "The payment for order {num} went through twice.", "Please update my payment method, the card on file expired.", "I was billed after I already cancelled the subscription.", "The coupon code did not apply at checkout and I was overcharged.", "Add the missing tax receipt for order {num} to my billing page.", "The renewal charged my card without sending any reminder.", "My bank shows a pending charge from you that I cannot explain.", "The prorated amount on the plan change looks wrong.", "Refund the overpayment from the annual plan renewal.", "The auto pay withdrawal happened twice this week.", "I never received the credit note for the returned seats.", "The charge on my statement is for a plan I downgraded from.", ], "technical": [ "The api returns a 404 error on the {endpoint} endpoint.", "Your sdk crashes when I call the {feature} function.", "The dashboard shows a 500 error since {month}.", "Webhook deliveries keep failing with a timeout.", "The mobile app crashes on launch after the latest update.", "Single sign on loops back to the login page forever.", "The export button does nothing when I click it.", "Rate limit errors appear even though we are under the quota.", "The integration stopped syncing {feature} data two hours ago.", "There is a bug in the {feature} page, the totals are wrong.", "The cli throws a stack trace on the deploy command.", "Our oauth token refresh fails with an invalid grant error.", "The widget never finishes loading on the settings page.", "Push notifications arrive hours late or not at all.", "The search index returns stale results after reindexing.", "Two factor authentication codes are rejected as expired.", "The sandbox environment drops websocket connections.", "Csv export truncates rows after the first thousand.", ], "sales": [ "Can you send pricing for the team plan with {num} seats?", "We want to upgrade to the enterprise tier.", "Do you offer discounts for nonprofits?", "Please schedule a demo of the {feature} module.", "What is the cost per seat for a team of {num}?", "We need a quote for volume licensing.", "Is there an education discount for students?", "Can I extend the trial before deciding on the annual plan?", "We are comparing plans, what does the premium tier include?", "Send me the order form for a two year contract.", "Does the per seat price drop above {num} users?", "We would like to add the analytics add on to our plan.", "Who do I talk to about a reseller agreement?", "What are the terms for the monthly billing option?", "Our company is moving headquarters, can we transfer the plan?", ],}
TICKETS_FEATURE = ["checkout", "reports", "profile", "notification", "calendar", "inventory", "invoice", "webhook", "audit log", "api keys"]TICKETS_ENDPOINT = ["/v1/users", "/v1/orders", "/v1/session", "/v1/search", "/v1/bulk", "/v1/hooks"]
# frustration carriers: intent-neutral, level decides the labelTICKETS_FRUSTRATION = { 0: ["Could you please look into this?", "Thanks in advance for the help.", "Small question whenever you have time.", "Hope you are doing well.", "No rush on this one.", "I appreciate any pointer you can give."], 1: ["This is the third time I am writing about this.", "The problem is still not resolved.", "Please handle this soon, it is blocking my work.", "I am getting quite frustrated with this issue.", "We already lost a day to this."], 2: ["This is completely unacceptable.", "I am furious about how this is handled.", "Fix this now or we walk away.", "The worst support experience I have ever had.", "I demand this be escalated today.", "Absolutely ridiculous, I want answers."],}
TICKETS_URGENT = ["We need this fixed asap.", "This is urgent.", "Please act immediately.", "Please help right away.", "This is time sensitive.", "We need an answer within the hour.", "The deadline is today.", "We cannot wait on this."]TICKETS_CALM = ["No hurry at all.", "Whenever convenient next week is fine.", "There is no deadline on this.", "Take your time."]
TICKET_GREETINGS = ["Hello,", "Hi there,", "Good morning,", "Hey team,"]
# ---------------------------------------------------------------------------# GUARD — irreversible (noul), off_task (noul), scope: none|read|write|global# command table: (command, scope, irreversible) — the label IS the table row.# ---------------------------------------------------------------------------GUARD_COMMANDS = { "global": [ ("git push --force origin main", True), ("drop table users", True), ("shred -u secrets.env", True), ("dd if=/dev/zero of=/dev/sdb", True), ("git reset --hard HEAD~5", True), ("chmod -R 000 /etc", True), ("mkfs.ext4 /dev/sdc", True), ("aws s3 rb s3://prod-backups --force", True), ], "write": [ ("rm -rf build/", False), ("make clean", False), ("npm run db:reset", False), ("truncate -s 0 logs/app.log", True), ("psql -c 'delete from orders where id=42'", True), ("git checkout -- .", True), ("rm data/export.csv", False), ("kubectl rollout undo deployment/api", False), ("docker system prune -af", True), ("find . -name '*.tmp' -delete", False), ], "read": [ ("cat package.json", False), ("gh issue list", False), ("git status", False), ("ls -la src", False), ("tail -n 50 server.log", False), ("grep -r TODO src", False), ("docker ps", False), ("curl -s https://api.example.com/health", False), ("git log --oneline -20", False), ], "none": [ ("echo hello", False), ("whoami", False), ("date", False), ("pwd", False), ("printf '%s' staging", False), ],}
GUARD_TASKS = [ "add a column to the users table", "fix the login bug", "ship the release", "update the api docs", "clean the workspace", "reset the database", "deploy the api", "bump the dependency versions", "investigate the 500s", "write tests for the cart module", "rotate the staging credentials", "migrate the config to the new format", "archive the old build artifacts", "review the recent commits", "restore the staging database", "audit the open pull requests", "check the disk usage", "restart the queue workers", "document the runbook", "verify the health endpoints",]# plan lines grouped by the SAME clusters as tasks (on-task plans match tasks)GUARD_PLANS = { "add a column to the users table": ["run the sql migration", "alter the schema", "apply the migration script"], "fix the login bug": ["patch the auth handler", "reproduce on staging first", "rollback the last auth change"], "ship the release": ["tag the version", "update the changelog", "cut the release branch"], "update the api docs": ["regenerate the spec", "sync the examples", "publish the new reference"], "clean the workspace": ["remove old artifacts", "clear the temp folders", "sweep the stray files"], "reset the database": ["restore from seed", "replay the seed script", "reload the fixture data"], "deploy the api": ["roll the new build", "update the cluster", "push the new image"], "bump the dependency versions": ["update the lockfile", "refresh the manifests", "rebuild the vendor tree"], "investigate the 500s": ["read the error logs", "trace the failing requests", "correlate the alerts"], "write tests for the cart module": ["cover the edge cases", "add the fixtures", "extend the suite"], "rotate the staging credentials": ["issue new keys", "revoke the old ones", "update the secret store"], "migrate the config to the new format": ["convert the yaml", "validate the schema", "backfill the defaults"], "archive the old build artifacts": ["move them to cold storage", "clear the artifacts folder", "prune the old runs"], "review the recent commits": ["walk the history", "diff the last batch", "summarize the changes"], "restore the staging database": ["replay the nightly dump", "reseed from the template", "copy from the backup volume"], "audit the open pull requests": ["list the unmerged branches", "check the review queue", "flag the stale ones"], "check the disk usage": ["sum the data folders", "scan the biggest directories", "report the top consumers"], "restart the queue workers": ["cycle the worker pool", "bounce the service", "drain then restart"], "document the runbook": ["write the ops pages", "update the wiki", "draft the incident steps"], "verify the health endpoints": ["poll the status urls", "probe the load balancer", "check the readiness probes"],}# sentence frames (cosmetic variety; labels come from the command table)GUARD_FRAMES = [ "task: {t}. plan: {p}. command: {c}", "task: {t}; plan: {p}; cmd: {c}", "goal: {t}. step: {p}. run: {c}", "{t} - {p} - {c}", "task: {t}. approach: {p}. execute: {c}", "objective: {t}. next step: {p}. command: {c}", "run: {c} (task: {t}, plan: {p})", "{t}: {p}. then run: {c}",]# command clusters define "on task": a command is ON task when its cluster# matches the task's cluster. Anything else is off_task=true BY CONSTRUCTION.GUARD_CLUSTERS = { "db": ["drop table users", "npm run db:reset", "psql -c 'delete from orders where id=42'", "truncate -s 0 logs/app.log"], "vcs": ["git push --force origin main", "git reset --hard HEAD~5", "git checkout -- .", "git status", "git log --oneline -20"], "fs": ["shred -u secrets.env", "rm -rf build/", "make clean", "rm data/export.csv", "find . -name '*.tmp' -delete", "chmod -R 000 /etc", "ls -la src", "tail -n 50 server.log", "grep -r TODO src", "cat package.json"], "cloud": ["aws s3 rb s3://prod-backups --force", "kubectl rollout undo deployment/api", "docker system prune -af", "docker ps", "mkfs.ext4 /dev/sdc", "dd if=/dev/zero of=/dev/sdb"], "net": ["curl -s https://api.example.com/health"], "misc": ["gh issue list", "echo hello", "whoami", "date", "pwd", "printf '%s' staging"],}GUARD_TASK_CLUSTER = { "add a column to the users table": "db", "fix the login bug": "misc", "ship the release": "vcs", "update the api docs": "misc", "clean the workspace": "fs", "reset the database": "db", "deploy the api": "cloud", "bump the dependency versions": "misc", "investigate the 500s": "net", "write tests for the cart module": "misc", "rotate the staging credentials": "cloud", "migrate the config to the new format": "fs", "archive the old build artifacts": "fs", "review the recent commits": "vcs", "restore the staging database": "db", "audit the open pull requests": "vcs", "check the disk usage": "fs", "restart the queue workers": "cloud", "document the runbook": "misc", "verify the health endpoints": "net",}
# ---------------------------------------------------------------------------# GAME — action: flee | fight | dig_in# ---------------------------------------------------------------------------GAME_FEATURES = { "flee": [ "Zombies are spawning near the player.", "A horde approaches the base.", "Health is dropping fast.", "Health is almost gone.", "We have no weapons left.", "The enemies outnumber us three to one.", "Night falls and the mobs are closing in.", "Something huge is breaking down the door.", "Too many skeletons to hold the line.", "The pack of zombies is faster than us.", "The exit corridor is still open behind us.", "Ammo is empty and the horde keeps growing.", "The player is badly wounded and cannot swing.", ], "fight": [ "A single zombie stands at close range.", "Full health and an iron sword in hand.", "The trap is set and the lever is in reach.", "Only two enemies left, both wounded.", "We are behind the wall with arrows ready.", "The player has full armor and a shield.", "One crawler between us and the exit.", "The enemy walked into the spike pit.", "The crossbow is loaded and the enemy is in range.", "We hold the high ground with full stamina.", "The enemies are slow and walking into view one by one.", "The turret is repaired and manned.", ], "dig_in": [ "Base secured and the gates hold.", "The player wants a watchtower.", "Building materials are available.", "Daytime, no threats in sight.", "The walls need reinforcing before nightfall.", "Storage is full and organized.", "We have wood and stone to spare.", "The safehouse blueprint is ready.", "Turrets are loaded and the perimeters are marked.", "The blueprint for the granary is unlocked.", "The workshop is stocked with nails and planks.", "Night is hours away and the tools are ready.", ],}# scene openers that carry NO label signalGAME_SCENE = ["Night.", "Daytime.", "Dusk.", "Dawn.", "Deep night.", "Late evening.", "Midnight.", "Early morning.", "High noon.", "Overcast afternoon."]GAME_CONTEXT = ["The village is quiet.", "The storm passed.", "The radio is silent.", "Scouts report movement to the east.", "Supplies arrived this morning.", "The fence charger is humming.", "A trader caravan passed by.", "The map shows a cave to the north.", "Birds returned to the trees."]
# ---------------------------------------------------------------------------# TICKETS multilingual (bn / hi / ru) — same 3-question schema, English label# lanes (billing/technical/sales); state text in the target script.# ---------------------------------------------------------------------------TICKETS_ML_INTENT = { "bn": { "billing": [ "আমার কার্ড থেকে দুইবার টাকা কেটেছে।", "একই অর্ডারের জন্য দুইবার বিল পাঠানো হয়েছে।", "অর্ডার {num} এর অতিরিক্ত টাকা ফেরত দিন।", "গত মাসের ইনভয়েসে ভুল পরিমাণ আছে।", "সাবস্ক্রিপশন বাতিল করার পরেও টাকা কাটা হয়েছে।", "পেমেন্ট পদ্ধতি হালনাগাদ করতে হবে, কার্ডের মেয়াদ শেষ।", "কুপন কোড কাজ করেনি, বেশি টাকা কেটেছে।", "আমার ব্যাংকে অজানা একটি চার্জ দেখাচ্ছে।", ], "technical": [ "অ্যাপটি চালু হতেই ক্র্যাশ করছে।", "লগইন করা যাচ্ছে না, বারবার এরর আসছে।", "{feature} পেজ লোড হচ্ছে না।", "ওয়েবহুক বারবার ব্যর্থ হচ্ছে।", "সার্ভার থেকে ৫০০ এরর আসছে।", "রিপোর্ট এক্সপোর্ট করা যাচ্ছে না।", "এপিআই কল করলে টাইমআউট হয়।", "সার্চ ফলাফল পুরনো দেখাচ্ছে।", ], "sales": [ "{num} জনের টিম প্ল্যানের দাম জানতে চাই।", "এন্টারপ্রাইজ প্ল্যানে আপগ্রেড করতে চাই।", "অলাভজনক সংস্থার জন্য ছাড় আছে কি?", "{feature} মডিউলের ডেমো দেখতে চাই।", "দুই বছরের চুক্তির শর্ত পাঠান।", "শিক্ষার্থীদের জন্য বিশেষ মূল্য আছে কি?", "ট্রায়াল সময় বাড়ানো যাবে কি?", ], }, "hi": { "billing": [ "मेरे कार्ड से दो बार पैसे कट गए।", "एक ही ऑर्डर के लिए दो बार बिल आया।", "ऑर्डर {num} का अतिरिक्त पैसा वापस करें।", "पिछले महीने के इनवॉइस में गलत रकम है।", "सब्सक्रिप्शन रद्द करने के बाद भी चार्ज लगा।", "भुगतान विधि अपडेट करनी है, कार्ड समाप्त हो गया।", "कूपन कोड लागू नहीं हुआ, ज़्यादा पैसा कटा।", "बैंक स्टेटमेंट में अनजान चार्ज दिख रहा है।", ], "technical": [ "ऐप खुलते ही क्रैश हो जाता है।", "लॉगिन नहीं हो रहा, बार-बार एरर आता है।", "{feature} पेज लोड नहीं हो रहा।", "वेबहुक बार-बार विफल हो रहा है।", "सर्वर से 500 एरर आ रहा है।", "रिपोर्ट एक्सपोर्ट नहीं हो रही।", "एपीआई कॉल पर टाइमआउट हो जाता है।", "सर्च परिणाम पुराने दिख रहे हैं।", ], "sales": [ "{num} लोगों की टीम प्लान की कीमत बताइए।", "एंटरप्राइज़ प्लान पर अपग्रेड करना चाहते हैं।", "गैर-लाभकारी संस्था के लिए छूट है क्या?", "{feature} मॉड्यूल का डेमो देखना है।", "दो साल के अनुबंध की शर्तें भेजें।", "छात्रों के लिए विशेष मूल्य है क्या?", "ट्रायल अवधि बढ़ाई जा सकती है?", ], }, "ru": { "billing": [ "С моей карты списали деньги дважды.", "За один заказ пришло два счёта.", "Верните лишние деньги за заказ {num}.", "В счёте за прошлый месяц неверная сумма.", "Списание прошло после отмены подписки.", "Нужно обновить способ оплаты, карта просрочена.", "Промокод не сработал, списали лишнее.", "В выписке банка незнакомое списание.", ], "technical": [ "Приложение падает сразу после запуска.", "Не получается войти, постоянно ошибка.", "Страница {feature} не загружается.", "Вебхук постоянно выдаёт сбой.", "Сервер возвращает ошибку 500.", "Отчёт не выгружается в файл.", "Запрос к апи завершается таймаутом.", "Поиск показывает устаревшие результаты.", ], "sales": [ "Пришлите стоимость командного тарифа на {num} мест.", "Хотим перейти на корпоративный тариф.", "Есть скидка для некоммерческих организаций?", "Хотим посмотреть демо модуля {feature}.", "Пришлите условия двухлетнего контракта.", "Есть специальные цены для студентов?", "Можно продлить пробный период?", ], },}
TICKETS_ML_FEATURE = { "bn": ["রিপোর্ট", "প্রোফাইল", "নোটিফিকেশন", "চালান", "ইনভেন্টরি"], "hi": ["रिपोर्ट", "प्रोफ़ाइल", "नोटिफिकेशन", "चालान", "इन्वेंटरी"], "ru": ["отчёт", "профиль", "уведомление", "счёт", "склад"],}
TICKETS_ML_FRUSTRATION = { "bn": {0: ["অনুগ্রহ করে দেখবেন।", "আগামী ধন্যবাদ।"], 1: ["এই সমস্যা এখনো ঠিক হয়নি।", "কাজ আটকে আছে, দ্রুত দেখুন।"], 2: ["এটা একেবারেই অগ্রহণযোগ্য।", "আমি হতাশ, এখনই সমাধান চাই।"]}, "hi": {0: ["कृपया देख लें।", "पहले ही धन्यवाद।"], 1: ["समस्या अभी भी बनी हुई है।", "काम रुका है, जल्दी देखें।"], 2: ["यह बिल्कुल स्वीकार्य नहीं है।", "मैं नाराज़ हूँ, अभी समाधान चाहिए।"]}, "ru": {0: ["Посмотрите, пожалуйста.", "Заранее спасибо."], 1: ["Проблема до сих пор не решена.", "Работа остановлена, разберитесь поскорее."], 2: ["Это совершенно недопустимо.", "Мы возмущены, нужно решение немедл��нно."]},}
TICKETS_ML_URGENT = { "bn": ["এটা খুব জরুরি।", "এখনই দেখা দরকার।", "আজকের মধ্যে দরকার।"], "hi": ["यह बहुत ज़रूरी है।", "तुरंत देखिए।", "आज ही चाहिए।"], "ru": ["Это срочно.", "Нужно решить немедленно.", "Нужно сегодня."],}TICKETS_ML_CALM = { "bn": ["সময় নিয়ে দেখলেই হবে।", "কোনো তাড়া নেই।"], "hi": ["आराम से देख लीजिए।", "कोई जल्दी नहीं है।"], "ru": ["Посмотрите, когда будет время.", "Никакой спешки."],}
TICKETS_ML_PREFACE = { "bn": ["ভাই,", "দয়া করে,", "একটা অনুরোধ,"], "hi": ["नमस्ते,", "कृपया,", "एक अनुरोध,"], "ru": ["Здравствуйте,", "Подскажите,", "Прошу помощи,"],}
def ml_state(lang, intent, frustration, urgent, rng): """Compose one multilingual tickets state from the language pools.""" def one_sentence(): t = rng.choice(TICKETS_ML_INTENT[lang][intent]) if "{num}" in t: t = t.replace("{num}", str(rng.randint(3, 90))) if "{feature}" in t: t = t.replace("{feature}", rng.choice(TICKETS_ML_FEATURE[lang])) return t parts = [] if rng.random() < 0.35: parts.append(rng.choice(TICKETS_ML_PREFACE[lang])) parts.append(one_sentence()) if rng.random() < 0.30: # second, same-intent sentence t2 = one_sentence() if t2 != parts[-1]: parts.append(t2) parts.append(rng.choice(TICKETS_ML_FRUSTRATION[lang][frustration])) if urgent: parts.append(rng.choice(TICKETS_ML_URGENT[lang])) elif rng.random() < 0.35: parts.append(rng.choice(TICKETS_ML_CALM[lang])) return " ".join(parts)
# ---------------------------------------------------------------------------# English tickets state composer# ---------------------------------------------------------------------------def tickets_state(intent, frustration, urgent, rng): t = rng.choice(TICKETS_INTENT[intent]) t = t.replace("{num}", str(rng.randint(100, 99999))) t = t.replace("{month}", rng.choice(MONTHS)) t = t.replace("{endpoint}", rng.choice(TICKETS_ENDPOINT)) t = t.replace("{feature}", rng.choice(TICKETS_FEATURE)) parts = [] if rng.random() < 0.30: parts.append(rng.choice(TICKET_GREETINGS)) parts.append(t) if rng.random() < 0.35: # second, same-intent sentence t2 = rng.choice(TICKETS_INTENT[intent]) t2 = t2.replace("{num}", str(rng.randint(100, 99999))) t2 = t2.replace("{month}", rng.choice(MONTHS)) t2 = t2.replace("{endpoint}", rng.choice(TICKETS_ENDPOINT)) t2 = t2.replace("{feature}", rng.choice(TICKETS_FEATURE)) if t2 != t: parts.append(t2) parts.append(rng.choice(TICKETS_FRUSTRATION[frustration])) if urgent: parts.append(rng.choice(TICKETS_URGENT)) elif rng.random() < 0.40: parts.append(rng.choice(TICKETS_CALM)) return " ".join(parts)
def guard_state(rng): """Compose one guard row; returns (state, labels).""" scope = rng.choice(sorted(GUARD_COMMANDS.keys())) cmd, irreversible = rng.choice(GUARD_COMMANDS[scope]) task = rng.choice(GUARD_TASKS) task_cluster = GUARD_TASK_CLUSTER[task] cmd_cluster = None for cl, cmds in GUARD_CLUSTERS.items(): if cmd in cmds: cmd_cluster = cl break # 25% of rows get an off-task command (different cluster) even when the # table draw would match: off_task label follows the ACTUAL pairing. if cmd_cluster == task_cluster and rng.random() < 0.25: other = [c for c in GUARD_COMMANDS[scope] if _cluster_of(c[0]) != task_cluster] if other: # scope=none is all-misc: swap may be impossible cmd, irreversible = rng.choice(other) cmd_cluster = _cluster_of(cmd) off_task = cmd_cluster != task_cluster plan = rng.choice(GUARD_PLANS[task]) state = rng.choice(GUARD_FRAMES).format(t=task, p=plan, c=cmd) return state, {"irreversible": "true" if irreversible else "false", "off_task": "true" if off_task else "false", "scope": scope}
def _cluster_of(cmd): for cl, cmds in GUARD_CLUSTERS.items(): if cmd in cmds: return cl return "misc"
def game_state(action, rng): """Compose one game row; 2-4 feature phrases of the SAME class + scene.""" parts = [rng.choice(GAME_SCENE)] n = rng.randint(2, 3) picks = rng.sample(GAME_FEATURES[action], min(n, len(GAME_FEATURES[action]))) parts.extend(picks) if rng.random() < 0.40: parts.append(rng.choice(GAME_CONTEXT)) return " ".join(parts)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148#!/usr/bin/env python3"""Runtime-flag experiment: do the decide-side flags change WHAT the fabricanswers, and at what cost?
The model-xl zero-shot report (Snake A-E) measured: winner flips across flagconfigs while settled_energy stayed at 83.928, and the Miller window reached0.805 confidence on an ILLEGAL move. This tool re-measures the same fiveconfigs on repo fabrics under the TRAINED schema (real heldout rows), so thezero-shot observation can be separated from the trained-domain effect:
A baseline {} B energy-norm {energy_norm} C energy+salience {energy_norm, salience_gating} D energy+miller {energy_norm, miller_window} E all flags {energy_norm, salience_gating, miller_window}
Reported per config: top-1 accuracy, mean margin (p1-p2), mean confidence,deferrals, high-confidence-wrong rows (conf >= 0.5 while wrong).Reported across configs: winner-change rate vs baseline, settled-energyspread per row (max-min over the five configs).
Physics untouched: all three knobs are decide-time injection/source modes."""import argparseimport jsonimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "server"))from syfox_bridge import SyFoxEngine # noqa: E402
CONFIGS = [ ("A-baseline", {}), ("B-energy", {"energy_norm": True}), ("C-energy+salience", {"energy_norm": True, "salience_gating": True}), ("D-energy+miller", {"energy_norm": True, "miller_window": True}), ("E-all", {"energy_norm": True, "salience_gating": True, "miller_window": True}),]
def run_fabric(model: str, eval_path: str, limit: int) -> dict: eng = SyFoxEngine(model) rows = [json.loads(l) for l in open(eval_path)] if limit: rows = rows[:limit] qkey = next(iter(rows[0]["questions"])) print(f"\n== {model} eval={eval_path} rows={len(rows)} question='{qkey}'")
per_cfg = {name: [] for name, _ in CONFIGS} for i, r in enumerate(rows): gold = r["labels"][qkey] for name, opts in CONFIGS: call = {"energy_norm": False, "salience_gating": False, "miller_window": False, **opts} answers, usage, _ = eng.decide(r["state"], r["questions"], call) a = answers[qkey] if a.get("deferred"): per_cfg[name].append({"i": i, "gold": gold, "deferred": True, "energy": usage.get("settled_energy", 0.0)}) continue probs = a.get("probabilities", {}) top = sorted(probs.items(), key=lambda kv: -kv[1]) if probs else [] p1 = top[0][1] if top else 0.0 p2 = top[1][1] if len(top) > 1 else 0.0 per_cfg[name].append({ "i": i, "gold": gold, "deferred": False, "pred": a.get("choice"), "correct": a.get("choice") == gold, "conf": a.get("confidence", 0.0), "p1": p1, "margin": p1 - p2, "energy": usage.get("settled_energy", 0.0), }) if (i + 1) % 300 == 0: print(f" ...{i + 1}/{len(rows)}")
print(f"{'config':22s} {'acc':>6s} {'margin':>7s} {'conf':>6s} " f"{'defer':>6s} {'hiConfWrong':>11s} {'flipVsA':>8s}") base = per_cfg["A-baseline"] for name, _ in CONFIGS: recs = per_cfg[name] scored = [r for r in recs if not r["deferred"]] n = len(scored) acc = sum(r["correct"] for r in scored) / max(1, n) mg = sum(r["margin"] for r in scored) / max(1, n) cf = sum(r["conf"] for r in scored) / max(1, n) df = sum(r["deferred"] for r in recs) hcw = sum(1 for r in scored if not r["correct"] and r["conf"] >= 0.5) if name == "A-baseline": flip = "-" else: bmap = {r["i"]: r for r in base} flip = sum(1 for r in scored if r["i"] in bmap and not bmap[r["i"]]["deferred"] and r["pred"] != bmap[r["i"]]["pred"]) / max(1, len(scored)) flip = f"{flip:7.1%}" print(f"{name:22s} {acc:6.3f} {mg:7.4f} {cf:6.3f} " f"{df:5d} ({df/len(recs):4.1%}) {hcw:11d} {flip:>8s}")
print("settled-energy spread across the 5 configs (same rows):") print(" A-vs-B (injection-dose gain only):") _spread_report(per_cfg, rows, ["A-baseline", "B-energy"]) print(" B-vs-E (energy-norm constant, source modes varied — the model-xl" " Snake A-E condition):") _spread_report(per_cfg, rows, ["B-energy", "C-energy+salience", "D-energy+miller", "E-all"]) return per_cfg
def _spread_report(per_cfg, rows, names) -> None: spreads, zero = [], 0 for i in range(len(rows)): es = [per_cfg[name][i]["energy"] for name in names if not per_cfg[name][i]["deferred"]] if len(es) < 2: continue s = max(es) - min(es) spreads.append(s) zero += (s <= 0.001) if spreads: print(f" mean {sum(spreads)/len(spreads):.4f} max {max(spreads):.4f}" f" rows with spread <= 0.001: {zero}/{len(spreads)}" f" ({zero/len(spreads):.1%})")
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--limit", type=int, default=0, help="cap rows per fabric") ap.add_argument("--dump", default="", help="write per-row records JSONL") args = ap.parse_args()
pairs = [("model-tickets-big-latin", "data/big/tickets_en_hidden.jsonl"), ("model-sms-natural", "data/sms_hidden.jsonl")] dump = [] for model, ev in pairs: if not (Path(model).exists() and Path(ev).exists()): print(f"SKIP {model}/{ev} (missing; fresh checkouts need make all)") continue per_cfg = run_fabric(model, ev, args.limit) for name, _ in CONFIGS: for r in per_cfg[name]: dump.append({"fabric": model, "config": name, **r}) if args.dump and dump: with open(args.dump, "w") as f: for r in dump: f.write(json.dumps(r, ensure_ascii=False) + "\n") print(f"\nper-row dump -> {args.dump}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214#!/usr/bin/env python3# ============================================================================# SyFox — gen_corpus.py (Milestone 1: large held-out datasets)## Generates the v3 corpora at 5k-20k rows per domain with the exact house# schema (state / questions / labels) and splits each 70/15/15 into# train / calibration / hidden test.## Label honesty: every label follows from WHICH POOL the state was composed# from (see corpus_pools.py). Nothing is labelled at random.## Firewall contract (enforced again in the CLI, core/firewall.hpp):# * *_train.jsonl — learnable (the only files `syfox learn` may read)# * *_cal.jsonl — calibration only (temperature/Platt fit; never learned)# * *_hidden.jsonl — bench only. NEVER taught, NEVER calibrated, NEVER# used for derivation or model selection.# A MANIFEST.json records row counts, label distributions and sha256 per# file so any later run can prove the splits were not touched.## Deterministic: seeded per-row RNG (seed, domain, index); re-running with# the same seed reproduces every file byte-for-byte.## Usage: python3 tools/gen_corpus.py [--seed 20260927] [--out-dir data/big]# ============================================================================import argparseimport hashlibimport jsonimport osimport randomimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import corpus_pools as pools
SEED = 20260927
# verbatim question schemas from the seed data (single-line JSON)Q_TICKETS = r'{"department":{"type":"choice","instructions":"Which team should handle this","criteria":{"billing":"payment or subscription issues","technical":"bugs or integration problems","sales":"pricing or account questions"}},"frustration":{"type":"score","instructions":"How frustrated the customer appears","criteria":["calm just stating facts","frustrated but civil","very angry strong language"]},"is_urgent":{"type":"noul","instructions":"the message conveys urgency or time sensitivity"}}'Q_GUARD = r'{"irreversible":{"type":"noul","instructions":"the command is irreversible or destructive"},"off_task":{"type":"noul","instructions":"the command is off task and unrelated to the goal"},"scope":{"type":"choice","instructions":"what does the command touch","criteria":{"none":"no changes at all","read":"only reads lists shows","write":"modifies project files or data","global":"system wide destructive or irreversible"}}}'Q_GAME = r'{"action":{"type":"choice","instructions":"What should the bot do next","criteria":{"flee":"run away escape avoid danger retreat safe","fight":"attack combat weapon sword strike","dig_in":"hide wait build shelter fortify safe"}}}'
TICKETS_QS = json.loads(Q_TICKETS)GUARD_QS = json.loads(Q_GUARD)GAME_QS = json.loads(Q_GAME)
def first_label(labels): return labels[sorted(labels.keys())[0]]
def compose_tickets_en(i, rng): intents = sorted(pools.TICKETS_INTENT.keys()) intent = intents[i % len(intents)] fr = (i // len(intents)) % 3 ur = (i // (3 * len(intents))) % 2 == 1 state = pools.tickets_state(intent, fr, ur, rng) return state, TICKETS_QS, {"department": intent, "frustration": str(fr), "is_urgent": "true" if ur else "false"}
def compose_guard(i, rng): state, labels = pools.guard_state(rng) return state, GUARD_QS, labels
def compose_game(i, rng): actions = sorted(pools.GAME_FEATURES.keys()) action = actions[i % len(actions)] return pools.game_state(action, rng), GAME_QS, {"action": action}
def compose_tickets_ml(lang, i, rng): intents = sorted(pools.TICKETS_ML_INTENT[lang].keys()) intent = intents[i % len(intents)] fr = (i // len(intents)) % 3 ur = (i // (3 * len(intents))) % 2 == 1 state = pools.ml_state(lang, intent, fr, ur, rng) return state, TICKETS_QS, {"department": intent, "frustration": str(fr), "is_urgent": "true" if ur else "false"}
def make_rows(name, n, composer, seed): """Compose n UNIQUE rows (dedup by state text; deterministic retries).""" rows, seen, dups = [], set(), 0 i = 0 while len(rows) < n: rng = random.Random(f"{seed}:{name}:{i}") state, qs, labels = composer(i, rng) i += 1 if state in seen: dups += 1 if dups > n * 3: sys.exit(f"gen_corpus: {name}: vocabulary exhausted at {len(rows)} rows") continue seen.add(state) rows.append({"state": state, "questions": qs, "labels": labels}) return rows, dups
def split_70_15_15(rows, seed): """Stratified 70/15/15 by first label (sorted-key order, same convention as bench.hpp first_label). Per stratum: seeded shuffle, round(0.15) to cal and hidden (min 1 when the stratum has >=3 rows), train keeps the rest.""" groups = {} for idx, r in enumerate(rows): groups.setdefault(first_label(r["labels"]), []).append(idx) cal_idx, hidden_idx = set(), set() for key in sorted(groups.keys()): idxs = list(groups[key]) rng = random.Random(f"{seed}:split:{key}") rng.shuffle(idxs) n = len(idxs) n_cal = round(n * 0.15) n_hid = round(n * 0.15) if n >= 3: n_cal = max(1, n_cal) n_hid = max(1, n_hid) if n - n_cal - n_hid < 1: n_cal = max(0, (n - 1) // 2) n_hid = n - 1 - n_cal cal_idx.update(idxs[:n_cal]) hidden_idx.update(idxs[n_cal:n_cal + n_hid]) train = [r for i, r in enumerate(rows) if i not in cal_idx and i not in hidden_idx] cal = [r for i, r in enumerate(rows) if i in cal_idx] hidden = [r for i, r in enumerate(rows) if i in hidden_idx] return train, cal, hidden
def dist(rows): d = {} for r in rows: k = first_label(r["labels"]) d[k] = d.get(k, 0) + 1 return dict(sorted(d.items()))
def sha256_of(path): h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(65536), b""): h.update(chunk) return h.hexdigest()
def write_jsonl(path, rows): with open(path, "w", encoding="utf-8") as fh: for r in rows: fh.write(json.dumps(r, ensure_ascii=False) + "\n")
def main(): ap = argparse.ArgumentParser(description="SyFox v3 corpus generator (70/15/15)") ap.add_argument("--seed", type=int, default=SEED) ap.add_argument("--out-dir", default=os.path.join( os.path.dirname(os.path.abspath(__file__)), "..", "data", "big")) ap.add_argument("--tickets", type=int, default=12000) ap.add_argument("--guard", type=int, default=8000) ap.add_argument("--game", type=int, default=8000) ap.add_argument("--ml", type=int, default=3600, help="rows per language for tickets_bn/hi/ru (15%% >= 500 -> >=3334)") args = ap.parse_args() os.makedirs(args.out_dir, exist_ok=True)
jobs = [ ("tickets_en", args.tickets, compose_tickets_en), ("guard", args.guard, compose_guard), ("game", args.game, compose_game), ("tickets_bn", args.ml, lambda i, rng: compose_tickets_ml("bn", i, rng)), ("tickets_hi", args.ml, lambda i, rng: compose_tickets_ml("hi", i, rng)), ("tickets_ru", args.ml, lambda i, rng: compose_tickets_ml("ru", i, rng)), ]
manifest = { "generator": "tools/gen_corpus.py", "seed": args.seed, "schema": "state/questions/labels (house format, unchanged)", "splits": {"train": 0.70, "cal": 0.15, "hidden": 0.15}, "firewall": { "train": "learnable (syfox learn)", "cal": "calibration only (syfox calibrate); never learned from", "hidden": "bench only; NEVER taught, calibrated, derived or used " "for model selection (enforced in core/firewall.hpp)", }, "files": {}, }
for name, n, composer in jobs: rows, dups = make_rows(name, n, composer, args.seed) train, cal, hidden = split_70_15_15(rows, args.seed) counts = {} for tag, part in (("train", train), ("cal", cal), ("hidden", hidden)): path = os.path.join(args.out_dir, f"{name}_{tag}.jsonl") write_jsonl(path, part) counts[tag] = len(part) manifest["files"][os.path.basename(path)] = { "rows": len(part), "label_dist": dist(part), "sha256": sha256_of(path), "role": tag, } print(f"{name}: {len(rows)} unique rows (dedup skipped {dups}) -> " f"train {counts['train']} / cal {counts['cal']} / hidden {counts['hidden']}") print(f" train dist {dist(train)}")
mpath = os.path.join(args.out_dir, "MANIFEST.json") with open(mpath, "w", encoding="utf-8") as fh: json.dump(manifest, fh, ensure_ascii=False, indent=1, sort_keys=True) fh.write("\n") total = sum(f["rows"] for f in manifest["files"].values()) print(f"manifest: {mpath} ({len(manifest['files'])} files, {total} rows total)")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195#!/usr/bin/env python3# ============================================================================# SyFox — gen_paraphrases.py (P3, v2.1)# Data augmentation for generalization: for each TRAIN state, generate up to# 5 paraphrased variants and write them as extra lessons. The fabric learns# the same outcome from differently-worded experiences, so the energy routes# no longer depend on one exact surface form.## Hard rules (honesty of the eval):# * TRAIN ONLY — the script REFUSES any path containing "heldout". Held-out# rows must stay unseen by the fabric, directly or through paraphrase.# * LABEL-SAFE — words are only REPLACED using the single-word synonym# table (data/synonyms.txt, shared with core/normalize.hpp), never# inserted; inserted fillers are neutral politeness only. Swapping# "urgent"->"immediately" keeps is_urgent=true true; a row that is not# urgent never gains an urgency word.# * DETERMINISTIC — a per-row seeded RNG; same input file -> same output.# * The core stays physics-only: this is OUTSIDE the substrate, a tool# that writes lesson files. No neural net anywhere.## Variant strategies (cycled per row, up to 5 per state):# 1 clause reorder — swap the first two sentence segments# 2 filler prefix — neutral lead-in ("please help:", "i think", ...)# 3 filler suffix — neutral sign-off ("thanks.", "please advise.", ...)# 4 combo — synonym swap + reorder (swap ALONE is deliberately# excluded: a table word folds back to the same stem,# so a synonym-only variant normalizes to an IDENTICAL# token stream = pure repetition. Measured on the# tickets heldout split: repetition-heavy augmentation# collapsed heldout accuracy 1.00 -> 0.33 (intern mass# grows linearly and damps injection by 1/sqrt(mass)),# so every variant here carries NEW token content.)# 5 fallback — a second filler prefix (only if a strategy above# produced no change)## Usage:# python3 tools/gen_paraphrases.py # all data/*_train.jsonl# python3 tools/gen_paraphrases.py --only tickets# ============================================================================import argparseimport jsonimport osimport randomimport reimport sys
SEED = 20260926DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")SYNONYMS = os.path.join(DATA, "synonyms.txt")
PREFIXES = ["please help:", "i think", "quick note:", "just to add,", "hey,"]SUFFIXES = ["thanks.", "thank you.", "please advise.", "appreciate it.", "let me know."]
WORD_RE = re.compile(r"[A-Za-z]+")
def load_synonyms(path): """canonical -> [alternates]; the map is symmetric (word <-> alternates).""" swap = {} if not os.path.exists(path): return swap with open(path, encoding="utf-8") as fh: for line in fh: line = line.strip() if not line or line.startswith("#") or ":" not in line: continue canon, rest = line.split(":", 1) canon = canon.strip().lower() variants = [v.strip().lower() for v in rest.split(",") if v.strip()] group = [canon] + variants for w in group: others = [x for x in group if x != w] swap.setdefault(w, []) for o in others: if o not in swap[w]: swap[w].append(o) return swap
def synonym_swap(text, swap, rng): """Replace the FIRST table word found with one of its alternates.""" words = list(WORD_RE.finditer(text)) candidates = [m for m in words if m.group(0).lower() in swap] if not candidates: return None m = candidates[0] alt = swap[m.group(0).lower()][rng.randrange(len(swap[m.group(0).lower()]))] return text[:m.start()] + alt + text[m.end():]
SENT_SPLIT = re.compile(r"(?<=[.!?])\s+")CLAUSE_SPLIT = re.compile(r",\s+|\s+\band\b\s+|\s+\bbut\b\s+")
def clause_reorder(text, swap, rng): """Swap the first two segments (sentences, else comma/and/but clauses).""" parts = SENT_SPLIT.split(text.strip()) if len(parts) >= 2: parts[0], parts[1] = parts[1], parts[0] return " ".join(parts) parts = CLAUSE_SPLIT.split(text.strip()) if parts and len(parts) >= 4: # split with captures: keep groups intact return text # capture-group splitting: too fiddly, skip if len(parts) >= 2: parts[0], parts[1] = parts[1], parts[0] return ", ".join(parts) return None
def filler_prefix(text, swap, rng): return PREFIXES[rng.randrange(len(PREFIXES))] + " " + text
def filler_suffix(text, swap, rng): return text + " " + SUFFIXES[rng.randrange(len(SUFFIXES))]
def combo(text, swap, rng): out = synonym_swap(text, swap, rng) out = clause_reorder(out or text, swap, rng) if out: return out out = filler_prefix(text, swap, rng) return out + " " + SUFFIXES[rng.randrange(len(SUFFIXES))]
STRATEGIES = [clause_reorder, filler_prefix, filler_suffix, combo]STRATEGY_NAMES = ["clause_reorder", "filler_prefix", "filler_suffix", "combo"]
def paraphrase_row(row, swap, rng, per_state): seen = {row["state"]} out = [] order = list(range(len(STRATEGIES))) rng.shuffle(order) # per-row strategy order, still seeded attempts = 0 while len(out) < per_state and attempts < per_state * 4: si = attempts % len(STRATEGIES) strategy = STRATEGIES[order[si]] text = strategy(row["state"], swap, rng) attempts += 1 if not text or text in seen: # guaranteed-change fallback: neutral prefix (always differs) text = PREFIXES[(attempts + len(out)) % len(PREFIXES)] + " " + row["state"] if text in seen: continue seen.add(text) variant = dict(row) variant["state"] = text variant["paraphrase_of"] = row["state"] variant["strategy"] = STRATEGY_NAMES[order[si]] out.append(variant) return out
def main(): ap = argparse.ArgumentParser(description="SyFox train-only paraphrase augmenter") ap.add_argument("--data-dir", default=DATA) ap.add_argument("--synonyms", default=SYNONYMS) ap.add_argument("--per-state", type=int, default=5) ap.add_argument("--seed", type=int, default=SEED) ap.add_argument("--only", default=None, help="substring filter on file name") args = ap.parse_args()
if "heldout" in args.synonyms: sys.exit("gen_paraphrases: refusing heldout synonyms path") swap = load_synonyms(args.synonyms) if not swap: sys.exit(f"gen_paraphrases: no synonym table at {args.synonyms}")
files = sorted(f for f in os.listdir(args.data_dir) if f.endswith("_train.jsonl") and (args.only is None or args.only in f)) if not files: sys.exit("gen_paraphrases: no *_train.jsonl files matched") for f in files: src = os.path.join(args.data_dir, f) if "heldout" in src: sys.exit(f"gen_paraphrases: refusing heldout input {src}") with open(src, encoding="utf-8") as fh: rows = [json.loads(line) for line in fh if line.strip()] out_path = src.replace("_train.jsonl", "_paraphrased.jsonl") total = 0 with open(out_path, "w", encoding="utf-8") as out: for i, row in enumerate(rows): rng = random.Random(f"{args.seed}:{f}:{i}") for v in paraphrase_row(row, swap, rng, args.per_state): out.write(json.dumps(v, ensure_ascii=False) + "\n") total += 1 print(f"{f}: {len(rows)} states -> {total} paraphrased lessons -> " f"{os.path.basename(out_path)}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168#!/usr/bin/env python3# ============================================================================# SyFox — gen_variants.py (v2.2)# Variant/paraphrase generation for mass-guarded re-teaching.## Physics contract (measured, v2.1 + v2.2):# * v2.1 measured raw re-teaching of near-duplicates REGRESSING held-out# accuracy (tickets 1.000 -> 0.500): intern() counts mass linearly and# injection damps by 1/sqrt(mass), so re-exposed surface forms re-weight# the field toward the training surface. That artifact is now fixed at# the ENGINE boundary: `syfox learn --augment` skips intern() for# concepts already in the vocabulary, so a variant lesson lays and# strengthens LANES only — coverage grows, acoustic mass does not.# * This generator therefore never needs to hold back: it produces the# variants; the mass guard makes them safe. The A/B stays reproducible# (train-only vs train+variants, `make models-vast`).## Variant ops per taught state (5-10 variants, deterministic — seeded by# the row index, never by wall-clock):# 1. synonym swap — 1-2 swappable words replaced via data/synonyms.txt# 2. clause rotation — comma/and-segments rotated left by one# 3. adjacent reorder — two adjacent words swapped (mid-sentence)# 4. filler addition — "Please", "I think", "Asap," style fillers# 5. combo — reorder + filler + synonym in one## Discipline (hard-coded, not optional):# * refuses *_heldout.jsonl paths — eval data is never transformed,# never generated from, never taught from;# * input must be a *_train.jsonl file; output is <stem>_expanded.jsonl;# * labels and question schemas are copied verbatim from the source row.# ============================================================================import jsonimport randomimport reimport sysfrom pathlib import Path
SEED = 20260927WORD_RE = re.compile(r"[A-Za-z]+")CLAUSE_RE = re.compile(r",\s+|\s+and\s+|\.\s+")
def load_synonyms(path: Path) -> dict: """canonical -> [variants]; used both directions for surface swaps.""" table = {} if not path.exists(): return table for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or ":" not in line: continue canon, rest = line.split(":", 1) variants = [v.strip().lower() for v in rest.split(",") if v.strip()] table[canon.strip().lower()] = variants return table
def swap_synonyms(text: str, table: dict, rng: random.Random, n_swaps: int) -> str: """Replace up to n_swaps swappable words (canonical->variant or variant->canonical).""" words = text.split(" ") swappable = [] for i, w in enumerate(words): lw = re.sub(r"[^a-z]", "", w.lower()) for canon, variants in table.items(): if lw == canon or lw in variants: swappable.append((i, canon, variants)) break if not swappable: return text rng.shuffle(swappable) for i, canon, variants in swappable[:n_swaps]: choice = rng.choice(variants + [canon]) words[i] = re.sub(r"[A-Za-z]+", choice, words[i], count=1) return " ".join(words)
def rotate_clauses(text: str) -> str: parts = CLAUSE_RE.split(text) if len(parts) < 2: return text parts = parts[1:] + parts[:1] return ", ".join(p.strip(" .") for p in parts) + "."
def swap_adjacent(text: str, rng: random.Random) -> str: words = text.split(" ") if len(words) < 4: return text lo, hi = 1, len(words) - 2 # never the first/last word i = rng.randint(lo, hi - 1) words[i], words[i + 1] = words[i + 1], words[i] return " ".join(words)
FILLERS_PRE = ["Please help:", "I think", "Quick one,", "Hey,"]FILLERS_POST = ["Please.", "Thanks.", "Asap please.", "Appreciate it."]
def add_filler(text: str, rng: random.Random) -> str: if rng.random() < 0.5: return f"{rng.choice(FILLERS_PRE)} {text[0].lower()}{text[1:]}" return f"{text} {rng.choice(FILLERS_POST)}"
def variants_for(state: str, table: dict, rng: random.Random, count: int, with_fillers: bool) -> list: out, seen = [], {state.lower()} ops = [ lambda s: swap_synonyms(s, table, rng, 1), lambda s: swap_synonyms(s, table, rng, 2), rotate_clauses, lambda s: swap_adjacent(s, rng), ] if with_fillers: ops += [lambda s: add_filler(swap_adjacent(s, rng), rng), lambda s: add_filler(swap_synonyms(s, table, rng, 1), rng)] for _ in range(count * 4): # retry budget for dedup if len(out) >= count: break op = rng.choice(ops) v = op(state) if v.lower() in seen or not v.strip(): continue seen.add(v.lower()) out.append(v) return out
def main() -> int: args = [a for a in sys.argv[1:] if not a.startswith("--")] with_fillers = "--full" in sys.argv if not args: print("usage: gen_variants.py FILE_train.jsonl [--full] (refuses *_heldout*)") return 2 src = Path(args[0]) if "heldout" in src.name: print(f"REFUSED: {src.name} is held-out eval data; never transformed, never taught from") return 2 if not src.name.endswith("_train.jsonl"): print(f"REFUSED: {src.name} must be a *_train.jsonl file (train-side discipline)") return 2 count = 8 if not with_fillers else 10 for a in sys.argv[1:]: if a.startswith("--count="): count = int(a.split("=", 1)[1])
table = load_synonyms(src.parent / "synonyms.txt") stem = src.name.replace("_train.jsonl", "") out_path = src.parent / (f"{stem}_expanded_full.jsonl" if with_fillers else f"{stem}_expanded.jsonl") rows = [json.loads(l) for l in src.read_text(encoding="utf-8").splitlines() if l.strip()]
written = 0 with out_path.open("w", encoding="utf-8") as f: for idx, row in enumerate(rows): rng = random.Random(SEED + idx) # deterministic per row state = row.get("state", "") for v in variants_for(state, table, rng, count, with_fillers): f.write(json.dumps({"state": v, "questions": row["questions"], "labels": row["labels"]}, ensure_ascii=False) + "\n") written += 1 print(f"{src.name}: {len(rows)} taught states -> {written} variants -> {out_path.name}" f" ({'full' if with_fillers else 'reorder+synonym'} mode)") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209#!/usr/bin/env python3"""Giant-model manual benchmark: per-domain hidden scoring + router +end-to-end + handcrafted probes, through the ctypes bridge.
Everything is measured with energy_norm ON (mandatory at corpus scale —v3.1.0 finding). Router accuracy: the 'domain' question asked on everyhidden row. End-to-end: router correct AND class correct in one decide call(the bridge returns answers for every question in one shot).
Usage: python3 tools/giant_bench.py --model-slug giant-latin --domains \ tickets_en,bank77,sms,clinc,... [--limit N] [--dump out.jsonl] python3 tools/giant_bench.py --probes --model-slug giant-latin"""import argparseimport jsonimport osimport sysimport timefrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "server"))from syfox_bridge import SyFoxEngine # noqa: E402
GIANT = Path(os.environ.get("GIANT_DIR", str(ROOT / "data" / "giant")))
def rank_of(gold: str, probs: dict) -> int: order = sorted(probs.items(), key=lambda kv: -kv[1]) for i, (k, _) in enumerate(order, 1): if k == gold: return i return len(order) + 1
def load_schemas() -> dict: return json.load(open(GIANT / "schemas.json"))
def build_questions(r: dict, schemas: dict) -> dict: """Full-schema rows pass through; schema-free rows (state/domain/labels, as shipped in the HF repo) get their questions rebuilt from schemas.""" if "questions" in r: return r["questions"] dom = r["domain"] spec = schemas["domains"][dom] if spec.get("type") == "noul_multi": return r["questions"] # noul keeps its questions inline rq = {"type": "choice", "instructions": "", "criteria": schemas["domains"]["_router"]["criteria"]} cq = {"type": "choice", "instructions": "", "criteria": spec["criteria"]} return {"domain": rq, spec["qkey"]: cq}
def hidden_path(dom: str) -> Path: for cand in (GIANT / f"{dom}_hidden.jsonl", GIANT / "eval" / f"{dom}_hidden.jsonl"): if cand.exists(): return cand return GIANT / f"{dom}_hidden.jsonl"
def run_domain(eng: SyFoxEngine, dom: str, limit: int, dump: list, schemas: dict) -> dict: rows = [json.loads(l) for l in open(hidden_path(dom))] if limit: rows = rows[:limit] rows = [{**r, "questions": build_questions(r, schemas)} for r in rows] qkeys = [k for k in rows[0]["questions"] if k != "domain"] qkey = qkeys[0] rt_ok = cl_ok = e2e_ok = defer = 0 n = 0 t0 = time.time() for i, r in enumerate(rows): answers, usage, _ = eng.decide(r["state"], r["questions"], {"energy_norm": True}) n += 1 da = answers.get("domain", {}) if da.get("deferred"): defer += 1 continue rt_hit = da.get("choice") == r["labels"]["domain"] rt_ok += rt_hit ca = answers.get(qkey, {}) gold = r["labels"].get(qkey) if ca.get("deferred"): continue if gold == "true" or gold == "false": cl_hit = (ca.get("choice") == gold) else: cl_hit = (ca.get("choice") == gold) cl_ok += cl_hit e2e_ok += (rt_hit and cl_hit) if dump is not None: probs = ca.get("probabilities", {}) top = sorted(probs.items(), key=lambda kv: -kv[1]) dump.append(json.dumps({ "domain": dom, "i": i, "gold_router": r["labels"]["domain"], "pred_router": da.get("choice"), "gold": gold, "pred": ca.get("choice"), "correct": bool(cl_hit), "conf": ca.get("confidence", 0), "gold_rank": rank_of(gold, probs) if probs else 0, "margin": round(top[0][1] - (top[1][1] if len(top) > 1 else 0), 5) if top else 0, }, ensure_ascii=False)) if (i + 1) % 1000 == 0: print(f" {dom}: {i + 1}/{len(rows)} " f"({time.time() - t0:.0f}s)", flush=True) secs = time.time() - t0 return {"domain": dom, "n": n, "router_acc": rt_ok / n, "class_acc": cl_ok / max(1, n - defer), "e2e_acc": e2e_ok / n, "deferred": defer, "secs": round(secs, 1), "ms_per_row": round(1000 * secs / max(1, n), 2), "qkey": qkey, "note": "noul_multi" if qkey == "irreversible" else ""}
def run_probes(model_slug: str) -> None: eng = SyFoxEngine(f"model-{model_slug}") schemas = json.load(open(GIANT / "schemas.json")) inv = {d: {v: k for k, v in schemas["domains"][d]["classes"].items()} for d in schemas["domains"] if schemas["domains"][d].get("classes")} rows = [json.loads(l) for l in open(GIANT / "probes.jsonl")] hits_r = hits_c = scored = 0 print(f"{'id':5s} {'domain':11s} {'router':7s} {'class':7s} " f"{'conf':>5s} state") for p in rows: answers, _, _ = eng.decide(p["state"], p["questions"], {"energy_norm": True}) da = answers.get("domain", {}) dom = p["domain"] qkey = schemas["domains"][dom]["qkey"] ca = answers.get(qkey, {}) r_ok = (not da.get("deferred") and da.get("choice") == p["expected_router"]) hits_r += r_ok line = f"{p['id']:5s} {dom:11s} {'ok' if r_ok else 'MISS':7s}" if p["expected_class"] is None: d = ca.get("deferred", da.get("deferred", False)) line += (f" {'defer' if d else 'ANSWERED':7s} " f"{ca.get('confidence', 0):5.3f} {p['state'][:48]}") else: scored += 1 c_ok = (not ca.get("deferred") and ca.get("choice") == p["expected_class"]) hits_c += c_ok name = schemas["domains"][dom]["classes"].get( ca.get("choice", ""), ca.get("choice", "?")) line += (f" {'ok' if c_ok else 'MISS':7s} " f"{ca.get('confidence', 0):5.3f} -> {name[:26]}") print(line, flush=True) print(f"\nrouter {hits_r}/{len(rows)} = {hits_r/len(rows):.3f} " f"class {hits_c}/{scored} = {hits_c/max(1, scored):.3f} " f"(OOD probes: answered-instead-of-deferred counted as MISS on router)")
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model-slug", default="giant-latin", help="model dir suffix, e.g. giant-latin") ap.add_argument("--domains", default="tickets_en,game,guard,bank77,sms,clinc,enron," "emotion,hate,agnews,polarity,dbpedia,boolq") ap.add_argument("--limit", type=int, default=0) ap.add_argument("--probes", action="store_true") ap.add_argument("--dump", default="") args = ap.parse_args()
if args.probes: run_probes(args.model_slug) return
eng = SyFoxEngine(f"model-{args.model_slug}") info = eng.info() schemas = load_schemas() print(f"model-{args.model_slug}: {info.get('nodes')} nodes / " f"{info.get('lanes')} lanes, energy_norm on") dump = [] if args.dump else None results = [] for dom in args.domains.split(","): dom = dom.strip() f = hidden_path(dom) if not f.exists(): print(f"skip {dom} (no hidden file)") continue r = run_domain(eng, dom, args.limit, dump, schemas) results.append(r) print(f"{r['domain']:11s} n={r['n']:5d} router={r['router_acc']:.3f} " f"class={r['class_acc']:.3f} e2e={r['e2e_acc']:.3f} " f"defer={r['deferred']:4d} ({r['ms_per_row']} ms/row)" f"{' [' + r['note'] + ']' if r['note'] else ''}", flush=True)
tot_n = sum(r["n"] for r in results) if tot_n: print(f"\nTOTAL rows={tot_n} " f"router={sum(r['router_acc']*r['n'] for r in results)/tot_n:.3f} " f"class={sum(r['class_acc']*(r['n']-r['deferred']) for r in results)/tot_n:.3f} " f"e2e={sum(r['e2e_acc']*r['n'] for r in results)/tot_n:.3f}") if args.dump: out = Path(args.dump) out.write_text("\n".join(dump) + "\n") print(f"per-row dump -> {out} ({len(dump)} rows)") (GIANT / "bench_hidden_summary.json").write_text( json.dumps(results, indent=1))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555#!/usr/bin/env python3"""Build the giant-model training corpus from 16 real domains.
RCA fixes baked in (the point of this corpus): Failure 2 (identical per-row instructions are hub pollution at learn) -> instructions are EMPTY on every row of every domain. Failure 3 (natural labels tokenize into shared hubs: "card", "true"...) -> globally-unique opaque anchors per class (te00, ga00, gu00, c00.., sm00, cl000...); no anchor token is shared across domains. Failure 1 (sequential multi-domain training makes late domains weak) -> domains are ROUND-ROBIN INTERLEAVED in the train file, so every domain gets lessons in every region of the stream; 3-epoch consolidation then strengthens rather than drowns.
Also emits: per-script calibration files, per-domain hidden eval files(router + class questions per row), a handcrafted probe file, schemas.json(anchors, class names, criteria) and MANIFEST.json (counts + SHA-256).
Hidden files carry "hidden" in their names -> the M1 firewall refuses themfor learn/calibrate. Data policy: every state string is verbatim datasettext (truncation is the only edit). Criteria for pre-existing domains arepreserved verbatim (only keys remapped to anchors); criteria for the new HFdomains are mined from TRAIN rows only (log-ratio, top-20)."""import hashlibimport jsonimport randomimport sysfrom collections import Counter, defaultdictfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "tools"))from bank77_prepare import mine_criteria # noqa: E402
GIANT = ROOT / "data" / "giant"HF_RAW = ROOT / "data" / "hf_raw"BIG = ROOT / "data" / "big"SEED = 77
# domain -> question key + anchor prefix + class-name resolutionDOMAINS = { "tickets_en": {"qkey": "department", "prefix": "te", "source": "big", "router": "support billing sales technical"}, "tickets_bn": {"qkey": "department", "prefix": "tb", "source": "big", "router": "support tickets bengali"}, "tickets_hi": {"qkey": "department", "prefix": "th", "source": "big", "router": "support tickets hindi"}, "tickets_ru": {"qkey": "department", "prefix": "tr", "source": "big", "router": "support tickets russian"}, "game": {"qkey": "action", "prefix": "ga", "source": "big", "router": "game commands actions"}, "guard": {"qkey": "irreversible", "prefix": "gu", "source": "big", "router": "safety destructive irreversible", "keep_schema": True}, # noul: instructions are the probe carrier "bank77": {"qkey": "intent", "prefix": "c", "source": "bank77", "router": "banking cards payments"}, "sms": {"qkey": "intent", "prefix": "sm", "source": "sms", "router": "text messages spam"}, "clinc": {"qkey": "intent", "prefix": "cl", "source": "hf", "router": "assistant requests weather"}, "enron": {"qkey": "spam", "prefix": "en", "source": "hf", "router": "email inbox messages"}, "emotion": {"qkey": "emotion", "prefix": "em", "source": "hf", "router": "feelings emotions reactions"}, "hate": {"qkey": "speech", "prefix": "ha", "source": "hf", "router": "social offensive posts"}, "agnews": {"qkey": "topic", "prefix": "ag", "source": "hf", "router": "news headlines sports"}, "polarity": {"qkey": "sentiment", "prefix": "po", "source": "hf", "router": "product reviews opinions"}, "dbpedia": {"qkey": "entity", "prefix": "db", "source": "hf", "router": "encyclopedia entities topics"}, "boolq": {"qkey": "truth", "prefix": "bo", "source": "hf", "router": "boolean question passage"},}
CLASS_NAMES = { "agnews": {"0": "world", "1": "sports", "2": "business", "3": "scitech"}, "emotion": {"0": "sadness", "1": "joy", "2": "love", "3": "anger", "4": "fear", "5": "surprise"}, "polarity": {"0": "negative", "1": "positive"}, "hate": {"0": "hate", "1": "offensive", "2": "neither"}, "enron": {"0": "ham", "1": "spam"}, "boolq": {"False": "false", "True": "true"}, "dbpedia": {str(i): n for i, n in enumerate( ["company", "educational_institution", "artist", "athlete", "office_holder", "mean_of_transportation", "building", "natural_place", "village", "animal", "plant", "album", "film", "written_work"])},}
TEXT_CAPS = {"enron": 400, "hate": 280, "agnews": 250, "polarity": 350, "dbpedia": 250, "boolq": 350}TRAIN_CAPS = {"clinc": 8000, "enron": 4000, "emotion": 4000, "hate": 4078, "agnews": 4000, "polarity": 4000, "dbpedia": 4000, "boolq": 4000}HIDDEN_CAPS = {"clinc": 4500, "enron": 2000, "emotion": 2000, "hate": 1500, "agnews": 2000, "polarity": 2000, "dbpedia": 2000, "boolq": 1500}CAL_CAPS = {"clinc": 3000, "enron": 800, "emotion": 700, "hate": 400, "agnews": 400, "polarity": 400, "dbpedia": 400, "boolq": 500}IMBALANCE_TRAIN_CAP = {"hate": {"1": 2500}} # offensive: real-world 78% share
def load_jsonl(p: Path) -> list: return [json.loads(l) for l in open(p) if l.strip()]
def dump_jsonl(p: Path, rows: list) -> None: p.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in rows) + "\n")
def sha256(p: Path) -> str: return hashlib.sha256(p.read_bytes()).hexdigest()
def hf_load(dom: str, tag: str) -> list: p = HF_RAW / f"{dom}_{tag}.json" if not p.exists(): return [] return json.loads(p.read_text())
def hf_state(dom: str, r: dict) -> str: t = " ".join(str(r["text"]).split()) cap = TEXT_CAPS.get(dom, 0) return t[:cap] if cap else t
def stratified_take(rows: list, n: int, rng: random.Random) -> list: """Deterministic stratified sample of n rows (as balanced as possible).""" by = defaultdict(list) for r in rows: by[r["label"]].append(r) for v in by.values(): rng.shuffle(v) out, i = [], 0 while len(out) < n and any(by.values()): for v in by.values(): if v: out.append(v.pop()) if len(out) >= n: break i += 1 return out
def carve(dom: str, rows: list) -> dict: """For domains without official cal/hidden: carve hidden + cal out.""" rng = random.Random(SEED) by = defaultdict(list) for r in rows: by[r["label"]].append(r) for v in by.values(): rng.shuffle(v) hidden_n, cal_n = HIDDEN_CAPS.get(dom, 0), CAL_CAPS.get(dom, 0) hidden, cal = [], [] for cls, v in by.items(): h = min(len(v), max(1, round(hidden_n * len(v) / len(rows)))) hidden.extend(v[:h]) c = min(len(v) - h, max(1, round(cal_n * len(v) / len(rows)))) cal.extend(v[h:h + c]) del v[:h + c] train = [r for v in by.values() for r in v] return {"train": train, "cal": cal, "hidden": hidden}
# --------------------------------------------------------------------------# domain loading -> {"train": [...], "cal": [...], "hidden": [...]} with# {"text", "label"} rows; labels are the DOMAIN's natural class names.
def norm_big(dom: str, split: str) -> list: out = [] for r in load_jsonl(BIG / f"{dom}_{split}.jsonl"): qk = next(iter(r["questions"])) if r["state"].strip() and r["labels"].get(qk): out.append({"text": r["state"], "label": r["labels"][qk], "row": r}) return out
def norm_bank77(split: str) -> list: fn = {"train": "bank77_train.jsonl", "cal": "bank77_cal_bare.jsonl", "hidden": "bank77_hidden.jsonl"}[split] out = [] for r in load_jsonl(ROOT / "data" / fn): if r["state"].strip(): out.append({"text": r["state"], "label": r["labels"]["intent"], "row": r}) return out
def norm_sms(split: str) -> list: out = [] for r in load_jsonl(ROOT / "data" / f"sms_{split}.jsonl"): if r["state"].strip(): out.append({"text": r["state"], "label": r["labels"]["intent"], "row": r}) return out
def norm_hf_split(dom: str, split: str) -> list: out = [] for r in hf_load(dom, split): if r["text"].strip() and r["label"] is not None: out.append({"text": hf_state(dom, r), "label": str(r["label"])}) return out
def _ids(rows: list) -> set: return {(r["text"], r["label"]) for r in rows}
def _drop(rows: list, ids: set) -> list: return [r for r in rows if (r["text"], r["label"]) not in ids]
def load_domain(dom: str) -> dict: spec = DOMAINS[dom] src = spec["source"] if src == "big": return {s: norm_big(dom, s) for s in ("train", "cal", "hidden")} if src == "bank77": return {s: norm_bank77(s) for s in ("train", "cal", "hidden")} if src == "sms": return {s: norm_sms(s) for s in ("train", "cal", "hidden")} pools = {s: norm_hf_split(dom, s) for s in ("train", "cal", "hidden")} rng = random.Random(SEED) if dom == "hate": # single official split -> carve pools = carve(dom, pools["train"]) if not pools["cal"]: # official train+test only pools["cal"] = stratified_take(pools["train"], CAL_CAPS[dom], rng) pools["train"] = _drop(pools["train"], _ids(pools["cal"])) if dom == "boolq": # one validation pool -> cal+hidden pool = pools["cal"] pools["hidden"] = stratified_take(pool, HIDDEN_CAPS[dom], rng) pools["cal"] = stratified_take(_drop(pool, _ids(pools["hidden"])), CAL_CAPS[dom], rng) # global disjointness: cal/hidden may never overlap each other or train pools["hidden"] = _drop(pools["hidden"], _ids(pools["cal"])) pools["hidden"] = _drop(pools["hidden"], _ids(pools["train"])) pools["cal"] = _drop(pools["cal"], _ids(pools["train"])) if dom in TRAIN_CAPS: pool = pools["train"] for lbl, cap in IMBALANCE_TRAIN_CAP.get(dom, {}).items(): group = [r for r in pool if r["label"] == lbl] rest = [r for r in pool if r["label"] != lbl] pool = stratified_take(group, cap, rng) + rest rng.shuffle(pool) if len(pool) > TRAIN_CAPS[dom]: pool = stratified_take(pool, TRAIN_CAPS[dom], rng) pools["train"] = pool if len(pools["hidden"]) > HIDDEN_CAPS.get(dom, 10**9): pools["hidden"] = stratified_take(pools["hidden"], HIDDEN_CAPS[dom], rng) if len(pools["cal"]) > CAL_CAPS.get(dom, 10**9): pools["cal"] = stratified_take(pools["cal"], CAL_CAPS[dom], rng) return pools
def alloc_anchors(dom: str, classes: list) -> dict: """Natural class name (or bank77 c## id) -> unique opaque anchor.""" spec = DOMAINS[dom] if dom == "bank77": return {c: c for c in classes} # already opaque (c00..c76) width = 3 if len(classes) > 99 else 2 return {c: f"{spec['prefix']}{i:0{width}d}" for i, c in enumerate(classes)}
def base_criteria(dom: str, train: list, anchor_of: dict) -> dict: """anchor -> criteria text. Existing domains keep their criteria verbatim (keys remapped); new HF domains mine top-20 from TRAIN rows only.""" spec = DOMAINS[dom] src = spec["source"] if src in ("big", "bank77", "sms"): c0 = train[0]["row"]["questions"][spec["qkey"]]["criteria"] if dom == "bank77": return {k: v for k, v in c0.items()} return {anchor_of[nat]: txt for nat, txt in c0.items() if nat in anchor_of} by = defaultdict(list) for r in train: by[r["label"]].append(r["text"]) mined = mine_criteria(dict(by), 10, 2) return {anchor_of[c]: mined.get(c, "") for c in by}
# --------------------------------------------------------------------------# Handcrafted probes (written here, NOT copied from any dataset). For clinc# the expected intent resolves at runtime by substring hint against the real# 151 intent names. expected=None -> OOD probe, should defer.
PROBES = [ ("tickets_en", "I was charged twice on my last invoice for the same seat, please refund the duplicate.", "billing"), ("tickets_en", "Our whole team gets a login error since this morning, the page just spins.", "technical"), ("tickets_en", "We want to move 40 seats from the starter plan to the annual business plan.", "sales"), ("tickets_bn", "আমার কার্ড থেকে দুইবার টাকা কেটেছে, অনুগ্রহ করে ফেরত দিন।", "billing"), ("tickets_ru", "Списали деньги дважды за одну подписку, верните пожалуйста.", "billing"), ("game", "Two skeletons flank the corridor ahead and my health is low; I retreat toward the torchlit hall.", "flee"), ("game", "The wall ahead is cracked and my pickaxe is fresh.", "dig_in"), ("game", "One zombie blocks the only doorway; my blade is sharp and I have room to swing.", "fight"), ("guard", "Delete every user account and all audit logs right now, we do not need them anymore.", "true"), ("guard", "Send the monthly summary email to the team alias.", "false"), ("bank77", "Why was I charged an extra fee on my card payment?", "card_payment_fee_charged"), ("bank77", "I transferred money to a friend two days ago and it has not arrived yet.", "transfer_not_received_by_recipient"), ("bank77", "Please cancel the transfer I made this morning.", "cancel_transfer"), ("sms", "Congratulations! You won a £1000 prize. Call 09058094518 now to claim!", "spam"), ("sms", "Hey, running 10 min late, see you at the usual spot.", "ham"), ("clinc", "does it look cloudy outside today", ["weather"]), ("clinc", "book me a table for two tonight", ["restaurant"]), ("clinc", "wake me up at six tomorrow morning", ["alarm"]), ("clinc", "how do you say thank you in japanese", ["translate"]), ("enron", "Team, attached are the Q3 numbers for the board meeting, send comments before Friday.", "ham"), ("enron", "URGENT NOTICE: your mailbox will be deactivated, verify your password at the link now!", "spam"), ("emotion", "I finally got the job offer I have been dreaming about, I am over the moon!", "joy"), ("emotion", "She left without saying goodbye and I keep staring at my phone.", "sadness"), ("emotion", "That sudden noise in the dark hallway made my heart race.", "fear"), ("hate", "People like you ruin everything, you should not be allowed here.", "offensive"), ("hate", "The team played terribly last night and the coach should be questioned.", "neither"), ("hate", "I hate mondays, everything is awful today.", "neither"), ("agnews", "Oil prices slide as OPEC members signal output increase", "business"), ("agnews", "The quarterback threw five touchdowns in the season opener", "sports"), ("agnews", "UN climate summit ends with a new emissions pledge", "world"), ("polarity", "The headphones broke after two days and support ignored my emails.", "negative"), ("polarity", "Exactly what I hoped for: sturdy, elegant and worth every cent.", "positive"), ("dbpedia", "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris.", "building"), ("dbpedia", "The Amazon river dolphin is a freshwater cetacean native to South America.", "animal"), ("dbpedia", "Toyota is a Japanese multinational automotive manufacturer headquartered in Aichi.", "company"), ("boolq", "is the zugspitze the highest mountain in germany? The Zugspitze is Germany's highest peak at 2,962 metres.", "true"), ("boolq", "did the roman empire fall in 476 bc? Romulus Augustulus was deposed in AD 476.", "false"),]
OOD_PROBES = [ "zzqvv plork wumfus xanquu blorp", "fragile dashboard vector quantum tulip echo forty-two", "seventeen purple o'clock beneath soon the", "qq zz pp xx vv kk jj ww ff dd",]
def clinc_intent_names() -> list: """Ordered intent-name list (int id -> name), cached from first-rows.""" cache = ROOT / "data" / "hf_cache" / "clinc_names.json" if cache.exists(): return json.loads(cache.read_text()) import urllib.request url = ("https://datasets-server.huggingface.co/first-rows" "?dataset=clinc%2Fclinc_oos&config=plus&split=validation") with urllib.request.urlopen(url, timeout=30) as r: data = json.loads(r.read().decode()) names = next(f["type"]["names"] for f in data["features"] if f["name"] == "intent") cache.parent.mkdir(parents=True, exist_ok=True) cache.write_text(json.dumps(names)) return names
def main() -> None: GIANT.mkdir(parents=True, exist_ok=True) names = clinc_intent_names() schemas, pools_by_dom, anchor_maps = {}, {}, {} for dom in sorted(DOMAINS): pools = load_domain(dom) spec = DOMAINS[dom] if spec.get("keep_schema"): # noul domain: keep the proven multi-question schema verbatim tmpl = pools["train"][0]["row"]["questions"] schemas[dom] = {"qkey": spec["qkey"], "source": spec["source"], "type": "noul_multi", "classes": {}, "criteria": {}, "router_anchor": None, "template_questions": tmpl} anchor_maps[dom] = {} pools_by_dom[dom] = pools print(f"{dom:11s} {spec['source']:6s} train={len(pools['train']):6d} " f"cal={len(pools['cal']):5d} hidden={len(pools['hidden']):5d} " f"classes=noul(x2)+scope") continue classes = sorted({r["label"] for r in pools["train"] + pools["cal"] + pools["hidden"]}) anchor_of = alloc_anchors(dom, classes) if dom == "bank77": cat = json.load(open(ROOT / "data" / "bank77_categories.json")) inv_lbl = {v: k for k, v in cat["label_of"].items()} name_of = {c: inv_lbl[c] for c in classes} elif dom == "clinc": name_of = {c: names[int(c)] for c in classes} elif spec["source"] == "hf": name_of = {c: CLASS_NAMES[dom].get(c, c) for c in classes} else: name_of = {c: c for c in classes} crit = base_criteria(dom, pools["train"], anchor_of) anchor_maps[dom] = anchor_of schemas[dom] = {"qkey": spec["qkey"], "source": spec["source"], "classes": {anchor_of[c]: name_of[c] for c in classes}, "criteria": crit, "router_anchor": None} pools_by_dom[dom] = pools print(f"{dom:11s} {spec['source']:6s} train={len(pools['train']):6d} " f"cal={len(pools['cal']):5d} hidden={len(pools['hidden']):5d} " f"classes={len(classes)}")
doms = sorted(DOMAINS) rt_of = {d: f"rt{i:02d}" for i, d in enumerate(doms)} for d in doms: schemas[d]["router_anchor"] = rt_of[d] router_q = {"type": "choice", "instructions": "", "criteria": {rt_of[d]: DOMAINS[d]["router"] for d in doms}} schemas["_router"] = {"criteria": router_q["criteria"]}
seen = {} for d in doms: for a in schemas[d]["classes"]: assert a not in seen, f"anchor collision {a}: {d} vs {seen[a]}" seen[a] = d print(f"anchors: {len(seen)} unique across {len(doms)} domains")
def class_q_of(dom: str) -> dict: return {"type": "choice", "instructions": "", "criteria": schemas[dom]["criteria"]}
# emit + write ---------------------------------------------------------- cal_by_script, hidden_out, manifest_rows = {}, {}, [] SCRIPT_OF = {"tickets_bn": "bengali", "tickets_hi": "devanagari", "tickets_ru": "cyrillic"} queues = {d: [] for d in doms} # per-domain train queues for dom in doms: pools = pools_by_dom[dom] rt = rt_of[dom] if DOMAINS[dom].get("keep_schema"): tmpl = schemas[dom]["template_questions"] for split, rows in pools.items(): conv = [{"state": r["row"]["state"], "questions": {"domain": router_q, **r["row"]["questions"]}, "labels": {"domain": rt, **r["row"]["labels"]}} for r in rows] if split == "train": queues[dom].extend(conv) elif split == "cal": cal_by_script.setdefault("latin", []).extend(conv) else: hidden_out[dom] = conv manifest_rows.append( {"domain": dom, "source": "big", "schema": "noul_multi", "train": len(pools["train"]), "cal": len(pools["cal"]), "hidden": len(pools["hidden"]), "classes": 2}) continue qkey = DOMAINS[dom]["qkey"] cq = class_q_of(dom) amap = anchor_maps[dom] for split, rows in pools.items(): conv = [{"state": r["text"], "questions": {"domain": router_q, qkey: cq}, "labels": {"domain": rt, qkey: amap[r["label"]]}} for r in rows] if split == "train": queues[dom].extend(conv) elif split == "cal": sc = SCRIPT_OF.get(dom, "latin") cal_by_script.setdefault(sc, []).extend(conv) else: hidden_out[dom] = conv manifest_rows.append({"domain": dom, "source": schemas[dom]["source"], "train": len(pools["train"]), "cal": len(pools["cal"]), "hidden": len(pools["hidden"]), "classes": len(schemas[dom]["classes"])})
# round-robin interleave across domains (Failure-1 fix) interleaved, exhausted = [], set() while len(exhausted) < len(doms): for d in doms: if d in exhausted: continue if not queues[d]: exhausted.add(d) continue interleaved.append(queues[d].pop(0)) dump_jsonl(GIANT / "train.jsonl", interleaved)
for sc, rows in sorted(cal_by_script.items()): dump_jsonl(GIANT / f"cal_{sc}.jsonl", rows) for dom, rows in sorted(hidden_out.items()): dump_jsonl(GIANT / f"{dom}_hidden.jsonl", rows)
# handcrafted probes ---------------------------------------------------- probes = [] pid = 0 for dom, state, expected in PROBES: spec = DOMAINS[dom] qkey = spec["qkey"] if spec.get("keep_schema"): questions = {"domain": router_q, **schemas[dom]["template_questions"]} else: questions = {"domain": router_q, qkey: class_q_of(dom)} if dom == "clinc": hits = [c for c in schemas[dom]["classes"] if any(h in schemas[dom]["classes"][c] for h in expected)] if not hits: continue anchor = hits[0] elif spec.get("keep_schema"): anchor = expected # noul: literal "true"/"false" else: inv = {v: k for k, v in schemas[dom]["classes"].items()} anchor = inv[expected] probes.append({"id": f"p{pid:02d}", "domain": dom, "state": state, "expected_router": rt_of[dom], "expected_class": anchor, "questions": questions}) pid += 1 for state in OOD_PROBES: dom = "tickets_en" # most familiar question schema probes.append({"id": f"p{pid:02d}", "domain": dom, "state": state, "expected_router": rt_of[dom], "expected_class": None, "questions": {"domain": router_q, "department": class_q_of(dom)}}) pid += 1 dump_jsonl(GIANT / "probes.jsonl", probes)
# schemas + manifest ---------------------------------------------------- (GIANT / "schemas.json").write_text(json.dumps( {"domains": schemas, "router": rt_of}, ensure_ascii=False, indent=1)) files = {} for f in sorted(GIANT.glob("*.jsonl")) + [GIANT / "schemas.json"]: files[f.name] = {"bytes": f.stat().st_size, "sha256": sha256(f)} manifest = { "seed": SEED, "recipe": { "instructions": "empty on every row (Failure-2 fix)", "anchors": "globally-unique opaque per-class anchors (Failure-3 fix)", "train_order": "round-robin domain interleave (Failure-1 fix)", "epochs": 3, "criteria": "existing domains verbatim (keys remapped); new HF domains mined top-20 from train only", }, "sources": { "big": "data/big/* synthetic corpora (SHA-256 MANIFEST.json)", "bank77": "PolyAI banking77 official splits", "sms": "UCI SMS Spam Collection", "hf": ["clinc/clinc_oos", "SetFit/enron_spam", "dair-ai/emotion", "tdavidson/hate_speech_offensive", "fancyzhx/ag_news", "fancyzhx/amazon_polarity", "fancyzhx/dbpedia_14", "google/boolq"], }, "domains": manifest_rows, "train_rows": len(interleaved), "lessons_per_epoch": 2 * len(interleaved), "files": files, } (GIANT / "MANIFEST.json").write_text(json.dumps( manifest, ensure_ascii=False, indent=1)) print(f"train rows {len(interleaved)} ({2*len(interleaved)} lessons/epoch)") print(f"probes {len(probes)} ({len(OOD_PROBES)} OOD)") print(f"cal files: { {k: len(v) for k, v in cal_by_script.items()} }")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135#!/usr/bin/env python3"""Score the HANDMADE probe set (data/handmade_probes.jsonl).
These probes are written by hand, deliberately NOT drawn from any trainingsplit, any evaluation split, or any mined-criteria vocabulary — they aresentences a person would actually type, with everyday wording. They exist toanswer one question: does the fabric GENERALISE, or does it only recognise theexact templates it was taught?
Every row carries an explicit label (the intent / class / department), so thegate is pass/fail per domain, with the failures printed so the failure SHAPEis visible (not just the count).
Usage: python3 tools/handmade_gate.py --schemas datasets/schemas.json \ --models bank77=model/b77-sem router=model/router16 \ --model-default model/giant-latin [--per-domain] [--dump out.jsonl]"""import argparseimport jsonimport osimport sysfrom collections import Counter, defaultdict
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(ROOT, "server"))from syfox_bridge import SyFoxEngine # noqa: E402
ROUTER_DOMAIN = "router"
def main(): ap = argparse.ArgumentParser() ap.add_argument("--probes", default=os.path.join(ROOT, "data", "handmade_probes.jsonl")) ap.add_argument("--schemas", default=os.path.join(ROOT, "datasets", "schemas.json")) ap.add_argument("--models", default="", help="domain=dir,domain=dir (router domain included)") ap.add_argument("--model-default", default="model/giant-latin") ap.add_argument("--router-criteria", default="", help="JSON file overriding the router criteria") ap.add_argument("--dump", default="") ap.add_argument("--quiet", action="store_true") ap.add_argument("--affinity-mix", type=float, default=None, help="v4.0 affinity field readout channel (0 = legacy, 1 = affinity); " "unset = use the model's RECORDED composition") ap.add_argument("--affinity-pmi", action="store_true", help="v4.0: log-odds (PMI) form of the contrast instead of the linear one") ap.add_argument("--ngrams", choices=["on", "off"], default="off", help="the character-trigram bridge (sub-word routing for unseen words)") args = ap.parse_args()
schemas = json.load(open(args.schemas)) doms = schemas["domains"] router_crit = doms["_router"]["criteria"] if args.router_criteria: router_crit = json.load(open(args.router_criteria)) if isinstance(router_crit, dict) and "criteria" in router_crit: router_crit = router_crit["criteria"]
per_model = {} for kv in args.models.split(","): if "=" in kv: k, v = kv.split("=", 1) per_model[k.strip()] = v.strip()
rows = [json.loads(l) for l in open(args.probes) if l.strip()] by_domain = defaultdict(list) for r in rows: by_domain[r["domain"]].append(r)
engines = {} dump = [] total_hit = total_n = 0 print(f"{'domain':<14}{'n':>5}{'hit':>6}{'acc':>9} model") print("-" * 62) for dom in sorted(by_domain): if dom == ROUTER_DOMAIN: mdir = per_model.get(dom, args.model_default) q = {"domain": {"type": "choice", "instructions": "", "criteria": router_crit}} qkey = "domain" else: spec = doms.get(dom) if spec is None: print(f"{dom:<14} NO SCHEMA") continue mdir = per_model.get(dom, args.model_default) qkey = spec["qkey"] q = {qkey: {"type": "choice", "instructions": "", "criteria": spec["criteria"]}} if mdir not in engines: eng = SyFoxEngine(mdir) eng.set_energy_norm(True) # only override the model's RECORDED composition when the operator # explicitly asked for a different readout (unset = keep it) if args.affinity_mix is not None: eng.set_affinity(args.affinity_mix, args.affinity_pmi) if args.ngrams != "off": eng.set_ngrams(args.ngrams == "on") engines[mdir] = eng eng = engines[mdir] hit = 0 fails = [] for r in by_domain[dom]: a, _, _ = eng.decide(r["state"], q, {"energy_norm": True}) ans = a.get(qkey, {}) pred = ans.get("choice", "") ok = (pred == r["label"]) and not ans.get("deferred") hit += ok total_hit += ok total_n += 1 if not ok: fails.append((r["id"], r["label"], pred, ans.get("deferred", False), ans.get("confidence", 0.0), r["state"][:52])) if args.dump: dump.append(json.dumps({"id": r["id"], "domain": dom, "gold": r["label"], "pred": pred, "deferred": ans.get("deferred", False), "confidence": ans.get("confidence", 0.0), "state": r["state"]}, ensure_ascii=False)) acc = hit / len(by_domain[dom]) if by_domain[dom] else 0.0 print(f"{dom:<14}{len(by_domain[dom]):>5}{hit:>6}{acc:>9.3f} {mdir}") if not args.quiet and fails: for fid, gold, pred, dfr, conf, st in fails[:14]: print(f" miss {fid:<10} gold={gold:<10} pred={pred:<10} " f"{'DEFER' if dfr else f'conf {conf:.2f}'} {st}") if len(fails) > 14: print(f" ... and {len(fails)-14} more")
print("-" * 62) print(f"{'TOTAL':<14}{total_n:>5}{total_hit:>6}{total_hit/max(1,total_n):>9.3f}") if args.dump: with open(args.dump, "w") as f: f.write("\n".join(dump) + "\n") print(f"per-row dump -> {args.dump}") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125#!/usr/bin/env python3"""Fetch real HF datasets for the giant model via parquet shards.
For each dataset+split: GET /api/datasets/{id}/parquet -> shard URLs, downloadup to 3 evenly-spaced shards (cached under data/hf_cache/parquet/), then samplerows EVENLY over the concatenated shard rows (numpy linspace) so class-orderedcorpora still give proportional class coverage. Output: data/hf_raw/{dom}_{split}.jsonwith verbatim dataset text (truncation happens later in giant_prepare.py).
No synthetic text is added here."""import jsonimport sysimport timeimport urllib.requestfrom pathlib import Path
import numpy as npimport pandas as pd
ROOT = Path(__file__).resolve().parent.parentCACHE = ROOT / "data" / "hf_cache" / "parquet"OUT = ROOT / "data" / "hf_raw"UA = {"User-Agent": "syfox-giant-prepare/1.0"}
def http_get(url: str, dest: Path) -> None: for attempt in range(4): try: req = urllib.request.Request(url, headers=UA) with urllib.request.urlopen(req, timeout=120) as r, open(dest, "wb") as f: while True: chunk = r.read(1 << 20) if not chunk: break f.write(chunk) return except Exception as e: # noqa: BLE001 if attempt == 3: raise print(f" retry {attempt + 1} for {dest.name}: {e}", file=sys.stderr) time.sleep(3 * (attempt + 1))
def shard_urls(ds: str) -> dict: req = urllib.request.Request( f"https://huggingface.co/api/datasets/{ds}/parquet", headers=UA) with urllib.request.urlopen(req, timeout=30) as r: return json.loads(r.read().decode())
def pick(urls: list, n: int) -> list: if len(urls) <= n: return urls idx = np.linspace(0, len(urls) - 1, n).round().astype(int) return [urls[i] for i in dict.fromkeys(idx.tolist())]
def fetch_split(ds: str, cfg: str, split: str, n_sample: int, textf: str, labf: str, tag: str) -> list: tree = shard_urls(ds) urls = pick(tree[cfg][split], 3 if split == "train" else 2) frames = [] for u in urls: name = "__".join(u.split("/datasets/")[1].split("/")) dest = CACHE / name if not dest.exists(): CACHE.mkdir(parents=True, exist_ok=True) print(f" downloading {name}") http_get(u, dest) cols = ([textf] if isinstance(textf, str) else list(textf)) + [labf] frames.append(pd.read_parquet(dest, columns=cols)) df = pd.concat(frames, ignore_index=True) if len(df) > n_sample: sel = np.linspace(0, len(df) - 1, n_sample).round().astype(int) df = df.iloc[sel] cols = [textf] if isinstance(textf, str) else list(textf) rows = [{"text": " ".join(str(x) for x in t), "label": l} for t, l in zip(df[cols].to_numpy().tolist(), df[labf].tolist())] out = OUT / f"{tag}.json" out.write_text(json.dumps(rows, ensure_ascii=False)) labs = sorted({str(r["label"]) for r in rows}) print(f"{tag}: {len(rows)} rows, {len(labs)} labels " f"e.g. {labs[:6]} | sample {rows[0]['text'][:50]!r}") return rows
PLAN = [ ("clinc", ("text", "intent"), { "train": ("clinc/clinc_oos", "plus", "train", 12000), "cal": ("clinc/clinc_oos", "imbalanced", "validation", 3300), "hidden": ("clinc/clinc_oos", "plus", "test", 4600)}), ("enron", ("text", "label"), { "train": ("SetFit/enron_spam", "default", "train", 8000), "cal": ("SetFit/enron_spam", "default", "test", 800), "hidden": ("SetFit/enron_spam", "default", "test", 2600)}), ("emotion", ("text", "label"), { "train": ("dair-ai/emotion", "split", "train", 8000), "cal": ("dair-ai/emotion", "split", "validation", 700), "hidden": ("dair-ai/emotion", "split", "test", 2100)}), ("hate", ("tweet", "class"), { "train": ("tdavidson/hate_speech_offensive", "default", "train", 9000)}), ("agnews", ("text", "label"), { "train": ("fancyzhx/ag_news", "default", "train", 8000), "hidden": ("fancyzhx/ag_news", "default", "test", 2000)}), ("polarity", ("content", "label"), { "train": ("fancyzhx/amazon_polarity", "amazon_polarity", "train", 8000), "hidden": ("fancyzhx/amazon_polarity", "amazon_polarity", "test", 2000)}), ("dbpedia", ("content", "label"), { "train": ("fancyzhx/dbpedia_14", "dbpedia_14", "train", 8000), "hidden": ("fancyzhx/dbpedia_14", "dbpedia_14", "test", 2000)}), ("boolq", (("question", "passage"), "answer"), { "train": ("google/boolq", "default", "train", 7500), "cal": ("google/boolq", "default", "validation", 3300)}),]
def main() -> None: for dom, fields, splits in PLAN: for tag, (ds, cfg, split, n) in splits.items(): fetch_split(ds, cfg, split, n, fields[0], fields[1], f"{dom}_{tag}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138#!/usr/bin/env python3"""SyFox vs JEV AI — measured head-to-head (v3.6.0).
JEV AI (TypeSafe AI, Sept 2026 early access) is the "System One" decisionmodel: state + typed questions (noul/choice/score) in, per-question value +probability + confidence out, no text generation. SyFox shares thatarchitecture (state + typed questions -> honest decided answers over asettled energy field), so the competition is measurable on JEV's own axes:
workflow accuracy JEV's vendor claim is 0.955; the launch-day self-report was 0.678; syfox measures choice/score accuracy + defer rates per fabric. latency JEV's third-party p50 is 236-276 ms for one question (launch range 70-500 ms); syfox measures the in-process decide path (latency_us p50/p95 in the bench). guardrail JEV reports a hold-precision axis (0.88); syfox measures its guardrail confusion matrix + OOD defer rate. calibration JEV's third-party ECE is 0.246 (laya-model.com/benchmarks); syfox publishes measured ECE per question type. cost JEV: $0.042 / M input tokens, output free; syfox runs locally at $0 compute cost (open core, no API meter).
This tool reads the JSON the C++ bench already measured (make bench ->build/bench-*.json) and prints the head-to-head. Every syfox number comesfrom an actual run in this repository; every JEV number is the PUBLISHEDfigure carried in the bench's jev_reference block. No syfox number is everestimated, and no JEV number is invented: their own press states themultipliers are self-reported ceilings."""import jsonimport osimport sys
BENCH_FILES = [ ("model-tickets", "build/bench-tickets.json"), ("model-game", "build/bench-game.json"), ("model-guard", "build/bench-guard.json"),]
def load(path): if not os.path.exists(path): return None with open(path) as f: return json.load(f)
def pct(x): return f"{100.0 * x:.1f}%"
def main(): rows = [] for model, path in BENCH_FILES: d = load(path) if d is None: print(f"missing {path}: run `make bench` first", file=sys.stderr) continue if not d.get("suite", "").startswith("syfox-jev-parity"): print(f"{path} is not a parity-suite run", file=sys.stderr) continue rows.append((model, d))
if not rows: sys.exit("no parity bench JSON found — run `make bench` first")
# Aggregate measured syfox numbers over the seed fabrics. answered_accs, all_lat, eces, ood = [], [], [], [] for model, d in rows: r = d["routing"] if r.get("choice_n"): answered_accs.append((r["choice_accuracy"], r["choice_n"])) if r.get("score_n"): answered_accs.append((r["score_accuracy"], r["score_n"])) all_lat.append(d["latency_us"]["p50"]) all_lat.append(d["latency_us"]["p95"]) c = d.get("calibration", {}) for k in ("choice_ece", "score_ece"): if k in c: eces.append(c[k]) ood.append(d["honesty"]["ood_defer_rate"])
n_acc = sum(n for _, n in answered_accs) acc = sum(a * n for a, n in answered_accs) / n_acc if n_acc else 0.0 lat_p50_max = max(all_lat) ece = sum(eces) / len(eces) if eces else 0.0 ood_min = min(ood)
jev = rows[0][1]["jev_reference"]
print("=" * 74) print("SYFOX vs JEV AI (TypeSafe) — measured head-to-head on JEV's axes") print("=" * 74) print(f"{'axis':<28}{'JEV AI (published)':<24}{'syfox (measured now)':<22}") print("-" * 74) print(f"{'decision API':<28}{'POST /v1/systemone':<24}{'POST /v1/systemone':<22}") print(f"{'question types':<28}{'noul/choice/score':<24}{'noul/choice/score':<22}") print(f"{'batch questions/call':<28}{'yes (parallel)':<24}{'yes (one settle)':<22}") print(f"{'workflow accuracy (vendor)':<28}{pct(jev.get('workflow_accuracy_vendor', 0.955)):<24}{pct(acc) + f' (n={n_acc} answered)':<22}") print(f"{'workflow accuracy (launch)':<28}{pct(jev['workflow_accuracy']):<24}{'-':<24}") print(f"{'latency (p50)':<28}{jev['latency_ms'] + ' ms':<24}{'<= ' + f'{lat_p50_max:.0f}' + ' us':<22}") print(f"{'input cost':<28}{'$0.042 / M tokens':<24}{'$0 (local core)':<22}") print(f"{'output cost':<28}{'free (typed value)':<24}{'free (typed value)':<22}") print(f"{'ECE (lower better)':<28}{str(jev.get('ece', 'n/a')):<24}{'measured ' + f'{ece:.3f}' + ':<22}") print(f"{'calibration study':<28}{'third-party ECE 0.246':<24}{'ECE published (mean ' + f'{ece:.3f}' + ')':<22}") print(f"{'honest defer w/ reason':<28}{'confidence only':<24}{'defer + reason (OOD ' + pct(ood_min) + ')':<22}") print(f"{'option cap / choice':<28}{'255 then two-stage':<24}{'unbounded criteria map':<22}") print(f"{'determinism':<28}{'not published':<24}{'bit-reproducible (CI)':<22}") print(f"{'full decision audit':<28}{'no':<24}{'evidence JSON + ledger':<22}") print("-" * 74) print(f"JEV reference source: {jev['source']}") print("syfox source: " + ", ".join(f"{m} ({p})" for m, p in BENCH_FILES if load(p))) print("syfox latency = in-process decide path (settle + readout), this tree,") print("measured by core/bench.hpp; JEV latency = their published end-to-end range.")
out = { "suite": "syfox-vs-jev-head-to-head", "syfox_measured": { "answered_accuracy": acc, "answered_n": n_acc, "latency_us_p50_max": lat_p50_max, "mean_ece": ece, "ood_defer_rate_min": ood_min, "per_model": [ {"model": m, "routing": d["routing"], "calibration": d.get("calibration", {}), "latency_us": d["latency_us"], "honesty": d["honesty"], "guardrail": d.get("guardrail", {})} for m, d in rows ], }, "jev_published": jev, } with open("build/jev_comparison.json", "w") as f: json.dump(out, f, indent=2) print("wrote build/jev_comparison.json")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/usr/bin/env python3"""Reasoning probe suite (v3.3): question-context selection before/after thequestion-conditioned readout gate.
Builds a small QA-style fabric (the same shape as the user's dense benchmark:statements + QA pairs as lessons), then runs the reported failure probes:
Test 1 who found the radio -> expect Tariq, was radio (salient noun) Test 2 same, {Tariq,Salma} only -> tie broken by criteria order, was Salma Test 4 unknown options xyz/abc/def -> winner by noise, exact-tie case Test 10 A->B->C chain -> transitive propagation Test 16 latest temperature -> temporal ordering Test 17 purple elephant / submarine -> OOD abstention
Usage: python3 tools/reasoning_probes.py [--rebuild] [--json-out F]"""import argparseimport jsonimport subprocessimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentBIN = str(ROOT / "build" / "syfox")MODEL = str(ROOT / "model-reasoning-probe")
LESSONS = [ # --- Test 1/2 fabric: Tariq / Salma / radio --- ("tariq found the radio in the lab", "tariq"), ("the radio was found by tariq", "tariq"), ("tariq picked up the radio", "tariq"), ("salma was there in the room", "salma"), ("salma saw the radio on the table", "salma"), ("who found the radio tariq did", "tariq"), ("who saw the radio salma did", "salma"), # --- Test 10 chain fabric: A -> B -> C (as event words) --- ("the alarm rang then the lights turned on", "lights"), ("the lights turned on then the door opened", "door"), ("what happens after the alarm the lights", "lights"), # --- Test 16 temporal fabric --- ("the temperature was twenty degrees in the morning", "twenty"), ("the temperature rose to twenty five degrees at noon", "twentyfive"), ("the temperature fell to twenty two degrees in the evening", "twentytwo"), ("the latest temperature reading was twenty two degrees", "twentytwo"), # --- v3.4 multi-hop chains (reported Tests 18/21 analogs) --- ("a sparrow is a bird", "bird"), ("a bird is an animal", "animal"), ("a sparrow has feathers and wings", "bird"), ("alpha relays to bravo", "bravo"), ("bravo relays to charlie", "charlie"), ("charlie relays to delta", "delta"), ("delta relays to echo", "echo"), # --- OOD block: no submarine / favorite-color lessons anywhere ---]
PROBES = [ { "name": "Test 1: who found the radio", "state": "The radio was found by Tariq. Salma was there.", "q": {"i": {"type": "choice", "instructions": "Who found the radio?", "criteria": {"Tariq": "the person who found it", "Salma": "a person present", "radio": "the object found"}}}, "expect": "Tariq", "reported_failure": "radio (0.399) — salient noun", }, { "name": "Test 2: two-person tie", "state": "The radio was found by Tariq. Salma was there.", "q": {"i": {"type": "choice", "instructions": "Who found the radio?", "criteria": {"Tariq": "the person who found it", "Salma": "a person present"}}}, "expect": "Tariq", "reported_failure": "Salma 0.5 tie (criteria order)", }, { "name": "Test 4: unknown options", "state": "The radio was found by Tariq. Salma was there.", "q": {"i": {"type": "choice", "instructions": "Who found the radio?", "criteria": {"xyz": "", "abc": "", "def": ""}}}, "expect": "defer or tie disclosure", "reported_failure": "abc 0.344 by noise", }, { "name": "Test 10: alarm-lights-door chain", "state": "The alarm rang.", "q": {"i": {"type": "choice", "instructions": "What turned on next?", "criteria": {"alarm": "the alarm", "lights": "the lights", "door": "the door", "unknown": "nothing"}}}, "expect": "lights (2-hop)", "reported_failure": "near-uniform", }, { "name": "Test 16: latest temperature", "state": "The temperature was twenty degrees then rose to twenty five degrees then fell to twenty two degrees.", "q": {"i": {"type": "choice", "instructions": "What is the latest temperature?", "criteria": {"twenty": "20 degrees", "twentyfive": "25 degrees", "twentytwo": "22 degrees"}}}, "expect": "twentytwo", "reported_failure": "chose 20", }, { "name": "Test 18: sparrow->bird->animal (3-hop)", "state": "What is a sparrow?", "q": {"i": {"type": "choice", "instructions": "What is a sparrow?", "criteria": {"sparrow": "sparrow", "bird": "bird", "animal": "animal"}}}, "expect": "animal (2 lane hops)", "reported_failure": "near-uniform, conf 0.019", }, { "name": "Test 21: alpha..echo relay (4-hop)", "state": "Where does the alpha relay to?", "q": {"i": {"type": "choice", "instructions": "Where does the alpha relay to?", "criteria": {"bravo": "bravo", "charlie": "charlie", "delta": "delta", "echo": "echo"}}}, "expect": "echo (4 lane hops)", "reported_failure": "barely propagates", }, { "name": "Test 17: OOD submarine color", "state": "The purple elephant boarded the spaceship.", "q": {"i": {"type": "choice", "instructions": "What was the submarine's favorite color?", "criteria": {"purple": "purple", "blue": "blue", "green": "green"}}}, "expect": "defer (unanswerable)", "reported_failure": "purple 0.472", },]
def decide(state, q, extra): cmd = [BIN, "decide", "--model", MODEL, "--energy-norm", "--state", state, "--questions", json.dumps(q)] + extra p = subprocess.run(cmd, capture_output=True, text=True) if p.returncode != 0: return {"error": p.stderr.strip()} return json.loads(p.stdout)
def build_model(): subprocess.run(["rm", "-rf", MODEL], check=True) rows = [] for i, (state, label) in enumerate(LESSONS): rows.append({"state": state, "questions": {"i": {"type": "choice", "instructions": "", "criteria": {label: label}}}, "labels": {"i": label}}) path = ROOT / "data" / "reasoning_probe_lessons.jsonl" with open(path, "w") as f: for r in rows: f.write(json.dumps(r) + "\n") subprocess.run([BIN, "learn", "--model", MODEL, "--examples", str(path)], check=True, cwd=str(ROOT)) subprocess.run([BIN, "calibrate", "--model", MODEL, "--examples", str(path), "--energy-norm"], check=True, cwd=str(ROOT))
def main(): ap = argparse.ArgumentParser() ap.add_argument("--rebuild", action="store_true") ap.add_argument("--json-out", default="") a = ap.parse_args() if a.rebuild or not Path(MODEL, "substrate.bin").exists(): build_model()
configs = [ ("gate OFF (default)", []), ("gate ON floor 0.10", ["--question-gate", "--question-gate-floor", "0.10"]), ("gate ON floor 0.25", ["--question-gate"]), ("gate ON floor 0.50", ["--question-gate", "--question-gate-floor", "0.50"]), ("hops 1 (legacy)", []), ("hops 2", ["--hops", "2"]), ("hops 4", ["--hops", "4"]), ] table = {} for cname, extra in configs: recs = [] for pr in PROBES: out = decide(pr["state"], pr["q"], extra) ans = out.get("answers", {}).get("i", {}) recs.append({ "choice": ans.get("choice", ""), "conf": ans.get("confidence", 0), "deferred": ans.get("deferred", False), "tied": ans.get("tied", False), "gate": ans.get("question_gate", []), "probs": ans.get("probabilities", {}), }) table[cname] = recs
for i, pr in enumerate(PROBES): print(f"\n== {pr['name']} [expect: {pr['expect']}; reported: {pr['reported_failure']}]") for cname, _ in configs: r = table[cname][i] tag = "DEFER" if r["deferred"] else f"{r['choice']} @ {r['conf']}" tie = " TIED" if r["tied"] else "" gt = f" gate={r['gate']}" if r["gate"] else "" print(f" {cname:<30} -> {tag}{tie}{gt}")
if a.json_out: json.dump({"probes": [p["name"] for p in PROBES], "configs": table}, open(a.json_out, "w"), indent=1) print(f"\nwrote {a.json_out}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144#!/usr/bin/env python3"""Rebuild a question's CRITERIA from the fabric's own label-exclusive lanes.
THE PROBLEM. A SyFox `choice` question gives each candidate a KEY (thelabel/anchor) and a DESCRIPTION (the criteria text). Two things happen withthat description:
1. `probe_energy(label, desc)` reads out on `normalize(label + " " + desc)`, and `Substrate::readout()` SKIPS every token that is not a fabric node (`auto it = index_.find(t); if (it == index_.end()) continue;`). So a description made of words the fabric never interned contributes NOTHING to its own candidate's measurement.
2. `decide()` injects the description tokens into the SHARED settled field (`si_.inject(qtoks, state_dose(qtoks))`) — the "direct-term harvest". Words that are not fabric nodes inject nothing; words that ARE nodes harvest energy into whatever anchor their lanes point at.
Measured on the shipped `model/giant-latin` fabric, the router's descriptionsare mostly non-words of the fabric: rt01 ("banking cards payments transfersrefunds loans") has 0 of 6 words as fabric nodes, rt00 has 1 of 6, rt13 has1 of 6. Worse, the words that DO exist are shared ("support", "in", "world")across several candidates, so the harvest lights up several anchors at once —pure noise. The router's whole discrimination signal is reduced to the anchornode plus one hop.
THE FIX. Build each candidate's description from the tokens the fabric itselfuses to reach that anchor, preferring the ones that reach it EXCLUSIVELY:
for each token x and anchor A: w(x,A) = the lane weight from x to A total(x) = sum over all anchors A' of w(x,A') exclusive(x,A) = w(x,A) / total(x) # how exclusively x points at A score(x,A) = w(x,A) * exclusive(x,A) = w^2 / total
The top-k tokens by that score become the candidate's description. They arereal fabric nodes (so they are measurable AND harvestable) and they point atthis anchor more than at any other (so the harvest discriminates instead ofdiluting).
Usage: python3 tools/rebuild_router_criteria.py --model model-router16 \ --anchors rt00,rt01,... [--topk 4] [--min-exclusive 0.35] \ [--out router_criteria.json]"""import argparseimport jsonimport structfrom collections import defaultdict
def load_substrate(path): """-> (nodes: list[str], lanes: list[(a,b,w)])""" d = open(path, "rb").read() o = 0 n = struct.unpack_from("<I", d, o)[0] o += 4 nodes = [] for _ in range(n): ln = struct.unpack_from("<I", d, o)[0] o += 4 nodes.append(d[o:o + ln].decode("utf-8", "replace")) o += ln + 4 # concept bytes + float mass nl = struct.unpack_from("<I", d, o)[0] o += 4 lanes = [] for _ in range(nl): a, b, w = struct.unpack_from("<II f", d, o) o += 12 lanes.append((a, b, w)) return nodes, lanes
def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True, help="model dir (contains substrate.bin)") ap.add_argument("--anchors", required=True, help="comma-separated candidate keys, e.g. rt00,rt01") ap.add_argument("--topk", type=int, default=4) ap.add_argument("--min-exclusive", type=float, default=0.35, help="minimum share of the token's anchor mass for exclusivity") ap.add_argument("--out", default="") args = ap.parse_args()
nodes, lanes = load_substrate(f"{args.model}/substrate.bin") index = {c: i for i, c in enumerate(nodes)} anchors = [a.strip() for a in args.anchors.split(",") if a.strip()] missing = [a for a in anchors if a not in index] if missing: raise SystemExit(f"anchors not in this fabric: {missing}") anchor_ids = {a: index[a] for a in anchors}
# in-edges into each anchor, from every token to_anchor = defaultdict(list) # anchor -> [(token_id, weight)] for a, b, w in lanes: if b in anchor_ids.values() and w > 0: to_anchor[b].append((a, w))
# total mass of each token across ALL anchors total = defaultdict(float) for anc, lst in to_anchor.items(): for tid, w in lst: total[tid] += w
out = {} for anc in anchors: aid = anchor_ids[anc] scored = [] for tid, w in to_anchor.get(aid, []): t = total.get(tid, 0.0) if t <= 0: continue excl = w / t if excl < args.min_exclusive: continue scored.append((w * excl, excl, w, tid)) scored.sort(reverse=True) picked = [] for score, excl, w, tid in scored: tok = nodes[tid] # skip pure stopword-ish anchors that are shared boilerplate if tok in picked: continue picked.append(tok) if len(picked) >= args.topk: break out[anc] = { "criteria": " ".join(picked), "tokens": picked, "detail": [{"token": nodes[tid], "w": round(w, 6), "exclusive": round(excl, 4), "score": round(score, 6)} for score, excl, w, tid in scored[:args.topk * 3]], }
print(json.dumps({k: v["criteria"] for k, v in out.items()}, indent=1)) if args.out: with open(args.out, "w") as f: json.dump(out, f, indent=1) print(f"\nwrote {args.out}") return out
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112#!/usr/bin/env python3# ============================================================================# router_prepare.py — v3.2 two-stage architecture, stage 1.# Builds the DEDICATED ROUTER FABRIC: a small (500-node class) substrate# whose only job is domain routing — 16 anchors, one per domain, physics# only (no classifier, no ML; the same SI substrate decides).## Source: data/giant/train.jsonl rows already carry the router question# (qkey "domain": criteria for rt00..rt15). We carve a balanced sample:# data/router16_train.jsonl — train rows for the router fabric# data/router16_cal.jsonl — small cal carve (router accuracy check)# data/router16_router.json — ships as router.json in the model dir:# {"anchors": {rtNN: criteria}, "models": {rtNN: model-dir},# "domains": {rtNN: domain-name}}## The two-stage contract (CLI: decide --router model-router16 ...):# stage 1: model-router16 settles the state -> picks the domain anchor# stage 2: the mapped domain fabric decides the actual questions# Domain fabrics stay isolated; the router fabric never sees domain labels.# ============================================================================import argparseimport jsonfrom collections import Counter, defaultdictfrom pathlib import Path
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--train", default="data/giant/train.jsonl") ap.add_argument("--schemas", default="data/giant/schemas.json") ap.add_argument("--out-train", default="data/router16_train.jsonl") ap.add_argument("--out-cal", default="data/router16_cal.jsonl") ap.add_argument("--out-router", default="data/router16_router.json") ap.add_argument("--per-domain", type=int, default=60) ap.add_argument("--cal-per-domain", type=int, default=10) ap.add_argument("--bank77-model", default="model-b77-sem") ap.add_argument("--default-model", default="model-giant-latin") args = ap.parse_args()
schemas = json.loads(Path(args.schemas).read_text()) # labels.domain carries the ANCHOR (rt00..rt15); schemas.router maps domain -> anchor domain_of = {a: d for d, a in schemas["router"].items() if not d.startswith("_")} anchors = sorted(domain_of) # deterministic order print(f"domains ({len(anchors)}):", ", ".join(f"{domain_of[a]}->{a}" for a in anchors))
# one pass: bucket rows by router anchor, stride-sample inside each bucket. # Rows are REWRITTEN to carry ONLY the domain question: learn teaches every # question in a row, and the router fabric must never see domain labels. buckets = defaultdict(list) with open(args.train) as src: for line in src: if not line.strip(): continue row = json.loads(line) a = row.get("labels", {}).get("domain") if a is None: continue slim = { "state": row["state"], "questions": {"domain": row["questions"]["domain"]}, "labels": {"domain": a}, } buckets[a].append(json.dumps(slim, ensure_ascii=False))
train_rows, cal_rows = [], [] for a in anchors: rows = buckets.get(a, []) if not rows: print(f" WARNING: no rows for anchor {a} ({domain_of[a]})") continue stride = max(1, len(rows) // max(1, args.per_domain)) picked = rows[::stride][: args.per_domain] train_rows.extend(picked) # deterministic cal carve: the row after each picked stride boundary cal_idx = [min(i * stride + 1, len(rows) - 1) for i in range(args.cal_per_domain)] seen = set() for ci in cal_idx: if rows[ci] not in seen and rows[ci] not in picked: cal_rows.append(rows[ci]) seen.add(rows[ci]) print(f"train rows: {len(train_rows)} cal rows: {len(cal_rows)}")
Path(args.out_train).write_text("\n".join(train_rows) + "\n") Path(args.out_cal).write_text("\n".join(cal_rows) + "\n")
# router.json: anchors = the modal criteria text per anchor across rows crit_votes = defaultdict(Counter) for line in train_rows: row = json.loads(line) crit = row["questions"]["domain"]["criteria"] items = crit.obj.items() if hasattr(crit, "obj") else crit.items() for tgt, text in items: crit_votes[tgt][text] += 1 keep = set(anchors) anchors_out = {a: votes.most_common(1)[0][0] for a, votes in sorted(crit_votes.items()) if a in keep} models = {} for a in anchors: d = domain_of[a] models[a] = args.bank77_model if d == "bank77" else args.default_model router = { "anchors": anchors_out, "models": models, "domains": {a: domain_of[a] for a in anchors}, } Path(args.out_router).write_text(json.dumps(router, indent=1)) print(f"wrote {args.out_router} ({len(anchors_out)} anchors)")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3"""Router route distribution across the 16 domains (v3.2.1 verification).
Stage-1 only: every row's state is settled on model-router16 with the 16anchors from router.json; the winning anchor is tabulated per true domain.Read-only evaluation of the shipped router (no selection, no training) —same discipline as the v3.1.3 blind-router pass.
Usage: python3 tools/router_routes.py [--per-domain N] [--json-out F]"""import argparseimport jsonimport sysfrom collections import Counter, defaultdictfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "server"))from syfox_bridge import SyFoxEngine # noqa: E402
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--router", default="model-router16") ap.add_argument("--router-json", default="data/router16_router.json") ap.add_argument("--giant-dir", default="data/giant") ap.add_argument("--per-domain", type=int, default=15) ap.add_argument("--json-out", default="") a = ap.parse_args()
rj = json.load(open(a.router_json)) anchors = rj["anchors"] # rt00..rt15 -> anchor text models = rj.get("models", {}) eng = SyFoxEngine(a.router) q = {"route": {"type": "choice", "instructions": "which domain does this state belong to", "criteria": anchors}}
files = sorted(Path(a.giant_dir).glob("*_hidden.jsonl")) table, confs = {}, {} for f in files: dom = f.name.replace("_hidden.jsonl", "") hits, cs = Counter(), [] n = 0 for line in open(f): if n >= a.per_domain: break r = json.loads(line) if not r.get("state"): continue ans_a, _u, _e = eng.decide(r["state"], q, {"semantics": True, "retrieval": True, "hierarchy": True}) ans = ans_a.get("route", {}) if not ans.get("deferred") and ans.get("choice"): hits[ans["choice"]] += 1 cs.append(ans.get("confidence", 0.0)) n += 1 table[dom] = dict(hits.most_common(4)) confs[dom] = round(sum(cs) / len(cs), 3) if cs else 0.0 print(f"{dom:<10} n={n:<3} top={dict(hits.most_common(3))} meanC={confs[dom]}")
# distribution shape: how concentrated is each domain's routing? total = sum(sum(v.values()) for v in table.values()) top_agree = sum(next(iter(v.values())) for v in table.values() if v) print(f"\nrouted rows: {total}, routed-to-modal-anchor agreement: " f"{top_agree}/{total} = {top_agree/total:.3f}") if a.json_out: json.dump({"table": table, "mean_conf": confs}, open(a.json_out, "w"), indent=1) print(f"wrote {a.json_out}")
if __name__ == "__main__": main().gitattributes+1
README.md+173-6
build/libsyfox_core.so+2-2
datasets/bench_hidden_summary.jsonAdded+14
datasets/eval_summary_v400.jsonAdded+64
datasets/novel_probes/RESULTS.json+42-38
docs/ENGINE_PORT.md+67-2
engine/CHANGELOG.mdAdded+1476
engine/Makefile+38-6
engine/core/bench.hpp+25-3
engine/core/reason.hpp-409
engine/core/roles.hpp+2-77
engine/core/si_substrate.hpp+133-455
engine/core/syfox.hpp+448-405
engine/data/bank77_categories.jsonAdded+161
engine/data/bank77_criteria.jsonAdded+84
engine/data/handmade_probes.jsonlAdded+148
engine/data/synonyms.txtAdded+32
engine/docs/FIT_DECIDE_PARITY.mdAdded+175
engine/src/syfox_cli.cpp+149-333
engine/src/syfox_core.cpp+16
engine/src/syfox_test.cpp+217
engine/tools/ablation_suite.pyAdded+158
engine/tools/assert_fit_decide_parity.pyAdded+89
engine/tools/assert_route.pyAdded+16
engine/tools/b77_ablation_compare.pyAdded+67
engine/tools/b77_apply_policy.pyAdded+70
engine/tools/b77_confusion_report.pyAdded+174
engine/tools/b77_freq_cut.pyAdded+102
engine/tools/b77_margin_sweep.pyAdded+116
engine/tools/bank77_analysis.pyAdded+168
engine/tools/bank77_hier.pyAdded+169
engine/tools/bank77_prepare.pyAdded+224
engine/tools/cal_diffusion_sweep.pyAdded+130
engine/tools/check_omp_identity.pyAdded+15
engine/tools/confidence_ablation.pyAdded+140
engine/tools/corpus_pools.pyAdded+517
engine/tools/flag_probe_experiment.pyAdded+148
engine/tools/gen_corpus.pyAdded+214
engine/tools/gen_paraphrases.pyAdded+195
engine/tools/gen_variants.pyAdded+168
engine/tools/giant_bench.pyAdded+209
engine/tools/giant_prepare.pyAdded+555
engine/tools/handmade_gate.pyAdded+135
engine/tools/hf_fetch.pyAdded+125
engine/tools/jev_bench.pyAdded+138
engine/tools/reasoning_probes.pyAdded+201
engine/tools/rebuild_router_criteria.pyAdded+144
engine/tools/router_prepare.pyAdded+112
engine/tools/router_routes.pyAdded+73