Commit Graph

1290 Commits

Author SHA1 Message Date
jgrusewski
010445b5df docs(plans): pivot Phase 1.7 to TFT GRN heads; add Phase 2C (TGN Δt Fourier) + 2D (TFT VSN)
User directive 2026-05-17: borrow TFT GRN over the planned 2-layer MLP heads.
GRN structure: 2-layer GELU MLP body (eta_2 → eta_1) + GLU gate + main +
skip-projection from trunk → final sigmoid. Gives per-horizon "linear vs
deeper-transform" gating, matches the regime-conditional alpha pattern
(pearl_snapshot_alpha_is_regime_conditional). 5x parameter count vs the
2-layer MLP but the gated residual is exactly what TFT empirically wins on.

Phase 2C (TGN Δt Fourier features): 8 sin/cos features of Δt at log-spaced
periods [60s, 6s, 600ms, 60ms] appended to snap_features. Critical with
decision-stride>1 where Δt varies across positions. Bumps FEATURE_DIM 32→40.

Phase 2D (TFT VSN): per-feature softmax-normalised gates at the trunk entry,
replacing raw concat of snap_features. Learns to down-weight noisy
features per regime (canonical: trade-flow in low-volume, OFI in
spread-Q4). 2 new param tensors, 1 new cuda kernel (fwd+bwd).

Existing 2-layer MLP kernels from Tasks 1.3/1.4 stay in the cubin as
ablation baseline; wired path becomes GRN.

Phase 1.7 plan now spells out the full GRN forward + backward chain rule
(skip + sigmoid(gate) * main → outer sigmoid), kernel signatures,
parameter Xavier init, AdamW × 10 setup, and an extended numerical-grad
check covering all 10 new param tensors.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 21:41:02 +02:00
jgrusewski
b5530b551b docs(plans): model capacity scale-up — 3-phase implementation plan
Three sequenced architectural capacity additions to push h6000 AUC
from current ~0.72-0.74 cross-fold plateau toward ≥0.78 deployment
target. Each phase independently deployable + measurable.

Phase 1 — Per-horizon specialisation (~1.5hr code):
  - LayerNorm between Mamba2 trunk and CfC K-loop (with backward
    + per-row param-grad reduction kernel; no atomicAdd).
  - 2-layer GELU MLP heads [hidden=128 → mid=64 → 1] per horizon;
    ISV lambda integrates into the trunk-grad component of head
    backward. Tasks 1.1-1.8 fully detailed (kernel source +
    integration + numerical grad check + smoke + deploy).

Phase 2A — Decision-stride sampling (~1.5hr code):
  - User-prioritised lever. Yield every S-th snapshot per training
    sequence; K=64 with stride=4 covers 256 ticks of context for
    the same compute as 64 ticks at stride=1. Mamba2's dt_s scalar
    becomes stride-aware. Tasks 2A.1-2A.5 fully detailed (loader
    refactor + test + CLI plumbing + synthetic smoke + deploy).

Phase 2B — 2-stack Mamba2 (~2hr code, sketch):
  - Two Mamba2Block instances; forward chain
    snap_feat → mamba2_l1 → LN → mamba2_l2 → LN → CfC.
  - Acceptance criteria + key implementation notes documented;
    bite-sized tasks elaborated when Phase 1+2A results land.

Phase 3 — Attention pool over Mamba2 K-positions (~4-6hr code,
sketch):
  - Replace CfC's zero-init initial state with an attention-
    pooled context vector over all K Mamba2 outputs. Design
    decision documented (Option A: attention sets initial state,
    preserving CfC's recurrent path).

Cross-phase deployment loop documented: fold-1 smoke → 3-fold
CV → per-fold comparison + isv-snapshot trajectory archive.

Honors `superpowers:writing-plans` skill: exact file paths,
complete code in every step, exact commands with expected output,
TDD-style steps, frequent commits, no placeholders in Phase 1
tasks. Self-review pass complete.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 21:18:49 +02:00
jgrusewski
ef35b10f3e refactor(ml-alpha): drop competitive-gate machinery — stacked is default
Per user direction "no gating, this is the new default": the stacked
Mamba2 -> CfC -> heads design is THE production architecture. There's
no competing-baseline comparison to run. Validation reduces to normal
training metrics (per-horizon val AUC, train loss curve, sanity floor
of >0.5 AUC).

Deletions:
  - crates/ml-alpha/src/gate/cfc_vs_mamba2.rs (gate verdict logic)
  - crates/ml-alpha/src/gate/mod.rs
  - crates/ml-alpha/examples/alpha_gate.rs (gate runner binary)

Renames:
  - crates/ml-alpha/src/gate/auc.rs -> crates/ml-alpha/src/eval/auc.rs
  - lib.rs: pub mod gate -> pub mod eval (gate implied comparison;
    eval doesn't)

Spec amendments:
  - Drop the "Gate baseline strategy" amendment (committed earlier
    this session)
  - Reframe the stacked-architecture amendment as a "decision" not a
    "gate"; production path is unambiguous
  - Reframe Section 4 "Validation gate: CfC must meet Mamba2" -> just
    "Validation: per-horizon val AUC" with the >0.5 sanity floor

Doc cleanups: stale "Mamba2 gate baseline" mentions in build.rs and
pinned_mem.rs replaced with neutral wording. The Argo template
comment about "downstream gate consumption" becomes "for monitoring".

Test status: all 26+ ml-alpha tests pass. AUC tests (6/6) still pass
under the eval:: namespace.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 23:17:33 +02:00
jgrusewski
6e868fd136 spec(ml-alpha): gate-baseline ablation strategy amendment
Defines the Mamba2-only baseline for the stacked-vs-baseline gate
verdict as an ablation of the SAME PerceptionTrainer (a --bypass-cfc
flag), not a separate model. Apples-to-apples; same data window,
same hyperparameters, same code path. The only difference is whether
the CfC step is in the loop.

Three ablation options evaluated:
  1. --bypass-cfc flag (recommended): Mamba2 -> heads directly
  2. --mamba2-state-dim 2 (crippled Mamba2, CfC stays)
  3. Frozen CfC initialized to identity (no code branch needed)

Option 1 wins on clarity: it answers "is CfC additive on top of
Mamba2" unambiguously, with the same Mamba2 capacity and same
training regime in both arms.

Concrete next-session work documented (1-2 hours):
  - PerceptionTrainerConfig.bypass_cfc: bool + step() branch
  - alpha_train --bypass-cfc CLI flag
  - alpha-perception-template.yaml workflow parameter + bash branch
  - submit both runs, fetch summaries, alpha_gate, commit verdict

gate_verdict logic unchanged — the cfc/mamba2 naming in the report
becomes stacked/bypass at the binding layer; the verdict math is
generic.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 23:12:34 +02:00
jgrusewski
d4e46aba94 feat(ml-alpha): multi_horizon_heads kernel (128->5 sigmoid)
Per-horizon P(up) at h ∈ {30, 100, 300, 1000, 6000} snapshots forward.
Single-block 5-thread kernel; each thread is its own 128-dim dot
product + sigmoid. No atomicAdd.

Tests (5/5 pass on sm_86) assert invariants only:
  - sigmoid output ∈ [0, 1] for all heads
  - zero weights + zero bias → 0.5 exactly
  - bias = +20 → saturates near 1
  - bias = -20 → saturates near 0
  - per-head independence (mixed-bias configuration)

Addendum updated to explicitly state no-CPU-mirror discipline per
feedback_no_cpu_test_fallbacks.md.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 21:51:48 +02:00
jgrusewski
3389a59281 spec(ml-alpha): stacked Mamba2 -> CfC amendment
Mid-execution architecture revision: Mamba2 stays as a sequence
encoder; CfC becomes the layer on top (replacing the Phase 1d.3 MLP
stacker). Gate becomes 'stacked AUC >= Mamba2-only stacker AUC at
every horizon' — proves the CfC layer is additive, rather than CfC
alone beating Mamba2 alone.

Plan 1 kernels (cfc_step, heads, projection, BCE, AdamW, Graph A)
are unchanged. Only CfcTrunk's forward path gains a Mamba2 prefix
that consumes the snapshot stream and emits a 128-dim h_mamba which
CfC reads. The Mamba2 kernel (mamba2_alpha_kernel.cubin) is already
in the build.

Option B (parallel + fused dual-stream) is documented as the Plan 2
fallback if the stacked gate fails.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 21:42:57 +02:00
jgrusewski
d3b60b2ef3 build(ml-alpha): multi-cubin build.rs + placeholder kernels + local MappedF32Buffer
Cargo.toml: drops gbdt; adds memmap2 + approx; keeps ml-core only
(cannot depend on ml: would cycle since ml depends on ml-alpha for
the Mamba2 gate baseline).

build.rs: compiles 7 cubins (mamba2_alpha + 6 new placeholders)
with -O3 --use_fast_math --ftz --fmad. Skips kernels whose source
isn't present yet so partial check-ins work. Every env::var paired
with rerun-if-env-changed per the canonical build pearl.

src/pinned_mem.rs: local copy of MappedF32Buffer (mirrors
ml::cuda_pipeline::mapped_pinned::MappedF32Buffer). Drives the only
permitted CPU<->GPU path per feedback_no_htod_htoh_only_mapped_pinned.
Eventually the move-to-ml-core refactor will deduplicate; out of
scope for the Phase A branch.

Addendum: updates the import path to ml_alpha::pinned_mem.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 21:35:35 +02:00
jgrusewski
2deec0cf91 plan(ml-alpha): Phase A API addendum — cudarc 0.19 canonical patterns
Plan 1 was written against an older cudarc device-centric API. cudarc 0.19
moved alloc/launch ownership to the stream (partly for CUDA Graph capture
hygiene). This addendum pins:

- MlDevice -> CudaContext -> CudaStream construction
- Cubin load + module + function caching
- MappedF32Buffer staging -> DtoD-async -> CudaSlice (canonical CPU->GPU)
- Slow-path readback via DtoD into a staging MappedF32Buffer
- launch_builder(&func).arg(...).launch(cfg) idiom
- IsvBus and MappedPinnedSnapshotSlot/FillSlot using the real
  MappedF32Buffer API (host_slice_mut, read_all, dev_ptr field)
- CUDA Graph A capture via stream.begin_capture / end_capture / instantiate

Plan 1 kernel .cu source, CPU oracles, finite-diff thresholds, smoke
criteria, and gate logic are unchanged. Only Rust binding code uses
these patterns.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 21:31:53 +02:00
jgrusewski
056b4abe52 plan(ml-alpha): three-plan rollout for CfC+PPO greenfield
Plan 1 (Phase A, ~3000 lines): ml-alpha library scaffold, ISV bus,
mapped-pinned slots, CUDA build.rs, six perception kernels with
bit-equiv tests, AdamW + BCE, Graph A capture, Phase A trainer +
binary, CfC-vs-Mamba2 gate. Bite-sized 5-step TDD across 18 tasks.

Plan 2 (Phase B, ~780 lines): build_state, policy_forward (CfC
actor+critic), sample_action, replay buffer, multi-env rollout, GAE,
advantage_normalize, fused PPO loss, EWC, Graphs B+C, seven ISV
controllers, kill-switch, atomic weights swap, walk-forward CV across
6 folds. 19 tasks; tasks 2+ use compressed Step 2-5 TDD cycle pending
re-detail at the Plan 1 gate boundary.

Plan 3 (live, ~560 lines): IBKR adapter audit, AlphaPpoStrategy in
trading_agent_service, cold-start 4-state FSM, disconnect/failure
handling, observability, alpha-control IPC + fxt CLI, restart
semantics, paper trading harness (5 days), $1k live deploy with
manual ack gate, 5-day live window. 10 tasks.

Each plan has gate-pass criteria gating the next. On failure: post-
mortem + spec delta, no advance.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 20:48:14 +02:00
jgrusewski
90d14aaba5 spec(ml-alpha): GPU/CPU contract, CUDA Graphs, cold-start, disconnect handling
Critical-review pass on the CfC+PPO design adds:
- Public API: mapped-pinned ingress slots, single DtoH per decision
- Section 5.5: CUDA Graph capture topology (perception / policy / training),
  kernel inventory, cuBLAS Lt epilogue fusion, persistent ring layouts,
  determinism mode, build-time cubin compilation, perf budget
- Section 5.6: Databento/IBKR disconnect + failure response, never-do list
- Section 6 cold-start: 4-state bootstrap, Phase B walk-forward stats as
  pre-deployment kill-switch baseline, always-live ISV controllers

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 20:27:25 +02:00
jgrusewski
d4ea54d780 spec(ml-alpha): CfC + PPO greenfield design
Approved design document for the ml-alpha rebuild. Seven sections plus
appendices, all 7 sections + ISV-driven auto-tuning addition approved
via the brainstorming-skill flow.

Key architectural decisions:
- Full closed-loop scope: training + offline inference + live IBKR
- Three components: ml-alpha library, alpha_train binary, AlphaPpoStrategy
  in trading_agent_service (reuses existing data_acquisition,
  trading_service, broker_gateway, and the 1177-LOC IBKR adapter that
  already exists in trading_engine)
- Snapshot-level CfC perception trunk (Closed-form Continuous-time, the
  trainable LTC variant from Hasani 2022) — chosen over Mamba2 for
  native multi-time-scale via per-cell learnable τ; hard validation
  gate requires CfC AUC ≥ Mamba2 baseline before continuing
- 5 multi-horizon heads at {30, 100, 300, 1000, 6000} snapshots forward
- Decision-stride 50 snapshots (~1 min); empirically validated this
  session (per-bar→stride=200 flipped 3-fold mean Sharpe from -4.29 to
  +1.78 at quarter-tick cost)
- Action: target_position categorical ∈ {-10, ..., +10}; max_train=10
  fixed at architecture level, max_live ≤ 10 runtime-cappable
- Reward in price units (position-size invariant): dense per-segment
  PnL − C_trade·|Δcontracts| − C_vol·vol_excess; C_trade=0.034 fixed
  (IBKR $1.70 RT ÷ $50/point), C_vol=0 default
- Full online learning with EWC anchoring + 80/20 offline/live replay
  buffer + kill-switch on σ-band metric deviations (loss, mean reward,
  hit-rate, KL, entropy)
- All hyperparameters that vary during training are ISV-driven
  (controller outputs, not magic numbers) per
  pearl_controller_anchors_isv_driven.md
- Fully GPU-resident on hot path per feedback_cpu_is_read_only.md
- $35k starting capital; conservative max_live ramp 1→2→3 contracts
  with manual config bumps gated on realized track record
- Documented IBKR-specific quirks (PDT, mid-session margin spikes,
  rollover, halts, rate limits) with concrete design responses

Supersedes the abandoned 2026-05-16-alpha-ppo-trainer.md (DQN-port plan)
which inherited the wrong architectural shape.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 19:59:51 +02:00
jgrusewski
110d3b4125 chore(ml): delete dead imports, parens, and the unused MappedI32::read
Cleanup of compiler warnings flagged by both local cargo check and the
cluster ensure-binary log. Per `feedback_no_hiding`, every site is
either deleted or wired up — no #[allow] suppressions.

Lib (5 sites):
- gpu_backtest_evaluator.rs:34 — drop unused DevicePtrMut.
- gpu_dqn_trainer.rs:49 — drop unused DevicePtrMut (8 device_ptr_mut
  calls don't need the trait import in current cudarc). Line 19852:
  drop unnecessary parens around `b * sh2`.
- training_loop.rs:20 — drop unused DevicePtrMut; unbrace single-
  symbol use at 5766.
- state_reset_registry.rs:4 — delete the 10-symbol use-block of slot
  constants. Names appear in description strings (documentation only),
  symbols are never referenced.

Examples (3 sites):
- alpha_dqn_h600_smoke.rs:181, 186 — drop COL_RAW_CLOSE, FEAT_DIM,
  FillCoeffs, FillModel imports.
- alpha_baseline.rs:79 — delete unused MappedI32::read. Batched path
  uses read_all for N-element action readback; the single-element
  method was leftover from the pre-batched legacy path.

Lib + examples now have zero removable warnings. The remaining
unsafe_block lints (each cudarc kernel launch needs unsafe) are
structural and not actionable under the project's -W unsafe-code
policy.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 10:20:03 +02:00
jgrusewski
d49003de6d feat(regime): vol_ref floor controller + cross-invocation disk persist
Closes the TrainingPersist loop for the regime defense per the
KELLY_F_SMOOTH precedent (pearl_kelly_cap_signal_driven_floors).

Three layers:

(1) Per-step: alpha_regime_vol_update_kernel tracks min(vol_obs > 1e-12)
in new slot 553 (REGIME_VOL_OBS_MIN_INDEX). Filtered against artifact-
zero observations from stationary snapshots where curr == prev.

(2) Per-cell: stacker_threshold_controller_update gains a fifth branch
that reads vol_ref (slot 550) at cell-end, computes
`target = floor_target_ratio × vol_ref`, slow-EMAs the floor anchor
(slot 552) toward the target with rate `floor_update_rate` (0.1 per
cell). Subfloor 1e-12 inside the kernel guards against the anchor
collapsing to zero.

(3) Per-invocation: alpha_baseline reads
`config/ml/alpha_baseline_state.json` at startup and seeds slot 552
from the `regime_vol_ref_floor` field. At end of main(), the learned
floor is written back via tmp+rename atomic write so concurrent
walk-forward invocations see a consistent file. Matches the
cross-fold-persistent shape of KELLY_F_SMOOTH.

Block extended to 15 slots (539..=553). Smoke + kernel unit test
pass -1/-1 for the new floor-controller indices (backward compat).

Walk-forward CV verdict (Q1 fxcache, 3 sequential folds):

  iteration                       fold-A  fold-B  fold-C  mean ± SD
  pre-defense (no regime)         +91.52  -21.44  +46.74  +38.94 ± 56.88
  hardcoded 1e-9 floor            -19.77  +65.04  +6.45   +17.24 ± 43.42
  learned floor (0.5 × cell_min)  +74.78  -12.72  +8.80   +23.62 ± 45.59
  learned floor (0.1 × vol_ref)   -19.53  -26.51  +15.46  -10.20 ± 22.49

Controller infrastructure is structurally correct (loop closes, floor
persists across invocations, kernel + disk + ISV all roundtrip). The
TUNING is data-dependent — single-quarter CV doesn't have enough
regime diversity to anchor the floor against. Multi-quarter fxcache
validation is the next step (built cluster-side on the 9-quarter
2024-Q1..2026-Q1 ES futures dataset, downloaded as a single artifact
for local CV).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 09:22:20 +02:00
jgrusewski
3c035ce1ae feat(regime): vol_ref bootstrap window + ISV-driven permanent floor
Two coupled fixes to the vol-EMA regime detector exposed by walk-forward
CV after all features were promoted to always-on:

(1) Bootstrap window for vol_ref (slot 551 = REGIME_VOL_REF_SAMPLES)
- Replace the Pearl-A "first observation replaces directly" bootstrap
  with a running mean over the first N=100 vol_ema observations, then
  switch to β-tracking. For IID observations the running-mean estimator
  has variance σ²/N — a 100-sample mean is 10× less noisy than the
  single-shot replace.

(2) Permanent floor on vol_ref (slot 552 = REGIME_VOL_REF_FLOOR)
- The bootstrap alone exposed the asymmetric deadband-deadlock: if
  vol_ref converged to a tiny value during a calm initial stretch,
  vol_ref / vol_ema fired the moment any realistic vol resumed and
  Kelly stayed trapped at regime_scale_floor=0.25 forever. Floor
  lives in ISV slot (TrainingPersist) with a hardcoded 1e-12 sub-floor
  inside the kernel as numerical-underflow guard.
- Host seeds slot 552 with 1e-9. Future controller kernel will refine
  this from observed cell-level vol minima with cross-fold persistence.

Walk-forward CV on Q1 fxcache (3 folds, window=700K, train_frac=0.6):
  cost   fold-A   fold-B          fold-C    mean ± SD
  0.00   -19.77   +65.04 (100%)   +6.45     +17.24 ± 43.42

Fold B turnaround is the headline: -47.64 (bootstrap-only) → +65.04
(bootstrap + floor) confirms the floor is the load-bearing fix.
Cross-fold std-dev compressed 24% at cost=0; mean dropped from +38.94
(pre-defense) to +17.24 (with defense). Classic mean/variance trade.

Block extended to 14 slots (539..=552). Kernel sig: vol_ref_floor
moved from f32 scalar to vol_ref_floor_index i32, so the anchor is
named/addressable in ISV.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 01:31:20 +02:00
jgrusewski
d090685ca9 feat(phase-e-4-a-T16): vol-regime detection + cost-aware training
Adds two coupled interventions on the regime fragility exposed by
walk-forward CV (mean Sharpe +27 ± 56 at half-tick across 3 folds —
std-dev ≈ mean means the strategy is regime-dependent).

(1) Vol-EMA regime detector (new ISV slots 549/550)
- New alpha_regime_vol_update.cu kernel: per inference step, reads B
  parallel-env mid prices, computes cross-env mean squared log-return,
  and maintains ISV[549]=REGIME_VOL_EMA (Wiener-α with 0.4 floor +
  Pearl A bootstrap) and ISV[550]=REGIME_VOL_REF (slow tracker β=0.005,
  ≈200-step horizon).
- Block-tree-reduce (no atomicAdd), guards against zero/non-finite mids.

(2) Pre-emptive Kelly attenuation (modified stacker controller)
- stacker_threshold_controller.cu takes 3 new args: regime_vol_ema_idx,
  regime_vol_ref_idx, regime_scale_floor.
- Multiplies its reactive Sharpe-error Kelly output by
    regime_scale = clamp(vol_ref / vol_ema, 0.25, 1.0)
- Disabled when indices = -1 (backward-compatible smoke + kernel test).

(3) Cost-aware training (--train-cost-hi)
- alpha_compose_backtest --train-cost-hi: when > --train-cost, each
  training epoch samples cost ~ U[lo, hi] so the Q-network learns
  cost-conservative behaviour across the realistic ES range.

(4) Wiring
- alpha_compose_backtest --regime-scale enables both per-step regime
  kernel firing during eval AND the regime hookup in the per-episode
  controller call. Mapped-pinned mids buffers, all compute device-side.
- ExecutionEnv exposes current_mid() so the host gather reads the
  active snapshot mid per env without leaking the private cursor field.

Smoke + test sites pass -1/-1 for regime indices (backward compat).
Doc: docs/isv-slots.md ledger for slots 549/550.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 00:28:01 +02:00
jgrusewski
3dc022b843 feat(phase-e-4-a): T10 Mamba2 backward chain + KC calibration
T10 wires the C51 → Mamba2 backward chain in both binaries:
- New alpha_train_window_store_batched_kernel captures per-step windows
  for end-of-epoch re-forward (Mamba2 cache required for backward).
- Mamba2Block::backward_from_h_enriched lets the C51 grad-input feed
  directly into Mamba2 backward, skipping the unused W_out projection.
- alpha_c51_grad_input → backward_from_h_enriched → Mamba2AdamW.step
  closes the loop in alpha_dqn_h600_smoke and alpha_compose_backtest.

Smoke (--temporal --c51): all 4 KCs PASS. R_mean -6.3 → +4.2 vs
Phase E.3 close R_mean -4.7 (no-temporal). EARLY_Q_MOVEMENT
calibration (mamba2_snapshot + mamba2_weight_distance) lifts the
diagnostic from 0.0023 (head-only) to 0.0590 (head + encoder),
giving an honest learning signal when the encoder absorbs gradient.

Backtest (--c51 --temporal --window-k 16 --isv-continual):
  cost=0.0000  best τ=0.250  Sharpe_ann=+34.56  (was +10.41 head-only,
                                                  -22.54 frozen-Mamba2)
  cost=0.0625  best τ=0.250  Sharpe_ann=+33.22
  cost=0.1250  best τ=0.250  Sharpe_ann=+30.85  (Phase 1d.4 baseline: -4.0)
  cost=0.2500  best τ=0.250  Sharpe_ann=+27.73
  cost=0.5000  best τ=0.250  Sharpe_ann=+15.68

Caveat: in-sample results; OOS gate next.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 23:49:25 +02:00
jgrusewski
0ab54dc8ef feat(phase-e-4-a): batched parallel-env TRAINING (greenfield)
T15: training rewrite mirroring T14 eval. N_par parallel envs
lockstep H steps per epoch; ONE batched C51 update at B = N_par * H.
Expected ~15× speedup vs sequential.

- NEW kernel alpha_h_enriched_store_batched_kernel for batched
  h_enriched slot writes
- Training section greenfielded: legacy sequential loop deleted
- CLI flag --n-train-par (default 50)
- Terminal next-state slot zeroed; done=1 at horizon masks Q_next
  contribution in Bellman projection — no terminal Mamba2 forward
- docs/isv-slots.md updated per kernel-audit-doc hook

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 23:11:01 +02:00
jgrusewski
90c9d54454 feat(phase-e-4-a): batched parallel-env eval rewrite (greenfield)
The Phase E.4.A T14 backtest at B=1 with per-step stream.synchronize()
was running ~150μs/step × 9M steps = ~22 min — dominated by sync
overhead, not GPU compute. RTX 3050 Ti to L40S swap wouldn't help
(launch overhead is the bottleneck, not FLOPS).

Solution: batched parallel envs. N=cli.n_eval_episodes environments
run in LOCKSTEP per cell — ONE sync per step (instead of N syncs).
Expected ~30× speedup at N=500.

Changes:

1. ExecutionEnv snapshots → Arc<Vec<SnapshotRow>>
   - new() wraps Vec into Arc internally (backward compat)
   - new_arc() takes pre-existing Arc (for parallel envs)
   - snapshots_arc() accessor for snapshot sharing
   - 50MB × N memory duplication avoided

2. alpha_window_push_batched_kernel (NEW CUDA)
   - Same chronological shift+insert semantics as single-env kernel
   - Grid (state_dim_blocks, B, 1): one thread per (batch, feature)
   - launcher: launch_alpha_window_push_batched

3. MappedI32 (per-binary) gains len param + read_all()
   - smoke & backtest pass len=1 for existing single-int use
   - backtest passes len=N for batched action readback

4. backtest binary eval loop GREENFIELDED
   - Legacy sequential 'for ep in 0..N { for step in ... }' loop
     body deleted entirely
   - New: 'for step in 0..horizon' outer, lockstep over N envs
   - Build N envs sharing snapshots_arc at cell start
   - Per step: gather N states (CPU loop, <100μs for N=500) →
     write to mapped-pinned [N, STATE_DIM] → push kernel B=N →
     Mamba2 batched forward → C51 batched forward → Thompson
     batched → ONE sync → read N actions → step N envs on CPU
   - ISV-continual moved from per-episode to per-cell (single fire
     with aggregate stats)

5. docs/isv-slots.md updated per kernel-audit hook

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 22:52:43 +02:00
jgrusewski
2feeeda8bb fix(phase-e-4-a): GPU kernel for h_enriched slot copy — eliminate per-step CPU roundtrip
The Phase E.4.A T8 wiring stored Mamba2's per-step cache.h_enriched
into h_enriched_buf_dev via a dtoh+htod sequence:

  let h_host = stream.clone_dtoh(cache.h_enriched.cuda_data())?;
  let mut buf_host = stream.clone_dtoh(&h_enriched_buf_dev)?;  // <- whole buffer
  for j in 0..hidden_dim { buf_host[slot_offset + j] = h_host[j]; }
  stream.memcpy_htod(&buf_host, &mut h_enriched_buf_dev)?;     // <- whole buffer

This violates feedback_cpu_is_read_only AND
feedback_no_htod_htoh_only_mapped_pinned. Worse, the buffer-wide
dtoh+htod every step is ~20K floats × 600 steps × 500 eps × 30 cells
= ~9M roundtrips totaling significant PCIe latency in the backtest.

Fix: new tiny CUDA kernel alpha_h_enriched_store_kernel in
alpha_window_push.cu (one thread per hidden-dim feature, writes
src[j] → buf[slot_offset + j]). Replaces the dtoh/htod sequence
in both smoke and backtest binaries.

Estimated speed-up at backtest scale: 3-6× on the temporal eval
path. Pure-GPU per-step inference restored — no synchronisation
points on the hot path.

docs/isv-slots.md updated per kernel-audit-doc hook.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 22:20:28 +02:00
jgrusewski
2fe76f2f34 docs(phase-e-4-a): execution status + T10 backward_from_h_enriched patch sketch
Two documentation deliverables produced while T14 backtest runs:

1. Plan update (specs/2026-05-15-phase-e-4-a-temporal-foundation.md):
   adds 'Execution Status' section reflecting actual T1-T14
   progression. T5 deferred (real MBP-10 peek), T9 skipped (GRN
   moved to E.4.B per integration notes), T10 partial (new C51
   grad-input kernel landed but Mamba2 backward wiring deferred),
   T14 in flight. Documents the 4 execution learnings:
   research-first saved a week of duplicate kernel work; cheap
   falsification experiments (Path 2, Path 3) avoided expensive
   investments; C51 borrow was the largest single Sharpe-lift in
   the session; GpuTensor/CudaSlice interop friction is the real
   integration cost.

2. T10 patch sketch (specs/2026-05-15-t10-mamba2-backward-from-h-enriched.md):
   ready-to-apply patch for ml-alpha::Mamba2Block adding a new
   public method backward_from_h_enriched(cache, d_h_enriched).
   Bypasses the W_out projection backward, accepts the
   [B, hidden_dim] gradient from C51's grad-input kernel directly,
   zero-initialises dw_out/db_out (AdamW step on zero grad is a
   no-op with correct moment decay — effectively freezes W_out
   params which is correct semantics since Phase E never uses
   them). Includes the smoke binary wiring snippet that consumes
   the new method via launch_alpha_c51_grad_input → Mamba2
   backward → AdamW step. Application gated on T14 backtest
   validation — if frozen Mamba2 already lifts Sharpe, T10
   becomes optimisation rather than prerequisite.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 22:08:31 +02:00
jgrusewski
75d67bd203 feat(phase-e-4-a): alpha_c51_grad_input kernel (T10 prerequisite)
Phase E.4.A Task 10 partial: adds the C51 gradient-w.r.t.-input
kernel needed to chain the C51 head's loss gradient back into the
Mamba2 temporal encoder.

Kernel signature: alpha_c51_grad_input_kernel reads probs[B, A, K],
m[B, K], actions[B], W[A*K, in_dim] and writes d_input[B, in_dim].
Math: dL/d_input[b,j] = Σ_k (p[b,a_taken,k] − m[b,k]) · W[a_taken*K+k, j]
(only the taken-action column of W contributes; restricted by the
sparse-over-actions C51 CE gradient structure).

Status: kernel + Rust launcher in place. Mamba2 backward NOT yet
wired in the smoke binary because ml_alpha::Mamba2Block::backward
takes d_logit [B, 1] (post-W_out scalar gradient), not
d_h_enriched [B, hidden_dim]. Two paths to complete:
  1. Modify ml-alpha to expose backward_from_h_enriched(cache,
     d_h_enriched) bypassing W_out.
  2. Replicate the post-W_out backward sequence inline.

Both deferred pending backtest validation (T14): if frozen Mamba2
already lifts backtest Sharpe meaningfully, T10 becomes
optimisation rather than prerequisite. Smoke gate already passed
gate 1 (R_mean +3.9 vs C51-flat -1.1) with frozen weights.

docs/isv-slots.md updated.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 21:24:43 +02:00
jgrusewski
35dcb87709 refactor(phase-e-4-a): window push to shift+insert (chronological layout)
Switch alpha_window_push from circular-buffer-with-head_idx layout
to shift+insert layout matching production mamba2_update_history.
Slot 0 = oldest, slot K-1 = newest after each push, matching
Mamba2Block's [B, K, in_dim] input contract directly (no reorder).

Cost: O(K-1) shifts per state_dim feature per push. For K=16,
state_dim=10: 10 threads × ~15 ops each = trivial.

Kernel signature: drops head_idx, adds K. Test updated to verify
chronological shift across 3 pushes into 4-slot buffer.
docs/isv-slots.md updated per kernel-audit-doc hook.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 21:06:23 +02:00
jgrusewski
6e86e5b435 feat(phase-e-4-a): alpha_window_push circular-buffer kernel + GPU test
Phase E.4.A Task 6: tiny CUDA kernel that pushes a state[state_dim]
vector into slot `head_idx` of a circular window buffer
[K, state_dim]. Host tracks head_idx and zeros buffer on episode
reset. This is the GPU-side append primitive that the smoke
binary's per-step inference will call (T7) before Mamba2 over the
buffer (T8).

GPU smoke (alpha_window_push_circular_writes_to_indexed_slot):
writes state_a at slot 0, state_b at slot 2, verifies non-targeted
slots stay zero. PASS.

docs/isv-slots.md: documents kernel as slot-agnostic per
kernel-audit-doc hook requirement.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:52:32 +02:00
jgrusewski
eb49e2a0f7 feat(alpha): Phase E.3 follow-up — C51 distributional Q + Thompson + L1-L10 depth + falsifications
C51 distributional Q-network with GPU Thompson selection borrowed
minimally from production (alpha_c51.cu: forward, project, grad,
expected_q, thompson_select kernels; ~260 lines). Uses Huber
negative-tail compression in projection per production
block_bellman_project_f. Action selection 100% GPU via mapped-pinned
i32 output + __threadfence_system + host volatile read (matches
gpu_training_guard MappedBuffer pattern).

Backtest result (2D sweep, 500 episodes per cell, 30 cells):
  cost=0    C51 +10.41 vs linear-Q -15.72  (+26pt, BEATS Phase 1d.4
                                            no-RL baseline +4.4 by 6pt)
  cost=0.125 C51 -13.81 vs -29.17  (+15pt closes half-tick gap)
Win rate at cost=0 best τ: linear-Q 0.008 → C51 0.552.

Calibration hypothesis vindicated; documented in
memory/pearl_c51_thompson_closed_phase_e3_gap.md.

Also in this commit (Phase E.3 follow-up cleanup):
- --pruned-actions falsified (2.4× worse Sharpe). Documented in
  memory/pearl_action_pruning_falsified.md.
- --real-spread falsified for ES futures (76% of bars at 1-tick floor).
- SnapshotRow bid_l/ask_l extended from [f32; 3] to [f32; 10].
  L4-L10 synthesized in this commit; real MBP-10 peek lands in E.4.A T5.
- docs/isv-slots.md updated per kernel-audit-doc hook requirement.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:43:57 +02:00
jgrusewski
eb9047fc30 docs(phase-e): E.4 temporal encoder design + E.4.A implementation plan
Design doc (specs/): TFT-style architecture for Phase E execution
policy — sliding window → Mamba2 SSM → GRN trunk → MoE regime gate
→ C51 head → Thompson selector. Two core pillars added per user:
  A) Full L1-L10 LOB depth input via hybrid MBP-10 peek
  B) ISV-continual-learning: controllers fire at training AND
     inference; Q-net weights frozen at inference but effective
     policy adapts via ISV modulation

Plan doc (plans/): 14-task implementation plan for E.4.A foundation
(window buffer + L1-L10 depth + Mamba2 forward+backward + ISV-eval
controllers). Falsification gates: smoke R_mean improvement ≥ 50%,
backtest cost=0 Sharpe ≥ +8 (no regression vs C51-flat +10.41),
half-tick Sharpe ≥ -8 (closes 5pt+ of 10pt gap to Phase 1d.4
baseline -4.0).

TGGN (foxhunt Temporal Graph Gated Network) explicitly deferred to
Phase E.5+: existing CPU graph implementation + GPU adapter at
ml-supervised/src/tgnn/ — marginal benefit for single-instrument ES
futures vs the TFT-Mamba2 stack; revisit for multi-instrument
extension or production HFT inference layer.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:42:35 +02:00
jgrusewski
588a6d38af docs(phase-e-4-a): mamba2 + grn integration research — use ml-alpha Mamba2Block
Findings:
- Production Mamba2 (gpu_dqn_trainer) is coupled to SH2=256 trunk +
  ofi_embed + ISV[8] temporal routing — not portable to Phase E.
- ml-alpha::mamba2_block::Mamba2Block is from-scratch, fully
  configurable (in_dim/hidden_dim/state_dim/seq_len), GPU-pure with
  forward_train/backward/AdamW. Used in Phase 1d.2 to lift AUC 0.50
  to 0.66. ml-alpha is already a workspace dep of ml.
- GRN skipped for E.4.A — Mamba2 output goes straight to C51 head.
  Reintroduce GRN in E.4.B if Sharpe gates don't pass.
- Controller-at-inference: kernel has no training-mode branches;
  Wiener state preserved across episodes/cost cells for natural
  live-deployment simulation.

Revises Tasks 8-10 of the plan: use Mamba2Block API instead of
writing custom kernels. Only new CUDA needed: alpha_c51_grad_input
(C51 gradient w.r.t. input features, for Mamba2 backward chain).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 20:32:47 +02:00
jgrusewski
85792ed28a feat(alpha): stacker-threshold + Kelly-attenuation controller kernel
Phase E.2 Task 16. Engagement-rate self-correcting controller per
pearl_engagement_rate_self_correction. Single-block, single-thread
kernel; runs once per rollout-end boundary.

ISV slots driven:
  543  STACKER_THRESHOLD_INDEX        clamp [0, 0.5]  P-controller on rate
  545  TRADE_RATE_OBSERVED_EMA_INDEX  Pearl A+D floored Wiener-α
  546  STACKER_KELLY_ATTENUATION_INX  clamp [0.1, 1.0] P-controller on Sharpe

Reads ISV[544] TRADE_RATE_TARGET_INDEX (TrainingPersist anchor, set once
at training start).

Control law:
  observed = trade_count / max(decisions, 1)
  ISV[545] ← Pearl_A+D_floored(observed, prev, x_lag)
              [α* floor = 0.4 per pearl_wiener_alpha_floor_for_nonstationary;
               controller co-adapts with policy → need responsive EMA]
  err_rate = ISV[545] - ISV[544]
  ISV[543] ← clamp(0, 0.5, ISV[543] + k_threshold · err_rate)

  err_sharpe = rollout_sharpe - target_sharpe
  ISV[546] ← clamp(0.1, 1.0, prev_atten + k_atten · err_sharpe)
             where prev_atten = 1.0 if ISV[546] == 0.0 (sentinel-start)
             else ISV[546]

Wiener-α is INLINE (not via canonical apply_pearls_ad_kernel chain)
because the EMA is part of the control loop, not a separate diagnostic
slot. Lower latency, fewer kernels per step.

Floor at 0.1 on Kelly attenuation per
pearl_blend_formulas_must_have_permanent_floor — can't be 0, would
zero out position sizing permanently.

Pub launcher `launch_stacker_threshold_controller` in alpha_kernels.rs
with full safety asserts. Slot indices passed as i32 args (decouple
slot numbering from kernel).

GPU smoke test `stacker_threshold_controller_smoke_matches_hand_
computation` verifies 2-iteration sequence:
  Iter 1 (Pearl A):  observed=0.30 → ISV[545]=0.30; ISV[543]: 0.05 → 0.052
  Iter 2 (Pearl D):  observed=0.05 → ISV[545]=0.175 (α* hit floor 0.5)
                                     ISV[543]: 0.052 → 0.05275
Both within 1e-5 tolerance. Anchor slot 544 unchanged.

`cargo test -p ml --lib alpha_kernels`: 6 pass (compile witness + 5 GPU
smokes including this one) on RTX 3050 Ti in 2.18s.

Audit doc docs/isv-slots.md updated per Invariant 7.
2026-05-15 17:28:07 +02:00
jgrusewski
8958637c77 feat(alpha): stabilize alpha_dqn_h600_smoke — reward norm + target net + grad clip
Three stabilizers applied to the H=600 DQN smoke after initial run showed
unstable training (early_mvmt=2268× at lr=1e-6, NaN at lr=1e-4):

  1. Reward normalization (--reward-scale, default 1000)
     Rewards divided by scale BEFORE the Munchausen target. TD error
     drops from ~1000 (raw reward magnitude at H=600) into O(1) target /
     gradient / weight-update scale. Action selection + rollout-R
     reporting use ORIGINAL rewards (so rvr math stays correct against
     the Task 7c baseline).

  2. Target network (--target-update-every, default 10 episodes)
     Separate w_target_dev / b_target_dev buffers. Q_next(s') forward
     uses target weights; SGD updates online only. Hard-update copies
     online → target every K episodes. Breaks the V_soft(s') chase-its-
     own-tail divergence of online-only Munchausen.

  3. Gradient clipping (--grad-clip, default 1.0)
     New `alpha_clip_inplace_kernel` in alpha_linear_q.cu (element-wise
     clamp). Applied to dW and db after grad, before SGD. Safety net.

Diagnostic fix: weight_norm was direction-insensitive — orthogonal
rotations don't change ||W||_F, so early_mvmt read ≈0 even when training.
Switched to weight_distance_from_init = ||W_now − W_init||_F +
||b_now − b_init||_F (captures rotation). q_early = q_init + distance
so kernel's |q_early − q_init| / |q_init| ratio = distance / ||W_init||_F.

With lr bumped back up to 1e-4 (default for the stabilized config),
verified at horizon=100, n_episodes=200:

  Q_SPREAD_EMA         = 23.64   (≥ 0.05)     PASS
  ACTION_ENTROPY_EMA   = 1.86    (≥ 1.0986)   PASS
  RETURN_VS_RANDOM_EMA = +0.586  (≥ 0.0)      PASS
  EARLY_Q_MOVEMENT_EMA = 0.0212  (≥ 0.01)     PASS
  Overall: PASS (H=6000 scale-up VIABLE)

early_mvmt grew monotonically (0.005 → 0.021) across the 200-episode
run — direction-sensitive diagnostic confirms genuine policy learning.

Audit doc docs/isv-slots.md updated per Invariant 7.

Next: H=600 / 1000-episode run on full data; if PASS holds, Task 13
(H=6000 scale-up) unlocks.
2026-05-15 15:57:24 +02:00
jgrusewski
fa30c2dd66 feat(alpha): alpha_dqn_h600_smoke — runnable Task 12 DQN smoke
Phase E.1 Task 12. Linear Q-network (W [9×10] + b [9], no hidden layer)
trained with ε-greedy + Munchausen target on the Phase E ExecutionEnv.
End-to-end runnable: load env, train, periodically launch
alpha_kill_criteria + apply_pearls_ad chain at episode boundaries, emit
PASS/FAIL verdict against the 4 kill criteria thresholds.

Pipeline per training step (all on GPU):
  1. forward Q_current on s_batch via alpha_linear_q_forward
  2. forward Q_next on s'_batch via alpha_linear_q_forward
  3. alpha_munchausen_target → targets[batch]
  4. alpha_linear_q_grad → dW, db (sparse over taken actions)
  5. alpha_linear_q_sgd_step on W and b (separate launches)
  6. every K episodes: kill_criteria + apply_pearls_ad chain → ISV[539..542]

Pipeline visibility bumps so examples can reach launchers:
  - cuda_pipeline::alpha_kernels module → pub
  - All launch_alpha_* fns → pub
  - launch_apply_pearls → pub
  - ALPHA_LINEAR_Q_CUBIN → pub

These are appropriate pub exports (Phase E.1 public API surface).

Initial micro-smoke (horizon=100, n_episodes=50, lr=1e-6):
  Q_SPREAD_EMA         = 3.12   (≥ 0.05)    PASS
  ACTION_ENTROPY_EMA   = 2.12   (≥ 1.0986)  PASS
  RETURN_VS_RANDOM_EMA = +1.03  (≥ 0.0)     PASS
  EARLY_Q_MOVEMENT_EMA = 2268   (≥ 0.01)    PASS [unphysical scale]
  Overall: PASS (uncalibrated)

Known stability issues — flagged in the binary's CLI docstring:
  - lr=1e-4 diverges to NaN (Q grows, Munchausen target explodes)
  - lr=1e-6 stays finite but Q grows 2000× over 50 episodes
  - Follow-ups: gradient clipping, target network, reward normalisation

Bug fixed during development: `stream.memcpy_htod(&host, &mut buf.clone())`
was uploading to a TEMPORARY clone (dropped immediately) — `kc_scalar_dev`
and `kc_action_counts_dev` never got their host data → entropy=0, early_mvmt=0,
rvr stuck at the alloc-zeros default. Fixed by removing `.clone()` and using
direct `&mut` refs.

Reads:
  config/ml/alpha_fill_coeffs.json   (Task 5c)
  ISV slots 547/548                  (Task 7c baseline)

Writes:
  config/ml/alpha_dqn_h600_smoke.json (verdict + per-checkpoint KC trajectory)

Reproduction:
  cargo run -p ml --release --example alpha_dqn_h600_smoke -- \
    --mbp10-dir /home/jgrusewski/Work/foxhunt/test_data/futures-baseline-mbp10/ES.FUT \
    --horizon 600 --n-episodes 1000

Audit doc docs/isv-slots.md updated per Invariant 7.
2026-05-15 15:39:30 +02:00
jgrusewski
36ab50814e feat(alpha): alpha_linear_q kernels + launchers for Task 12 DQN smoke
Phase E.1 Task 12a. Three new CUDA kernels for the H=600 DQN smoke
(Task 12 proper) that lands in a follow-up commit:

  alpha_linear_q_forward_kernel    Q = X · W^T + b
  alpha_linear_q_grad_kernel       dW, db sparse MSE-TD over taken actions
  alpha_linear_q_sgd_step_kernel   element-wise params -= lr · grad

Architecture: single linear layer, no hidden layer. The Phase E state
vector has meaningful direct features (alpha_logit, spread_bps, position,
ofi_sum_5, …) so linear Q can capture real relations like Q[Buy] ∝
alpha_logit. If linear can't pass the kill-criteria gate, no architecture
upgrade will save it — and the smoke proceeds with NoisyNet escalation
per the plan.

Sparse gradient: only the taken action contributes (standard DQN TD
loss). No atomicAdd needed — one thread per (i, j) loops over the batch
and adds only when actions[b] == i.

GPU contract:
  - No host branches inside any kernel (graph-capture compatible)
  - No atomicAdd (per feedback_no_atomicadd)
  - All compute on GPU (forward, grad, weight update)
  - Tiny launch overhead — fits per-step (batch=64 forward = 576 threads,
    1 block; grad = 99 threads, 1 block)

Three pub(crate) Rust launchers in alpha_kernels.rs match the
launch_apply_pearls pattern. Cubin embedded via include_bytes!.

Smoke test `linear_q_forward_grad_sgd_round_trip_matches_hand_math`
exercises all three kernels end-to-end on a small (batch=2, state_dim=2,
n_actions=3) case with full hand-math:

  Forward:  Q = [[2.1, 3.2, 0.3], [4.1, 5.2, 0.3]] ✓
  Grad:     dW = [[-1.8, -2.7], [0.8, 1.0], [0, 0]]
            db = [-0.9, 0.2, 0] ✓
  SGD:      W' = [[1.18, 0.27], [-0.08, 0.90], [0, 0]]
            b' = [0.19, 0.18, 0.30] ✓

All within 1e-4 tolerance. `cargo test -p ml --lib alpha_kernels`:
5/5 pass on RTX 3050 Ti in 2.04s (compile witness + 4 GPU smokes).
Audit doc docs/isv-slots.md updated per Invariant 7.
2026-05-15 15:25:23 +02:00
jgrusewski
ebbd28437a test(alpha): chained pipeline smoke — Task 12 wiring validation
End-to-end test for the kernel COMPOSITION that the H=600 DQN smoke
(Task 12 proper) will use at each rollout boundary:

  t+0  alpha_kill_criteria_compute_kernel  → scratch[0..4]
  t+1  apply_pearls_ad_kernel(n_slots=4)   → ISV[539..543]

The two prior alpha_kernels smokes (munchausen + kill_criteria) validated
kernels in isolation. This smoke validates the COMPOSITION on the same
stream — failures here are different (stream-ordering, Pearls index base,
Wiener offset base, scratch visibility) and would silently break Task 12.

Two iterations with stationary synthetic inputs:

  Iter 1 (Pearl A bootstrap)
    prev_x_mean=0 AND x_lag=0 → ISV[539..542] populated with raw scratch
    observations = [0.2041, 0.8980, 1.0670, 0.1] within 0.01 tolerance.
    Anchor slots 547/548 remain at Task 7c values (-5185, 4953).

  Iter 2 (Pearl D stationary)
    dx_mean = dx_step = 0 → α* = 0 → ISV unchanged from iter 1 within
    1e-4. Stationary signal stays at the bootstrap value.

Test would catch:
  - Producer's scratch write not visible to applicator (stream-ordering)
  - Wrong Pearls isv_idx_base / wiener_offset_base
  - Pearl A sentinel detection broken (formula yields 0 at t=0)
  - Wiener state corruption (iter 2 drifts from iter 1)

Reuses launch_apply_pearls from sp4_wiener_ema.rs (pub(crate)). Helper
fn run_chained_iter factors the producer→applicator sequence so the two
iterations are byte-identical apart from the Wiener state's evolution.

`cargo test -p ml --lib alpha_kernels`: 4 pass (compile witness + 2 prior
GPU smokes + this chained smoke) on RTX 3050 Ti in 1.89s total. Audit doc
docs/isv-slots.md updated per Invariant 7.

Remaining Task 12 work (full H=600 DQN trainer integration with this
pipeline at rollout boundaries) is queued for a dedicated session.
2026-05-15 15:14:56 +02:00
jgrusewski
697bb586d0 test(alpha): kill-criteria GPU smoke matching hand-computed observations
Adds the second of the two Phase E.1 kernel smoke tests in
alpha_kernels.rs (companion to the munchausen_target smoke from
91d1a52b9). End-to-end exercises the alpha_kill_criteria_compute_kernel
launcher with synthetic inputs covering all 4 outputs:

  q_values = [[1, 2, 3], [5, 5, 5]]   →  q_spread        ≈ 0.2041
  action_counts = [10, 30, 60]        →  action_entropy  ≈ 0.8980
  rollout_R=100, isv[547]=-5185,
                 isv[548]=4953       →  return_vs_random ≈ 1.0670
  q_init=50, q_early=55              →  early_movement   = 0.1000

ISV buffer is sized to 552 floats with slots 547/548 populated using the
committed Task 7c baseline values — this exercises the production
slot-indexing path through the kernel's
`isv[random_baseline_mean_slot]` / `isv[random_baseline_std_slot]` reads,
not just isolated kernel arithmetic.

Does NOT chain apply_pearls_ad_kernel afterward — the smoothing path is
canonical SP4 applicator territory already covered elsewhere. This test
isolates the kill-criteria producer arithmetic.

Tolerance 0.01 on all four observations; passes on RTX 3050 Ti in <2s
including kernel JIT.

`cargo test -p ml --lib alpha_kernels`: 3 pass (compile witness + both
GPU smokes). Audit doc docs/isv-slots.md updated per Invariant 7.
2026-05-15 14:52:06 +02:00
jgrusewski
91d1a52b9c refactor(alpha): rename phase_e_* → alpha_* — system-scoped naming
The kill-criteria producer, Munchausen target kernel, Rust launchers,
fit/baseline binaries, and their output JSON artifacts are *durable
infrastructure* of the alpha trading system (live across Phase E/F/G/...),
not milestone-scoped to Phase E specifically. Aligns with the earlier
`phase_e_isv_slots.rs` → `alpha_isv_slots.rs` rename rationale.

What was renamed:

  Code files:
    crates/ml/src/cuda_pipeline/phase_e_kill_criteria.cu       → alpha_kill_criteria.cu
    crates/ml/src/cuda_pipeline/phase_e_munchausen_target.cu   → alpha_munchausen_target.cu
    crates/ml/src/cuda_pipeline/phase_e_kernels.rs             → alpha_kernels.rs
    crates/ml/examples/phase_e_fit_fill_model.rs               → alpha_fit_fill_model.rs
    crates/ml/examples/phase_e_random_baseline.rs              → alpha_random_baseline.rs

  Artifacts:
    config/ml/phase_e_fill_coeffs.json                         → alpha_fill_coeffs.json
    config/ml/phase_e_random_baseline.json                     → alpha_random_baseline.json

  Kernel function names:
    phase_e_kill_criteria_compute_kernel  → alpha_kill_criteria_compute_kernel
    phase_e_munchausen_target_kernel      → alpha_munchausen_target_kernel

  Rust launcher names:
    launch_phase_e_kill_criteria          → launch_alpha_kill_criteria
    launch_phase_e_munchausen_target      → launch_alpha_munchausen_target

  Static cubin names:
    PHASE_E_MUNCHAUSEN_TARGET_CUBIN       → ALPHA_MUNCHAUSEN_TARGET_CUBIN

Historical milestone tags in doc-comments ("Phase E.1 Task N (2026-05-15)")
are RETAINED — they record WHEN the work landed and what plan it
implemented, which doesn't change with the system-scoped rename.

Plus: ADDS the alpha_munchausen_target GPU smoke test in alpha_kernels.rs.
End-to-end validates the launcher + kernel against hand-computed expected
values: batch=2 with one terminal sample; expected targets [29.8, 1.1];
got match within 0.05 tolerance on RTX 3050 Ti. PROVES the Task 9/10
kernels actually run on GPU.

All affected references updated in:
  - build.rs (kernel compile list)
  - mod.rs (module registration)
  - state_reset_registry.rs (4 RegistryEntry descriptions for slots 539-542)
  - alpha_isv_slots.rs (slot table comment)
  - docs/isv-slots.md (audit-doc cross-references)

Verified:
  cargo test -p ml --lib alpha_kernels: 2/2 pass (including GPU smoke)
  cargo test -p ml --lib state_reset_registry: 10/10 pass
  cargo build -p ml --release --example alpha_fit_fill_model --example alpha_random_baseline: clean
2026-05-15 14:30:40 +02:00
jgrusewski
feb2e8cc34 feat(alpha): phase_e_kernels — Rust launchers for Task 9 + Task 10 cubins
Phase E.1 Task 11. Two pub(crate) launchers expose the kill-criteria
producer (Task 9) and Munchausen target augmentation (Task 10) for use
by future trainer integration:

  launch_phase_e_kill_criteria(stream, kernel, q_values_dev, action_counts_dev,
                               scalar_inputs_dev, isv_dev, batch, n_actions,
                               scratch_out_dev)
    → kicks the kill_criteria producer; caller chains apply_pearls_ad_kernel
      (n_slots=4, isv_idx_base=ALPHA_ISV_BLOCK_LO=539) to smooth into slots
      539..542 via Pearl A bootstrap + Pearl D Wiener-α.

  launch_phase_e_munchausen_target(stream, kernel, q_next_dev, q_current_dev,
                                   actions_dev, rewards_dev, dones_dev,
                                   gamma, alpha_m, tau, log_clip_min,
                                   target_out_dev, batch, n_actions)
    → one-thread-per-sample target augmentation; α_m/τ/log_clip_min are
      scalar args so a downstream ISV-driven controller can tune them.

Plan deviation: Task 11 plan-spec said "replace hardcoded n_step=32,
gamma=0.999 literals" but grep across gpu_dqn_trainer.rs found ZERO such
literals — the trainer already reads gamma via read_isv_signal_at(
GAMMA_DIR_EFF_INDEX) and epsilon via read_isv_signal_at(AUX_TRUNK_EPS_
INDEX). The actual E.1 deliverable was Rust launchers for the new
cubins, which this commit lands.

Both launchers follow the launch_apply_pearls pattern in
sp4_wiener_ema.rs — pre-loaded CudaFunction as parameter, u64 device
pointers, debug_assert! guards.

Audit doc docs/isv-slots.md updated per Invariant 7.
Tested via `cargo test -p ml --lib phase_e_kernels` — 1 compile-witness
passes. Real GPU integration test in Task 12.
2026-05-15 14:17:29 +02:00
jgrusewski
b1ba41d403 feat(alpha): Munchausen DQN target term kernel (Vieillard et al. 2020)
Phase E.1 Task 10. Standalone target-augmentation kernel:

  m            = α_m · max(τ · log π(a|s), log_clip_min)
  V_soft(s')   = max(Q_next) + τ · log Σ exp((Q_next − max) / τ)
  target       = r + m + γ · V_soft(s')   (terminal: r + m)

π(a|s) ∝ exp(Q_online(s, a) / τ) — softmax policy from the online net.
Munchausen bonus is implicit KL regularisation between successive policies;
soft-V replaces the hard max bootstrap with a τ-weighted softmax average.

Both softmaxes are computed via log-sum-exp with the max-trick. This is
essential at τ ≈ 0.03 where raw exp(Q/τ) would overflow f32 for any
Q-spread > 25 nats. The kernel is one-thread-per-batch-sample, no
atomicAdd, no host branches.

α_m, τ, log_clip_min are kernel args (not hard-coded), so a Phase E.2+
controller can ISV-drive them. Typical Vieillard values: α_m=0.9, τ=0.03,
log_clip_min=-1.0.

Does NOT touch any ISV slot — pure target augmentation.

Cubin: target/release/build/ml-*/out/phase_e_munchausen_target.cubin (12.8 KB).

Launcher integration is Task 11 (consumes target_out where the C51/MSE
loss kernels currently consume `r + γ · max_a' Q_target`). Audit doc
docs/isv-slots.md updated per Invariant 7.
2026-05-15 14:11:00 +02:00
jgrusewski
d493b729bf feat(alpha): phase_e_kill_criteria producer kernel (slots 539-542)
Phase E.0 Task 9. Single-block, single-thread CUDA producer that writes 4
raw scalar observations into a contiguous scratch_out[0..4] block:

  scratch_out[0] → ISV[539] Q_SPREAD_EMA          (kill: ≥ 0.05)
  scratch_out[1] → ISV[540] ACTION_ENTROPY_EMA    (kill: ≥ 0.5·ln(9) ≈ 1.10)
  scratch_out[2] → ISV[541] RETURN_VS_RANDOM_EMA  (kill: ≥ 0, i.e. ≥ random)
  scratch_out[3] → ISV[542] EARLY_Q_MOVEMENT_EMA  (kill: ≥ 0.01, learned)

Downstream `apply_pearls_ad_kernel` (n_slots=4) chained on the same stream
applies Pearl A first-observation bootstrap + Pearl D Wiener-α smoothing —
composes with the canonical val_sharpe_delta_compute_kernel pattern rather
than reimplementing Wiener math (per feedback_no_cpu_compute_strict — one
Wiener implementation in the codebase, the GPU one).

Inputs:
  q_values[batch, n_actions]   most-recent Q forward output (device)
  action_counts[n_actions]     empirical action histogram (device)
  scalar_inputs[3]             [rollout_R_mean, q_init_norm, q_early_norm]
                               via mapped-pinned (host writes between rollouts)
  isv                          reads slots 547 + 548 (random baseline
                               mean/std — populated once by Task 7c,
                               TrainingPersist)

No atomicAdd (per feedback_no_atomicadd), no host branches
(per pearl_no_host_branches_in_captured_graph), no CPU compute
(per feedback_cpu_is_read_only). __threadfence_system() before exit for
the chained Pearls applicator's visibility guarantee.

Cubin produced: target/release/build/ml-*/out/phase_e_kill_criteria.cubin
(16.8 KB).

Launcher integration is Task 11 (separate commit so this task can stand
alone for cubin validation). Audit doc docs/isv-slots.md updated per
Invariant 7.
2026-05-15 14:07:41 +02:00
jgrusewski
8bf8bdf874 feat(alpha): state_reset_registry entries + dispatch arms for slots 539..548
Per feedback_registry_entries_need_dispatch_arms — both must land in the
same commit; the test `every_fold_and_soft_reset_entry_has_dispatch_arm`
walks training_loop.rs::reset_named_state source and asserts coverage.

- 10 RegistryEntry rows appended after SP22 block (full producer/consumer
  rationale per existing dense-description pattern)
- 7 dispatch arms in reset_named_state (the 3 TrainingPersist anchors
  — slots 544/547/548 — are not dispatched per the existing convention)
- All sentinels 0.0 per pearl_first_observation_bootstrap

All 10 registry tests pass. Audit doc docs/isv-slots.md updated per
Invariant-7.
2026-05-15 12:19:30 +02:00
jgrusewski
aa5908aa53 feat(alpha): reserve ISV slot block 539..550 for alpha trading system
12 contiguous slots reserved for durable alpha-system infrastructure:
- 539-542: diagnostics (Q-spread, action entropy, return-vs-random,
  early-Q-movement EMAs) — read by Phase E kill criteria
- 543-546: stacker-threshold controller (threshold, target, observed-rate,
  Kelly attenuation) — engagement-rate self-correction
- 547-548: random-uniform baseline (mean, std) — anchor for kill criterion 541
- 549-550: reserved spare (absorb growth without bumping ISV_TOTAL_DIM)

Named `alpha_isv_slots` rather than `phase_e_isv_slots` because these slots
are intended to outlive any individual Phase E/F/G milestone — the SP4..SP22
naming was iteration-scoped, but this block is system-scoped infrastructure.

ISV_TOTAL_DIM bumped to 551. All indices validated in 4 unit tests
(bounds, membership, uniqueness, total-dim coverage). Audit doc
docs/isv-slots.md updated per Invariant-7.
2026-05-15 10:53:41 +02:00
jgrusewski
9c26e78cdc docs(phase-e): implementation plan for execution-layer RL policy
32 tasks across 5 milestones (E.0 foundation → E.4 shadow-mode), with
locked design decisions from three rounds of focused research memos:
- Q1 (fill sim): medium-tier Poisson regression from 5.2M trade tape
- Q2 (reward): terminal-only, n-step credit (consumes ISV slot 517)
- Q3 (alpha trust): implicit calibrated trust via state features
- Q4 (state window): current snapshot + 2 short-horizon scalars
- Q5 (sizing): hybrid decoupled fractional Kelly × Phase E attenuation

Trainer choice: DQN primary (Rainbow + Munchausen target), PPO control
on H=600 truncated only if kill criteria fire. Exploration: ε-greedy
with kill-criteria gate at end of week 2; NoisyNet escalation (4-6 days
due to dead scaffolding in our codebase) if criteria fail; RND beyond
that.

ISV consumption: 5 existing slots (n_step=517, γ=43-46, ε=41, Kelly=280,
reward_caps=452-453); new block 539..550 reserved for Phase E (10 in
active use, 2 spare). One new controller (stacker-threshold
engagement-rate-self-correction at slot 543).

Hardcoded by design: Kelly contract cap (Category-1 safety),
kill-criteria thresholds (circuit breakers). All other knobs are
ISV-driven per pearl_controller_anchors_isv_driven.

Decisive gates at week 1 (H=600 kill criteria), week 4 (composition
backtest Sharpe at half-tick > 0), and week 5 (shadow-vs-backtest
PnL within 30%).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 10:42:14 +02:00
jgrusewski
5d79bf0b22 docs(phase1d): implementation plan for regime-gated tick reasoning + memory accumulator
26 tasks across 5 milestones (1d.0 through 1d.4) with decisive falsification
gates at each. Anchors to commit db874b184 (Phase 1c validation) and references
real APIs: ml::trainers::mamba2, ml-alpha::training, backtesting::strategies.

Each task is bite-sized (TDD steps + commit). Decisive gates:
- 1d.0: best calibrated Brier ≤ 0.250
- 1d.1: Mamba AUC > 0.72 at K=100
- 1d.2: Mamba AUC > 0.55 at K=6000 (DECISIVE for two-head architecture)
- 1d.3: regime-gated conditional accuracy > 0.65
- 1d.4: out-of-sample Sharpe > 1.5

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 01:13:42 +02:00
jgrusewski
2a2f16b944 design(foxhuntq): architectural pivot away from per-bar DQN to decoupled Belief Bus + Conformal DRL
After 16+ SP-runs producing WR pinned at ~0.435 — and a session-end smoke
showing SP22 H6 vNext K=3 head architecture moves WR to 0.458 only via
degenerate Hold-collapse (PF erodes 1.45 → 1.08) — pivot to a research-
honest architecture: distributional supervised alpha + meta-labeling gate +
Coverage-Gated Kelly execution, integrated through a novel GPU-native
publish-subscribe Belief Bus substrate.

This is a DESIGN doc only. No implementation yet. v1 → v4 evolution captured
in the doc itself; v4 is research-honest with explicit prior-work citations:

  - Bellemare/Dabney distributional RL (already shipped in foxhunt SP5+)
  - Lopez de Prado triple-barrier + purging + meta-labeling
  - Vovk/Romano/Gibbs-Candès conformal prediction foundations
  - Sun-Yu 2025 NeurIPS CPTC (change-point-aware CP)
  - Gan et al. 2025 NeurIPS arXiv:2510.26026 (CP for infinite-horizon RL —
    we PORT Algorithm 1 directly in Phase 7, not invent)
  - Zhu-Zhu ICML 2025 AlphaQCM (QCM variance estimation, adopted)
  - Berti-Kasneci 2025 TLOB (motivates MLP baseline)

Honest novelty narrowed to three claims after literature review:

  1. Belief Bus substrate — GPU-native pub/sub bus with per-slot
     distributional semantics + conformal coverage + causal DAG metadata.
     Extends our existing 539-slot ISV pattern (already novel architecture
     vs published trading systems). The substrate integration is not in
     literature.

  2. Application domain — imbalance-bar HFT futures + MBP-10 microstructure +
     triple-barrier labels. Existing distributional CP + DRL papers use
     daily stocks, general RL benchmarks, or alpha formula discovery.

  3. Adaptive controllers + per-slot conformal coverage — every adaptive
     quantity in the system (Kelly priors, reward caps, Adam β1, regime
     probabilities) gets conformal coverage attached. Not seen in
     literature.

Tiered success criteria recalibrated per CFTC 2014 E-mini HFT study
(median firms hit ~55% WR / PF 1.2-1.4):

  - Minimum viable: WR ≥ 50% AND PF ≥ 1.4 → deploy
  - Goal:           WR ≥ 53% AND PF ≥ 1.7
  - Stretch:        WR ≥ 55% AND PF ≥ 2.0 (original v1 target — aggressive
                                            top-quartile HFT)

Eight phases with explicit falsification gates:

  Phase 0: Purged walk-forward + bar audit (Lopez de Prado hygiene)
  Phase 1a: MLP baseline alpha (cheapest falsification)
  Phase 1b: TLOB/Mamba2/Liquid encoders
  Phase 1C (conditional): tick-resolution if bar fails
  Phase 2: Multi-head IQN + QCM + class weights
  Phase 3: Belief Bus substrate
  Phase 4: CPTC calibration
  Phase 5: Coverage-Gated Kelly execution (deployment trigger if viable)
  Phase 6: Production wiring + 2-week shadow mode
  Phase 7 (optional): Port arXiv:2510.26026 conformal-DRL Q-residual

Phase 7 specifically detailed with concrete Algorithm 1 port (~1100 LOC
total), tunable params (k=5-10 ours vs 1-5 paper, due to γ=0.99 vs 0.8),
and falsification gate (empirical coverage ≥ 88% + PF improvement ≥ 0.2).

Deferred indefinitely (research-grade risk too high):
  - Neural SDE (training instability per Kidger 2021)
  - Hawkes process bar replacement (O(N²) MLE prohibitive at HFT scale)
  - Multi-asset portfolio
  - Learned in-trade exit head

Total minimum-viable path: Phases 0-6 ~6-8 weeks engineering + 20 hours
L40S compute. Falsification gates at every step.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 19:21:25 +02:00
jgrusewski
19bb3bc3c8 fix(sp22-vnext): aux_outcome CF half mirror on-policy (NOT all -1)
Smoke train-k95mj epoch 0 + epoch 1 printed
`trade_outcome_ce=0.000e0` — K=3 CE EMA stuck at Pearl A sentinel
across all training steps.

Root cause chain:

  1. insert_batch is called with bs = total = 4_096_000 (cf-mult-
     expanded), replay cap = 300_000 (L40S GpuProfile). Tail-clip:
     off = 3_796_000, slice(off..) takes the last 300K elements.
  2. Prior fix (256a5fa5a) filled CF half [base_total, total) with
     -1 mask via cuMemsetD32Async. Last 300K elements at
     [3_796_000, 4_096_000) are entirely in this CF half → 100%
     mask.
  3. Replay ring fills with 300K mask labels. PER gather samples
     batches → every batch has label == -1 for all samples →
     aux_trade_outcome_loss_reduce returns
     loss = 0 / fmaxf(valid=0, 1) = 0 every step.
  4. aux_outcome_ce_ema_update bootstrap requires `loss > 0.0f`;
     never fires → ISV[538] pinned at 0.0 sentinel.

Fix: CF half mirrors the on-policy half (matches K=2 sibling
aux_sign_labels which writes the same bar-resolved label to both
halves). Replace cuMemsetD32Async(-1) + single memcpy with TWO
memcpy_dtod calls (on-policy half + CF half), both sourced from
the same exp_aux_to_label_per_sample[base_total].

Semantic justification: the K=3 outcome label depends on the bar's
trade-close event, not the action. The CF action's hypothetical
trade outcome at the same bar approximates to the same label. The
B4b-1 kernel writes -1 to non-close slots (~97%) and 0/1/2 to
close slots (~3%); duplicating into CF preserves this sparsity →
ring tail retains ~7-9K real labels per 300K-element fill →
Pearl A bootstraps → K=3 head trains.

Lib suite 1016/0 green. Bug was runtime-only (small-batch lib
tests don't trigger the off > 0 tail-clip path). Audit doc
updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 16:19:15 +02:00
jgrusewski
878cc9ba72 feat(sp22-vnext): F-3c follow-up — K=3 CE EMA in stdout HEALTH_DIAG aux line
The F-3c commit (cdd3dc6ed) pushed `aux_trade_outcome_ce_ema` into
the regression-detection metrics vec but never wired a `tracing::
info!` console emit. Smoke `train-q5k5k` ran clean past the
rollout + post-rollout phases — but `argo logs train-q5k5k | grep
aux_trade_outcome` returned zero hits, so the operator had no way
to read the K=3 head's CE EMA trajectory.

Fix: extend the existing K=2 aux HEALTH_DIAG print

  HEALTH_DIAG[N]: aux [next_bar_mse=… regime_ce=… w=…]

to include `trade_outcome_ce=…`:

  HEALTH_DIAG[N]: aux [next_bar_mse=… regime_ce=…
                       trade_outcome_ce=… w=…]

Reads ISV[538] via the same `trainer.read_isv_signal_at(...)`
accessor the regression-detection vec uses — single source of
truth, no duplicated mirroring.

Expected operator-visible trajectory across smoke epochs:
  Epoch 0 (cold-start, Pearl A sentinel):     0.000
  Epoch 1+ (first non-zero bootstrap):       ~1.099 (= ln(3))
  Healthy learning:                           0.5 - 0.7
  Pinned at ln(3) for many epochs:            head can't learn

cargo check -p ml clean. Audit doc updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:47:01 +02:00
jgrusewski
256a5fa5ab fix(sp22-vnext): K=3 aux_outcome_labels CF-half buffer underrun
Phase B4b-2 introduced `exp_aux_to_label_per_sample` sized
`[alloc_episodes × alloc_timesteps]` (no cf-mult expansion — the
B4b-1 per-step kernel only writes the on-policy half). The batch
finalisation cloned into the emitted `aux_outcome_labels` with size
`total = base_total × 2` (cf-mult expanded), so
`dtod_clone_i32(src, total, ...)` invoked `src.slice(..total)` on a
half-sized source → `CudaSlice::try_slice` returned `None` → the
internal `unwrap()` panicked at cudarc safe/core.rs:1648.

Repro: workflow train-xzv56 panicked after rollout completed
(timestep=999) on fold 0; rollout itself ran clean, the OOM from
the prior commit is gone.

Fix: replace the single `dtod_clone_i32` with a 3-step build:

  1. alloc_zeros::<i32>(total)
  2. cuMemsetD32Async(ptr, 0xFFFFFFFFu32, total, stream) — fills
     all `total` slots with i32 mask sentinel -1 (byte pattern
     0xFFFFFFFF reinterprets as i32(-1))
  3. memcpy_dtod the first `base_total` real labels from
     exp_aux_to_label_per_sample into the on-policy half

CF half remains at -1. The K=3 sparse-CE loss masks `label == -1`
out of the mean and B_valid count, so CF samples contribute zero
gradient — exactly the semantic we want (CF actions have no
observed trade-close outcome to predict against).

Lib suite: 1016/0 green. Audit doc updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:26:46 +02:00
jgrusewski
0acf77e656 config(dqn): strip H100-tuned VRAM overrides from dqn-production.toml
dqn-production.toml hard-coded three H100-tuned values that shadow
GpuProfile auto-detection: batch_size=16384, buffer_size=500K,
gpu_n_episodes=4096. After the L40S-default flip lands (prior commit
8b8bb1af7), workflow `train-ft8ph` deterministically OOMed at fold 0/1/2
with `build_next_states_f32` 4 GiB alloc — because the H100-sized
hyperparams.batch_size + buffer_size + gpu_n_episodes ate ~38 GB of the
L40S's 46 GB usable VRAM before the rollout step.

DqnTrainingProfile.apply_to() runs AFTER train_baseline_rl.rs populates
hyperparams from GpuProfile, so the production TOML always wins. All
three fields are `Option<...>` in the TOML schema — removing the lines
turns apply_to into a no-op for them, and the GpuProfile-detected values
flow through:

  field            | L40S  | H100   | (was forced)
  batch_size       | 4096  | 8192   | 16384
  buffer_size      | 300K  | 500K   | 500K
  gpu_n_episodes   | 2048  | 4096   | 4096

Two pinned assertions in training_profile.rs::tests checked the old
contract `hp.batch_size == 16384`. Rewritten to assert
`hp.batch_size == baseline_batch_size` — locks the new contract that
VRAM-tuned values stay GpuProfile-sourced.

Lib suite 1016/0 green. Audit doc updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:05:06 +02:00
jgrusewski
bbd52c3aa7 feat(sp22-vnext): FoldReset registry entries for B5b/C collector buffers
Two collector-side device buffers used by the K=3 trade-outcome head
were missing FoldReset registry coverage:

  - prev_aux_outcome_probs [alloc_episodes × 3]
    TRUE stale-read risk. Producer writes end-of-step; consumer
    (experience_state_gather) reads start-of-next-step into
    state[121..124). Without FoldReset the new fold's step-0 state
    gather would inject the previous fold's last-step softmax probs
    into the first batch's state slots.

  - exp_aux_to_input_buf [alloc_episodes × 262]
    Cleanliness-only. Concat kernel overwrites all 262 columns every
    step before the K=3 forward reads them, so no steady-state stale-
    read risk. Registered for parity with the rest of the K=3
    pipeline + to satisfy feedback_registry_entries_need_dispatch_
    arms (the pin test asserts every registry entry has a matching
    dispatch arm in reset_named_state).

Both fields promoted to pub(crate) on GpuExperienceCollector so
reset_named_state can reach them. Matching dispatch arms added with
the standard memset_zeros pattern (is_win_per_env / hold_baseline_
buffer style).

Tests: All 10 state_reset_registry tests pass, including the critical
every_fold_and_soft_reset_entry_has_dispatch_arm pin test that walks
the dispatch body and validates parity with registry entries. Full
lib suite 1015/1 (the failing test is the pre-existing
test_dqn_checkpoint_round_trip NoisyLinear flake — pred1/pred2 sign
mismatch surfacing ~30-50% of full-suite runs, documented in
project_sp22_h6_vnext_resume memory as unrelated to this work).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 13:12:34 +02:00
jgrusewski
4b40710b7c feat(sp22-vnext): Phase B5b-2 collector trade plan forward — resolves K=3 asymmetry
Phase B5b's K=3 input concat passed plan_params=NULL because the
collector had no trade plan launch. Trainer-side K=3 forward trained
on real plan_params while the collector queried at plan_params=0 —
documented train/inference asymmetry on the plan-conditioning surface.

Phase B5b-2 mirrors the (now-corrected) trainer
`launch_trade_plan_forward` chain on the collector inside the rollout
step:

  1. SGEMM:    hidden[N, AH] = h_s2_q[N, SH2] @ W_fc[AH, SH2]^T
  2. bias+relu in-place on hidden
  3. SGEMM:    pre_out[N, 6]  = hidden[N, AH] @ W_out[6, AH]^T
  4. trade_plan_activate → exp_plan_params[N, 6]

Weight resolution uses the same `aux_w_ptrs` array the K=3 forward
already consumes (`f32_weight_ptrs_from_base`); indices 91-94 match
the corrected trainer-side reads. The `trade_plan_activate` kernel is
loaded from `EXPERIENCE_KERNELS_CUBIN` (same cubin the rest of
`exp_module_extra` uses; the trainer loads it from there too).

The K=3 concat now takes `exp_plan_params.raw_ptr()` instead of NULL
— both sides see f(h_s2; W_plan_*_init), symmetry restored. Plan
tensors at [91..94] still have no backward (no Adam updates), so the
plan-head weights stay at Xavier cold-start forever. This commit
delivers the symmetry the K=3 head requires, not a learned plan
signal — adding a real plan-head backward is a follow-up project.

New struct fields on GpuExperienceCollector:
  - exp_trade_plan_hidden_buf  [alloc_episodes × adv_h]
  - exp_trade_plan_pre_out_buf [alloc_episodes × 6]
  - exp_plan_params            [alloc_episodes × 6]
  - exp_trade_plan_activate_kernel: CudaFunction

Lib test suite: 1016/0 green maintained. Audit doc updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:41:59 +02:00
jgrusewski
fb9b62a1f9 fix(plan-head): trainer trade plan forward reads from wrong param indices
`launch_trade_plan_forward` read `w_fc/b_fc/w_out/b_out` from
`padded_byte_offset(&param_sizes, [82..86))` — i.e., the ISV-conditioning
+ recursive-confidence tensors (`b_isv_gate`, `w_isv_gamma`,
`b_isv_gamma`, `w_conf_fc`). The actual plan tensors live at
`[91..95)` per `compute_param_sizes` and the matching Xavier
init block. No backward exists for the plan head, so the plan
tensors at `[91..94]` sat at cold-start Xavier values forever
while `plan_params` was being driven by whichever ISV/conf
weights happened to occupy the wrong offsets.

Every downstream consumer (`backtest_plan_kernel`, `plan_isv` slots
in `experience_kernels`, `compute_plan_params` in `q_value_provider`,
regime gating, and the SP22 H6 vNext B5b concat path) was therefore
conditioning on noise correlated with ISV optimisation, not on a
learned plan. Discovered while preparing Phase B5b-2 (collector
trade plan launch). Two-line index fix + diagnostic comment +
audit doc entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:35:48 +02:00
jgrusewski
cdd3dc6edb feat(sp22-vnext): Phase F-3c — HEALTH_DIAG snap + console line for K=3 CE EMA
Completes the F-3 observability story. Smoke runs now print
aux_trade_outcome_ce_ema every epoch in the standard HEALTH_DIAG output
— no ISV inspector required.

Changes:

health_diag.rs:
- New field aux_trade_outcome_ce: f32 appended at END of
  HealthDiagSnapshot per "Field order is stable; adding fields
  appends to the end" doc rule. Existing fields' byte offsets
  preserved → no kernel-side word offset re-validation.
- snapshot_size_is_stable pin: 149 × 4 → 150 × 4 = 600 bytes.

health_diag_kernel.cu:
- New WORD_AUX_TRADE_OUTCOME_CE = 149 (appended at end).
- WORD_TOTAL = 150 (was 149); static_assert bumped.
- New kernel arg aux_trade_outcome_ce_idx appended after
  moe_lambda_eff_idx.
- New mirror write after the existing MoE mirrors. Stream-implicit
  ordering: aux_outcome_ce_ema_update (F-3b) fires before
  health_diag_isv_mirror, so the read picks up the just-updated EMA.

gpu_health_diag.rs:
- launch_isv_mirror gets new aux_trade_outcome_ce_idx: i32 arg.

gpu_dqn_trainer.rs:
- launch_health_diag_isv_mirror passes
  AUX_TRADE_OUTCOME_CE_EMA_INDEX as the new arg.

training_loop.rs:
- Per-epoch metrics push appends ("aux_trade_outcome_ce_ema",
  ISV[538]) to the standard out vec. Console / CSV automatically
  includes the new column.

End-to-end F-3 chain now closed:
  K=3 fwd → aux_to_loss_scalar_buf → aux_outcome_ce_ema_update
  → ISV[538] → health_diag_isv_mirror → snap.aux_trade_outcome_ce
  → training_loop metrics → console.

Operator sees CE every epoch:
- Cold-start: 0.000
- After bootstrap: ~1.098 (= ln(3))
- After training: ideally 0.5-0.7 (head learning)

Phase F end-to-end ready. The vNext stack has:
- Full GPU kernel chain (A2-A5 + D + plan-conditioning)
- Full Rust wireup (B0-B4, B4b-1/2, C-1/C-2, B5b)
- Real labels reaching trainer
- K=3 → policy via state slots + atom-shift
- End-to-end CE observability

Verification:
- cargo check -p ml clean.
- cargo test -p ml --lib → 1016/0 green (incl. bumped
  snapshot_size_is_stable byte-size pin test).

Audit: docs/dqn-wire-up-audit.md Phase F-3c section.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 12:22:43 +02:00
jgrusewski
02479c885d feat(sp22-vnext): Phase F-3b — K=3 CE EMA launcher wireup + reset registry
Completes the Phase F-3 observability chain. Kernel + ISV slot landed
in F-3a; this commit wires the launcher into the trainer's per-step
training graph and registers the FoldReset entry.

Changes:
- gpu_dqn_trainer.rs:
  - New pub(crate) static AUX_OUTCOME_CE_EMA_CUBIN embed
  - New aux_outcome_ce_ema_kernel: CudaFunction field on GpuDqnTrainer
  - Constructor loads kernel handle + struct-init
  - New launch_aux_outcome_ce_ema() method (single-thread launch,
    ISV slot 538, α=0.05)
- training_loop.rs:
  - Launch call appended after launch_aux_heads_loss_ema()
  - New dispatch arm "aux_trade_outcome_ce_ema" in reset_named_state
- state_reset_registry.rs:
  - New RegistryEntry for "aux_trade_outcome_ce_ema" (FoldReset
    sentinel 0.0)

End-to-end observability now live: K=3 head's batch-mean sparse-CE
flows into ISV[538] every step via Pearl A-bootstrapped EMA.
Smoke runs can read this slot to verify learning:
- Cold-start: 0.0
- After first step with B_valid > 0: bootstrap to first observation
  (~1.098 = ln(3) for uniform K=3 prediction)
- Healthy learning: monotonic decrease toward 0.5-0.7 over epochs
- Falsification: pinned at ~1.098 for many epochs

Phase F prep complete. The trade-outcome aux head's:
- Forward chain (A2-A5 + B0-B4)
- Real labels reach trainer (B4b-1/2)
- K=3 → policy state (C-1/C-2)
- K=3 → Q-target atom-shift (D)
- Plan-conditioning (B5b)
- Smoke observability (F-3 + F-3b)
are all wired. Phase F deployment (argo-train.sh smoke) is next.

Verification:
- cargo check -p ml clean.
- cargo test -p ml --lib → 1016/0 green (incl. every_fold_and_soft_
  reset_entry_has_dispatch_arm pin test).

Audit: docs/dqn-wire-up-audit.md Phase F-3b section.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 11:34:32 +02:00