Two targeted fixes to the SP9 Kelly cold-start warmup floor (Fix 37,
commit `48a8b9ee7`) for quirks observed in smoke-test-wrwkz on a
5-epoch L40S smoke. Atomic per `feedback_no_partial_refactor`.
**Quirk 1 — EMA target saturation:** ep1 HEALTH_DIAG showed
`stat_count_tgt=419 div_tgt=105002 temp_tgt=1.0 conf [stat=1.000
bhv=0.333 tmp=1.000] floor=0.0`. Pearl A sentinel-bootstrap on the
3 EMA target updaters (`kelly_*_target_ema_kernel.cu`) caused the
first observation to replace the sentinel directly, so
`target = first_obs`, `current/target = 1.0`, `confidence = 1.0`,
`floor = base × (1 − 1.0) = 0` — defeating the cold-start mechanism.
The principled fix per `feedback_isv_for_adaptive_bounds.md`:
"sufficient" is defined in absolute terms via Invariant-1 numerical
anchors. The 3 target ISV slots become constructor-written constants
(written ONCE in trainer constructor, identical pattern to existing
`config.cql_alpha → ISV[CQL_ALPHA_INDEX=48]` from Plan 1 Task 12).
- ISV[KELLY_SAMPLE_COUNT_TARGET_INDEX=333] = 100.0 (trades)
- ISV[KELLY_DIVERGENCE_TARGET_INDEX=334] = 2.0 (ratio)
- ISV[KELLY_TEMPORAL_TARGET_INDEX=335] = 5.0 (epochs)
**Quirk 2 — divergence ratio explosion:** ep1 showed
`divergence=70005`. Algebraically `intent_f / max(eval_f, 1e-6) =
0.07 / 1e-6 = 70 000` because `ISV[EVAL_DIST_F_INDEX=338]` was still
at Pearl A sentinel 0 before the first val window populated it.
Algebraically the warmup-floor kernel still derived
`behavioral_conf = 0` (correct semantic), but the synthetic 70 000
in HEALTH_DIAG masked the real signal flow.
Fix: explicit sentinel detection in
`intent_eval_divergence_compute_kernel.cu`:
if (eval_f < SENTINEL_THRESHOLD=1e-5)
divergence = SENTINEL_DIVERGENCE=1e6 // forces behavioral_conf=0
else
divergence = intent_f / eval_f
Same `behavioral_conf = 0` outcome but with explicit provenance —
HEALTH_DIAG now reads `divergence=1e6` until eval_f matures.
**Atomic structure:**
- DELETE 3 EMA target updater kernels (`.cu` files)
- DELETE 3 entries from `crates/ml/build.rs::kernels_with_common`
- DELETE 3 cubin static byte arrays + 3 struct fields + 3 cubin
loaders + 3 fields in trainer construction tuple in
`gpu_dqn_trainer.rs`
- DELETE 3 launches in `launch_sp9_kelly_warmup_floor` (chain
shrinks 5 → 2: q_var_mag_ema + main warmup-floor)
- DELETE 3 scratch slots; SP5_SCRATCH_TOTAL 268 → 265;
SCRATCH_SP9_EVAL_DIST_BASE slides 265 → 262
- ADD constructor-write of 3 Invariant-1 anchors (100.0, 2.0, 5.0)
immediately before layout-fingerprint write
- UPDATE 3 dispatch arms in `reset_named_state` to rewrite the
Invariant-1 anchors at fold boundary (NOT sentinel 0) — these
are constants, not stateful EMAs
- UPDATE 3 registry descriptions to reflect Invariant-1 anchor
semantic + smoke-test-wrwkz evidence
- UPDATE `intent_eval_divergence_compute_kernel.cu` with
sentinel-detect branch
- ISV slot layout UNCHANGED (3 target slots @ ISV[333..336)
remain); Wiener-buffer linear span (`SP5_PRODUCER_COUNT=165`)
UNCHANGED — 3 wiener triples for deleted producers become
reserved-unused like Pearl 6's [525..543) carve-out
- audit doc Fix 37.1 entry with full provenance + smoke evidence
**Verification:**
- `SQLX_OFFLINE=true cargo check -p ml` — clean (only pre-existing
18 warnings; no new errors or warnings).
- `SQLX_OFFLINE=true cargo test -p ml --lib state_reset` — 4/4 pass
including `every_fold_and_soft_reset_entry_has_dispatch_arm`.
- `SQLX_OFFLINE=true cargo test -p ml --lib sp5_isv_slots` — 9/9
pass including `sp9_slots_contiguous_above_sp8_block`.
**Expected smoke signature post-fix:**
- floor: starts ≈ base_floor × 1.0, decays as confidence accumulates
- divergence: 1e6 until first val window, small (≤ 5) afterward
- conf: stat=count/100, bhv=0 until eval_dist matures, tmp=ep/5
- combined_conf reaches 1.0 only when at least one axis genuinely
matures (typically temporal at epoch 5 in fold 0)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per pearl_cold_start_exit_signal_or.md + pearl_controller_anchors_isv_driven.md:
the Kelly cap's `warmup_floor` and its release condition were both
regime-encoded constants. Single-axis statistical cold-start exit
(`total_trades >= 10` in trade_physics.cuh::kelly_position_cap) created
a chicken-and-egg deadlock: cap closed → no trades → no Kelly samples →
cap stays closed. T10 wsnc6 ep1-3 evidence (post-Fix 36):
intent_dist_f rising to 0.47 while eval_dist_f pinned to 0.00 with
kelly_f=0 across all epochs — train-vs-eval divergence as direct
symptom of the cold-start deadlock.
SP9 lifts the floor and its release condition fully onto ISV. The exit
condition is OR'd across statistical / behavioral / temporal axes per
the pearl — any single axis firing exits cold-start.
Atomic commit per feedback_no_partial_refactor:
- 9 new ISV slots @ [330..339):
- KELLY_WARMUP_FLOOR_INDEX (330) — adaptive floor consumed by
unified_env_step_core
- Q_VAR_MAG_EMA_INDEX (331) — historical EMA baseline for the
self-relative `base_floor` ratio (eliminates 0.5 hardcoded
half-Kelly)
- INTENT_EVAL_DIVERGENCE_INDEX (332) — behavioral-axis numerator
- 3 EMA targets (sample_count / divergence / temporal)
- 3 EVAL_DIST_{Q,H,F}_INDEX — replaces DtoH
read_eval_intent_magnitude_distribution()
- ISV_TOTAL_DIM 330 → 339; SP5_PRODUCER_COUNT linear span 156 → 165
- 9 new scratch slots @ [259..268); SP5_SCRATCH_TOTAL 259 → 268
- 7 new producer kernels (single-block cold-path, chained through
apply_pearls_ad_kernel for Pearl A bootstrap + Pearl D Wiener-α):
- eval_intent_dist_compute_kernel.cu — GPU reduction of
intent_mag_buf, replaces DtoH path per
feedback_no_cpu_compute_strict.md
- intent_eval_divergence_compute_kernel.cu
- q_var_mag_ema_compute_kernel.cu
- kelly_sample_count_target_ema_kernel.cu
- kelly_divergence_target_ema_kernel.cu
- kelly_temporal_target_ema_kernel.cu
- kelly_warmup_floor_compute_kernel.cu — main producer combining
all 8 ISV inputs
- consumer migration in trade_physics.cuh::unified_env_step_core:
health_safety_sp9 = fmaxf(health_safety_sp5,
isv[SP9_KELLY_WARMUP_FLOOR_INDEX])
threading through apply_kelly_cap's health_floor parameter; zero
sentinel → no-op via fmaxf so existing path's behavior is preserved
- DELETE read_eval_intent_magnitude_distribution() in
gpu_backtest_evaluator.rs (was DtoH read_all + host loop) per
feedback_no_htod_htoh_only_mapped_pinned.md; replaced by
intent_mag_dev_ptr_and_n() GPU accessor; metrics.rs:908 consumer
migrated from DtoH to launch + ISV mapped-pinned read
- 9 new state-reset registry FoldReset entries + 9 dispatch arms in
reset_named_state (Pearl A bootstrap on first observation)
- HEALTH_DIAG sp9_kelly_warmup line emits floor + divergence + 3
confidence axes + 3 EMA targets per feedback_no_hiding
- audit doc Fix 37 entry with full provenance, files touched, pearls
applied, verification
Constants: only KELLY_FLOOR_MIN_RATIO=0.25, KELLY_FLOOR_MAX_RATIO=1.0,
EPS_DIV=1e-6 — Invariant 1 numerical-stability anchors per
feedback_isv_for_adaptive_bounds.md. All thresholds, targets, and
the floor itself are signal-driven via ISV.
Pre-existing 18 cargo warnings unchanged. State-reset contract test
`every_fold_and_soft_reset_entry_has_dispatch_arm` passes for all 9
new entries; SP5 ISV slot layout test
`sp9_slots_contiguous_above_sp8_block` passes;
`SQLX_OFFLINE=true cargo check -p ml` clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Brainstorm spec for SP9 (Fix 37). Resolves the val-Flat-collapse pathology
surfaced in T10 train-multi-seed-wsnc6 ep1-3: training intent_dist_f=0.47
but eval_dist_f=0.00 because Kelly cap pinned eval mag to Quarter, with
trade_count=1 in 214k bars (chicken-and-egg: cap closed → no trades → no
Kelly samples → cap stays closed).
Architecture per pearl_controller_anchors_isv_driven and
pearl_cold_start_exit_signal_or:
final_kelly_f = max(measured_kelly_f, warmup_floor)
warmup_floor = base_floor × (1 − combined_confidence)
base_floor = clamp(q_var_mag / q_var_mag_ema, MIN, MAX)
combined_confidence = max(statistical, behavioral, temporal)
All thresholds ISV-driven via Pearl D Wiener-α; only Invariant 1 numerical
anchors (clamp ranges, EPS) remain as constants.
Scope: 9 new ISV slots, 6 new GPU producer kernels including a
mandatory eval_dist GPU migration (eliminating DtoH readback at
gpu_backtest_evaluator.rs:1353 per feedback_no_cpu_compute_strict).
~1000-1200 LOC, single atomic commit per feedback_no_partial_refactor.
Pearls authored as part of brainstorm:
- pearl_controller_anchors_isv_driven (regime-encoded constants)
- pearl_cold_start_exit_signal_or (OR'd signals across statistical /
behavioral / temporal axes)
Per pearl_controller_anchors_isv_driven.md: Fix 35 (CQL formula direction
flip) is necessary but insufficient — `const float MAX_BUDGET = 1.0f;` at
line 113 of loss_balance_controller_kernel.cu is regime-encoded the same
way the original CQL target_ratio formula was. Under healthy training
the cap is fine; under val-Flat-collapse it lets the controller saturate
budgets to 1.0 while the model is regressing into Flat.
The pearl prescribes the structural fix: pick the canary that fires
under the failure mode → train_active_frac (Long+Short / total during
training rollout). Lift it onto ISV with Pearls A+D smoothing; route it
through a producer kernel that derives per-(head, branch) cap via linear
interpolation FLOOR + active_frac × (CEIL - FLOOR); read the cap from
ISV in the controller kernel (no more hardcoded 1.0).
Atomic commit per feedback_no_partial_refactor:
- new kernel: train_active_frac_compute_kernel.cu — single-thread
reduction over monitoring_summary[5..17), writes scratch[250]; chained
apply_pearls_ad → ISV[TRAIN_ACTIVE_FRAC_INDEX=321]
- new kernel: loss_balance_max_budget_compute_kernel.cu — 8 threads
(2 heads × 4 branches), reads ISV[TRAIN_ACTIVE_FRAC_INDEX], writes
scratch[251..259); chained apply_pearls_ad ×8 →
ISV[LB_MAX_BUDGET_{CQL,C51}_BASE..+4)
- consumer: loss_balance_controller_kernel.cu — replace
`const float MAX_BUDGET = 1.0f;` with per-(head, branch) ISV reads,
defensive Pearl A bootstrap clamp
- 9 new ISV slots @ [321..330); ISV_TOTAL_DIM 321 → 330;
SP5_PRODUCER_COUNT linear span 147 → 156
- 9 new scratch slots @ [250..259); SP5_SCRATCH_TOTAL 250 → 259
- delete CPU train_active_frac compute (training_loop.rs:3392-3396) per
feedback_no_cpu_compute_strict; delete host field
`last_train_active_frac: f32`; replace with accessor reading from ISV
- 3 new state-reset registry entries (FoldReset; Pearl A bootstrap on
first observation) + dispatch arms in reset_named_state
- audit doc: Fix 36 entry with full provenance, files touched, pearls
applied, verification
Pre-existing 18 cargo warnings unchanged. State-reset contract test
`every_fold_and_soft_reset_entry_has_dispatch_arm` passes for all 3 new
entries; SP5 ISV slot layout test
`sp8_max_budget_slots_contiguous_and_above_activation_block` passes;
`SQLX_OFFLINE=true cargo check -p ml` clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`target_ratio[CQL][b] = ANCHOR_CQL_RATIO * (1 - flatness[b])` had the
sign inverted: it pushed CQL HIGH when Q was flat (the collapse state)
and LOW when Q had variance. Per pearl_2_budget_kernel.cu, `flatness =
var_q / σ²`, so flatness HIGH means Q has variance — exactly when
overconfidence-risk-driven CQL pressure should kick in.
Symptom (T10-v3 train-multi-seed-x7sl2 logs): Once IQN Fix 34 woke
IQN-mag/ord/urg branches and produced real Q-targets, the controller's
inverted formula sent cql_budget to MAX_BUDGET=1.0 saturation on every
branch, the conservative pull kept Q flat, the model collapsed to
single-Flat-action eval (val_active_frac=0, dir_entropy=0,
trade_count=1, sharpe=0).
Fix is one operational character: `(1 - flatness)` → `flatness`. C51
formula was already correctly aligned (`flatness * ANCHOR_C51_RATIO`)
and unchanged.
Per pearl_controller_anchors_isv_driven.md: the inverted formula was
masked for months because the IQN-dead regime (Fix 34) suppressed
cql_raw on mag/ord/urg, never letting the controller engage with the
inverted target. Fixing the IQN regime exposed the dormant formula bug.
ANCHOR_CQL_RATIO=2.0 and MAX_BUDGET=1.0 remain hardcoded; Fix 36 will
make those ISV-driven via a GPU train_active_frac canary signal per
the pearl's "pick the canary that fires under the pathology" rule.
execute_training_pipeline consumes cached_target_h_s2_ptr via .take(), so
the SP6 Pearl 5 per-branch loop (4 sequential iqn calls per step) only
worked for branch 0. Branches 1, 2, 3 saw cached_ptr=None, returned a
"non-fatal" Err logged as a warning, and silently skipped apply_iqn_
trunk_gradient — only the direction branch's IQN quantile signal ever
reached the trunk, for months.
Surfaced in T10-retry train-multi-seed-ksjcm logs as repeated:
WARN: IQN parallel branch 1 step failed (non-fatal):
WARN: IQN parallel branch 2 step failed (non-fatal):
WARN: IQN parallel branch 3 step failed (non-fatal):
cached_target_h_s2_ptr is None.
Pre-existing since SP6 Pearl 5 (P4.T3-era multi-quantile IQN per-branch
τ schedules) — masked by the non-fatal warning classification.
Likely explains:
- cql_mag persistence at SP7 smoke (cql_mag=0.07 vs cql_dir=1.0):
CQL was the only learning signal mag had because IQN-mag was dead.
- SP7 c51 1000:1 controller suppression on mag/ord/urg may stabilize
at non-collapse values once IQN signal returns to those branches.
Fix is local: re-set cached ptr inside both 4-branch loops (parallel arm
near line 2123, sequential arm near line 2308). The ptr is the same
value (target_h_s2 is per-step, not per-branch), but the .take()
contract requires set-per-call. Defensive single-shot semantic preserved
— if a future bug skips the set, IQN errors loud rather than reusing
stale ptr.
Per feedback_no_partial_refactor: SP6 changed the call pattern 1→4 per
step but didn't migrate the cache contract. Per feedback_no_hiding: the
non-fatal classification hid the structural bug; escalation to hard
error deferred to next commit after post-fix T10 validates the warnings
disappear.
Audit doc updated with Fix 34 entry.
The SP7 controller wrote real budgets to ISV[BUDGET_CQL_BASE/C51_BASE] and
the activation flag correctly transitioned 0→1, but downstream SAXPY ops
still saw exactly 0.02/0.05 every step. Root cause: compute_adaptive_budgets
ran host-side Rust with `if cql_active >= 0.5 { real } else { bootstrap }`,
captured into the aux_child CUDA Graph at step 0 of each fold (when
cql_active is FoldReset sentinel 0.0). The bootstrap branch resolves to
literal 0.02/0.05 and freezes into kernel arg buffers; ~1000 graph replays
per fold use frozen scalars regardless of runtime ISV state.
Same disease as SP4 host-side EMA elimination 2026-05-01. Fix:
- New consume_lb_budget_kernel.cu (8 threads, 1 block): reads ISV slots
for activation flag + controller budget per (head, branch); applies
if/else dispatch on-device; writes trunk_mean + per-branch correction
to mapped-pinned scratch buf [10] = (cql_trunk + cql_corr×4 + c51_trunk
+ c51_corr×4). Same cubin houses dqn_{scale,saxpy}_f32_dev_ptr_kernel
variants reading alpha from a device pointer (no kernel-arg freeze).
- Buffer + launcher + cubin loading + 4 dev-ptr accessor methods
in gpu_dqn_trainer.rs.
- apply_c51_budget_scale / apply_cql_saxpy + per-branch variants take
alpha_dev_ptr: u64 instead of scalar f32. The "skip when ≈ 1.0"
optimization is dropped — the value lives on-device. Existing scalar
dqn_{saxpy,scale}_f32_kernel are NOT modified — they remain reused
by distill, VSN dW dilution, etc.
- compute_adaptive_budgets refactored to launch the dispatch kernel
inline (captured along with consumers; replay-time fresh values
every step) and stop returning host-resolved CQL/C51 scalars.
IQN/ENS keep their host-side resolution (out-of-scope per change
scope — no activation-flag dispatch).
- HEALTH_DIAG reads from lb_budget_effective_buf via new accessor
methods on FusedTrainingCtx; dead caches on GpuDqnTrainer
(last_{cql,c51}_budget_eff / _per_branch) deleted.
- Audit doc Fix 33. Memory pearl out-of-tree.
Bootstrap byte-equivalence preserved: kernel-arg constants
cql_bootstrap=0.02 / c51_bootstrap=0.05 remain byte-identical to the
prior host-side CQL_BOOTSTRAP_BUDGET / C51_BOOTSTRAP_BUDGET literals
and to loss_balance_controller_kernel.cu's COLD_START_FLOOR_* anchors.
Files: consume_lb_budget_kernel.cu (new), build.rs, gpu_dqn_trainer.rs,
fused_training.rs, training_loop.rs, dqn-wire-up-audit.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After sp5 merge with -X theirs, two compile errors needed manual fix:
- gpu_her.rs lost the DevicePtrMut trait import
- gpu_tlob.rs Fix 20 regression test used the 4-arg adam_step signature
before sp5's Pearl 4 added β1/β2/ε params.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The SP7 controller's CQL reference signal was reading cql_sx (post-SAXPY,
budget-scaled) which created a self-perpetuating deadlock at small
budget values: cql_sx_norm = budget × raw_grad → small budget → small
cql_sx → controller can't update → budget stays small.
The earlier offset 6 → 3 attempt failed because grad_decomp_launch_cql
was never effectively populating slot 3 — the snapshot pattern measures
‖grad_buf − snapshot‖, but apply_cql_gradient writes to cql_grad_scratch
(separate buffer), not grad_buf, so the snapshot delta is always 0.
This commit adds a real producer kernel cql_raw_norm_compute that reads
cql_grad_scratch directly and computes ‖raw_cql‖ over mag/dir/trunk
slices. Wired to fire AFTER apply_cql_gradient and BEFORE
apply_cql_saxpy, populating grad_decomp_result_pinned[3..6] with the
raw norm independent of cql_budget.
SP7 launcher updated to read from offset 3 (now: real raw CQL norm,
not the never-populated cql snapshot delta). HEALTH_DIAG label renamed
cql_sx → cql_raw to reflect the new contract; component index in the
cached grad_component_norms_* arrays switched 2 → 1.
The historical grad_decomp_launch_cql() call is removed — keeping it
would overwrite the slot with 0 after cql_raw_norm_compute fires. The
paired grad_decomp_snapshot_cql snapshot is left in place to scope the
diff to Path A; buffer cleanup (grad_snapshot_cql allocation +
grad_decomp_launch_cql definition) belongs in a follow-up commit per
feedback_no_partial_refactor.
Files: cql_raw_norm_kernel.cu (new, 97 LOC), build.rs,
gpu_dqn_trainer.rs (struct field + cubin static + load + launcher +
SP7 read offset 6→3), loss_balance_controller_kernel.cu (docstring +
arg comment), fused_training.rs (4 launch_cql_raw_norm call sites,
1 dead grad_decomp_launch_cql call removed), training_loop.rs
(HEALTH_DIAG label + index), audit doc Fix 31 SP7 Path A entry.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The SP7 smoke at 237b3dbfb showed all 8 (head, branch) combinations
stuck at bootstrap across 5 epochs, despite Q-variance and gradient
norms being non-zero. The activation flag mechanism is monotonic per
fold (once active, stays active), so 8/8 inactive across all observed
epochs implies the kernel never hits the active path — but we can't
confirm whether that's because (a) grad_decomp_result_pinned reads
zero at SP7's epoch-boundary call site, or (b) something else.
Added two HEALTH_DIAG lines:
- grad_decomp_pinned — reads bytes [0..12,24..36,36..48] of the
pinned buffer the SP7 kernel reads; surfaces iqn/cql_sx/c51 mag/
dir/trunk norms exactly as the kernel sees them.
- lb_active_per_branch — reads LB_{CQL,C51}_ACTIVE_BASE+0..4 from
ISV; surfaces the activation flag state per (head, branch).
Together these disambiguate "grad_decomp not populated at SP7 read
time" from "values populated but kernel cold-start branch fires for
other reasons".
Purely additive — no behavior change. Audit doc Fix 31 sub-bullet.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
SP7 T1 added 24 ISV slots (LB_DIFF_VAR_CQL_BASE=297 ... LB_C51_ACTIVE
through 321) without bumping ISV_TOTAL_DIM, leaving SP7's wiener-state
and activation slots out-of-bounds of the allocated pinned buffer
(294 * 4 = 1176 bytes; SP7 slots write to bytes 1188..1284). GPU
direct-pointer writes silently corrupted memory in the next page;
CPU read_isv_signal_at returned garbage in release builds.
This explains the SP7 smoke's confusing zero-budget-everywhere
observation: the activation flag was reading OOB memory, the consumer
saw inconsistent values, and the controller's actual ISV state was
never visible.
Bumped ISV_TOTAL_DIM to 321 (max valid index 320, covering
SP5_SLOT_END-1). Made pub(crate) so the new contract test can reference
it from sp5_isv_slots.rs. Updated layout_fingerprint_seed()'s slot
entries to include the previously missing D3 and SP7 slots
(TRAINING_SHARPE_EMA=294 through LB_C51_ACTIVE_BASE=317) and updated
ISV_TOTAL_DIM= literal to 321 in lockstep per feedback_no_partial_refactor.
Added contract test all_sp5_slots_fit_within_isv_total_dim to
permanently gate this class of bug at cargo test time. The test would
have caught SP7 T1 instantly; future slot allocations cannot regress
this.
Files: gpu_dqn_trainer.rs (ISV_TOTAL_DIM + comment + fingerprint),
sp5_isv_slots.rs (test), docs/dqn-wire-up-audit.md (Fix 31 sub-bullet).
Cargo check workspace clean. Cargo test ml --lib 935 passed (934
baseline + 1 new contract test); 16 pre-existing GPU-hardware failures
unchanged.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The SP7 controller's flatness gate reads per-branch Q-variance from
ISV[Q_VAR_PER_BRANCH_BASE=222..226) but that signal was not visible in
HEALTH_DIAG. The existing "var_q" in the main HEALTH_DIAG line is
realized step-return variance per magnitude bin from
gpu_experience_collector — a trade-outcome metric, semantically
distinct from per-branch Q-output variance.
Added one emit line immediately after cql_budget_per_branch:
HEALTH_DIAG[E]: q_var_per_branch [dir=X.XXXX mag=X.XXXX ord=X.XXXX urg=X.XXXX]
Reads ISV[222..226) via read_isv_signal_at — the same slots written by
q_branch_stats_kernel.cu (scratch slot 2 per branch) and routed into ISV
by apply_pearls_ad_kernel in launch_sp5_pearl_1_atom. No new ISV slots,
no kernel change, no StateResetRegistry entry.
Class 2 signal (mag_concat_scale / q_rms): Option A infeasible — q_rms
is a per-sample register variable in mag_concat_qdir with no existing ISV
slot; h_s2_rms_ema at ISV[96] is the only available proxy. Option B
(new ISV slot) blocked pending explicit controller OK. See audit doc for
full stop-and-report rationale.
Files touched:
crates/ml/src/trainers/dqn/trainer/training_loop.rs (+28 LOC)
docs/dqn-wire-up-audit.md (+13 LOC)
[ISV slot decision: Option A reused existing Q_VAR_PER_BRANCH_BASE=222..226]
Cargo check workspace clean. State-reset contract test passes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Fixes the SP7 controller dormancy discovered in smoke-test-8556k:
per-branch budgets stuck at exactly bootstrap constants because the
kernel's cold_start_basis numerically equaled the consumer's bootstrap
fallback, AND the Wiener-α was clamped at ALPHA_FLOOR=1e-4 from step 1.
Architectural change:
- 8 new ISV slots LB_{CQL,C51}_ACTIVE_BASE per (head × branch).
Activation flag is monotonic per fold, FoldReset on boundary.
- Kernel only sets active=1 when grads are populated AND on subsequent
active-state computation; cold-start branch leaves active=0 (fresh
branch) or holds prior budget steady (transient grad gate).
- Consumer dispatches on activation: bootstrap when active<0.5,
controller verbatim when active>=0.5. No more spurious bootstrap
when controller writes legitimate small values.
- Welford-α hybrid (max of 1/max(1,epoch_idx_in_fold) and Wiener-α)
gives full update on first active step, falls off as 1/N until
Wiener takes over with meaningful variance estimates. EPOCH_IDX_INDEX
is the existing per-fold-reset counter (no new tuned constants).
State reset registry: 2 new sp7_lb_*_active FoldReset entries +
matching dispatch arms in reset_named_state. Contract test
(every_fold_and_soft_reset_entry_has_dispatch_arm) gates compile.
GPU unit test sp7_loss_balance_controller_activation_flag_transitions
exercises 3 transitions (cold start → both flags 0; active → both
flags 1 with controller-computed budget != bootstrap; transient grad-
gate → flags hold at 1, prior budget held verbatim). Passes on local
RTX 3050 Ti.
Audit doc: Fix 31 sub-bullet describing the activation-flag fix.
Memory pearl out-of-tree (controller will dispatch separately).
Touched:
crates/ml/src/cuda_pipeline/sp5_isv_slots.rs
crates/ml/src/cuda_pipeline/loss_balance_controller_kernel.cu
crates/ml/src/cuda_pipeline/gpu_dqn_trainer.rs
crates/ml/src/trainers/dqn/fused_training.rs
crates/ml/src/trainers/dqn/state_reset_registry.rs
crates/ml/src/trainers/dqn/trainer/training_loop.rs
crates/ml/tests/sp5_producer_unit_tests.rs
docs/dqn-wire-up-audit.md
Cargo check workspace clean. Cargo test ml --lib clean (incl. contract
test + 6 sp5_isv_slots tests). 16 pre-existing failures unchanged.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Surfaced the SP7 T7 dispatch-arm bug at runtime (unknown-name panic at
fold boundary). This test enumerates RegistryEntry names from
StateResetRegistry::new() and asserts each has a match arm in
reset_named_state, catching the bug at `cargo test -p ml --lib`
instead of mid-training.
Source-introspection design — no production-code change. Test fails
fast if a future contributor adds a registry entry without the
corresponding dispatch arm.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The pearl_loss_balance_controller memory pearl is at
~/.claude/projects/.../memory/pearl_loss_balance_controller.md (not in
git — user-memory subsystem). MEMORY.md index entry updated.
This audit-doc commit records the T8 landing for the Fix 31 chain.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-existing test bug: line 164 asserted `ef >= 0.05` (post-Kelly-cap
eval_dist), which gates on Kelly cold-start warmup completing within
the smoke's training horizon — not on whether the Q-head learned to
prefer Full magnitude. On the local-laptop smoke (1 quarter MBP-10),
Kelly warmup never completes, pinning eval_dist[Full] = 0 even when
Q(Full) > Q(Half) clearly.
Per `project_magnitude_eval_collapse_kelly_capped`, the diagnostic
split landed in #212: intent_dist measures policy learning, eval_dist
measures policy + Kelly-cap. Tests asserting on Q-learning success
must use intent_dist; the test was never updated.
Smoke now PASSES with intent_full=0.057 (intent_full=0.866 in the
prior re-run — both above the 0.05 threshold; Q(Full) is clearly
preferred when Kelly cap doesn't suppress it).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
T2 (commit aa2854017) registered 4 SP7 ResetEntries:
sp7_lb_diff_var_cql → ISV[297..301)
sp7_lb_sample_var_cql → ISV[301..305)
sp7_lb_diff_var_c51 → ISV[305..309)
sp7_lb_sample_var_c51 → ISV[309..313)
But never added their dispatch arms in `reset_named_state`. At fold
boundary, the dispatcher panics with "unknown name 'sp7_lb_diff_var_cql'"
because every FoldReset entry must have a matching match arm.
Same shape as bug #281 (SP5 Layer A bug-fix). Surfaced by the SP7 T7
local sanity smoke (test_magnitude_distribution).
The 4 new arms mirror the existing `sp5_budget_cql` / `sp5_budget_c51`
template — `for b in 0..4 { write_isv_signal_at(BASE + b, 0.0); }`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two clarity-only edits surfaced by code review:
- M1: compute_adaptive_budgets header docstring claimed floors of
"0.05 C51, 0.05 IQN, 0.02 CQL, 0.02 Ens" — stale post-T7 (IQN is now
0.11, others are sentinel-aware bootstrap). Rewritten to reflect the
SP7 contract: IQN keeps BASE_IQN=0.11 structural floor; C51/CQL/ENS
use sentinel-aware bootstrap.
- M2: last_ens_budget_eff docstring misattributed ENS to "SP5 Pearl 2
(flatness-modulated)" — Pearl 2 stopped writing BUDGET_ENS_BASE in
T6. Rewritten to state ENS has no active controller driver in SP7;
bootstrap-only.
Comment-only — zero runtime effect. cargo check clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Atomic per feedback_no_partial_refactor — launch site + consumer floor
change + stale doc are three halves of the same contract:
(a) launch_loss_balance_controller wired into the per-step pipeline
after launch_sp5_pearl_2_budget (FLATNESS_BASE populated) and after
backward (grad_decomp pinned slots populated).
(b) compute_adaptive_budgets replaces hard floors (0.02/0.05) with
sentinel-aware bootstrap. The controller may now drive budgets near
zero when the structural target says so. IQN keeps BASE_IQN=0.11
structural floor (reference, can't be 0).
(c) All 4 stale "B4/G5" budget-eff docstrings rewritten to reflect
actual ownership: last_iqn_budget_eff (Pearl 2 flatness),
last_cql_budget_eff (SP7 controller), last_c51_budget_eff (SP7
controller), last_ens_budget_eff (Pearl 2 flatness +
sentinel-aware bootstrap). The previous claims (e.g.,
"0.10×(1−regime)×health") were never implemented; per
feedback_trust_code_not_docs, code wins over docs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Four comment/docstring sites still described the pre-SP7 Pearl 2 as
writing "20 floats / 5 outputs / c51/cql/ens" after the T6 kernel-
signature shrink. Updated to reflect the current 6-arg kernel writing
8 floats (IQN + flatness only) into scratch[115..119, 127..131).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Kernel signature reduced from 9 to 6 args; pearl_2_budget_update now
writes only budget_iqn[4] and flatness[4]. Launcher migrated atomically:
arg list shrinks, apply_pearls smoothing loop shrinks from 5 slot-blocks
to 2.
SCRATCH_PEARL_2_C51, SCRATCH_PEARL_2_CQL, SCRATCH_PEARL_2_ENS deleted as
orphan constants per feedback_wire_everything_up. The corresponding
producer scratch slots (111..115, 119..127) become reserved-for-future
inside the buffer.
CQL/C51/ENS budget ownership now lives in the SP7 loss-balance
controller (loaded in T5; wired in T7).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two clarity-only edits surfaced by code review:
- Rename `cql_dev` → `cql_sx_dev` in `launch_loss_balance_controller`.
The launcher uses `grad_decomp_result_dev_ptr + 6 * f32_size` which
is the cql_sx (post-budget) slot, not cql (pre-budget at offset 3).
The variable name now reflects that.
- Add `// 213` inline annotation on `base_wiener_offset` to match the
pattern used by all four sibling launchers (lines 11062, 11194, 11303).
No semantic impact — pointer arithmetic and parameter order unchanged.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
LOSS_BALANCE_CONTROLLER_CUBIN static, kernel slot in GpuDqnTrainer,
6 SCRATCH_LB_* index constants (218..242), pub(crate) launch_loss_balance_controller
that runs the producer + 24 apply_pearls_ad smoothing launches.
SP5_SCRATCH_TOTAL bumped 218→242 with updated docblock and allocation
comment to match the 24 new slots.
Component pointers into grad_decomp_result_pinned: IQN at offset 0,
CQL_SX at offset 6, C51 at offset 9 (3-float layout per
launch_grad_decomp docstring).
Producer-only — call site in training_loop.rs lands at T7 atomically
with the consumer floor change and stale-doc deletion per
feedback_no_partial_refactor.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds the kernel to the build.rs manifest after pearl_1_ext_num_atoms_kernel
and before the SP5 Layer D producers (matching the chronological SP5/SP7
producer ordering). nvcc-compiled cubin lands under
$OUT_DIR/loss_balance_controller_kernel.cubin and is loaded by
gpu_dqn_trainer.rs in T5.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three comment-only edits surfaced by code review:
- M1: Annotate `tid >= 8` guard with `// 8 = 2 heads × 4 branches`.
- M2: Header pseudocode `actual_ratio = h_norm / iqn_norm` clarified —
the implementation correctly omits the inline `fmaxf` because the
outer guard already enforces `iqn_n >= EPS_DIV`. Comment now states
the invariant explicitly.
- M3: Header "No atomicAdd" line now cites `feedback_no_atomicadd` for
consistency with sibling pearl kernels.
Comment-only — zero runtime effect. cargo check clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Single-block 8-thread kernel: 2 heads (CQL, C51) × 4 branches. Reads
3-float views into grad_decomp_result_pinned for IQN/CQL_SX/C51, plus
FLATNESS_BASE for the per-branch target modulator. Writes new budgets +
raw Wiener observations (diff² and sample²) to producer scratch.
Per-branch flatness-modulated target ratio (CQL → ANCHOR×(1-flatness),
C51 → ANCHOR×flatness). Wiener-optimal α from per-branch EMA state
slots, clamped to [1e-4, 0.5]. Cold-start seeds at consumer-side
bootstrap (0.02 CQL, 0.05 C51) on first observation; sentinel-aware.
Producer-only commit; build.rs entry, kernel slot, launch site land in
subsequent tasks.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rewrite the three sp5_budget_c51/cql/ens registry descriptions to be
accurate at HEAD aa2854017: replace present-tense "driven by"/"no longer
writes" with future-tense "will be driven by"/"will stop writing", replace
non-existent C51_BOOTSTRAP_BUDGET/CQL_BOOTSTRAP_BUDGET/ENS_BOOTSTRAP_BUDGET
named constants with their actual anonymous .max() literal line references,
and apply the "(Pearl 2 will stop writing...)" parenthetical uniformly to all
three slots (cql was missing it). Audit doc T2 bullet updated accordingly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4 new ResetEntries × 4 slots each cover ISV[297..313). Sentinel 0
triggers Pearl A first-observation bootstrap on fold boundary, matching
the existing Pearl 2/3/4/5/6/8 pattern.
Also: corrected the stale sp5_budget_cql description claiming a
non-existent "regime_stability allocator" (per
feedback_trust_code_not_docs); clarified sp5_budget_c51 / sp5_budget_ens
to reflect SP7 ownership.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Minor item 1: Remove extra column-alignment spaces from the 4 SP7
constants (LB_DIFF_VAR_CQL_BASE, LB_SAMPLE_VAR_CQL_BASE,
LB_DIFF_VAR_C51_BASE, LB_SAMPLE_VAR_C51_BASE) so they match the
no-alignment style of surrounding SP5 constants (BUDGET_C51_BASE etc.).
Constant values (297, 301, 305, 309) and inline comments are unchanged.
Minor item 2: Soften the Fix 31 T7 stub in dqn-wire-up-audit.md from
"sentinel-aware consumer" to "sentinel-aware bootstrap with bootstrap
constants matching the kernel's cold-start basis (defined in T7)"
so the audit entry does not forward-reference specific constant names
before they land.
Cargo check: clean (zero warnings, zero errors).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Update stale (118) → 137 unique-slot count and [174..294) = 120 → [174..313) = 139
range in the SP5_PRODUCER_COUNT docstring. Update inline comment unique-slot count
121 → 137 with SP7 T1 breakdown entry. Append SP7 Task 1 history paragraph matching
the established Layer D D3 paragraph style.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
LB_DIFF_VAR_CQL_BASE=297, LB_SAMPLE_VAR_CQL_BASE=301,
LB_DIFF_VAR_C51_BASE=305, LB_SAMPLE_VAR_C51_BASE=309. Bumps SP5_SLOT_END
297 → 313 and SP5_PRODUCER_COUNT 123 → 139. Helper fns mirror the
existing budget_*/flatness/q_var_per_branch pattern. Layout fingerprint
extended. slot_layout_no_overlaps_and_total_correct asserts the new
total.
Audit doc Fix 31 stub added; will be extended commit-by-commit through
Tasks 2-9 of the SP7 plan.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Critical re-review of v1 caught:
1. Task 6 retained Pearl 2 kernel signature with (void) no-op args
"to save 3-site cascade" — that's the partial-refactor anti-pattern
feedback_no_partial_refactor explicitly forbids. v2 does the full
contract change: signature shrinks 9→6 args, launcher migrates
atomically.
2. SCRATCH_PEARL_2_C51/_CQL/_ENS would become orphan constants —
feedback_wire_everything_up says delete or wire. v2 deletes them in
T6.
3. Audit-doc updates were separated into a single late commit — would
fail check_audit_doc_updates pre-commit gate on T1-T6. v2 folds Fix
31 stub into T1 and extends it commit-by-commit.
4. T5 referenced grad_decomp_*_result_dev_ptr field names that don't
exist — actual layout is one shared 27-float pinned buffer with
per-component byte offsets (iqn=0, cql_sx=24, c51=36). v2 uses
pointer arithmetic from grad_decomp_result_dev_ptr.
5. Tasks 1, 2, 4 had "if file shape X then Y, otherwise Z" placeholder
branches — writing-plans skill forbids these. v2 has concrete patches
based on reading the actual files.
Also corrected: T2 fixes the stale "regime_stability allocator"
description in state_reset_registry.rs alongside the new entries.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Outcome-driven controller replacing Pearl 2's hardcoded-0 CQL budget and
floor-pinned C51 budget with multiplicative ratio adaptation. Targets
`grad_split_bwd cql/iqn = 2.0` and `c51/iqn = 1.0` per slice (trunk, dir,
mag). Slow EMA (α=0.01) consistent with existing controller pearls; Pearl
A sentinel-bootstrap on fold boundary; Pearl D Wiener-optimal smoothing.
Replaces ghost docstring at fused_training.rs:3409 ("0.10×(1−regime)×health"
formula was never implemented). Pearl 2 keeps owning IQN budget (reference
denominator) and FLATNESS_BASE (consumed by NoisyNet σ pearl); stops
writing CQL/C51/ENS slots so the new controller is the sole driver.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes Fix 29 audit row #13 — the last ⚠ Stale row from the Bug-1
contract drift triage. Pre-fix, `backtest_plan_state_isv` extracted
raw_close as `features[bar*feat_dim + 0]`. Post Bug-1 (commit
`5a5dd0fed`) `features[..+0]` is z-normed log-return, NOT raw_close.
The resulting `equity = cash + position*raw_close` and
`unrealized = position*(raw_close - entry_price)` formulas mixed
z-normed-log-return as a dollar price, corrupting val plan_isv
slots [PNL_VS_TARGET] (slot 1) and [PNL_VS_STOP] (slot 2). Other
plan_isv slots (progress, conviction, drift, regime, remaining)
don't depend on raw_close and were correct pre-fix.
Resolution: route raw_close from the upload-once `prices` buffer
(layout `[n*max_len*4]` raw OHLC). Close is at column index 3 — the
same index `backtest_env_kernel.cu` already reads from for portfolio
mark-to-market (line 64 of that kernel; OHLC layout is canonical
across the val backtest path). Reading from `prices` aligns the val
plan_isv path with env_step's source-of-truth, eliminating the
mixed-units pathology end-to-end.
Sites fixed:
- crates/ml/src/cuda_pipeline/backtest_plan_kernel.cu:74-100
Kernel signature: `const float* features` and `int feat_dim`
parameters dropped, replaced by `const float* prices` (the
[n*max_len*4] raw OHLC buffer). Raw_close read becomes
`prices[(w*max_len + current_step)*4 + 3]`. Multi-line comment
block documents the Bug-1 origin and the env_step parity
reference. The `bool have_close` / `prices != nullptr` guard
semantics preserved — callers without OHLC data fall back to
`unrealized = 0` exactly as pre-fix.
- crates/ml/src/cuda_pipeline/gpu_backtest_evaluator.rs:~1956
Single launcher (`evaluate_dqn_graphed` chunk loop, the only
invocation site of `plan_state_isv_kernel`) updated to pass
`&self.prices_buf.dev_ptr` instead of `&self.features_buf.dev_ptr`
and to drop the now-unused `feat_dim_i32` local + `.arg()` call.
Inline comment explains the Bug-1 origin.
- docs/dqn-wire-up-audit.md
Stale-B row appended to Fix 30's table. The standalone Stale-B
DEFERRED paragraph at the bottom replaced by the commit summary
+ the Fix 30 closure note (all 4 ⚠ Stale and 1 ❓ Ambiguous rows
from Fix 29's deferred follow-ups now resolved).
Migration scope per `feedback_no_partial_refactor`: kernel signature
changed → every consumer migrates in the same commit. Single launcher;
verified via `grep -rn backtest_plan_state_isv` (only the kernel
definition + the gpu_backtest_evaluator launcher + load site appear).
Verification:
- SQLX_OFFLINE=true cargo check -p ml --offline (43.68s) clean.
- SQLX_OFFLINE=true cargo build -p ml --release --offline
--features cuda (1m 30s) clean; cubin recompiled via nvcc.
- Pre-commit DtoD-via-pinned guard passes (the prereq commit
`4d966e62f` migrated `gpu_backtest_evaluator.rs`'s buffers to
MappedF32Buffer, eliminating the 5 `_via_pinned` callers that
had blocked any prior staging of this file).
Refs Fix 29 row #13. `feedback_no_partial_refactor` (single launcher
migrated alongside kernel signature change in one commit),
`feedback_no_functionality_removal` (PNL_VS_TARGET / PNL_VS_STOP
slots preserved — only their data source corrected; the audit's
"drop the slots" alternative explicitly rejected),
`feedback_no_hiding` (no fallback to z-normed reads remaining;
kernel either gets real raw_close or falls through to
`have_close=false` with `unrealized=0`, identical to pre-fix
smoke-test semantics where prices==NULL),
`feedback_no_cpu_compute_strict` n/a (zero new host-side compute),
`feedback_no_htod_htoh_only_mapped_pinned` already satisfied
(`prices_buf` is `MappedF32Buffer` post the prereq migration),
`feedback_trust_code_not_docs` (the kernel comment said
"raw_close from features buffer" for months — accurate-when-written
pre-Bug-1, stale-after-Bug-1; verify-against-code disambiguates).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Prerequisite for the deferred Fix 30 Stale-B kernel-side fix
(`backtest_plan_kernel.cu` raw_close source). The DtoD-via-pinned
pre-commit guard (`scripts/pre-commit-hook.sh::check_no_dtod_via_pinned`,
commit `5275932f4`) blocks any commit that stages `gpu_backtest_evaluator.rs`
against the file's 5 pre-existing `clone_to_device_*_via_pinned` callers
that landed before the guard. Stale-B has to stage this file (to thread
`prices_buf` into the `backtest_plan_state_isv` launcher), so the
migration must land first as its own atomic commit per
`feedback_no_partial_refactor`.
Migration scope. Single file, four buffer fields:
- prices_buf CudaSlice<f32> → MappedF32Buffer [n*max_len*4]
- features_buf CudaSlice<f32> → MappedF32Buffer [n*max_len*feat_dim]
- portfolio_buf CudaSlice<f32> → MappedF32Buffer [n*8] (kernel-mutated)
- window_lens_buf CudaSlice<i32> → MappedI32Buffer [n]
Init sites (lines ~651-664 post-edit). 4 `clone_to_device_*_via_pinned`
calls replaced with `MappedF32Buffer::new(host.len())` +
`write_from_slice(host)`. No memcpy_dtod_async + stream.synchronize()
pair at construction — mapped-pinned coherence makes the kernel see
host writes after the next stream-sync barrier.
Reset site (`reset_evaluation_state`, line ~1485 post-edit). In-place
`self.portfolio_buf.write_from_slice(&portfolio_init)` replaces the
prior buffer-replacement
`self.portfolio_buf = clone_to_device_f32_via_pinned(...)`. No alloc
churn per epoch; the device pointer stays stable across resets which
matches MappedF32Buffer's intended use.
Consumer sites (17 kernel arg passes). `arg(&self.X_buf)` →
`arg(&self.X_buf.dev_ptr)` so the launcher receives the device pointer
the kernel expects. Sites: launch_gather (×2), launch_gather_chunk,
launch_env_step, env_batch_kernel chunked path, plan_state_isv kernel,
metrics_kernel. CUdeviceptr (u64) is passed by reference exactly as
metrics_dev_ptr already does at the metrics launch site (~line 2497).
Kernel-mutated MappedF32Buffer precedent. portfolio_buf is mutated by
the env_step kernel every step. The same file's `plan_diag_buf` (a
MappedF32Buffer) is also kernel-written via dev_ptr (lines ~1230-1256)
and host-read via host_ptr — direct precedent. The IQN τ migration
(commit `facbf76eb`) confirms cuMemHostAlloc DEVICEMAP for kernel
reads. The mapped_pinned.rs module docstring states explicitly:
"Kernels write through dev_ptr (with __threadfence_system())".
What this change touches:
- crates/ml/src/cuda_pipeline/gpu_backtest_evaluator.rs
Field types (lines 299-321), init block (lines 641-665), reset
(lines 1462-1471), 17 kernel arg passes across 6 launchers.
- docs/dqn-wire-up-audit.md
Fix 30 Stale-B paragraph extended with the prereq commit summary.
Stale-B itself remains DEFERRED (kernel-side fix lands next).
Verification:
- SQLX_OFFLINE=true cargo check -p ml --offline (44.38s) clean.
- SQLX_OFFLINE=true cargo build -p ml --release --offline
--features cuda (53.78s) clean.
- grep -n "clone_to_device_.*_via_pinned\|upload_.*_via_pinned"
crates/ml/src/cuda_pipeline/gpu_backtest_evaluator.rs returns
zero hits.
- grep -n "self\.\(prices\|features\|window_lens\|portfolio\)_buf"
shows every kernel-arg site followed by `.dev_ptr`. The only
non-`.dev_ptr` references are the field declarations, the
constructor moves into `Self { ... }`, and the
`write_from_slice` calls in `reset_evaluation_state`.
- Pre-commit DtoD-via-pinned guard now passes on staging this file.
Eliminates the last 5 `_via_pinned` callers in
`gpu_backtest_evaluator.rs`. Per
`feedback_no_htod_htoh_only_mapped_pinned`, `feedback_no_partial_refactor`
(every consumer of a field-type change migrates in one commit),
`feedback_no_hiding` (no `--no-verify`; the migration IS the fix the
guard is asking for).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes Fix 29 audit row #18. The synthetic-data overlay kernel
`phantom_liquidity_gbm` in `dqn_utility_kernels.cu:1050-1096` was
flagged ❓ Ambiguous because its writer wrote `log_ret` to
`market_features[bar*market_dim + 0]` and `+3` — the WRITER's
downstream consumer contract was unverifiable post Bug 1 (commit
`5a5dd0fed`) which redefined feature index 0 from raw log-return to
z-normed log-return.
Investigation result: zero callers in the entire codebase. The audit
grep `grep -rn "phantom_liquidity_gbm" crates/ml/src/ services/
crates/ bin/` returns ONLY the kernel definition itself — no
`load_function`, no `launch_builder`, no Rust-side launcher. The
kernel has been compiled but never invoked since at least early 2026.
Resolution: delete the kernel definition and replace with an
explanatory comment block. Per `feedback_no_hiding` an orphan kernel
with an ambiguous post-Bug-1 contract is exactly the failure mode the
rule warns against — a future re-wirer would have written
synthetic z-normed log-returns into a slot the production pipeline
expects raw log-returns at, re-introducing the very Bug-1 drift the
audit was triaging. Per `feedback_wire_everything_up` a kernel that
compiles but is unconsumed is either wired in the same commit or
deleted; this kernel was never wired since its writer existed.
The replacement comment block (23 lines) documents the design intent
(GBM-based synthetic-data augmentation) so any future re-introduction
has the spec available, plus the re-introduction conditions:
caller wiring must land in the same commit, and the writer/consumer
contract for `market_features[..+0]` (z-normed vs raw log-return)
must be explicit at the kernel boundary.
What this change touches:
- crates/ml/src/cuda_pipeline/dqn_utility_kernels.cu:1037-1096
47-line kernel definition + ══ comment header deleted; 23-line
DELETED notice replaces it. Net -24 lines.
- docs/dqn-wire-up-audit.md
Fix 30 Ambiguous-A row appended with the dead-code-deleted
resolution. Stale-B deferral note also added (separate paragraph)
documenting the pre-existing `_via_pinned` guard block requires a
dedicated `gpu_backtest_evaluator.rs` migration commit before the
Stale-B kernel-side fix can land.
Verification:
- SQLX_OFFLINE=true cargo build -p ml --release --offline
--features cuda (1m 30s) clean; cubin recompiled via nvcc.
- Pre-commit guards pass.
- Final grep for `phantom_liquidity_gbm` returns only the comment
block in the kernel file.
Refs Fix 29 row #18 deferred follow-up. `feedback_no_hiding`
(delete orphans, do not leave them as ambiguous landmines),
`feedback_wire_everything_up` (every module/feature/kernel built
must be wired to a production path or removed),
`feedback_no_functionality_removal` does NOT apply: a kernel with
zero callers is not a functional feature, and the audit doc retains
the design intent so any future re-introduction can rebuild the
mechanism with the correct post-Bug-1 contract.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes Fix 29 audit row #12. Pre-fix, `scripted_policy_select` read
`state[MARKET_START]` as `close_now` and computed
`recent_ret = (close_now - prev_close) / prev_close`. Post Bug-1
(commit `5a5dd0fed`) `state[MARKET_START]` is z-normed log-return at
the WRITER, not raw_close, so the formula mixed two unrelated signals
(z-normed return vs dollar price). The seed-phase MOMENTUM /
MEAN_REV / VWAP_DEV branches degenerated to noise-floor below the
±0.0001f cutoffs, leaving 60% of seed-phase episodes (the non-UNIFORM
20%+20%+20%) effectively in DIR_HOLD instead of expressing the
intended scripted-policy diversity.
Resolution: route raw_close from the same fxcache target buffer the
env_step kernel reads from. Kernel signature gains
`const float* targets`, `const int* episode_starts`, `int t`,
`int total_bars` parameters. Per-thread `bar_idx = episode_starts[i]
+ t` (matching `experience_kernels.cu:1769`'s indexing convention),
then `close_now = targets[bar_idx*6 + TARGET_RAW_CLOSE]`. Bounds-clamp
to `[0, total_bars-1]` mirrors env_step's out-of-bounds early-return.
Sites fixed:
- crates/ml/src/cuda_pipeline/scripted_policy_kernel.cu
Kernel signature extended; close_now read source switched;
`FXCACHE_TARGET_STRIDE` / `FXCACHE_TARGET_RAW_CLOSE` mirrored as
#defines (kernels can't import Rust constants; co-locating the
literals in a comment-block keeps the cross-language contract
visible at the call site for any future TARGET_DIM bump). The
previous `bar_idx` parameter renamed `t`; the LCG seed now mixes
per-thread `bar_idx = episode_starts[i] + t` instead of the
per-step `t` — stronger entropy across episodes, no behavioural
regression (UNIFORM policy still produces 4-direction uniform).
- crates/ml/src/cuda_pipeline/gpu_experience_collector.rs:~3735
Single launcher updated to pass `&targets_buf.dev_ptr`,
`&self.episode_starts_buf`, `t as i32`, and `total_bars` (already
in scope from line 3301). Inline comment explains Bug-1 origin.
Migration scope per `feedback_no_partial_refactor`: single launcher;
no other call sites. Verified via
`grep -rn scripted_policy_select crates/ml/src/`. NO new `PS_*` slot
or `PORTFOLIO_STRIDE` bump required — the targets buffer is the
canonical raw_close source and routing it directly avoids cascading
through the ~12 PORTFOLIO_STRIDE consumers (kelly_cap_update_kernel,
trade_stats_kernel, gpu_experience_collector, ml-core mirror, etc.).
This is the "route raw_close directly" branch of the audit's contract
decision; the alternative "add an extra state slot" branch was
explicitly rejected as cascade-heavy for a seed-phase-only signal.
Verification:
- SQLX_OFFLINE=true cargo check -p ml --offline (43.87s) clean.
- SQLX_OFFLINE=true cargo build -p ml --release --offline
--features cuda (1m 30s) clean; cubin recompiled via nvcc.
- No host-side compute added; all reads on GPU.
- `targets_buf` is mapped pinned by upstream caller (per
`feedback_no_htod_htoh_only_mapped_pinned`).
Refs Fix 29 row #12. `feedback_no_partial_refactor` (single launcher
migrated in same commit), `feedback_no_functionality_removal`
(`recent_ret` signal preserved — only its data source is fixed; the
CUSUM-substitution alternative path explicitly rejected because the
recent_ret signal IS the scripted-policy contract, not an
implementation accident), `feedback_no_hiding` (no fallback to
z-normed-log-return reads; kernel either gets real raw_close or
clamps to total_bars-1 boundary), `feedback_no_cpu_compute_strict`
n/a (zero new host-side compute), `feedback_trust_code_not_docs` (the
kernel comment said `state[MARKET_START + 0] = close_now` for months
— accurate-when-written, stale-after-Bug-1; verify-against-code
disambiguates).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes Fix 29 audit rows #14 and #15 (Bug-1 contract drift in val/HPO
close-price extraction). Both sites read `target[0]` thinking it is
raw_close, but post Bug-1 (commit `5a5dd0fed`) `target[0]` is
preproc_close (z-normed log-return). The `fv[3]` fallback path is
unreachable on every production code path because
`set_val_data_from_slices` (in `dqn/trainer/mod.rs:1704`) always yields
`Vec<f64>` of length 6 from `[f64; 6]` slices post `TARGET_DIM=6` bump
(commit `063fd2716`), so `target.len() >= 2` is an always-true guard.
Per `feedback_no_hiding` the dead fallback is removed in the same edit
rather than left as a silent wrong-units path.
Sites fixed:
- crates/ml/src/trainers/dqn/trainer/metrics.rs:576
(val window_prices for GpuBacktestEvaluator)
- crates/ml/src/hyperopt/adapters/dqn.rs:2492
(HPO adapter val_close_prices for window-aggregated backtest)
Both now read `target[TARGET_RAW_CLOSE]` (col 2). Both import the named
constant from `crate::fxcache` so a future column rename moves the call
site with the writer (Fix 27 prevention pattern).
Verification:
- SQLX_OFFLINE=true cargo check -p ml --offline (8.03s) clean.
- No GPU code changed; cubin not affected.
Affects val Sharpe annualization + window equity curves on training
metrics; affects HPO val score on every trial. Pre-fix would yield
"prices" of magnitude ~stddev(log_return) (~7e-5 for ES 1-min) feeding
into PnL math that expects dollar prices, producing degenerate
backtest output. Post-fix prices are real raw_close values.
References Fix 27 Bug B (host-side Welford) — same kind of bug surfaced
at val/HPO consumer rather than training Welford. References
feedback_no_hiding (delete unreachable fallbacks rather than leaving
silent wrong-units fall-through), feedback_no_partial_refactor (both
consumers of the same (fv, target) tuple convention migrate together),
feedback_trust_code_not_docs (the `target.len() >= 2` guard read as
defensive but was masking a contract drift).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The kernel block at experience_kernels.cu:698-704 divided
market_features[0..3] by vol_normalizer at runtime — designed for the
pre-Bug-1 pipeline where features arrived as RAW log returns (~±0.001).
After Bug 1 fix (commit 5a5dd0fed) moved z-normalization to the WRITER
(precompute_features.rs::NormStats::normalize_batch before fxcache write,
plus data_loading.rs DBN-fallback path applying the same op), features
arrive already-z-normalized. The runtime division then created a
1000-13000× DOUBLE NORMALIZATION inflating column 0 of next_states to
raw-price magnitude.
DIAG_AUX_LABEL diagnostic ground truth (production train-multi-seed-bn42w):
- features_raw_cuda col 0 mean_abs = 0.443 (clean z-norm at SOURCE)
- aux_nb_label_buf mean_abs = 5398 (= 0.443 × inv_vol ~ 13245)
- ratio matches 1 / vol_normalizer for ES 1-min realised vol ~7.5e-5
This bug caused label_scale=5481 in 50-epoch validation (cancelled
train-multi-seed-bn42w) while smoke ran with smaller window producing
smaller inv_vol → label_scale ~25-432. Both wrong, just different
inflation factors.
What changed:
- experience_kernels.cu:698-704 block deleted; replaced with header
comment explaining why. Kernel parameter `vol_normalizer` retained
in signature with `(void)vol_normalizer;` to silence the
unused-warning — removing the param would cascade through
gpu_experience_collector.rs config struct + launcher + per-epoch
Welford in training_loop.rs (60 lines). Bounded scope: leave the
pipe wired, gut the consumer.
- DIAG_AUX_LABEL diagnostic removed per its Fix 28 removal gate
(gpu_dqn_trainer.rs ~12981 diagnostic block ~165 lines + the
DIAG_AUX_LABEL_SOURCE_PTRS OnceLock static ~22 lines +
training_loop.rs populate site ~22 lines).
- Audit doc Fix 29 entry with audit results + open follow-ups.
Bug-1 contract audit (this commit's exhaustive re-check, 18 sites
classified):
- 1 ⚠→✅: experience_kernels.cu:698-704 (this fix)
- 13 ✅: env-step kernel body, mirror universe, feature mask/noise,
target reads at col 2 raw_close (Fix-27 already correct), DT
rewards kernel, curriculum/hindsight/portfolio_sim kernel target
reads, kernel header docs, PS_PREV_CLOSE state-layout slot
- 4 ⚠ Stale (deferred — separate triage commits):
* scripted_policy_kernel.cu:59-65 — seed-phase momentum reads
state[MARKET_START] as raw_close, but post-Bug-1 it is z-normed
log-return. Affects seed-phase scripted policy quality only.
* backtest_plan_kernel.cu:77-100 — val plan_isv reads
features[bar*feat_dim+0] as raw_close. Corrupts val plan_isv
slots [PNL_VS_TARGET]/[PNL_VS_STOP].
* metrics.rs:576 — val_data → window_prices reads target[0] as
close (clones Fix-27 Bug B at host-side; affects val Sharpe).
* hyperopt/adapters/dqn.rs:2492 — same target[0] pattern in HPO
val_close_prices.
- 1 ❓ Ambiguous: dqn_utility_kernels.cu:1089-1093 synthetic feature
overlay; needs downstream-consumer contract verification.
Verification:
- SQLX_OFFLINE=true cargo check -p ml --offline (47.87s) clean.
- SQLX_OFFLINE=true cargo build -p ml --release --offline
--features cuda (1m 30s) clean; cubin recompiled via nvcc.
- Next L40S production run should show label_scale ~0.8 (matching
kernel docstring expectation).
Refs: DIAG_AUX_LABEL diagnostic from Fix 28 in dqn-gpu-hot-path-audit.md
(commit 2683d4637) which captured the ground truth that pinned this
bug. Cancelled validation runs train-multi-seed-p5qzw (label_scale=808)
and train-multi-seed-bn42w (label_scale=5481) both blocked on this —
Fix 27 cleared the host-side variant (Welford reading target[0] as
raw_close); this Fix 29 closes the kernel-side variant. Bug 1 chain
(label_scale=5443 from 4-month-old #193) closes here.
feedback_trust_code_not_docs (the kernel comment said `#13 Vol
normalization` for months — accurate-when-written, stale-after-Bug-1).
feedback_no_partial_refactor does not apply because the kernel
parameter is retained as a no-op, deliberately leaving the
launcher/config-struct contract intact while the consumer is gutted.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Production training run train-multi-seed-bn42w showed label_scale=5481
(raw_close magnitude) at epoch 4 vs smoke's ~25 at the same commit
29b1d34c6. The 5-layer data-loading defense + DBN spread filter + target
stride/column fix all in place — yet column 0 of next_states_buf still
sees raw-price-magnitude values in production but not in the
multi_fold_convergence test path.
This one-shot diagnostic fires once at the first training batch and
prints:
- aux_nb_label_buf stats (the kernel input; should be ~0.8 z-norm)
- next_states_buf col 0 sample (what strided_gather reads)
- features_raw_cuda col 0 sample (the source feature buffer)
- targets_raw_cuda col 2 sample (raw_close — the suspected leak)
- Verdict line interpreting the 4 stats
Three numbers will pin the source. If aux_buf ~5500: raw_close leaked
into next_states. If features_raw_cuda col 0 ~5500: the writer didn't
normalize. If targets_raw_cuda col 2 ~5500 but aux_buf ~0.8: only
production reads raw_close, smoke doesn't.
One-shot via static AtomicBool. Pre-graph-capture, no perf impact.
Removal gate: delete once the leak source is identified and fixed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two latent bugs converged in the cancelled 50-epoch run
(train-multi-seed-p5qzw at 96769d171, label_scale=808 vs smoke
baseline 22-28):
Bug A (latent since 063fd2716, 2026-04-19): TARGET_DIM was bumped 4→6
in fxcache (added raw_open at col 4 + mid_price_open at col 5), but
N consumer kernels in experience_kernels.cu + dt_kernels.cu hardcoded
stride 4 when indexing targets[bar*4+col]. Reading at the old stride
against the stride-6 buffer slid every lookup into the wrong bar's
data. Smoke harness paths (multi_fold_convergence) didn't exercise
expert_action_override / compute_difficulty_scores / hindsight_relabel
heavily; production 368k-bar run surfaced the drift via the
compounded label_scale = 30× expected magnitude.
Bug B (introduced today at 5a5dd0fed, 2026-05-02): the Bug 1 fix
changed targets[0] from raw_close to log-return-normalized
preproc_close. training_loop.rs::epoch_vol_normalizer's Welford pass
still read targets[0] expecting raw_close → output was
ln(log_return/log_return) ~ stddev 0.6 → triggered sanity-band warning
+ default fallback (5e-4); but downstream label_scale consumers fed
the corrupt value through.
Sites fixed:
HOST (1 site):
- training_loop.rs:570-573, :603 — w[i].1[0] → w[i].1[TARGET_RAW_CLOSE]
+ warning message updated
GPU (5 sites in experience_kernels.cu):
- line 3768 — kernel param doc OHLCV → fxcache TARGET_DIM=6
- lines 3806-3808 — bar*4+3 → bar*6+2 (raw_close column)
- lines 3974-3975 — i*4+2 → i*6+2 (stride-only)
- lines 4015, 4020 — bar*4+2 → bar*6+2 (stride-only)
- lines 3400-3404 — t_offset = global_idx*4 → *6 (stride-only)
- lines 1553-1561 — kernel header doc updated to 6-column layout
GPU (1 site in dt_kernels.cu):
- line 793 — kernel param doc OHLC → fxcache TARGET_DIM=6
- lines 803, 807 — i*4+3 → i*6+2 (raw_close col 2)
HOST docstring (decision_transformer.rs:1049) — [num_bars, 4]
→ TARGET_DIM=6 with reference to fxcache constant module.
Structural prevention: 6 named column constants
(TARGET_PREPROC_CLOSE / TARGET_PREPROC_NEXT / TARGET_RAW_CLOSE /
TARGET_RAW_NEXT / TARGET_RAW_OPEN / TARGET_MID_OPEN) added to
crates/ml/src/fxcache.rs co-located with the existing TARGET_DIM
(promoted from private to pub). Co-locating in the contract-owner
module means future renames or column adds force every consumer to
update at the same call site. Compile-time density test asserts
columns are dense and exhaustive. Host-side consumer training_loop.rs
imports TARGET_RAW_CLOSE; GPU kernels reference the constant module
in comments + use literal stride 6 with a header block documenting
the contract (kernels can't import Rust constants).
PPO consumer NOT in scope: ppo_experience_kernel.cu reads at stride 4
but PPO has its own set_raw_market_data path uploading 4 columns from
Vec<f64>. PPO write/read pair is internally consistent at stride 4,
unaffected by fxcache stride bump. Production train_baseline_rl.rs
flow doesn't invoke set_raw_market_data, so PPO GPU collector is
currently orphaned. Consolidating PPO onto fxcache target buffer is a
separate refactor.
Verification:
- SQLX_OFFLINE=true cargo check -p ml --offline clean
- cargo build -p ml --release --offline --features cuda clean
(cubin compiles via nvcc; release build under 2 min)
- cargo test -p ml --lib -- target_layout 1/1 pass
(target_columns_dense_and_exhaustive)
- audit grep "targets[var * 4 +]" returns ZERO hits in production
- re-run of train-multi-seed-p5qzw will show label_scale ~22-30
(not 808) — gating production validation
Refs: cancelled train-multi-seed-p5qzw at 96769d171, 50-epoch
validation blocker. Bug origins: 063fd2716 (target_dim 4→6 bump) and
5a5dd0fed (Bug 1 column-0 semantic fix). feedback_no_partial_refactor
(every consumer of shared buffer contract migrates in same commit),
feedback_trust_code_not_docs (kernel doc OHLCV/OHLC strings stale
post-bump), feedback_no_quickfixes (proper structural fix not
one-line patch), feedback_wire_everything_up (column constants land
co-located with fxcache::TARGET_DIM so writer + caller share single
contract module).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Plan task #296. Pearl 7 was an INVESTIGATION task in the SP5 brainstorm:
the pre-SP5 50-epoch baseline (train-multi-seed-cv2mw, F0 epochs 4-9)
showed intent_dist freezing at exact Bin(2, 0.5) ratios (0.25/0.50/0.25),
suggesting a hidden binary action decomposition somewhere downstream.
The plan §C4 closure rule: if post-SP5 smokes show intent_dist drifting
normally (no freeze), Pearl 7 closes with no code changes.
Verdict from 3 retained SP5-era smokes: intent_dist drifts smoothly each
epoch. No Bin(2, 0.5) freeze observed at:
- smoke-test-ks2wf (post-spread-filter, 5845e4403)
- smoke-test-7pv9v (Layer D additive, f42b5fff8)
- smoke-test-w9nsw (D4 atomic, 2e9e276a0)
(smoke-test-cnlrw (sanitize-only, 8434737a6) cached log was pruned
before evidence-collection; 3 retained smokes sample post-spread-filter
and full Layer D production paths and decisively satisfy the closure
rule on their own.)
Likely cause: SP5 Layer A's per-branch parameter lifting (C51 atom span,
NoisyNet σ, IQN τ schedule, loss budgets, Adam β/ε, Kelly floors) added
enough independent variability at every shared site that no single
2-state decomposition can dominate intent_dist in steady state.
What lands:
- docs/dqn-wire-up-audit.md Pearl 7 closure entry
- memory/pearl_intent_dist_freeze_resolved.md (new)
- memory/MEMORY.md Topic Files Index entry
No code changes. No follow-up spec opened. The escalation trigger
(re-freeze for ≥3 consecutive epochs in a future run) is documented
in the audit entry.
Closes plan task #296.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires the 3 Layer D producer kernels into the production hot path AND
removes the host-side EMA arithmetic for sharpe/max_dd/low_dd_ratio in
the same commit per feedback_no_partial_refactor + feedback_no_cpu_compute_strict.
Sites migrated (host → GPU kernel + ISV slot):
training_sharpe_ema → launch_training_metrics_ema → ISV[294]
max_dd_ema → launch_training_metrics_ema → ISV[295]
low_dd_ratio → launch_training_metrics_ema → ISV[296]
LearningHealth.compose → launch_health_composition → ISV[290..294)
trade-PnL aggregation → launch_sp5_pnl_aggregation → ISV[286..290)
Behavior preserved within float precision: every EMA β decay constant,
warmup/clamp wrapper, and downstream consumer formula migrates verbatim.
The kernels reproduce the host computations bit-for-bit (verified by the
GPU-gated unit tests landed in D1/D2/D3 at f42b5fff8 and the D1-rewrite
re-verification at 66f7e64d1; smoke-test-7pv9v PASSED with the additive
kernels loaded but unwired). The additional Pearl A+D smoothing layer
(ALPHA_META=1e-3) is the SP5 architectural change the entire Layer D
programme commits to (cf. pearl_first_observation_bootstrap +
pearl_wiener_optimal_adaptive_alpha).
Removed: host-side EMA arithmetic at training_loop.rs:5043-5099 (~57
lines covering max_dd α=0.1 + low_dd_ratio α=0.15 + training_sharpe
adaptive-α + sentinel branches). Struct fields self.training_sharpe_ema,
::_initialized, self.max_dd_ema, self.low_dd_ratio are KEPT because
external consumers exist (HEALTH_DIAG emit at training_loop.rs:3899,
adaptive-DSR aux-weight controller at 3772, smoke tests at
td_propagation.rs:126/135/155 + generalization.rs:102/103, registry log
emit at 6646); they now hold ISV-Pearl-smoothed values populated by
read_isv_signal_at(294/295/296) after the kernel chain completes.
Also added: GpuDqnTrainer::synchronize_isv_stream() — public cold-path
stream-sync helper at gpu_dqn_trainer.rs:~18475. Single cuStreamSynchronize
of the training stream, mirroring the existing per_branch_q_gap_ema()
embedded sync. Used once per epoch by D4's read-back path.
Out of scope (deferred to D5):
- HealthEmaTrackers::update host-side α=0.1 EMA (metrics.rs:23-25):
produces D2's inputs; D2's launcher takes already-EMA'd scalars.
Eliminating this needs a 4th kernel; out of D4 scope.
- LearningHealth::update warmup wrapper + [0.2, 0.95] clamp
(learning_health.rs:114-124): may have non-DQN consumers (PPO, eval);
deferred to a separate refactor.
- compute_epoch_financials per-bar equity walk: stays as host-side
input source for D1; D1 reproduces it on GPU as a PARALLEL producer
publishing to ISV.
Verification:
- cargo check + build clean
- sp5_isv_slots + state_reset_registry unit tests 8/8 pass
- cargo test -p ml --lib: 933 pass / 14 fail (identical to pre-D4
baseline; failing tests are pre-existing GPU-context-required tests,
not regressions)
- `git grep "= EMA_BETA *|= (1.0 - EMA_BETA)"` returns 0 (was already
0 — gate is a no-op for SP5 because production uses literal
coefficients, not a named EMA_BETA constant). Meaningful gate
`git grep "0.9 \* self.max_dd_ema|0.85 \* self.low_dd_ratio"` also
returns 0 — confirms host EMA arithmetic deletion.
- Order-of-ops: launches chained on training stream before consumer
reads; stream-event sync only (synchronize_isv_stream once per epoch
for cold-path host scalar refresh; producer→consumer paths on the
same stream observe FIFO order without explicit fence).
Mapped-pinned discipline (per feedback_no_htod_htoh_only_mapped_pinned):
D1's step_returns + done_flags consumed via fresh MappedF32Buffer
allocations populated by host_slice_mut — no HtoD copy. Once-per-epoch
cold-path; matches existing pattern at training_loop.rs:1318.
L40S smoke validation deferred to next dispatch — D4 is structurally
risky enough (HEALTH_DIAG visibility behaviour change + ISV-Pearl-
smoothing on host-scalar reads + first-epoch cold-start interaction
with Pearl A) to validate separately. Closes feedback_no_cpu_compute_strict
sweep for SP5 scope (modulo D5 follow-up).
Refs: SP5 plan §D Task D4. Builds on D1-rewrite (66f7e64d1), D2
(e49756ac9), D3 (f42b5fff8). First D4 attempt was blocked by D1
per-trade vs per-bar mismatch; resolved by D1-rewrite.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The original D1 kernel (commit 5ee795f14) was authored against a brief
that assumed per-trade event arrays exist in production. They don't.
Production has per-bar step_returns + done_flags with episode-boundary
resets, plus already-aggregated summary scalars (sum_returns,
sum_sq_returns) on TradeStats. The previous D4 agent found this
mismatch as a structural blocker and stopped before any code changes.
This rewrite fixes the kernel internals to match compute_epoch_financials
in financials.rs bit-for-bit. The slot allocation (ISV[286..290) for
PNL_TOTAL/MEAN/VAR/MAX_DD), Pearls A+D chain, and reset registry are
unchanged — only the kernel interface and max_dd internals shift.
What changed:
- pnl_aggregation_kernel.cu: full rewrite. New signature consumes
step_returns[N], done_flags[N], num_bars, n_trades, sum_returns,
sum_sq_returns, initial_capital. pnl_total uses log-space
compounded growth (financials.rs:80-97). pnl_mean/pnl_var are
per-trade (financials.rs:122-124). pnl_max_dd implements per-bar
equity walk over last 10K bars with reset at done_flags > 0.5
AFTER processing the bar's return (matches financials.rs:163-194
line-by-line, including 1.0 cap).
- launch_sp5_pnl_aggregation: signature updated to match. 2
MappedF32Buffers + 5 i32/f32 scalars instead of 3 mapped-pinned
buffers + 1 count. Same Pearls A+D chain on the same stream.
- sp5_isv_slots.rs: PNL slot docstring updated to reflect the actual
output semantics (slot constants unchanged).
- SCRATCH_PNL_AGG_BASE docstring + cubin static docstring + field
docstring updated.
- sp5_producer_unit_tests::pnl_aggregation_kernel_correctness:
rewritten with new oracle. Inputs cover an episode boundary at
bar 2 so the reset semantics are observable; expected values
derived analytically from the host formula (no CPU oracle in the
test process, per feedback_no_cpu_test_fallbacks).
- Audit doc: D1-rewrite entry supersedes original D1 entry, with a
line-by-line formula provenance table for D4 reviewers.
Unchanged: ISV slot allocation (sp5_isv_slots.rs constants),
SP5_SLOT_END/SP5_PRODUCER_COUNT/ISV_TOTAL_DIM, wiener offsets,
state_reset_registry arm + dispatch, build.rs cubin registration.
The kernel filename stays the same; only the file contents change.
Formula fidelity provenance (financials.rs as the oracle):
- pnl_total: lines 80-97 (log-space sum, 1e-10 floor, exp − 1)
- pnl_mean: line 122 (per-trade sum_returns / n_trades)
- pnl_var: lines 123-124 (per-trade E[X²] − E[X]², .max(0))
- pnl_max_dd: lines 163-194 (10K window, post-update reset, 1.0 cap)
Tests: cargo check + cargo build --features cuda clean; ISV slot +
state_reset_registry tests pass (8/8 unchanged); rewritten GPU
correctness test fires on next L40S smoke.
This unblocks D4 atomic wiring (D1+D2+D3 into the production hot
path with host-EMA removal). D4 dispatch resumes once this lands.
Refs: SP5 plan §D Task D1 + the structural blocker investigation by
the prior D4 agent (no commit; investigation reported up).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Third of 3 Layer D producer kernels. Replaces host-side training_sharpe_ema,
max_dd_ema, low_dd_ratio updates (host-side EMAs in training_loop.rs) with
a fused GPU kernel chained through apply_pearls_ad_kernel. Per
feedback_no_cpu_compute_strict.
Note: agent investigated training_loop.rs and found the third metric is
low_dd_ratio (not gamma_blend as the original plan brief named). The
authored kernel reproduces the actual host-side EMA triplet present in
the codebase.
Additive only — no consumer wiring, no behavior change. The kernel +
launcher are loaded into GpuDqnTrainer and the slots are reserved on the
ISV bus, but the host-side updates continue to run unchanged. D4 (atomic
Layer D commit) wires this and D1+D2 to call sites in the same atomic
refactor per feedback_no_partial_refactor. Also note: training_loop.rs
gains two state-reset-registry dispatch arms (sp5_health_composition for
D2 + sp5_training_metrics_ema for D3) — registry plumbing required by
the new entries, NOT consumer wiring of the kernels themselves; same
pattern as SP5 Layer A bug-fix #281.
What this lands:
- training_metrics_ema_kernel.cu (single-block 3-thread fused EMA)
- Rust launcher launch_training_metrics_ema()
- 3 new ISV slots (TRAINING_SHARPE_EMA_INDEX..LOW_DD_RATIO_INDEX, 294..297)
- ISV_TOTAL_DIM 294 → 297, SP5_PRODUCER_COUNT 120 → 123 (linear span)
- LAYOUT_FINGERPRINT_SEED bump (auto via slot string)
- StateResetRegistry entries for D2 (sp5_health_composition) + D3
(sp5_training_metrics_ema) with reset_named_state dispatch arms
- build.rs cubin registration
- GPU-gated unit test in sp5_producer_unit_tests.rs (analytical EMA)
- SP5 contiguity slot test
training_metrics_ema_slots_contiguous_and_above_health_block
- Audit doc append
Formula fidelity: kernel reproduces the host-side EMA update for
sharpe/max_dd/low_dd_ratio bit-for-bit within float precision. β decay
constants and any warmup/clamp logic migrate as Invariant 1 anchors with
no algorithmic change. Verified by unit test asserting kernel output
matches an analytical EMA sequence within 1e-6 rel-err.
Tests: cargo check + cargo build clean; ISV slot + state_reset_registry
unit tests pass (8/8 incl. new contiguity check); GPU correctness test
fires on next L40S smoke.
Refs: SP5 plan §D Task D3, builds on D1 (5ee795f14) + D2 (e49756ac9).
Layer D additive infrastructure complete after this commit; D4 (atomic
5-site host-EMA → GPU migration) is next.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Second of 3 Layer D producer kernels. Replaces multi-step host arithmetic
in LearningHealth composition (q_gap_ema + q_var_ema + grad_norm_ema →
composed health score) with a fused GPU kernel chained through
apply_pearls_ad_kernel. Per feedback_no_cpu_compute_strict.
Additive only — no consumer wiring, no behavior change. The kernel +
launcher are loaded into GpuDqnTrainer and the slots are reserved on the
ISV bus, but the host-side composition continues to run unchanged. D4
(atomic Layer D commit) wires this and D1+D3 to call sites in the same
atomic refactor per feedback_no_partial_refactor.
What this lands:
- health_composition_kernel.cu (single-block fused composition)
- Rust launcher launch_health_composition()
- 4 new ISV slots (HEALTH_SCORE_INDEX..GRAD_NORM_NORM_INDEX, slots 290..294)
- ISV_TOTAL_DIM 290 → 294, SP5_PRODUCER_COUNT 116 → 120 (linear span)
- LAYOUT_FINGERPRINT_SEED bump (auto via slot string)
- StateResetRegistry entries (sentinel 0.0; per-fold reset enabled)
- build.rs cubin registration
- GPU-gated unit test in sp5_producer_unit_tests.rs (formula fidelity)
- Audit doc append
Formula fidelity: kernel reproduces the host-side LearningHealth::compose
(or equivalent) computation bit-for-bit within float precision. Migration
is structural only — no algorithmic change. Verified by unit test
asserting kernel output matches a Rust copy of the host formula within
1e-6 rel-err.
Tests: cargo check + cargo build clean; ISV slot + state_reset_registry
unit tests pass; GPU correctness test fires on next L40S smoke.
Refs: SP5 plan §D Task D2, builds on D1 (5ee795f14).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First of 3 Layer D producer kernels. Replaces host-side trade-PnL
aggregation loop in training_loop.rs with a GPU kernel chained through
apply_pearls_ad_kernel for smoothing. Per feedback_no_cpu_compute_strict.
Additive only — no consumer wiring, no behavior change. The kernel +
launcher are loaded into GpuDqnTrainer and the slots are reserved on the
ISV bus, but the host-side aggregation continues to run unchanged. D4
(atomic Layer D commit) wires this and the other two D2/D3 kernels to
call sites in the same atomic refactor per feedback_no_partial_refactor.
What this lands:
- pnl_aggregation_kernel.cu (single-block tree-reduce, no atomicAdd)
- Rust launcher launch_sp5_pnl_aggregation()
- 4 new ISV slots (PNL_TOTAL_INDEX..PNL_MAX_DD_INDEX, slots 286..290)
- ISV_TOTAL_DIM 286 → 290; SP5_PRODUCER_COUNT semantics formalised as
wiener-buffer linear-span (110 → 116; the unique-slot count diverged
from the linear span at D1 — pre-D1 they coincided by accident at the
Pearl 6 carve-out's introduction)
- LAYOUT_FINGERPRINT_FRAGMENT extended with PNL_* entries
- StateResetRegistry sp5_pnl_aggregation entry + dispatch arm
(sentinel 0.0; fold-reset; PnL is NOT cross-fold persistent unlike
Pearl 6 Kelly stats, so it takes the standard sentinel-bootstrap
path per pearl_first_observation_bootstrap)
- build.rs cubin registration
- GPU-gated unit test pnl_aggregation_kernel_correctness with
analytical ground truth (no CPU reference per
feedback_no_cpu_test_fallbacks)
- Audit doc append documenting D1 + the SP5_PRODUCER_COUNT semantic
clarification
Tests: cargo check + cargo build --release --features cuda clean;
ISV slot + state_reset_registry unit tests 6/6 pass (incl new
pnl_aggregation_slots_contiguous_and_above_kelly_block); GPU
correctness test fires on next L40S smoke alongside existing 17 SP5
producer unit tests.
Refs: SP5 plan §D Task D1, validated SP5 Layer A/B at 5845e4403.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>