Commit Graph

413 Commits

Author SHA1 Message Date
jgrusewski
57de1a8b4e docs(plans): integrated RL trainer (DQN + PPO + BCE + aux) plan
Single integrated trainer where 5 loss heads (BCE direction, C51
distributional Q, categorical π, scalar V, aux prof+size) sit on a
shared Mamba2+CfC encoder. Joint training with adaptive loss-balance
λ weights via the existing pearl_loss_balance_controller infrastructure.
Discrete 9-action grid shared between Q and π heads; reward = per-trade
realized PnL from LobSimCuda.

Designed in response to lob-backtest-sweep-jpdhg result (PF=0.24,
sharpe=-9.72, mono-anti-cal in conviction→PnL): the encoder learns
directional AUC but never sees PnL-aware gradient because
stop_grad_aux_to_encoder blocks the aux head's gradient. RL training
fixes this by making the encoder optimize per-trade realized PnL via
Q-head Bellman + π-head clipped surrogate.

Every hyperparameter (γ, τ, PPO clip ε, entropy coef, rollout steps,
PER α, reward scale, loss-balance λs) is ISV-driven per
pearl_controller_anchors_isv_driven and feedback_isv_for_adaptive_bounds.
12 new ISV slots (400-411) + 12 reused existing slots + 8 new controller
kernels following the Wiener-α + first-observation-bootstrap pattern.

10 phases (A-H, ~3 weeks), falsifiable gate G8 = profit_factor > 1.0
on 2M-event backtest sweep.
2026-05-22 22:07:45 +02:00
jgrusewski
458d678e9f docs(plans): multi-resolution input architecture migration plan
Greenfield Phase 1 plan addressing temporal receptive field mismatch
(auc_h1000=0.576 plateau): replace seq_len=32 raw-tick input with
3-scale aggregation [(1,10), (30,10), (100,12)] covering 1510 ticks.

10 tasks total, executed via subagent-driven development. Falsifiable
gate: auc_h1000 >= 0.65 on clean front-month data.
2026-05-22 20:48:05 +02:00
jgrusewski
783297e002 feat(loader): instrument_id filter + outdated test fix + sp18 fingerprint 2026-05-22 15:56:31 +02:00
jgrusewski
c535be046f baseline(per-horizon-cfc): 3-seed h6000 baseline JSON skeleton + retrieval gap
Per spec §4.1 + Q-3-seed-baseline. Both baseline Argo workflows
succeeded:
- alpha-perception-baseline-seed16963 (39min)
- alpha-perception-baseline-seed16964 (26min)

Precise AUC values deferred: train pod stdout is in MinIO archive
(xl.meta format, needs mc auth). The on-disk alpha_train_summary.json
on /feature-cache/alpha-perception-runs/f22f3f948/ corresponds to
seed 16963 (last to finish). Task 15 implementer retrieves via debug
pod mount of feature-cache PVC.

Known data point: seed 16962 = 0.7454 best_auc_h6000.

The Smoke 1 invariant gate threshold is signal-derived per
pearl_tests_must_prove_not_lock_observations — formulas captured in
the JSON for Task 15 to apply once values are retrieved.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 16:10:48 +02:00
jgrusewski
ed34d356a8 docs(per-horizon-cfc): kickoff — spec + plan + historical record
Spec: docs/superpowers/specs/2026-05-21-per-horizon-cfc-inference-design.md
Plan: docs/superpowers/plans/2026-05-21-per-horizon-cfc-inference-plan.md

Spec went through 2 critical-review passes (32 total findings, all resolved).
Bucketing source: CfC.tau (per-channel, trained, log-uniform init at HIDDEN_DIM=128).
Atomic refactor reverts MTER scaffolding. 5 ISV-driven controllers. All-on-device
transition (no bulk DtoH). Single fused per-branch kernel. Compact ragged heads_w_skip.
Validated via 3 Argo smokes (training stability, CRT.diag inference differentiation,
fxt-backtest end-to-end).

Also committing historical record: superseded MTER spec/plan, intervention A
plan, ISV λ controller spec/plan, GPU log ring spec/plan. Per spec §5.3 these
stay as audit trail; not in build path.

Plan has 18 tasks, full TDD with bite-sized steps, ready for
subagent-driven-development execution.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 15:05:28 +02:00
jgrusewski
faa9a73c10 spec(crt-train): output smoothness retraining intervention (intervention A)
Per project_crt_diag_findings.md — CRT.diag + diag.2 empirically
falsified all three hypotheses about why the model's per-event output
doesn't track horizon-specific dynamics. Labels ARE differentiated per
horizon, AUC=0.66 IS per-event measured, but per-event predictions
behave identically across all 5 horizons (2.5-event mean run length
raw, 3.3-event after aggressive Wiener-α EMA smoothing). h6000
predictions should change every thousands of events, not every 3.3.

Diagnosis: training dynamics issue. The BCE loss provides no signal
pushing toward horizon-coherent predictions. Adjacent-event labels at
horizon K share K-1/K of the forward window so SHOULD produce similar
predictions, but the loss doesn't require this.

Intervention A (this spec, minimum-scope): output smoothness
regularizer
  L_smooth[h] = λ[h] × mean_t (p[h](t) - p[h](t-1))²

With horizon-weighted λ (stronger for h6000 than h30): forces h6000
predictions to change slowly while leaving h30 responsive.

Implementation surface:
  - multi_horizon_heads.cu backward: extend grad_probs with smoothness
    gradient
  - perception.rs trainer step: prev_probs_d buffer, per-horizon (p[t]
    - p[t-1])² accumulation
  - heads.rs: SMOOTHNESS_LAMBDA constant per horizon
  - alpha_train.rs: --smoothness-base-lambda CLI flag

Validation gate (CRT.train Gate):
  MUST: per-horizon AUC ≥ baseline - 0.02 (no signal destruction)
  WIN: h6000 mean_run_len ≥ 100 events; h6000/h30 ratio ≥ 10× (horizons
       actually differentiated post-training)
  STRETCH: CRT.1 controller smoke shows mean PnL CORRELATED with
       conviction (vs anti-correlated in lnfwd)

Future work if intervention A doesn't pass WIN:
  B: horizon-conditional output structure (architecture change)
  C: curriculum on horizon (multi-day training)
  D: different label generation (majority-vote vs single-point)

Status: Design — awaiting user review before plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 22:59:49 +02:00
jgrusewski
e27fc90b9b arch(crt-1): open_trade_state 24→64 byte expansion — atomic refactor (C1.1)
Per spec §7 (v3 architecture reset, promoted from v2 Phase B into CRT.1).
Single-cache-line layout. Every reader and writer of open_trade_state
migrates in this commit per feedback_no_partial_refactor.

New 64-byte layout (existing 24-byte fields preserved at original offsets):
  Offset  Size  Field
    0     8     entry_ts_ns                              (u64)
    8     4     entry_px_x100                            (i32)
   12     4     entry_size                               (i32)
   16     4     realized_at_open                         (f32)
   20     4     conviction_at_entry                      (f32)  ← NEW
   24     4     conviction_ema                           (f32)  ← NEW
   28    16     conviction_per_horizon_ema [4 × f32]    ← NEW
   44     4     pnl_adjusted_conviction_ema              (f32)  ← NEW
   48     4     peak_unrealized_pnl                      (f32)  ← NEW
   52     4     degradation_consecutive_events           (u32)  ← NEW
   56     4     disagreement_consecutive_events          (u32)  ← NEW
   60     1     horizon_idx_dominant_at_entry            (u8)   ← NEW
   61     3     pad

The 24-byte prefix is unchanged so downstream readers (stop_check_isv in
decision_policy.cu, max_hold event-rate check in resting_orders.cu) need
only update the stride constant. The new fields at offsets 20..63 are
populated by subsequent CRT.1 tasks (C1.2 multi-horizon conviction, C1.4
composite exit signal).

Open branch in pnl_track.cu zeros the new fields implicitly because
alloc_zeros on the device slot zero-initialises everything; subsequent
writes only touch the 0-23 byte range (existing fields). Close branch
reset-loop iterates OPEN_TRADE_STATE_BYTES which now zeros all 64.

Files changed:
  crates/ml-backtesting/src/lob/mod.rs  — pub const OPEN_TRADE_STATE_BYTES: usize = 64
  crates/ml-backtesting/cuda/pnl_track.cu  — #define OPEN_TRADE_STATE_BYTES 64
  crates/ml-backtesting/cuda/resting_orders.cu — comment + stride literal 24→64
  crates/ml-backtesting/tests/stop_controller.rs — open_trade_state_64_byte_layout test

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:25:05 +02:00
jgrusewski
7ae0a8d461 plan(crt-1): unified inventory controller implementation plan
Per spec v3 (commit 9ad76c4df). Supersedes the v2 Phase A plan
(2026-05-20-crt-phase-a-continuous-controller.md) which is now an
artifact — its load-bearing commits (A0.5 forward_step, A1
decision_stride deletion) are preserved; its A2 scalar conviction-EMA
work is REPLACED by the multi-horizon §4.4 formula here.

Six tasks (all under one Gate CRT.1, no inter-task gates):
  C1.1 open_trade_state 24→64 byte atomic refactor (spec §7)
  C1.2 multi-horizon ISV-weighted conviction (spec §4.4) replacing
       scalar EMA approach
  C1.3 no-trade band in seed_inflight (delta_floor config field)
  C1.4 composite exit_signal safety circuit-breaker (spec §4.3)
  C1.5 local compile + tests
  C1.6 cluster smoke + Gate CRT.1 validation

Gate CRT.1 acceptance = v2 §9 Gate 2 tiered MUST/WIN structure intact.

What ships in this plan:
  - Continuous evaluation (every event, via existing forward_step)
  - Multi-horizon ISV-weighted conviction (one unbounded factor =
    net_edge / (var + cost²); rest bounded; per pearl_one_unbounded_signal)
  - target_lots = direction × |conviction_ema| × envelope_max (no aggregate
    rescale; the v2 A2/A2.1 bug is structurally absent)
  - No-trade band: kernel skips seed when |target − effective| < delta_floor
  - open_trade_state 64-byte expansion for per-trade trajectory tracking
  - Composite exit_signal as safety circuit-breaker (primary exit is
    emergent target→0)

What stays out of scope (CRT.2 / CRT.3):
  - Adaptive max_lots / threshold / vol target (CRT.2)
  - Self-tuning percentile gate (CRT.2)
  - LoRA + EWC++ + shadow eval (CRT.3)

Status: ready for execution.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:18:45 +02:00
jgrusewski
9ad76c4dfe spec(crt): v3 architecture reset — collapse Phase A+B into CRT.1 unified controller
Empirical trigger: Phase A as designed in v2 failed Gate 1 catastrophically
on both smoke vjmwc (commit 3d8f12deb) and lkrdf (commit fe2498769 with
amplification clamp). Both produced ~155k trades (62× baseline), 9100%
max-drawdown (175× baseline), and Sharpe -15.7. The clamp had effectively
zero impact on the outcome, confirming the bug is structural not formulaic.

Architectural finding: the v2 phase split (A: continuous control / B:
signal-driven position management) is artificial. They are the same
mechanism. A scalar EMA on max(|p-0.5|) cannot smooth direction jitter
between horizons; only the multi-horizon ISV-weighted conviction formula
(v2 §4.4, deferred to Phase B in v2) is structurally coherent.

User-validated mental model: signal vector at any moment IS a forward
prediction of the trade trajectory; optimal position = inventory implied
by current beliefs; trade actions are sparse because most events
produce only fractional adjustments to a stable optimum. Continuous
evaluation, discrete action.

v3 phase structure (replaces v2 A/B/C/D):
  CRT.1  Unified Inventory Controller (was A+B merged)
  CRT.2  Adaptive Risk Envelope (was Layer C, unchanged)
  CRT.3  Online Weight Adaptation (was Layer D, unchanged)

CRT.1 components:
  - forward_step every event (already shipped: A0.5)
  - decision_stride deleted (already shipped: A1)
  - Multi-horizon ISV-weighted conviction (§4.4 promoted from Phase B)
  - Wiener-α EMA on multi-horizon conviction (§4.2 promoted)
  - target_lots = direction × |conviction_ema| × envelope_max
  - No-trade band in seed_inflight: skip if |delta| < delta_floor (NEW)
  - open_trade_state 24→64 expansion (§7 promoted from Phase B)
  - Conviction-degradation exit emergent from target→0; composite-signal
    safety layer (§4.3) preserved as circuit-breaker

What survives from v2 commits on the branch:
  a0e81fbdf forward_step incremental SSM (A0.5)
  92f8b10ed forward_step_into eliminates GPU↔CPU round-trip
  045850e8f delete decision_stride field (A1)
  3d8f12deb buffer-level seed bit-identity test

What gets superseded in CRT.1 implementation:
  1d889d2de A2 scalar conviction-EMA with aggregate rescale — replaced
            by multi-horizon §4.4 formula
  fe2498769 A2.1 clamp on broken rescale — same reason

The three conviction-EMA device slots (conviction_ema_d et al.) STAY
in LobSimCuda — the EMA mechanism is reused on the multi-horizon
conviction scalar. The `final_size *= scale` rescale step is deleted.

Gate restructure:
  v2 Gate 1 (Layer A standalone) — REMOVED
  v2 Gate 2 (Layer B) — PROMOTED as Gate CRT.1
  v2 Gate 3/4 — unchanged as CRT.2/CRT.3

Status: Design v3 — awaiting plan rewrite before implementation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:15:28 +02:00
jgrusewski
2e87ed0daf memo(crt-a): forward_only cost investigation — Case 2 (stateless K-window)
forward_only requires the full K=seq_len window on every call and resets
Mamba2 h_s2 to zero each invocation — no cross-call state carry. Additionally,
the call is inside the stride=200 gate in harness.rs (spec §3.2 claim "already
every event" is incorrect as of HEAD). Moving to stride=1 without a forward_step
implementation would be a ~200x GPU cost increase. A0.5 must implement
forward_step with persistent h_s2, a dedicated K=1 CUDA graph, and session-reset
hook. Memo documents exact file paths, line numbers, required struct/method
changes, and open questions for the A0.5 implementer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:43:52 +02:00
jgrusewski
b508c38529 plan(crt-a): remove fallbacks — greenfields, resolve properly
Per user direction: no fallbacks, greenfields, kernel updates acceptable.

Changes:
  1. Task A0.5 ADDED — pre-planned task that fires if A0 investigation
     finds forward_only is stateless K-window (Case 2) or has periodic
     reset (Case 3). Refactors PerceptionTrainer to maintain persistent
     SSM state and expose forward_step(snapshot, b) that advances by 1
     event. Bit-identical to forward_only of equivalent window per a
     new golden test in incremental_forward.rs.

     This is NOT a fallback — it's a pre-planned task whose execution
     is determined by actual investigation outcome. Case 1 → A0.5 is
     a no-op. Case 2 or 3 → A0.5 fires in full. Either way the plan
     proceeds without user-approval pause.

  2. Task A2 reframed — Wiener-α conviction-EMA is a "load-bearing
     component of continuous control," not a "minimal Phase B subset."
     Without smoothing, event-rate trading is structurally incoherent.

  3. Task A2 test fallback REMOVED — instead of "if helpers don't
     exist, omit the unit test," the plan now says "add the helpers
     properly to the public API." Step 1 audits the LobSimCuda public
     API and adds missing accessors. Greenfields — accessors stay on
     the API permanently if testing needs them.

  4. Task A5 (conditional hyperactivity mitigation) DELETED. A2 is
     designed correctly the first time with Wiener-α floor at 0.4. If
     A4 cluster smoke shows hyperactivity, that's an A2 bug to fix
     properly, not a tuning knob to nudge.

  5. Scope contract updated — Phase A vs Phase B split is by code-path
     responsibility (continuous control infrastructure vs multi-horizon
     signal-driven policy), NOT by "shipping less to be safe."

  6. Notes for the Implementer — explicit "No fallbacks" section
     replaces the implicit-fallback language. STOP-and-notify-user for
     Case 2 deleted (A0.5 handles it inline).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:37:24 +02:00
jgrusewski
235961987d plan(crt-a): Phase A continuous controller implementation plan
Per docs/superpowers/specs/2026-05-20-continuous-reasoning-trader-design.md
(v2, commit 8ba8755b4). One plan per phase per writing-plans guidance —
Phase B/C/D plans written after each prior gate closes.

Phase A scope:
  A0 - Investigate forward_only cost model (read-only research,
       writes memo to docs/superpowers/memos/). STOP condition if
       trunk forward is stateless K-window per call (Case 2) —
       requires user approval to expand scope.
  A1 - Atomic delete of decision_stride (greenfields, no compat).
       Removes from SweepBase, ResolvedSimVariant, BatchedSimConfig,
       BacktestHarness, all YAMLs.
  A2 - Minimal Wiener-α conviction-EMA smoothing in decision_policy_*
       kernels. Three new device slots: conviction_ema_d,
       conviction_diff_var_ema_d, conviction_sample_var_ema_d. Floor
       at 0.4 per pearl_wiener_alpha_floor_for_nonstationary.
       First-observation bootstrap. Direction stays from raw alpha;
       magnitude/sizing uses smoothed value.
  A3 - Local compile + tests.
  A4 - Cluster smoke + Gate 1 validation against spec §3.6 acceptance.
       Memory entry on closure (green/red/yellow).
  A5 - Conditional hyperactivity mitigation (raise floor 0.4→0.6 OR
       add target-delta hysteresis). Fires only if Gate 1 reveals
       trade-count balloon.

Out of scope (deferred): full §4.4 multi-horizon conviction formula,
§4.3 conviction-degradation exit, §5 envelope, §6 LoRA adapter, §7
open_trade_state expansion — all Phase B/C/D.

Pearl conformance:
  - feedback_no_partial_refactor (atomic delete)
  - feedback_no_legacy_aliases (no compat shim)
  - feedback_push_before_deploy
  - pearl_wiener_optimal_adaptive_alpha
  - pearl_wiener_alpha_floor_for_nonstationary
  - pearl_first_observation_bootstrap
  - feedback_stop_on_anomaly (Gate 1 RED → diagnose, don't advance)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:33:16 +02:00
jgrusewski
8ba8755b48 spec(crt): v2 amendments from critical review — 12 issues + greenfields
Self-critical review of v1 (commit 0f3484325) found 12 issues. All
fixed inline. Spec marked Status: Design v2 with explicit changelog.

LOAD-BEARING FIXES
  1. §4.4 conviction cold-start: removed backwards "uniform fallback"
     branch that maintained trading authority when net_edge=0 across
     all horizons (exactly when model has no edge). Replaced with ε
     floor on net_edge_h. Single formula, smooth bootstrap, no regime
     switch.
  3. §4.3 exit logic: 5 OR conditions → 1 composite exit_signal scalar
     (max of degradation, disagreement, pnl_decay terms). SL/trail and
     8h circuit-breaker stay orthogonal as safety, not exit policy.
     Attribution per term recorded in §7 state for observability.
  6. §9 Gate 2: PF > 1.0 (2.5× improvement, unrealistic) → tiered
     MUST (no-regression) + WIN (real lift, four candidate criteria) +
     explicit STOP condition if MUST passes without WIN.
  7. §9.1.1: alpha-realization metric defined explicitly as
     realized_pnl / max(unrealized during signal-validity window).
     Was hand-waved in v1; now formulated.

TRACTABLE INLINE FIXES
  2. §7 open_trade_state: 128 → 64 bytes. Diagnostic-only fields
     (scale_up/down counts, max/min target reached) moved to a
     separate audit buffer (single source of truth keeps state lean).
  4. §5.1 envelope: multiplicative formula → additive bounded
     contributions. tanh(sharpe), min(dd/cap), clamp(vol). No single
     factor can crash envelope to zero. Floor (envelope_floor lots)
     and hard-cap (envelope_hard_cap) remain.
  5. §5.2 threshold: hand-waved "self-tune toward PF" → explicit
     3-arm bandit (lower, current, higher percentile) every K_eval
     closed trades, Wiener-α EMA target with floor, bounded
     [0.5, 0.95].
  8. §3.4 + §3.6: Layer A wall-time ≤ 5× → ≤ 2× (controller is
     light, 5× would indicate structural bug, not config tuning).
  9. §4.2: explicit Wiener-α formula for conviction EMA with floor
     at 0.4 per pearl_wiener_alpha_floor_for_nonstationary.
 10. §6.2.1: shadow eval defined explicitly with backtest-mode (last
     15% of fold) and live-mode (parallel-prediction-only) variants.
     Promotion criteria spelled out (PF, Sharpe, tail loss).
 11. §6.2: Layer D loss explicit (primary = value regression on
     realized PnL conditional on state; secondary = EWC++ regularizer
     toward base). Was three losses with no specified combination.
 12. §10.5: adapter regime over-fit risk added with sample-count
     down-weighting, cross-regime shadow eval, periodic adapter reset
     as hard backstop.

GREENFIELDS (per user direction)
  - §3.3: decision_stride field DELETED from YAML + Rust (not
    deprecated). No backwards-compat shim. Per
    feedback_no_legacy_aliases.
  - §7.1: open_trade_state 24→64 byte migration is atomic, no old
    layout shim.
  - §8: boundary matrix decision_stride row marked REMOVED, not
    DEPRECATED.

§13 pearl conformance: per-section pearl application (not bulk
citation). Added pearl_audit_unboundedness_for_implicit_asymmetry,
pearl_no_deferrals_for_complementary_fixes acknowledgement (layers
are sequenced amplifications, not parallel fixes), and the new
pearl_stop_checks_run_at_deadline_cadence from S2.

Status: Design v2 — awaiting user review before writing-plans.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:24:03 +02:00
jgrusewski
0f34843253 spec: continuous-reasoning trader architecture (4-layer rebuild)
Integrated spec for the continuous-reasoning trader rework. Replaces
the rule-based discrete policy with a 4-layer signal-driven architecture:

  Layer A: continuous control loop (every event, not every stride)
  Layer B: signal-driven position management (multi-horizon fusion,
           continuous sizing, conviction-degradation exit, open_trade_state
           expanded 24→128 bytes)
  Layer C: adaptive risk envelope (ISV-derived max_lots, threshold,
           target_annual_vol)
  Layer D: online weight adaptation (LoRA + EWC++, offline-batch
           per-session, shadow-eval gated)

Phased gates: A unlocks B; B is where alpha lives; C amplifies B;
D amplifies whatever's working. Each gate has explicit pass criteria.

Conviction definition: ISV-weighted multi-horizon agreement.
weight_h = max(pnl_ema_win - pnl_ema_loss, 0) / (var + cost^2).
Net edge x SNR per horizon, scale-normalised, cold-start uniform fallback.

Pearl conformance: 13 existing pearls referenced and respected
(ISV-driven anchors, first-observation bootstrap, Wiener-alpha floor,
blend-with-floor, z-score normalisation, one-unbounded multiplicand,
trade-level vol bootstrap, deadline cadence, single-source-of-truth,
atomic refactor, adaptive-not-tuned).

Hardcoded boundary preserved for hardware/exchange realities (latency,
cost, annualisation, instrument bounds). Everything else adaptive.

Status: design — awaiting user review before implementation plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:11:46 +02:00
jgrusewski
bf619a2e7b feat(ml-backtesting): max-hold + exit_px defensive + spec criteria revision
Three follow-ups from cluster smoke gp74n (trade_vol pearl validation):

1. Max-hold force-close: max_hold_ns added as per-backtest config
   (default 0 = disabled). Fires force-flat (3, 0) when current_ts -
   entry_ts >= max_hold_ns, BEFORE SL/trail check. Tested via
   max_hold_forces_close. Sweep YAML sets 60s cap to bound the long
   tail observed in gp74n (263985s pathological hold).

2. exit_px defensive sanity check: 500/1024 gp74n trades reported
   exit_px = ±i32::MAX/100 (float→int saturation sentinel from likely
   NaN segment_realized). Defensive fix in pnl_track_step: if exit_px
   is non-finite or diverges from entry_px by >10%, fall back to
   entry_px with zero realised_pnl. Root cause to be traced separately.

3. Spec §9.2 criteria revision: mean_hold<30s replaced with p95<600s
   + max<=max_hold_ns. The 30s threshold reflected the pre-pearl
   sub-cost churning bug, not a real feature criterion. p95 catches
   long-tail pathology while letting alpha-driven exit timing breathe.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 08:10:00 +02:00
jgrusewski
9b29f9fd0a feat(ml-backtesting): trade-vol floor replaces 2×cost literal in stop_check_isv
Replaces the Task 12 `2.0f * cost` floor (hardcoded multiplier) with
trade_vol = sqrt(realised_return_var) bootstrapped from cost². Per
pearl_trade_level_vol_for_stop_distance.md: microstructure ATR is the
wrong time scale for trade-level stop decisions; per-horizon
realised_return_var is the right one, with cost² as a structural cold-
start sentinel.

cost now appears exactly once — inside the sqrt as a bootstrap sentinel,
never as a distance multiplier. The 2.0f literal is eliminated;
controller is fully ISV-driven.

var_avg accumulates realised_return_var in the same single-pass horizon
loop as ema_loss/ema_win. Cold-start (var_avg=0): trade_vol = cost.
Post-bootstrap: sqrt(var_avg) dominates.

Test retargeted: cost_floor_prevents_sub_cost_stops →
trade_vol_floor_prevents_sub_cost_stops, with boundaries straddling
trade_vol=cost=0.125 instead of the prior 2*cost=0.25 (no-fire Δ=0.08,
fire Δ=0.20).

Spec §5, §10, §11, §12 amended.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 01:45:37 +02:00
jgrusewski
da6e887174 feat(ml-backtesting): cost-floor in stop_check_isv prevents sub-cost churning
Cluster smoke w7b4p showed 44864 closed trades in 1M events at 200ms
latency — physically impossible without sub-cost churning. Root cause:
sl_distance = max(pnl_ema_loss, atr) ≈ 0.05 at cold-start, but round-trip
cost = 2 × 0.125 = 0.25. Every stop-out guaranteed loss > 5× distance;
EMA converges sub-cost.

Amendment: triple-max sl_distance = max(pnl_ema_loss, atr, 2*cost);
trail_distance = max(pnl_ema_win, atr, 2*cost). cost is an ISV-discipline
strategy anchor (already per-backtest from P4 — no new state slot, no
tuned constants). Added cost_per_lot_per_side_per_b param to both decision
kernel signatures and threaded cost_per_lot_per_side_d through both launch
sites in step_decision_with_latency.

Test: cost_floor_prevents_sub_cost_stops validates unrealized in (ATR, 0.25)
does NOT fire SL; unrealized > 0.25 DOES fire. Spec amended (§10, §12).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 01:27:28 +02:00
jgrusewski
4101796ad9 refactor(ml-backtesting): delete StopRules + use_cold_start_stopgap atomically
- StopRules struct + sl_tp_rules field + all literals deleted; the ISV
  stop controller (Tasks 2-9) replaces this dead data path.
- use_cold_start_stopgap propagation deleted across harness,
  batched_config, fxt-backtest, sweep_smoke.yaml, and 5 test files.
- Q1 stopgap branch in harness.rs deleted; replaced with the original
  simple strategy-upload loop.
- decision_floor_coldstart test retargeted: cold_start_persistent_
  bullish_with_default_stops_never_closes -> ..._now_closes, asserts
  trades > 0 AND |pos| <= max_lots (99 trades, pos=1 on local GPU).
- CBSW spec + plan prefixed with SUPERSEDED headers.

Per feedback_single_source_of_truth_no_duplicates +
feedback_no_partial_refactor: contract change migrates every consumer
in one commit. No legacy wrappers; no version suffixes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 00:40:14 +02:00
jgrusewski
091707cae7 plan(ml-backtesting): ISV-driven stop controller implementation plan
11 tasks, each one commit, TDD-disciplined (test → fail → impl →
pass → commit). Covers all 11 sections of the spec at
docs/superpowers/specs/2026-05-19-isv-driven-stop-controller-design.md:

- Tasks 1-2: state slots + ATR EMA in book_update_apply_snapshot
- Task 3: stop_check_isv shared __device__ helper skeleton
- Tasks 4-6: SL trigger, trail-TP + HWM ratchet, multi-horizon avg
- Task 7: bytecode VM parity (wire helper into decision_policy_program)
- Task 8: seed_inflight_limits_batched target-delta + in-flight summation
- Task 9: pnl_track_step trail_hwm reset on close
- Task 10: atomic deletion of StopRules + use_cold_start_stopgap +
          integration-test retarget + CBSW SUPERSEDED markers
- Task 11: cluster smoke validation via argo-lob-sweep.sh

All 10 §9.1 unit tests have explicit failing-test scaffolds before
their implementations, and the retargeted integration test
(cold_start_persistent_bullish_now_closes) flips the assertion to
prove the fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:32:38 +02:00
jgrusewski
1ecce0d826 spec(ml-backtesting): critical-review pass on ISV stop controller — 9 fixes
Issues caught in self-review and fixed:

1. Encoding ambiguity: stop-fire writing (2, 0) would have silently
   collapsed weak-alpha no-op semantics with force-flat. Introduced
   distinct side=3 = force-flat; preserved side=2 = no-op for entry
   path. Updated §3 + §5 + §7 truth table.

2. trail_hwm reset on close was implied in §4 but missing from §8's
   touched-files list. Added pnl_track.cu modification (§7.1) +
   added to §8 Added list.

3. __device__ helper enforcement: §3 now mandates stop_check_isv()
   as a shared __device__ function called from both decision kernels,
   not duplicated code.

4. Kernel arg additions enumerated explicitly in new §4.1 table —
   every kernel-launch site gets named, no "thread through every kernel"
   hand-wave.

5. seed_inflight_limits_batched (resting_orders.cu:439–475) named
   explicitly in §1 + §7 — the actual kernel that needs the position-
   target-semantics fix.

6. In-flight order summation: naive delta = target_signed - pos was
   strictly worse than the original additive bug under non-zero
   latency (would produce pos = pre + K·delta after fills). Fixed
   §7 algorithm to compute effective_position by scanning all
   active∈{1, 2} slots and summing their signed sizes. Added
   position_target_not_additive_with_latency test.

7. ATR α=0.4 honest justification in §10: not strictly derived from
   pearl_wiener_alpha_floor_for_nonstationary (which is about co-
   adapting control loops, not passive observation); chosen as a
   pragmatic project-wide constant matching isv_kelly_update_on_close.

8. CUDA Graph host-branch-free affirmation added to §3 — explicit
   compatibility with P5 graph capture.

9. Cold-start symmetry caveat (§5): at n_trades_seen=0 both EMAs are
   0 so sl_distance == trail_distance == atr — asymmetry only
   emerges post-bootstrap. Acknowledged honestly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:20:04 +02:00
jgrusewski
11d1279990 spec(ml-backtesting): ISV-driven stop controller — supersedes falsified CBSW
Replaces StopRules::default()-all-zeros (the actual cause of the cluster
smoke's n_trades=0, falsifying the CBSW dilution diagnosis) with an
ISV-driven SL + trail-stop controller folded into the existing decision
kernel(s). Per-backtest ATR EMA on mid-price + per-horizon pnl_ema_*
drive distances under max(real, floor) per
pearl_blend_formulas_must_have_permanent_floor. No new kernel; single
source of truth in step_decision*. Folds in the position-target
semantics fix (200-event local repro showed position_lots=199 from
additive-vs-target order semantics) — same commit.

Removes: StopRules, sl_tp_rules, Q1 stopgap field/branch,
use_cold_start_stopgap propagation. Marks CBSW spec + plan SUPERSEDED.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:06:37 +02:00
jgrusewski
2130bee006 plan(ml-backtesting): CBSW cold-start aggregator implementation plan
4-task atomic ladder (Q1-Q4) implementing spec 566e8bcb0. Each task
maps to one commit per feedback_no_partial_refactor:

  Q1: Cold-start stopgap (bytecode max-confidence policy upload)
  Q2: CBSW kernel aggregator + Tier 1 revert (atomic)
  Q3: Memory pearl pearl_conviction_bootstrap_for_kelly_aggregation
  Q4: Parallelism spec §3.4 cross-reference

Kernel ABI unchanged across all 4 commits — Q2 modifies only
decision_policy_default's body (decision_policy_program left as a
pluggable bytecode-VM experiment surface). Q2 atomically deletes
the Q1 stopgap field/CLI/YAML/harness branch in the same commit
that lands the kernel fix (feedback_no_legacy_aliases compliance:
grep returns zero hits for use_cold_start_stopgap post-Q2).

Validation gates per spec §9:
  - Q1: cluster smoke n_trades > 100, total_pnl != 0 (diagnosis
    confirmation). If n_trades = 0 still, STOP — downstream bug.
  - Q2: pre-existing 11 CUDA tests still pass; 7 new cbsw_*
    regression tests pass; cluster smoke n_trades > 100; ev/s
    rate ratio Q2/Q1 ≥ 0.95.

Self-review confirms all 11 spec sections covered, no placeholders,
type/signature consistency across tasks.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:53:28 +02:00
jgrusewski
566e8bcb0a spec(ml-backtesting): CBSW review pass — 11 fixes (perf + correctness)
Critical review surfaced 11 actionable issues in the v1 spec; 10 fixed
inline (#11 — legacy-comparison test — dropped per user decision since
empirical legacy behavior is already known: n_trades=0).

Performance:
1. expf → piecewise-linear ramp (~5× cheaper on GPU, no transcendental
   in the hot path). Operationally equivalent: monotonic, saturating,
   midpoint at K. Side-benefit: pure max-confidence at cold-start
   (sq=0 instead of sigmoid's 11.9% leakage).
2. Single fused per-horizon pass replaces the two-loop sketch.
3. Tier 2 scope narrowed to decision_policy_default ONLY. The bytecode
   VM (decision_policy_program) stays unchanged — runs only for custom
   strategy experiments, never in production policy. Halves Tier 2's
   surface area + test cost.
4. __device__ helpers cbsw_signal_quality + cbsw_weight introduced for
   single source of truth.

Correctness bugs (silently present in v1 sketch, would have shipped):
5. strong_h and sq_min_active initializers added (were referenced
   before init in the per-horizon loop).
6. Attribution mask at cold-start was setting all 5 bits because every
   w[h] >= floor > 1e-9; trades would pollute ALL horizons'
   recent_sharpe. Fix: binary split — at sq_min_active < 0.5 attribute
   only to strong_h; at mature, attribute per weights > floor + epsilon.
7. sq_min was "min over h", which permanently locked the aggregator
   into cold-start mode if any horizon never gets attributed (e.g.,
   h6000-only-trading regime). Fix: sq_min_active = min over h with
   n_trades_seen > 0; cold horizons don't gate maturity.
8. Opposing-horizons case now correctly fires on the strongest single
   horizon at cold-start (piecewise-linear sq=0 → pure max-conf), with
   explicit design-choice note explaining why this conservatism trade-
   off favors firing.

Spec hygiene:
9. Rate validation committed to a measurement gate (Q2 ev/s ≥ 95% of
   Q1 ev/s) instead of back-of-envelope estimate.
10. Kernel ABI explicitly stated as unchanged → feedback_no_partial_
    refactor compliance is trivial at the kernel boundary.
12. Tier 1's use_cold_start_stopgap field is DROPPED in Q2 atomically
    (not orphaned), and DoD checklist includes a grep-zero gate for
    feedback_no_legacy_aliases compliance.

Risks updated: removed the sigmoid-narrowing risk (irrelevant now);
added register-pressure risk with the rate-gate mitigation; added
explicit "cold-start may lose on noisy trades" risk with empirical
escalation path (bump kelly_floor 0.20 → 0.40 if Q2 smoke shows large
negative PnL).

Math walk-throughs rewritten for piecewise-linear (different numbers
at cold-start): cold = pure max-conf, mature = pure weighted-sharpe,
clean separation at sq_min_active threshold.

Awaiting review of the revised spec before writing-plans dispatch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:47:13 +02:00
jgrusewski
1271d03931 spec(ml-backtesting): CBSW cold-start aggregator design
The post-trunk-grows threshold-tuning smoke (81decf40f) produced
n_trades=0 despite the model having a HEALTHY max-conviction
distribution (74.6% of decisions ≥ 0.30, 26.7% ≥ 0.70, full spread
across [0,1]). Diagnosis: the linear-weighted-mean aggregator in
decision_policy_default is structurally dilution-bound at cold-start
— single-horizon strong signals get washed out when uniform-floor
weights produce mean-over-horizons aggregation.

Solution: Conviction-Bootstrapped Sharpe Weighting (CBSW). Hybrid
max-confidence × weighted-sharpe with a per-horizon sigmoid transition
keyed on n_trades_seen vs MIN_TRADES_FOR_VAR_CAP. Cold-start: sig_mag
(decision-time conviction) drives weights AND max-confidence aggregator
fires single-horizon trades. Mature: recent_sharpe (historical) drives
weights AND linear-mean aggregator emphasizes strong-Sharpe horizons.
Permanent floor preserved per pearl_blend_formulas_must_have_permanent_floor.

Mirrors DQN bootstrap pattern (pearl_thompson_for_distributional_action_
selection): when historical estimates are uncertain, use available
signal as the bootstrap. Sig_mag is the ISV signal at decision time;
recent_sharpe is the ISV signal at trade-close time. Transition
self-terminates based on data accumulation, not time constants.

3-tier delivery (one spec, atomic commits):
  Q1: Bytecode VM stopgap — upload max-confidence 7-instruction
      program per backtest. Validates diagnosis; zero kernel work.
  Q2: Kernel CBSW — replace weight + aggregator in both decision
      kernels. 5 new regression tests covering cold/mature/transition.
  Q3: New memory pearl pearl_conviction_bootstrap_for_kelly_aggregation
      capturing the lesson.
  Q4: Cross-reference from parallelism spec (deployability sweep
      depends on CBSW being live to produce meaningful verdict).

The parallelism work (P1-P6) is fully working — confirmed by the
threshold-tuning smoke completing end-to-end (Succeeded status, 500k
decisions, artifacts written, aggregator parquet emitted). What's
blocked is the deployability VERDICT, because the dilution bug means
all variants would show n_trades=0 regardless of cost/latency/threshold.
CBSW unblocks the verdict.

Awaiting review before transitioning to writing-plans for Q1-Q4
implementation plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:38:55 +02:00
jgrusewski
2b18835437 plan(ml-backtesting): deployability-sweep parallelism implementation plan
7-task atomic ladder (P1-P7) implementing spec d646c1eb3. Each task
maps to one commit per feedback_no_partial_refactor:

  P1: Per-backtest sim parameter arrays (BatchedSimConfig + kernel ABI)
  P2: seed_inflight_limits_batched kernel (replaces host roundtrip)
  P3: detect_close_transitions_batched kernel (replaces close-detect loop)
  P4: Threshold gate + per-fill cost integration
  P5: CUDA Graph capture of forward_only (1.3× forward target)
  P6: Batched-cell sweep schema + 140-variant runner
  P7: 3-pod scale + final verdict

Measurement gates per §9 of the spec (P2 ≤90s, P5 ≤60s, P6 ≤30min,
P7 ≤60min target / ≤120min firm). Stride=8 fallback activated at P6
if measurement misses by >20%.

Self-review confirms all 13 spec sections covered, no placeholders,
type consistency across tasks.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:39:17 +02:00
jgrusewski
d646c1eb3c spec(ml-backtesting): apply 9 critical-review fixes to parallelism spec
Critical review surfaced 9 issues; all fixed inline:

1. §1 — Reframed "140× amortization" as "amortization on forward; sim
   runs parallel". True win is on the ~2ms forward shared across 140
   cells, not on sim work which scales linearly with n_backtests.
2. §2 — Made the 1h target vs firm bound explicit (≤1h target, ≤2h
   firm). Acknowledges Graph capture realistic speedup is 1.2-1.5×,
   not 2×.
3. §5 — Dropped atomicAdd. Plain `+=` under the single-writer-per-block
   convention (existing pattern across sim kernels). No race.
4. §4 — Documented max-over-horizons threshold rationale (vs per-
   horizon or aggregate-conviction). Flagged per-horizon as a follow-up
   tweak if dilution pathway matters in the verdict.
5. §7 P5 + §10 risk — Captured-vs-uncaptured tolerance is 1e-5 relative,
   NOT strict bit-identity. CUDA Graph capture can reorder reductions
   harmlessly by 1 ULP; strict bit-identity would be a false-positive.
6. §8 — Made explicit that parallel_sim_equivalence + independence
   tests are BOTH required. Equivalence alone is necessary but not
   sufficient (a shadow-backtest[0] bug still passes equivalence).
7. §3.3 — Specified output schema: `cell_W{n}/sim_<variant_name>/`
   with summary.json carrying a resolved `sim_config` block (verdict
   emitter reads that, not the directory name).
8. §7 P4 — Enumerated apply_fill_to_pos call sites + added grep-verify
   step before commit, so no fill path silently loses cost.
9. §9 — Tightened rate-validation gates with hard targets (P2 ≤90s,
   P5 ≤60s) instead of generous minute envelopes. Added §9.1 stride=8
   fallback as explicit Plan-B if Graph capture under-delivers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:27:38 +02:00
jgrusewski
bd35bdb6a3 spec(ml-backtesting): deployability-sweep parallelism + rate design
Brainstormed live with claude-opus-4-7. Targets ≤1h wall-clock per
4-quarter sweep on 1-3 L40S pods (vs ~750 GPU-hours naive). Three
multiplicative levers: per-backtest sim parameter matrix (~140×),
CUDA Graph capture (~2×), pod-level parallelism (~3×). Verified by
code-read during scoping:
  - forward_only has no graph capture (X11 plan said so, X11 commit
    didn't ship it)
  - two host-roundtrip loops in sim.rs need GPU-ization for batching
    to pay off (dispatch_latent_market_orders + close-detection)
  - cost system is a literal-zero placeholder in pnl_track.cu:92

7-commit atomic ladder (P1-P7), each gated by tests + a measured rate
target. bf16 explicitly deferred to follow-up.

Awaiting review before transitioning to writing-plans for the
implementation plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:08:24 +02:00
jgrusewski
d45dde8458 plan(ml-alpha): trunk-grows refactor + deployability validation roadmap
20-commit atomic ladder (X0–X19) + Phase 1→2 gate + Phase 2 runtime
runbook. Implements spec da1dd92bf:

  X0:    perception_forward_golden fixture (bit-equivalence gate)
  X1:    CfcTrunk v2 weight skeleton (no callers)
  X2–X9: incremental weight-group migrations (VSN, Mamba2 ×2, LN ×2,
         attn-pool, CfC, GRN heads), each gated by golden fixture
  X10:   hoist forward kernels into CfcTrunk methods
  X11:   capture_graph_a covers full v2 forward + captured-vs-uncaptured
         equivalence test
  X12:   CheckpointV2 envelope + save/load (V1 hard-rejected)
  X13:   PerceptionTrainer.save_checkpoint delegate
  X14:   alpha_train saves best_h6000 checkpoint
  X15:   verify ml-backtesting accepts CheckpointV2 (no code change)
  X16:   max_drawdown_pct with \$35k base
  X17:   emit_deployability_verdict + tiered logic + 6 unit tests
  X18:   GPU smoke test against real trained checkpoint
  X19:   three sweep YAMLs (smoke, threshold-tuning, deployability)
  Gate:  fold-0 smoke must reproduce recorded 3-fold A/B numbers
         within ±0.010 absolute before Phase 2 begins
  P.1–6: Argo runtime (training → smoke → threshold → sweep → verdict)

Self-review confirms 1:1 spec coverage. Three soft adaptation points
(HEAD_MID constant, Mamba2Block accessors, BacktestHarnessConfig field
names) resolve at code-read time. One placeholder (todo!() in X11
explanatory text) is called out in self-review for replacement when
that commit lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 01:04:30 +02:00
jgrusewski
da1dd92bf8 spec(ml-alpha): trunk-grows refactor + deployability validation (supersedes prior)
Supersedes the 2026-05-19 deployability spec (commit 07d5de504). The
prior spec assumed CfcTrunk::save_checkpoint was the producer-side
wiring point — discovered at execution time that alpha_train trains via
PerceptionTrainer (full v2: VSN + Mamba2 ×2 + LN ×2 + attn-pool + CfC +
heads), not the simpler CfcTrunk. The existing LOB backtester loads
CheckpointV1 envelopes that only know about CfC weights, so there is no
producer for a checkpoint containing the full v2 model.

New scope: one bigger spec covering refactor + deployability end-to-end.

Phase 1 (X0–X19, code commits): grow CfcTrunk to own the full v2
inference graph; restructure PerceptionTrainer to wrap a trunk + add
training-only state (grads, AdamW). Discipline: bit-equivalence golden
fixture (X0) gates every refactor commit (X1–X11). CheckpointV2
envelope (X12) replaces V1. Verdict emitter (X17) reuses the tiered
classification (Pass-robust / Pass-nominal / Fail-inconclusive / Fail /
Fail-degenerate) from the superseded spec.

Phase 2 (Argo runtime): production training → smoke gate → threshold
pre-registration → 560-cell deployability sweep → verdict + memory
update.

Hard gate before Phase 2: post-refactor fold-0 smoke must reproduce
recorded 3-fold A/B numbers (best_mean_auc 0.7529, best_h6000 0.7639,
both within ±0.010 absolute) from project_ml_alpha_v2_ab_verdict
memory. Prior spec marked SUPERSEDED in its header, kept in history as
audit trail.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:54:45 +02:00
jgrusewski
4938ac2ec5 plan(ml-alpha): v2 deployability validation — atomic-commit roadmap
Five-commit implementation plan + two-step runtime runbook for the
deployability spec committed at 07d5de504. Bite-sized TDD tasks:

  C1: wire save_checkpoint(best_h6000) into alpha_train.rs (~10 LOC)
  C2: max_drawdown_pct field on Summary, $35k starting-capital base
  C3: emit_deployability_verdict + tiered logic + 6 unit tests
  C4: GPU integration smoke test (#[ignore], env-var-gated)
  C5: three sweep YAMLs (smoke, threshold-tuning, deployability)
  C6: runtime — Argo prod training → smoke → threshold pre-reg → full sweep
  C7: commit verdict, update memory

Self-review confirms 1:1 spec section ↔ task coverage. Two soft
adaptation points (AlphaTrainSummary struct name, BacktestHarnessConfig
defaults) marked as code-read-and-adapt; no hard TBDs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:40:15 +02:00
jgrusewski
07d5de5048 spec(ml-alpha): v2 deployability — stress anchor + max-dd gate + diagnostics
User revisions to design spec from this session:

1. §2.1 — split anchor into realistic (200 ms, 1 tick) and stress (400 ms,
   1.5 tick). Realistic remains the hard verdict gate; stress grades the Pass
   into Pass-robust vs Pass-nominal.

2. §2.2 — expand metrics from Sharpe-only to four: annualized daily Sharpe
   and max-drawdown are hard gates (median across windows > 1.0 and < 20%
   respectively); Sortino and profit factor are diagnostics. Per-window
   summary.json schema extended.

3. §2.6 — verdict emitter rewrites to two-anchor logic, tiered output:
   Pass-robust / Pass-nominal / Fail-inconclusive / Fail / Fail-degenerate.

4. §3.3 — added max-dd computation and zero-trade-window failure modes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:32:30 +02:00
jgrusewski
0809390cd5 spec(ml-alpha): v2 deployability validation — falsifiable LOB-backtest verdict
Closes the wiring gap between the existing real-LOB backtest system (C1–C19 on
this branch) and the v2 ml-alpha model. alpha_train.rs currently never calls
save_checkpoint, so the LOB harness/sweep/aggregate machinery has never been
pointed at a real trained model.

Design defines a single-pass falsifiable deployability gate: produce a
production checkpoint (cv-n-folds=1, cv-train-window=4 → train on 2024
quarters, val on 2025-Q1, hold out 2025-Q2..2026-Q1), pre-register one
threshold on the W0 val window, then evaluate median Sharpe across 4
held-out walk-forward quarters at the realistic Scaleway→IBKR anchor (200ms
RTT, 1-tick all-in cost). Pass iff median > 1.0; inconclusive in [0.8, 1.0]
counts as fail; smoke gate halts the full sweep on any wiring failure.

Approved through brainstorming. Awaiting user spec-review before plan
handoff.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 00:26:48 +02:00
jgrusewski
6b7920474d spec(ml-alpha): mark AUC-regret controller SUPERSEDED — empirically falsified
The motivating "50% saturation hit-rate" observation came from gm67g
fold 0 (Option-2 config, commit 004b662c8 — itself a -0.003 mean_auc
regression vs ISV-σ at 410ab6b0e). Re-running the same diagnostic on
the actual production baseline (ISV-σ 3 folds: rxm5t/r57lx/x24d6,
logs retrieved from MinIO argo-logs bucket) on 215 horizon-epoch
observations:

  saturated λ→AUC up:     8/13 = 61.5%   median Δauc = +0.0025
  non-saturated→AUC up:  96/202 = 47.5%   median Δauc = -0.0012
  difference:            +14pp in favor of the controller working

The BCE-z-score controller is empirically correlated with the
optimization target. No evidence it's misaligned with AUC. Spec
premise falsified.

Spec retained in tree as historical record. The diagnostic
methodology itself (saturation→Δauc analysis on archived MinIO logs)
is the durable artifact and is documented in the supersede block.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 23:24:01 +02:00
jgrusewski
1fc100ae74 spec(ml-alpha): AUC-regret controller — replace BCE-z-score signal with per-horizon-regret
The current λ controller boosts horizons by BCE-EMA z-score, which conflates
three distinct causes of high BCE — only one of which (under-trained
horizon) benefits from boosting. The other two (intrinsically harder
horizon, calibration drift) are unaffected by gradient-magnitude lifts.

Empirical motivation (gm67g fold-0, this branch's 3-fold run):
when λ_h6000 saturated at 2.0, h6000's next-epoch AUC went UP 2/4
times and DOWN 2/4 times. 50% hit rate ⇒ the BCE saturation signal
is misaligned with the optimization objective.

This spec replaces BCE-z-score with AUC-regret:

  best_auc[h]     = running max of per-horizon validation AUC
  regret[h]       = max(0, best_auc[h] - current_auc[h])
  regret_max_ema  = EMA of max_h regret[h]
  λ[h]            = clamp(1.0, 2.0, 1 + regret[h] / regret_max_ema)

Properties:
  - Aligned with the objective (AUC, not BCE)
  - Naturally bounded (regret ∈ [0, 1])
  - "At personal best" → λ=1.0 (no wasted boost)
  - Auto-saturation by design (max-regret horizon → ceiling)
  - Cold-start clean (e0: best=current, regret=0, uniform λ)
  - Zero hardcoded magic beyond bootstrap epsilons

Implementation surface ~250 LOC:
  - Split horizon_lambda kernel: horizon_loss_ema (per-step) +
    horizon_lambda (per-epoch, AUC-regret math)
  - Trainer state: drop z_max_ema, add best_auc + regret_max_ema
  - Per-epoch entry point: trainer.update_lambda_from_auc()
  - Extend isv snapshot log line with best_auc_h* + regret_h*

Test plan:
  - Local 9/9 perception_overfit
  - New synthetic-AUC unit test (controller correctness)
  - Cluster 5-epoch smoke + 3-fold A/B vs Option-2 baseline (004b662c8)
  - Success: mean_auc lifts ≥ +0.005 AND median sat→next-AUC delta positive

Awaiting user review before plan handoff.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 23:06:29 +02:00
jgrusewski
4425a77844 plan(ml-alpha): v2 multi-horizon implementation plan (V1-V13)
Concrete TDD-driven commit map for the v2 spec
(2026-05-18-ml-alpha-v2-multi-horizon-design.md). Thirteen commits
ordered by dependency: delete falsified path, build new kernels with
numgrad parity (V2-V8), trainer state bundle (V9), wire into
PerceptionTrainer (V10), local smoke (V11), cluster smoke (V12), 3-fold
A/B (V13). Per-commit verification gates and explicit stop conditions.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 13:22:48 +02:00
jgrusewski
1c2ee1d7c3 spec(ml-alpha): v2 multi-horizon redesign (A+B+C+D+E integrated)
Integrated design spec for the post-A/B redesign: Kendall sigma BCE
(A), L2 anchor on horizon tokens + shared Q (B), horizon-token
K-prepend replacing per-horizon Q_h (C), regime-aware MoE gate (D),
and inverted-axis attention pass (E). Bundled per
pearl_no_deferrals_for_complementary_fixes — all five axes have
orthogonal architectural scope and independent kill criteria.

Spec drops the C21-C25 per-horizon Q_h path (falsified by sweep
2026-05-18: mean_auc -0.019 vs single-Q baseline) and migrates the
existing init buffers into the new horizon-tokens prefix.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 13:20:26 +02:00
jgrusewski
f5632649ca spec(ml-alpha): per-horizon attention pool design (C20)
Captures the brainstormed "alternative attention pool variants"
follow-on from the original real-LOB integration brainstorm (Axis 1,
deferred from the LOB workstream as a separate model-side spec).

Design:
  Replace shared learned query Q[HIDDEN_DIM] with per-horizon queries
  Q_h[N_HORIZONS, HIDDEN_DIM]. Per-horizon softmax + context vectors
  feed multi-horizon heads directly (PATH A) — each horizon attends
  to a different part of the K=6000 LN_b output sequence. CfC k=0
  state is initialised by the MEAN of per-horizon contexts so the
  K-loop recurrence + state amplification (per
  pearl_state_amplifies_short_horizon_into_long_horizon) survives.
  Heads consume per-horizon context concat CfC h_K (residual) with a
  default 75/25 weight split.

Falsifiable claim (§0): A/B-tested win means h6000 mean_auc lifts by
≥ +0.01 absolute OR per-horizon distribution shifts toward short
horizons (h1000, h300) with no net h6000 loss. The 3-fold variance
band on the current architecture (mean_auc 0.7749 ± 0.024) means a
+0.01 lift is within noise — a meaningful effect needs ≥ +0.024 or
qualitative distributional shift.

Two new kernels (per_horizon_attention_pool_fwd + _bwd) + signature
extension on multi_horizon_heads_{fwd,bwd}. Variant-toggle config flag
(SharedQuery vs PerHorizonQuery) keeps the existing path fully
functional; new variant is opt-in. CheckpointV1 → V2 with explicit
discriminant + optional q_h field; V1 files load as SharedQuery, new
V2 training writes the discriminant.

Three validation rings:
  1. Per-(b,h) numgrad parity at K=16
  2. One-epoch smoke (no NaN, loss decreases)
  3. 30-epoch × 3-fold A/B (#204) — decision gate per §0 falsifiable claim

Implementation explicitly deferred. The decision to invest depends on
(a) GPU time budget (~3-6 hrs on L40S × 5 GPUs for the A/B), (b)
whether per-horizon cost-frontier sweeps (#202 follow-ups) surface
viable horizons beyond h6000 that would benefit from per-horizon
specialisation, and (c) the 3-fold variance noise floor making the
expected effect size visible.

Next step when ready: invoke superpowers:writing-plans against this
spec for the ~6-8 commit implementation plan.

Closes the "good to have" question from the recent brainstorm with a
concrete decision framework rather than ad-hoc implementation.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 10:20:38 +02:00
jgrusewski
fab2d70c92 plan(ml-backtesting): real-LOB integration implementation plan
10 atomic commits, ~40 sub-tasks, TDD per superpowers:writing-plans:
  C1 ml-alpha loader inference_only mode
  C2 ml-backtesting order types + SlotTag
  C3 policy tree + bytecode flatten
  C4 build.rs + book_update kernel + sim skeleton (3 fixtures)
  C5 order_match kernel + latency-aware fills (4 fixtures)
  C6 pnl_track kernel (1 fixture)
  C7 decision_policy kernel + per-horizon ISV-Kelly (3 fixtures)
  C8 BacktestHarness orchestrator + Ring 1b trainer-parity test
  C9 artifacts + aggregate + fxt-backtest binary
  C10 Ring 2 invariant fuzz (N in {1, 16, 256})

Plan ends with green Ring 1 (11 fixtures) + Ring 1b + Ring 2 (3 fuzz)
and a working fxt-backtest run|aggregate CLI. Ring 3 (production-day
replay), per-horizon cost-frontier sweep, model-checkpoint sweeps,
IBKR live adapter, and multi-fill P&L explicitly deferred.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 02:18:18 +02:00
jgrusewski
bfbaea2661 spec(ml-backtesting): real-LOB integration design
Greenfield LOB simulator + execution policy + backtest harness inside
existing ml-backtesting crate. Turns the AUC predictor into a P&L
producer at IBKR+Scaleway latency profile (100ms baseline).

Key design decisions:
- Reuse trainer's MultiHorizonLoader, Mbp10RawInput, snap_feature_assemble
  cubin, CfcTrunk captured graph verbatim (zero train-vs-deploy skew).
- Per-horizon ISV-Kelly + adaptive WeightedByRealizedSharpe aggregator
  (no static horizon mask; policy self-shifts capital).
- Block-per-backtest CUDA (32 threads/warp/block), ~1.4 KB shared mem.
- Three captured graphs (perception, step-event, decision); host branches
  only between captures.
- Mapped-pinned for all CPU/GPU buffers (hard requirement per
  feedback_no_htod_htoh_only_mapped_pinned).
- Three validation rings: N=1 bit-exact fixtures, trainer-parity check,
  N>1 invariant fuzz; production-day replay as Ring 3.

Single binary fxt-backtest with run + aggregate subcommands. No new
crates; extends existing ml-backtesting alongside barrier_backtest.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:51:11 +02:00
jgrusewski
c508d101c1 plan(perf): K-loop block-per-batch parallelization implementation plan
Bite-sized 22-task plan implementing the design at
docs/superpowers/specs/2026-05-17-kloop-parallelization-design.md.

Four atomic commits per the spec's Rollout section:
  Commit 1: reduce_axis0 kernel + cfc_step refactor (Tasks 1-10)
  Commit 2: GRN bwd refactor (Tasks 11-14)
  Commit 3: VSN bwd refactor (Tasks 15-17)
  Commit 4: attention_pool bwd refactor (Tasks 18-20)

Each commit covers kernel rewrite + per-batch scratch buffers +
reducer launches + memset_zeros wiring + smoke validation.

Tests added across commits:
  - cfc_bwd_b1_oracle.rs (Task 6): B=1 oracle vs single-sample helper
    within relative_eq 1e-5 (FP-tolerant, not bit-exact)
  - stacked_trainer_loss_shrinks_at_batch_32 (Task 7): first test
    that exercises the cross-batch reducer path
  - cfc_bwd_scratch_clears_between_steps (Task 8): scratch-zero
    regression guard

Acceptance gates 1-8 from the spec are mapped to Tasks 6, 7, 8, 9,
21, 22 (local + cluster A/B perf). Reference baseline for gate #8
is t6z89's per-epoch AUC trajectory.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 23:27:20 +02:00
jgrusewski
ea1d8703b7 spec(perf): revise K-loop parallelization design — full critical pass
Revises all 12 issues from the self-review pass:

1. (HIGH) Soften bit-equivalence claim — single-sample helper and
   batched kernel at B=1 are different CUDA kernels; FP order may
   differ. Acceptance is relative_eq ≤ 1e-6, not bit-exact.
2. (HIGH) Explicit asymmetry: only cfc_step has a single-sample GPU
   oracle. GRN/VSN/attn bwd rely on smoke + chain-rule preservation.
   feedback_no_cpu_test_fallbacks.md forbids a CPU reference oracle.
3. (HIGH) Realistic targets — 3× floor, 5× stretch. Drops 15× claim
   which was Amdahl-bounded under any reasonable assumption.
4. (MED) AdamW-after-reducer invariant stated explicitly: final grad
   buffer is OVERWRITE by reducer, meaningful only after reducer ran.
5. (MED) New B=32 smoke test (stacked_trainer_loss_shrinks_at_batch_32)
   actually exercises the cross-batch reduction path; existing
   perception_overfit suite is all B=1.
6. (MED) Rollout commit 1 bundles reduce_axis0 + first consumer
   (cfc_step refactor) to avoid feedback_wire_everything_up.md
   orphan-kernel anti-pattern.
7. (LOW) Drop "merge to ml-alpha-phase-a" — user already chose direct
   commits to that branch; clarify in Rollout.
8. (LOW) Add explicit scratch-sizing formula:
        scratch_bytes ≈ B × Σ(param tensor sizes per kernel).
9. (LOW) Remove resolved open question (memset_zeros ordering).
10. (STRUCT) Post-refactor bottleneck analysis section — names the
    next L40S floor (Mamba2 scan, launch latency, cuBLAS).
11. (STRUCT) cudaFuncSetAttribute note — refactored cfc_bwd's per-
    block shared mem drops to 1 KiB; no attribute change needed.
12. (STRUCT) Explicit Rollback section — atomic-commit-per-kernel +
    revert strategy; rollback baseline is the spec commit
    (54aa69c10) on ml-alpha-phase-a.

Plus locks the target pool to L40S — speedup must be attributable to
the refactor, not to a hardware bump. H100 / BF16 / larger batch
become candidates for a follow-up spec once the L40S floor is known.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 23:13:32 +02:00
jgrusewski
54aa69c108 spec(perf): K-loop block-per-batch parallelization design
Documents the design for fixing the single-SM bottleneck in five
backward/K-loop kernels: cfc_step (fwd+bwd), GRN bwd, VSN bwd, and
attention_pool bwd. All currently use grid=(1,1,1) with an internal
n_batch loop — on L40S (142 SMs) with B=32 this puts <1% of the GPU
to work in the K-loop critical path.

Architecture: block-per-batch (grid=(B,1,1)) for the kernel body, plus
per-batch grad scratch buffers reduced via a single parameterised
reduce_axis0 kernel (block tree-reduce, no atomicAdd per
feedback_no_atomicadd.md). Same pattern as the existing LayerNorm bwd
reducer — CUDA-Graph-safe, debuggable, and consistent with foxhunt's
no-cooperative-groups discipline.

Target: ≥3× epoch wall speedup (stretch 8-15×). Makes 3-fold CV
tractable (10.5h → 2-3h) and unblocks decision-stride / state-dim
sweeps that compound the gain.

Acceptance gates: (a) all 8 perception_overfit smokes still converge,
(b) new B=1 bit-equivalence test asserts the refactored batched bwd
kernel at B=1 matches the existing single-sample helper byte-for-byte,
(c) cluster A/B vs t6z89 baseline shows AUC trajectory within ±0.005
and epoch wall ≥3× faster.

Atomic refactor per kernel — one commit per kernel covering the
kernel rewrite, scratch buffer alloc, reducer launch wiring, and
smoke. No "_legacy" parallel kernels per feedback_no_legacy_aliases.md
+ feedback_no_partial_refactor.md.

Open implementation-plan decisions: exact memset_zeros ordering inside
the captured graph, batch-vs-per-tensor reducer launches, optimal
block_dim for reduce_axis0 itself.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 23:06:28 +02:00
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