Commit Graph

291 Commits

Author SHA1 Message Date
jgrusewski
136696d8b8 docs: full BF16 rewrite spec + plan — zero F32 on GPU
Spec: every CUDA kernel, every GPU buffer, every cuBLAS call → BF16.
37 HOT kernels + 11 WARM + 7 COLD = 55 total kernel files.
12 implementation tasks across 4 phases.

Phase 1: Foundation (buffer types, weight sets)
Phase 2: cuBLAS GemmEx BF16×BF16→BF16 (forward + backward)
Phase 3: Optimizer + loss kernels (Adam, C51, MSE, spectral norm)
Phase 4: Environment + auxiliary (experience, backtest, IQN, attention)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 20:42:37 +01:00
jgrusewski
be8f3310d5 feat: gradient stability + 9-agent audit bug fixes
Per-component gradient clipping:
- 2 new CUDA kernels (dqn_clipped_saxpy, dqn_clip_grad)
- CQL gradient isolated into separate scratch buffer
- Budget allocation: C51=70%, CQL=15%, IQN=10%, Ens=5%
- Dynamic budget — inactive components' share goes to C51

Spectral norm extended to all 10 weight matrices:
- Was trunk-only (W_s1, W_s2), now covers all heads
- 16 u/v power iteration buffers, batched GOFF sync-back
- Uniform sigma_max, end-to-end Lipschitz bounded

Bug fixes from 9-agent audit:
- Backtest episode reset: all 8 fields (was 5), max_equity updated before floor check
- gradient_clip_norm unified: 10.0 everywhere (was 10.0 vs 1.0)
- entropy_coefficient: Option<f64> → f64, single default 0.001
- Close price: unwrap_or(1.0) → direct indexing (no silent wrong rewards)
- step_count: only increments during training (was incrementing on inference)
- Quantile loss: single CUDA context (was 3×), silent fallbacks removed
- MaybeNoisyLinear: single-variant enum removed → direct NoisyLinear
- Budget fractions: exported as pub(crate) constants, referenced not hardcoded

Monitoring:
- Per-component gradient Prometheus gauges (C51 raw, combined)
- Diagnostic logging every 1000 steps

Tests: 7 new gradient budget tests, 1 gradient bounds smoke test
All 488 tests pass (359 ml-dqn + 129 ml)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 19:52:44 +01:00
jgrusewski
d256acb638 refactor: training kernel fully unified with trade_physics.cuh
Final 3 inline duplicates replaced with shared function calls:
- execute_trade(): notional cash model (was inline cash/position update)
- check_trailing_stop(): regime-adaptive trailing stop decision
- enforce_hold(): hold enforcement decision (action aliasing kept inline)

Training kernel now uses ALL 10 shared functions from trade_physics.cuh:
decode_exposure_index, compute_target_position, decode_order_type,
execute_trade, compute_tx_cost, enforce_hold, check_trailing_stop,
check_capital_floor, apply_margin_cap, update_hold_time

Zero inline duplicates remain. Both training and backtest kernels
use identical trade physics — no more train/eval mismatches.

Smoke test: Sharpe=4.89, 443 trades, no SIGSEGV.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 08:16:51 +01:00
jgrusewski
be65d8e5fc fix: hive findings — capital floor, dueling centering, metrics, CVaR objective
From 5-agent deep analysis:

Kernel fixes:
- Capital floor penalty: -1.0 → -10.0 (match reward range for C51)
- Add pre-trade capital floor check to training kernel (match backtest)
- Add tx cost to forced liquidation in both kernels
- Fix expected_q dueling centering: per-atom mean (was scalar mean)
- Fix Calmar: use exact full-window mean (was sampled for >4096 bars)
- Fix CVaR off-by-one: include VaR observation in Expected Shortfall
- Trailing stop: add vol_scale/trend_scale params to shared function
- Update reward v5 → v6 docstrings (12 occurrences)
- Fix annualization comment (sqrt(98280) not sqrt(252))

Rust fixes:
- CVaR penalty: additive → multiplicative discount on composite
  (prevents CVaR from dominating objective for undertrained models)
- Fix dd_threshold default mismatch (0.01 → 0.02 matching Default)
- Fix action entropy max_entropy (log2(3) → log2(9) for 9 actions)
- Fix Sortino denominator in financials.rs (N_negative → N_total)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 07:56:50 +01:00
jgrusewski
235503efe1 fix: shared trade physics, IQN arg swap, trailing stop, win_rate
- Upgrade compute_tx_cost: add spread_scale_override + Almgren-Chriss
  impact_scale = 1+sqrt(delta/max_pos) for both train and eval paths
- Wire training kernel to shared functions: replace 6 inline duplicates
  (decode, position map, order_type, tx_cost, capital floor) with
  trade_physics.cuh calls
- Fix IQN sample_taus_kernel: args 2-3 were swapped (seed/total)
- Add trailing stop to shared header + backtest kernel
- Fix win_rate test data: 6 instances used percentages (55.0) not
  ratios (0.55)
- Static analysis: 65 kernel launches audited (1 mismatch fixed),
  90+ buffers verified safe

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 00:47:34 +01:00
jgrusewski
94cf330dad docs: final fixes plan — 6 issues blocking H100 deployment
1. Backtest hold_time tracking + enforcement (train/eval mismatch root cause)
2. Document evaluator action masking strategy (Layer 2 in env_step)
3. Fix trial budget observer (shared AtomicUsize counter)
4. Dynamic CVaR threshold (0.05 / sqrt(bars_per_day))
5. Extract MIN_TRADES_DEGENERATE constant + fix stale test vectors
6. Integration test + local hyperopt validation

Root cause chain: broken trial budget → 21 evals → no hold in eval
→ NaN Sharpe → 1e6 penalty → "degenerate" result.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 01:06:28 +01:00
jgrusewski
6414f57e34 docs: eval cleanup spec + plan — remove dead 5-action path, fix train/eval mismatch
3 fixes: (1) Delete GpuActionSelector + branching_action_select (zero callers,
hardcoded 5 actions vs production 9), (2) Add hold enforcement to backtest
env_step kernel (same Layer 2 as training), (3) Dynamic trade insufficiency
threshold = max(window_bars / (min_hold * 20), 5).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 00:43:58 +01:00
jgrusewski
0b743c0f80 docs: plan to eliminate NVRTC — precompile all 25 CUDA kernels at build time
7 tasks: build.rs POC → parameterize #define → update launches → build all
→ replace runtime compilation → delete NVRTC infra → integration test.

Key insight: convert #define STATE_DIM/NUM_ATOMS to kernel params so each
kernel has ONE version regardless of model config. No multi-variant compilation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 23:58:30 +01:00
jgrusewski
d71bf5805e docs: trade lifecycle fix plan — address review feedback
- Fixed struct name: ExperienceCollectorConfig (not GpuExperienceCollectorConfig)
- Fixed max_pos scoping: moved declaration before action_select launch
- Fixed exiting_trade ordering: preliminary variable before trailing stop
- Documented hardcoded 5-action limitation in branching_action_select
- Zero Q-gap during hold periods (conviction meaningless when forced)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 23:02:39 +01:00
jgrusewski
2197db8472 docs: trade lifecycle fix spec — address review feedback
- Layer 1 now targets experience_action_select (GPU-fused training path)
  AND branching_action_select (backtest/fallback), not just the fallback
- Action masking covers both greedy AND random exploration paths
- Exposure index uses parameterized b0_size, not hardcoded 5 or 9
- Fixed end-of-episode variable name (total_bars, not timesteps_per_episode)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 22:53:13 +01:00
jgrusewski
3bd339b5a3 fix: backtest evaluator — correct annualization, window sizing, objective calibration
Root cause: backtest windows of 300K bars produced ±billions% returns via
multiplicative compounding, and sqrt(252) annualization was wrong for
1-minute bars.

Fixes:
- Window size capped to 10K bars (~25 trading days), evenly distributed
  across the full validation set (was clustered in first 6%)
- Annualization: configurable bars_per_day field in GpuBacktestConfig
  (default 390.0 for 1-min), produces sqrt(98280) ≈ 313.5
- tanh normalization recalibrated: Sharpe/5, Sortino/8 (was /2, /3)
- CVaR threshold scaled to per-bar: 0.003 with slope 1400 (was 0.05/200)
- VaR/CVaR strided sampling covers full window (was first 4096 only)
- financials.rs + ab_testing.rs: sqrt(252) → sqrt(98280) for consistency

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 19:43:26 +01:00
jgrusewski
70a9499f33 docs: config unification plan — single source of truth, 8 tasks 2026-03-25 09:01:12 +01:00
jgrusewski
07545a3df3 docs: reward v6 fixes plan 2026-03-25 01:49:53 +01:00
jgrusewski
a69174e99f fix: segment-based trade lifecycle + reversal P&L computation
- Trade detection now counts reversals (S100→L50) as completed segments
- old_pos_pnl saved before position update for correct reversal P&L
- realized_pnl writeback uses old position PnL on reversal bars
- 0% win rate persists — needs deeper investigation (likely tx cost interaction)

WIP: The trade_return formula produces correct sign for raw market moves,
but every trade still shows as a loss. Suspect tx costs on both entry AND
exit of each reversal segment exceed the 1-bar price movement.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 23:57:04 +01:00
jgrusewski
be2672596d docs: master plan — maximize all 25 DQN features for profitable ES trading
12 tasks covering:
- Reward v5: trade-aware hybrid (dense + sparse) with patience multiplier
- Dynamic trailing stop as environment physics (regime-adaptive)
- Activate 11 dormant features: IQN CVaR, HER, ensemble, DT, CQL, curiosity,
  count bonus, entropy, Kelly sizing, Q-gap conviction, CVaR action selection
- Three-phase training: behavioral cloning → online RL → DT refinement
- Ensemble consensus action selection with uncertainty-based sizing
- Full hyperopt search space (50+ dimensions)
- Smoke test validation: model must produce winning trades

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 22:00:45 +01:00
jgrusewski
825db90f23 feat: comprehensive DQN training pipeline overhaul — 16 bug fixes, MSE warmup, financial metrics
Major fixes:
- C51 v_range calibrated for reward v4 (±2.0, was ±25/±0.5)
- Wrong Flat index in Q-gap filter (qe[4]→qe[2] in branching_action_select)
- hold_time tracks total position duration (was only losing bars)
- Entropy coefficient wired to C51 backward kernel (0.001, was unwired)
- Count bonus wired to GPU action selection (per-branch UCB)
- Q-gap warmup ramp (0→threshold over 5 epochs, was static)
- IQN lambda gradient scaling (max_grad_norm × (1+lambda))
- PER beta annealing 4x faster (500 steps, was 2000)
- Reward normalization disabled (scrambled per-bar returns)
- Capital floor uses natural return (was hardcoded -1.0)
- Financial metrics pipeline: real per-trade GPU stats (was Trades=1)

New features:
- MSE loss CUDA kernel for C51 warmup phase
- Blended MSE→C51 loss with linear alpha ramp
- GPU trade_stats_reduce kernel for per-trade financial metrics
- TradeStats struct with real win/loss/PF from portfolio states
- Behavioral smoke test (Q-values, action entropy, trades)
- 50-epoch convergence test with anomaly detection
- c51_warmup_epochs in hyperopt search space (41D)

Dead code removed:
- portfolio_sim_kernel (150 lines CUDA)
- DSR/PnL/drawdown reward v2 computations
- 7 dead kernel params from env_step signature
- GpuPortfolioSimulator (never called)
- Reward normalization block + state fields

0 warnings, 0 errors, 1241 unit tests + 8 smoke tests pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:48:38 +01:00
jgrusewski
909650f2a1 plan: three-layer stable distributional loss architecture
Layer 1: Per-sample C51 loss clamp (MAX_CE=50) breaks PER feedback loop
Layer 2: Label smoothing (ε=0.01) on Bellman target prevents log(0)
Layer 3: IQN primary with fixed τ (QR-DQN style, CUDA Graph compatible)

5 tasks, each independently testable and committable.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 20:42:08 +01:00
jgrusewski
33d91cce5b spec: profitability roadmap — 11 findings from deep research
4 critical root causes fixed this session (stop-loss, dense shaping,
action aliasing, HFT objective weight). 7 remaining improvements
documented with priority order: three-phase hyperopt, behavioral
cloning warm start, curriculum learning, ensemble, multi-timeframe,
attention, Decision Transformer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 12:45:06 +01:00
jgrusewski
51037f60b8 spec: trading realism conformance — 7 real-market requirements
RTH/ETH cost differential, market impact (done), book depth fill quality,
macro events, weekend gap risk, margin utilization feature.
All configurable via TOML. We trade against real markets — simulation must match.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 09:35:55 +01:00
jgrusewski
1277e8d10e spec: dual distributional C51+IQN — CVaR position sizing + uncertainty gating
C51 for action selection (expected Q), IQN for risk quantification (CVaR).
Disagreement between C51 and IQN expected Q = uncertainty signal.
Architecture already 90% built — IQN head exists but output unused.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 09:05:22 +01:00
jgrusewski
98afee0a51 plan: 9-exposure action space + dual C51/IQN distributional architecture
Phase A: expand exposure 5→9 (25% steps, 81 factored actions)
Phase B: wire existing GpuIqnHead for CVaR position scaling —
C51 picks direction, IQN sizes the risk.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 09:03:19 +01:00
jgrusewski
739dd986bb spec: 9-exposure action space design — expand from 5 to 9 levels
25% step increments: {-100%, -75%, -50%, -25%, 0%, +25%, +50%, +75%, +100%}
Total factored actions: 81 (was 45). Branching Q-values: 15 (was 11).
Implementation after reward v2 H100 validation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 08:45:18 +01:00
jgrusewski
86863d72e6 plan: GPU composite reward implementation — 7 tasks
Task 1: CUDA kernel (8-component formula, PORTFOLIO_STRIDE=12)
Task 2: Config pipeline (DQNHyperparameters + TOML profiles)
Task 3: Experience collector (buffer alloc + kernel launch)
Task 4: Hyperopt adapter (31D→38D search space)
Task 5: Remove dead CPU reward code
Task 6: Integration test (smoke + hyperopt + GPU suite)
Task 7: H100 validation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:35:57 +01:00
jgrusewski
75885bccaf spec: address review — DSR formula, div-by-zero guards, stride constant
- DSR uses pre-update A/B values (Moody & Saffell correct)
- peak_equity/prev_equity init to initial_capital (not zero)
- Division-by-zero guards on drawdown and return calculation
- PORTFOLIO_STRIDE=12 constant replaces hardcoded 3 (7 locations listed)
- Remove use_dsr flag (w_dsr>0 implies enabled)
- RewardSection struct needed in training_profile.rs
- All TOML profiles use same [reward] section

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:30:35 +01:00
jgrusewski
530edd76b9 spec: no backward compat — composite reward is the only reward
Tests must match reality. All profiles use the full 8-component
composite reward. No legacy PnL-only fallback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:27:28 +01:00
jgrusewski
17382e9763 spec: GPU composite reward function — 8-component regime-adaptive design
DSR + normalized PnL + drawdown penalty + idle penalty + regime-adaptive
scaling + asymmetric loss + position-time decay + transaction costs.
All computed per-step in the CUDA kernel. Zero CPU involvement.

12 floats per-episode state, ~25 FLOPs per step, zero extra kernel
launches. 7 new hyperopt dimensions (Phase Fast fixed, Phase Full
searchable). Regime scaling from existing ADX/CUSUM features.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:25:37 +01:00
jgrusewski
43998a330a feat: two-phase hyperopt + backtest evaluator VRAM leak fix
Two-phase hyperopt splits 31D PSO search into sequential phases:
- Phase 1 (--phase fast, default): fix architecture to small network
  (hidden_dim=128, num_atoms=11), search learning dynamics (~15D).
- Phase 2 (--phase full): fix dynamics from Phase 1 JSON, search
  architecture (~5D). Halves dimensionality per phase → better convergence.
- Phase 1 output includes best_continuous_vector for Phase 2 consumption.

GpuBacktestEvaluator Drop impl: sync forked stream, destroy CUDA graph
and cuBLAS handles before CudaSlice buffers drop. Fixes 261MB/trial
VRAM leak on H100 hyperopt.

ml-core clippy fixes: hex literal, remove dead check_err drain,
unnecessary safety comment, unused OnceLock import.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 10:32:37 +01:00
jgrusewski
1ce22c7e9c docs: GPU segment tree spec + plan for O(log n) PER sampling
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 00:39:34 +01:00
jgrusewski
baf8308931 docs: training profile configuration system — spec + plan
TOML-based per-model training profiles replacing hardcoded hyperparameters.
8 config files (DQN/PPO/supervised × production/smoketest + hyperopt + walk-forward).
3-tier loading: env var > filesystem > embedded defaults.
Full CLI coverage for all profile fields.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 23:22:58 +01:00
jgrusewski
5738edaa0a perf: keep GPU training data resident across epochs — init 73ms → 0ms
Remove per-epoch GPU data freeing that forced re-upload every epoch.
Training data within a walk-forward window is immutable — uploading once
and keeping it GPU-resident eliminates the init phase entirely.

Epoch time: 153ms → 78ms on RTX 3050 (epochs 2+).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 16:29:32 +01:00
jgrusewski
c2d116dfdf perf: cuBLAS SGEMM pipeline + dead code elimination — 37s → 86ms/epoch (430x)
Phase 2: Replace 1-warp/sample fused kernels with cuBLAS SGEMM batched forward/backward.
- batched_forward.rs: cuBLAS SGEMM forward (10 GEMM + bias/ReLU per pass)
- batched_backward.rs: cuBLAS SGEMM backward (chain rule via GEMM, no atomicAdd)
- c51_loss_kernel.cu: standalone C51 distributional loss (256 threads, 2KB shmem)
- c51_grad_kernel: dL/d_logits with dueling routing for cuBLAS backward
- BF16 alignment fix: pad offsets to even for short2 vectorized loads
- Training step: 10.7ms → 0.7ms (15x) on RTX 3050

Phase 3: Unified cuBLAS Q-forward + dead code elimination (-4,400 lines net).
- Rewrite experience collector: timestep loop + cuBLAS replaces monolithic 3,272-line kernel
- Delete dqn_training_kernel.cu (1,385 lines) — replaced by dqn_utility_kernels.cu (118 lines)
- Delete dqn_experience_kernel.cu (3,272 lines) — replaced by experience_kernels.cu (656 lines)
- Remove BF16 warp-matvec helpers from common_device_functions.cuh (-159 lines)
- Remove dead methods/fields from GpuDqnTrainer (-500 lines)
- Experience collection: 348ms → 12ms (29x) on RTX 3050
- No fallback paths — cuBLAS is the only Q-forward implementation
- All 1,514 tests pass, GPU smoke test verified with real data

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 15:33:00 +01:00
jgrusewski
d4c9c9c34e docs: Phase 2 plan — cuBLAS batched GEMM + kernel fusion (10.7ms → <1ms/step)
Based on kernel deep dive: 1.56% occupancy on H100 from 1-warp/sample
architecture, 46KB stack spill, 47 kernel launches per step.

7 tasks: cuBLAS forward, batched backward, fuse BF16/EMA, multi-block
prefix sum, C51 loss kernel, H100 profiling.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 11:23:09 +01:00
jgrusewski
8b44a8c9c5 docs: Phase 1 implementation plan — eliminate PER CPU roundtrips
7 tasks: Philox RNG kernel, pre-allocated buffers, GPU-native sampling,
adam_step cleanup, profiling validation, to_host deprecation.

Target: 37s → 12-15s/epoch on H100.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 10:26:11 +01:00
jgrusewski
6e49d4a2be docs: H100 epoch optimization spec (37s → <5s) + phase profiling
Spec: 3-phase plan to reduce DQN training epoch from 37s to <5s on H100.
- Phase 1: eliminate 300 CPU roundtrips in PER sampling (GPU Philox RNG)
- Phase 2: increase kernel occupancy (batch_size 512+, cuBLAS profiling)
- Phase 3: pipeline overlap (dual-stream experience/training)

Profiling instrumentation added to training loop (init/experience/training/validation breakdown).

RTX 3050 baseline: training=97.2%, experience=2.3% — PER sampling
with CPU RNG + DtoH sync is the primary bottleneck.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 10:23:17 +01:00
jgrusewski
daf771c38d audit: annotate all remaining to_vec/memcpy_dtoh — categorized 158 sites
Every to_vec()/memcpy_dtoh across 48 files audited and annotated:
- ~100 false positives: Rust slice .to_vec() (cpu-side, never touches GPU)
- ~25 gpu-exit: legitimate scalar readbacks (loss, grad_norm, epoch state)
- ~20 test-only readbacks: gated by #[cfg(test)] scope
- ~10 cpu-side uploads: .to_vec() before from_vec() GPU upload
- ~3 checkpoint exports: export_to_host at epoch boundary

Annotations use inline comments: // cpu-side, // gpu-exit:, // test-only

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 19:36:41 +01:00
jgrusewski
643b9505a4 feat: WORKSPACE COMPILES — zero candle, zero errors, GPU-native
Final 58 compile errors fixed + GPU violation analysis:
- 23 files across ml, ml-dqn, ml-supervised, services
- flash_attention: CudaBlas + stream fields, GPU matmul/transpose
- ensemble adapters (tggn, tlob, mamba2, tft, ppo): StreamTensor/GpuLinear
- diffusion/xlstm/mamba trainable: StreamTensor ↔ GpuTensor conversion
- hyperopt adapters: fixed API signatures
- trainers (liquid, mamba2): checkpoint save via safetensors
- benchmarks: fixed to_scalar, RainbowAgent API
- services: MlDevice, PPO::load_checkpoint, Mamba2SSM constructor

Host-side softmax/distributional functions analyzed — operating on
legitimately-downloaded small output tensors at computation endpoints.
Not GPU violations (cold paths, <50 elements).

FULL WORKSPACE: 0 errors, 56 warnings, 0 candle dependencies.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 13:31:35 +01:00
jgrusewski
6d8ba0708c fix(ml-supervised): resolve all 104 compile errors — clean build
- mamba/mod.rs: ~90 errors fixed — _candle suffixed functions replaced,
  operator overloads→free functions, autograd→pseudo-gradients,
  checkpoint→JSON serialization
- gpu_tensor.rs: added gpu_eye, gpu_cat_dim0, gpu_stack_tensors
- TFT/SSD: unused imports cleaned, type mismatches fixed
- ml-core: GpuTensor algebra methods (17 new), cuda_compat.rs deleted,
  GpuVarStore::vars/all_vars/linear_xavier added

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 07:26:56 +01:00
jgrusewski
22004a7368 refactor(cuda): eliminate candle from ml-core, ml-ppo, and 4 thin crates
Hard refactor — no shims, no compat layers. Candle removed from Cargo.toml
and all source files in 6 crates:

- ml-core: MlDevice enum, checkpoint.rs (safetensors direct), cudarc imports
  fixed from candle re-export to direct, AdamWConfig lr_decay, cuda_compat
  gutted. Net -7,341 lines.
- ml-ppo: All 16 files rewritten. LSTM→CudaLSTM, VarMap→GpuVarStore,
  PPOAgent 2306→700 lines, checkpoint→binary format.
- ml-ensemble: GPU-resident sigmoid via custom CUDA kernel.
- ml-explainability: Integrated gradients via GPU finite-difference kernels.
- ml-labeling: Device→MlDevice.
- ml-hyperopt: Cargo.toml only.

Remaining: ml-dqn (24 files), ml-supervised (4 files), ml crate (104 files).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:27:56 +01:00
jgrusewski
0e2f82ab54 feat(cuda): complete Candle elimination + cudarc 0.19.3 upgrade
Integration of 7 hive agents:
- gpu_replay_buffer: 103 Candle refs → 0 (14 new CUDA kernels)
- gpu_action_selector: 27 refs → CudaSlice API
- signal_adapter: 26 refs → 3 new CUDA kernels
- gpu_experience_collector: 5 refs → CudaSlice output
- gpu_weights+iql+guard: 13 refs eliminated
- DQN forward: new forward_only_kernel for inference
- VarMap: F32 contiguous enforcement, fast-path extraction

New modules:
- ml-core/cuda_autograd: GpuTensor, GpuVarStore, GpuLinear, GpuAdamW
- ml-ppo/cuda_nn: CudaLinear, CudaLSTM, CudaAdam, networks
- ml-supervised/gpu_tensor: GpuTensor + cuBLAS for KAN, Diffusion

cudarc 0.17.3 → 0.19.3 (via candle 0.9.1 → 0.9.2)
safetensors 0.4 → 0.7

Zero errors, zero warnings workspace-wide.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 15:13:04 +01:00
jgrusewski
450c23a6d0 refactor(cuda): eliminate all CPU fallbacks — CUDA mandatory across ML stack
- Remove ALL #[cfg(feature = "cuda")] guards (~400+ occurrences)
- Remove ALL #[cfg_attr(not(feature = "cuda"), ignore)] test annotations (~250)
- Make cuda default feature in 9 ML crates (ml, ml-core, ml-dqn, ml-ppo, etc.)
- Convert nvrtc JIT compilation to precompiled nvcc (searchsorted, prefix_sum)
- Move compile_ptx_for_device() to ml-core for shared access
- Delete dead CPU code: multi_step.rs, self_supervised_pretraining.rs,
  training_guard_gpu_tests.rs, CPU PER buffer paths, CPU Q-diagnostics
- Replace unwrap_or(Device::Cpu) with hard errors everywhere
- Remove dead is_cuda() else branches in DQN/PPO/hyperopt trainers
- Change config defaults from "cpu" to "cuda" (rainbow, tlob, pipeline)
- Port IQL value network to GPU kernel (5 CUDA entry points)
- Port HER goal relabeling to GPU kernel (warp-per-sample)
- Wire DSR GPU-to-CPU sync in training loop
- cfg!(feature = "cuda") → true in inference_validator

Zero warnings, zero errors across entire workspace.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 21:01:28 +01:00
jgrusewski
d95e205d4b refactor(ml): delete mixed_precision module — BF16 unconditional on CUDA
Eliminate the entire mixed_precision runtime indirection layer:
- Delete crates/ml-core/src/mixed_precision.rs (training_dtype, ensure_training_dtype, align_dim_for_tensor_cores)
- Inline ~100 call sites across 130 files to constants:
  training_dtype(&device) → candle_core::DType::BF16
  ensure_training_dtype(x) → x.to_dtype(candle_core::DType::BF16)
  align_dim_for_tensor_cores(x, &device) → (x + 7) & !7
- Remove re-exports from ml-dqn, ml-supervised, ml lib.rs
- Clean config/toml/json/shell references

No CPU/Metal training path exists — BF16 is the only dtype.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 16:11:48 +01:00
jgrusewski
76e1010568 docs: add Kanidm SSO + NetBird mesh design spec and implementation plan
Design spec covers OIDC architecture (RS256 JWKS, WebAuthn-first),
7 service integrations, NetworkPolicy, and phased migration strategy.
Implementation plan: 17 tasks across 6 chunks, reviewed 3 rounds
(2 internal + 1 external Gemini 2.5 Pro expert review, all fixes applied).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 19:41:40 +01:00
jgrusewski
6a2b2d9dbe fix(plan): reviewer round 3 — tggn/tgnn module mapping, exit code, canonical imports
- B1: Add LIB_FILTER mapping for tggn→tgnn module name (prevents zero-test false positive)
- W1: Replace ml_supervised:: imports with canonical ml:: paths in supervised_gpu_smoke_test
- W4: Use clean pass/fail exit code instead of raw failure count

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:51:58 +01:00
jgrusewski
f42d1ae59d plan: add Task 3b (supervised_gpu_smoke_test) + wire into workflow script
- Add Task 3b: GPU smoke test for all 8 supervised models via UnifiedTrainable
- Wire supervised_gpu_smoke_test into Task 4 workflow shell script (replaces wildcard)
- Each supervised model gets explicit test filter: test_${MODEL}_gpu_smoke
- Retain fallback for model-specific _integration tests if they exist

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:43:28 +01:00
jgrusewski
eb78f078a2 docs: fix 8 reviewer issues in GPU test workflow plan
- Add bayesian_changepoint_test to core tests (spec 4.5)
- Replace fragmented YAML with complete WorkflowTemplate (all 4 templates)
- Add complete notify-result template with notify parameter gating
- Remove dead DQN_SMOKE_EPOCHS env var (no consumer in codebase)
- Replace templateRef with resource template (workflow-of-workflows)
  to fix PVC/volume context issue in ci-pipeline integration
- Fix supervised integration test || true → compile-check guard
- Remove dead epochs parameter from all consumers
- Inline shell script into YAML (no separate code block)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:27:16 +01:00
jgrusewski
4462404084 docs: add GPU test workflow implementation plan (8 tasks)
Covers PVC creation, test data population, TEST_DATA_DIR wiring,
WorkflowTemplate, CronWorkflow, argo-test.sh CLI, and CI integration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:15:27 +01:00
jgrusewski
696d0d6bff docs: rev 2 GPU test workflow spec — fix all 4 blockers
- Compile+test in same H100 pod (eliminates cross-node PVC transfer)
- New cargo-target-cuda-test PVC (30Gi) — zero contention with training
- onExit notify, podGC, activeDeadlineSeconds, fsGroup, gpu-warmup
- Continue-on-failure with per-model exit code capture
- CUDA_COMPUTE_CAP=90, complete change detection paths
- TEST_DATA_DIR marked as required prerequisite code change

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:10:01 +01:00
jgrusewski
9976b55d04 docs: H100 GPU test workflow design spec
Spec for Argo WorkflowTemplate that compiles with --features cuda
on CPU node and runs full GPU/CUDA test suite on H100 with real
market data from a dedicated test-data-pvc.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:00:52 +01:00
jgrusewski
4709ca8bc2 feat(dqn): enable Branching DQN with 45 factored actions (5×3×3)
Restore 45-action factored space via Branching DQN (Tavakoli 2018),
outputting 11 Q-values (5+3+3) instead of 45. This was reduced to 5
exposure-only actions during debugging and was never intended as permanent.

- Enable use_branching: true by default in DQNConfig and DQNHyperparameters
- Add branching paths to select_action_with_confidence and select_action_inference
- Update agent.rs select_action_factored for branching-aware selection
- Expand CountBonus to per-branch tracking with bonuses_branched()
- Add order_type + urgency distribution tracking in monitoring
- Add DQN_ORDER_ACTIONS=3, DQN_URGENCY_ACTIONS=3, DQN_TOTAL_ACTIONS=45 to CUDA header
- Fix 7 pre-existing clippy doc_markdown errors in regime_conditional.rs
- Fix pre-existing cognitive_complexity in replay_buffer_type.rs (extract helpers)
- Fix flaky GPU test OOM under parallel execution (CPU fallback + test VRAM safety)
- Delete unused flash_attention submodules (block_sparse, causal_masking, etc.)
- Add GPU hot-path guard scripts and ensemble/hyperopt adapter improvements

Tests: ml-dqn 416/0, ml 905/0, clippy 0 errors on both crates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 22:00:13 +01:00
jgrusewski
208cee4cf5 docs: fix 5 chunk 2 re-review issues in CUDA backtest plan
- Task 9: memcpy_stod_inplace → memcpy_htod (cudarc 0.17 API)
- Task 9: Fix transposed actions_history layout — accumulate CPU-side
  in window-major [window][step] layout, upload once before metrics kernel
- Task 9: Replace non-existent Tensor::from_raw_buffer with download-
  and-reupload pattern (temporary, replaced by Task 11 GPU gather kernel)
- Task 10: DqnOptimizer → DQNTrainer (hyperopt adapter) (actual struct name)
- Task 10: internal_trainer type → &InternalDQNTrainer (avoids name conflict
  with adapter's own DQNTrainer alias)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 09:40:51 +01:00