Commit Graph

41 Commits

Author SHA1 Message Date
jgrusewski
fdc8f30c8d docs: H100 graph-level optimization spec — 4 deferred fixes (~13s/epoch)
Fix 2: Eliminate validation graph re-capture (DtoD into same buffers)
Fix 3: Async validation on separate CUDA stream (overlap with experience)
Fix 4: Aux GEMM in graph_aux (GPU scalar + kernel sig change)
Fix 7: Mega-graph fusion (spectral+forward+aux → 2 launches)

Combined with 5 implemented fixes: 47s → ~16s/epoch

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 08:48:36 +02:00
jgrusewski
f1e53797ca docs: H100 epoch optimization v2 spec — 47s → 19s (2.5x speedup)
9 optimizations: single-copy weight sync, graph update vs re-capture,
async validation, aux GEMM fusion, conditional frequency, target sync,
mega-graph, batch_size 16K, validation subsampling.

50 trials × 40 epochs: 26hr → 10.6hr ($45/run savings at $3/hr)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 01:49:01 +02:00
jgrusewski
1a93b71c69 feat(v8): wire 5 dead CUDA kernels + config fixes
Kernels now wired with Rust load + launch methods:
- popart_normalize_kernel: running mean/var + in-place normalization
- exposure_pretrain_step: supervised direction pre-training with backward GEMM
- td_lambda_kernel: exponentially-weighted lambda-returns
- compute_difficulty_scores: per-bar curriculum difficulty
- hindsight_relabel_kernel: optimal exit relabeling

Config fixes:
- batch_size hyperopt range: [64, 512] → [512, 8192] (H100 capacity)
- micro_reward_scale: 0.001 → 0.01 (10x stronger bootstrap)
- micro_reward hyperopt range: [0, 0.005] → [0, 0.05]

900 tests pass, 0 regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 01:26:09 +02:00
jgrusewski
327349c5e2 docs: reward v8 master plan — 18-item comprehensive training overhaul
5 categories, 18 items:
A) v7.1 fixes: aux GEMM, CEA warmup, OFI gate, dead code
B) Bootstrap trap: GPU cosine epsilon, n-step→5, dense micro-reward
C) Initialization: supervised pre-train, pessimistic Q-init, phase schedule
D) Advanced: TD(λ), PopArt normalization, curriculum learning, hindsight relabel
E) Dead code removal

4 new CUDA kernels, 3 modified, 12 new config fields, 4 removed.
Full GPU, no CPU path, no memory copies. Target: 50%+ win rate.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 23:14:40 +02:00
jgrusewski
4ab7af5713 docs: reward v7.1 spec — 6 critical fixes for exposure degeneracy and training quality
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 22:21:11 +02:00
jgrusewski
d18b386be3 fix: promote entire backtest pipeline from bf16 to f32
CRITICAL CORRECTNESS FIX: bf16 has $32 resolution at $5K equity.
Transaction costs ($12.50), tick PnL ($12.50), and cumulative returns
were ALL below bf16 resolution — rounded to zero. Sharpe was quantized
to ~0.004 resolution. All previous hyperopt evaluations used garbage
metrics.

Changed to f32:
- backtest_env_kernel.cu: prices, portfolio_state, step_rewards,
  step_returns — both backtest_env_step and backtest_env_step_batch
- backtest_metrics_kernel.cu: all accumulators, shared memory,
  metrics_out, annualization_factor
- backtest_gather_kernel.cu: portfolio parameter (f32 → bf16 for
  model input at output stage only)
- gpu_backtest_evaluator.rs: all buffer types, upload paths,
  metrics download, shared memory byte calculations

Kept bf16: features_buf, states_buf (neural network input for
tensor cores), cuBLAS forward pass buffers.

Verified: Sharpe now has 6-digit precision (19.4745) vs bf16's
~0.004 resolution. All 345 tests + 3 smoke tests pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 13:58:11 +02:00
jgrusewski
5fb0089cd2 spec: f32 backtest pipeline — eliminate bf16 financial arithmetic
bf16 has $32 resolution at $5K equity. Transaction costs ($12.50),
tick PnL ($12.50), and cumulative returns are all below resolution.
All previous hyperopt evaluations used garbage metrics.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 13:43:04 +02:00
jgrusewski
c5b4046169 spec: GPU-native validation + H100 performance optimizations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 22:48:07 +02:00
jgrusewski
d4269252c6 docs: H100 maximum performance spec and implementation plan
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 11:15:24 +02:00
jgrusewski
42c8d85bba docs: spec for GPU regime + H100 training hang fix
Three issues in one spec:
1. H100 hang: cuBLAS set_stream() inside CUDA graph capture → deadlock
2. Bug: train_walk_forward calls non-stratified generate_folds()
3. GPU regime: classification kernel + prefix sum for O(1) range queries

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 21:25:05 +02:00
jgrusewski
95e96aa976 docs: spec for Q-value explosion / NaN investigation
Documented all findings from the training step performance session:
- Shared memory race was real but not the NaN source (racecheck: 0 hazards)
- NaN is non-deterministic numerical instability, NOT a concurrency bug
- Suspected math bug in gradient budget allocation during MSE warmup
- Investigation plan: GPU NaN detection kernels, gradient audit, git bisect

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 23:00:16 +02:00
jgrusewski
ca7201a1ec docs: spec for training step performance + Q-value explosion investigation
Two remaining issues: (1) ~400ms/step instead of ~1-7ms on RTX 3050,
(2) Q-value explosion when C51 kicks in at epoch 2.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 17:30:18 +02:00
jgrusewski
36d4c39f2d docs: spec + plan for C51 loss accumulator fix (separate MSE/C51 buffers)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 11:49:13 +02:00
jgrusewski
37d78e02c8 docs: spec for CUDA kernel safety fix (__restrict__ aliasing NaN bug)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 11:07:47 +02:00
jgrusewski
5b57a4b855 docs: spec for feature extraction pipeline fix (strict cache, symbol scoping)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 09:28:42 +02:00
jgrusewski
59ef927607 docs: spec for fixing 14 GPU test failures + OFI pipeline issue
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 00:57:49 +02:00
jgrusewski
0b185ddb54 docs: H100 GPU optimization spec — 9 optimizations for 2min→<10s epochs
CUDA events, multi-stream branches, graph-captured experience
collection, dynamic batch sizing, async readbacks, fxcache alignment.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 21:36:40 +02:00
jgrusewski
a643652d0e docs: feature pre-compute pipeline design spec
Flat binary .fxcache format (f64 + bf16 versions), precompute_features
binary, Argo workflow integration, local validation plan.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:30:42 +02:00
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
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
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
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
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
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
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
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
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
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
41440e9ae7 docs: add zero-CPU DQN training hot path design spec
Defines architecture for eliminating all 10 GPU→CPU sync barriers from
the training loop via 4 new GPU components: Training Guard (pinned
memory predicates), Q-Value Monitor (on-device accumulator), GPU-resident
action selection, and async experience collector readback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 15:49:40 +01:00