Commit Graph

1705 Commits

Author SHA1 Message Date
jgrusewski
bb665e0926 feat(infra): add backend service URLs to api-gateway K8s deployment
Add BROKER_GATEWAY_SERVICE_URL, DATA_ACQUISITION_SERVICE_URL, and
ML_SERVICE_URL env vars so the gateway can connect to all backend services.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 00:41:58 +01:00
jgrusewski
748370b198 feat(api_gateway): implement monitoring system status, health check, and metrics RPCs
Replace 3 stub RPCs with real implementations:
- get_system_status: fan-out gRPC health checks to all backends, reports SystemStatus
- get_health_check: fan-out checks with response time measurement, returns HealthCheck entries
- get_metrics: queries Prometheus for requested metric names

MonitoringServiceHandler now accepts backend URLs via with_backends() builder.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 00:38:34 +01:00
jgrusewski
b2654a1bcc feat(api_gateway): wire all proxy services into main.rs
- Read new env vars: BROKER_GATEWAY_SERVICE_URL, DATA_ACQUISITION_SERVICE_URL,
  ML_SERVICE_URL, TRADING_AGENT_SERVICE_URL
- Create lazy channels: trading channel shared by trading/risk/config proxies,
  separate channels for ML, broker, data_acq, trading_agent
- Register 7 new services on router with auth interceptor
- Update reflection service with all 6 new proto descriptors
- Add broker/data_acq/trading_agent to health check backend list

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 00:30:32 +01:00
jgrusewski
a35ad81885 feat(api_gateway): add 6 gRPC proxy services + server codegen for all protos
Enable server codegen for trading, risk, config protos in build.rs.
Add new compile blocks for broker_gateway, data_acquisition, ml protos.
Create 6 zero-copy forwarding proxies following TradingAgentProxy pattern:
- TradingDirectProxy (trading.TradingService, 16 RPCs)
- RiskServiceProxy (risk.RiskService, 8 RPCs)
- BrokerGatewayProxy (broker_gateway.BrokerGatewayService, 7 RPCs)
- DataAcquisitionProxy (data_acquisition.DataAcquisitionService, 5 RPCs)
- MlServiceProxy (ml.MLService, 10 RPCs)
- ConfigServiceProxy (config.ConfigService, 12 RPCs)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 00:28:28 +01:00
jgrusewski
fb4df12376 Merge branch 'feature/fxt-overhaul'
fxt 2.0 overhaul: consolidated proto/, absorbed monitoring into API Gateway,
new 15-command CLI with gRPC, MCP server mode, TUI cockpit framework.

159 files changed, net -11,835 lines.
2026-03-03 23:16:45 +01:00
jgrusewski
0fdcc496be fix: type-safe proto enums, MCP protocol compliance, TUI teardown
- Replace hardcoded i32 enum matches with ProtoEnum::try_from() in
  8 command files (cluster, config, data, model, risk, service, train, tune)
- Replace hardcoded i32 literals with enum variants (EmergencyStopType,
  ExportFormat, TrainingMode)
- Add JSON-RPC 2.0 PARSE_ERROR (-32700) for malformed JSON input
- Validate jsonrpc:"2.0" version on incoming MCP requests
- Change unreachable execute_tool catch-all from Ok to Err
- Fix TUI teardown to not mask original event_loop error
- Rename config_cmd module to config (commands::config)
- 77 tests pass, 0 clippy warnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:29:13 +01:00
jgrusewski
609f533abc feat: implement all 15 fxt CLI commands with real gRPC calls
- 13 commands with full gRPC implementations: service, train, tune,
  model, trade, broker, agent, data, risk, config, cluster, auth, backtest
- Streaming support: train logs --follow, broker executions --follow
- --json output on every command via OutputFormat/HumanReadable
- Fix web-gateway monitoring URL default (50057 → 50051, API Gateway)
- Rewire 7 remaining build.rs to consolidated proto/ root (web-gateway,
  backtesting_service, training_uploader, 3 test crates, e2e)
- Fix web-gateway ml_training.proto new fields (mode, max_epochs, resume)
- 75 fxt tests + 139 web-gateway tests, 0 clippy warnings, workspace clean

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:16:35 +01:00
jgrusewski
f60df5a65f fix(dqn): clippy let_underscore_must_use in CUDA sync cleanup
Replace `let _ = sync_tensor.to_vec0::<f32>()` with `drop()` to
satisfy clippy's let_underscore_must_use lint on the Result return.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:08:29 +01:00
jgrusewski
6770e28ca9 feat(dqn): per-sample quantile Huber loss for PER IS-weight correction
Add quantile_huber_loss_per_sample() that preserves the batch dimension
(mean over quantiles only) so PER importance-sampling weights can be
applied per-sample before final batch reduction. Mirrors the existing
quantile_huber_loss() but returns [batch] instead of scalar.

Two tests verify shape correctness, non-negativity, consistency with
the scalar variant (mean of per-sample == scalar loss), and IS weight
application behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:07:50 +01:00
jgrusewski
ba841f7c8b feat(dqn): checkpoint architecture validation via safetensors metadata
Embed DQNConfig architecture hash (SHA-256 of state_dim, num_actions,
hidden_dims, dueling/distributional/noisy/IQN flags) in safetensors
file header on save. Validate hash on load to catch shape mismatches
before touching the VarMap - prevents silent corruption from loading
checkpoints trained with different network architectures.

All 5 save paths (trainable_adapter, trainer serialize_model,
DQNAgentType::save_checkpoint, RegimeConditionalDQN per-head) now
embed metadata. All 3 load paths (DQN::load_from_safetensors,
trainable_adapter::load_checkpoint, ensemble adapter) validate.

No backward compatibility: checkpoints without metadata are rejected
with a clear error message to re-train.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:06:56 +01:00
jgrusewski
ab101f1110 feat: MCP server mode + TUI cockpit framework
MCP server (bin/fxt/src/mcp/):
- JSON-RPC 2.0 protocol over stdin/stdout
- 32 tool definitions across 11 domains
- McpServer with initialize/tools_list/tools_call handlers
- 21 unit tests

TUI cockpits (bin/fxt/src/tui/):
- Purple/cyan/dark navy theme from design spec
- 6 cockpit views: overview, training, trading, services, risk, data
- Crossterm event loop with key handling (1-6 switch, q quit, ? help)
- CockpitView trait for pluggable cockpit rendering

All 75 tests pass, 0 clippy warnings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:48:59 +01:00
jgrusewski
2f60e0cda0 fix(eval): train/eval parity - position tracking, cost differentiation, feature alignment
- Wire position-delta cost model: costs only apply on position changes,
  proportional to delta (not flat per-bar)
- Differentiate order types: Market=15bps, LimitMaker=5bps, IoC=10bps
- Apply urgency weight: Patient=0.5x, Normal=1.0x, Aggressive=1.5x
- Append 3 portfolio features (position, unrealized PnL, drawdown) to match
  training's 54-dim state vector (was 51, causing shape mismatch on load)
- Fix default num_actions 3->45 to match training's factored action space
- Add --bars-per-year CLI flag for per-symbol annualization
  (ES/NQ=347760, 6E=345000, ZN=105840)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:43:01 +01:00
jgrusewski
d1b9de3363 feat: unified FoxhuntClient with typed service accessors
Adds accessor methods for all 11 service clients (trading, ml, ml_training,
broker_gateway, trading_agent, monitoring, config, data_acquisition, risk,
health, config_service). All clients share a single gRPC channel.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:38:05 +01:00
jgrusewski
724bd64429 feat: fxt 2.0 skeleton — new command tree with 15 command groups
Clean rewrite of the fxt CLI with unified gRPC client, JSON/human
output abstraction, and stub implementations for all 15 command groups:
auth, trade, train, tune, model, agent, backtest, broker, data,
service, cluster, risk, config, watch (TUI), mcp.

Deleted old fat-client commands, client modules, types, prelude, and
tests (-12,769 net lines). Fixed pre-existing clippy issues in auth
module (indexing_slicing in encryption.rs, manual_let_else in
token_manager.rs, str_to_string in build.rs).

60 tests passing (53 lib + 7 binary), 0 clippy warnings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:35:18 +01:00
jgrusewski
3ef80b9efe fix(dqn): atomic checkpoints, CUDA sync, NormStats hard error, q_value_std warning
- Atomic checkpoint writes: write to .tmp then fs::rename() (POSIX atomic)
- Remove redundant thread::sleep(50ms) after CUDA tensor readback sync
- NormStats: bail on missing file instead of computing from test data (lookahead bias)
- q_value_std: warn when missing from training metrics instead of silent 0.0 fallback

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:34:19 +01:00
jgrusewski
66d6d0f2a5 chore: delete monitoring_service — absorbed into API Gateway
Remove from workspace members, delete K8s deployment, remove nginx routing.
Training metrics and system health now served directly by API Gateway.

Changes:
- Cargo.toml: remove services/monitoring_service from workspace members
- services/monitoring_service/: deleted entirely (6 files)
- infra/k8s/services/monitoring-service.yaml: deleted
- infra/k8s/network-policies/monitoring-service.yaml: deleted
- infra/k8s/network-policies/api-gateway.yaml: remove egress rule to monitoring-service
- infra/k8s/network-policies/web-gateway.yaml: remove egress rule to monitoring-service
- infra/k8s/services/api-gateway.yaml: remove stale MONITORING_SERVICE_URL env var
- infra/k8s/gitlab/tailscale-proxy.yaml: redirect monitor.fxhnt.ai to api-gateway:50051
- .gitlab-ci.yml: remove monitoring_service from compile, copy, and deploy loops
- services/trading_service/src/services/monitoring.rs: update stale comments to
  reference api_gateway (not monitoring_service) as training metrics host

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:26:00 +01:00
jgrusewski
4ecb20ab25 fix(dqn): wire hyperopt weight_decay through trainer to agent
The DQNConfig construction in trainer.rs hardcoded weight_decay to 1e-4,
ignoring the hyperopt-tuned value in DQNHyperparameters. This meant PSO
optimization of weight_decay (search space index 17, range [1e-5, 1e-3])
had no effect on actual training runs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:13:24 +01:00
jgrusewski
e338eda7ac fix(dqn): wire weight_decay to Adam optimizer
DQNConfig.weight_decay (default 1e-4, hyperopt range [1e-5, 1e-3]) was
silently ignored — ParamsAdam always received weight_decay: None. Now
conditionally passes Decay::DecoupledWeightDecay when weight_decay > 0,
enabling L2 regularization that hyperopt has been tuning for.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:07:40 +01:00
jgrusewski
1421c46ed4 feat: absorb monitoring service into API Gateway
Port Prometheus scraping and training metrics RPCs directly into
api_gateway, eliminating the monitoring-service backend proxy.
MonitoringServiceProxy replaced with MonitoringServiceHandler that
queries Prometheus directly for training metrics, GPU stats, and
active job counts.

Changes:
- monitoring_proxy.rs -> monitoring_handler.rs with embedded PrometheusClient
- Remove MonitoringBackendConfig and setup_monitoring_proxy from server.rs
- main.rs reads PROMETHEUS_URL + MONITORING_STREAM_INTERVAL instead of
  MONITORING_SERVICE_URL
- Remove monitoring-service from backend health check list
- Monitoring is always available (no graceful degradation needed)
- Fix fxt build.rs compile_protos type mismatch
- All 9 ported unit tests + 0 clippy warnings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:05:27 +01:00
jgrusewski
c112d34fec refactor: point fxt build.rs at proto/ root, delete fat-client protos
fxt now compiles from the same service protos as all backend services.
Deleted 8 fat-client protos (3,286 lines) from bin/fxt/proto/.
Updated include_proto! macros to use new package names (trading, ml,
config instead of foxhunt.tli, foxhunt.ml, foxhunt.config).
Added risk, data_acquisition, and config_service proto modules.
Fixed duplicate include_proto in agent.rs to use crate::proto.

Existing command implementations will be rewritten to use new proto
types in Task 6.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:54:04 +01:00
jgrusewski
7f5dfb70c6 docs: add DQN production hardening design
4-phase plan from deep audit: critical bug fixes (weight_decay, IQN PER,
q_value_std, 54/51 dim mismatch), train/eval parity (TradeExecutor,
checkpoint validation), SOTA improvements (differential Sharpe, PQN
LayerNorm, temporal PER, dormant neuron resets), and search space cleanup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:40:46 +01:00
jgrusewski
b70c6a0bd7 refactor: rewire all service build.rs to proto/ root directory
Delete per-service proto/ directories. All 7 services now compile
from the single canonical proto/ at workspace root.

- trading_service: 5 protos + ml_training client -> ../../proto/
- ml_training_service: ml_training server + fxt_trading client -> ../../proto/
- broker_gateway_service: broker_gateway -> ../../proto/
- trading_agent_service: trading_agent + ml client -> ../../proto/
- data_acquisition_service: data_acquisition -> ../../proto/
- api_gateway: 8 proto compilations -> ../../proto/
- monitoring_service: keeps local proto (3 training RPCs only, deleted in Task 5)

Added proto/fxt_trading.proto (fat-client proto, package foxhunt.tli)
separate from proto/trading.proto (backend, package trading) since the
API gateway needs both for protocol translation.

Added unimplemented stubs for merged monitoring.proto RPCs:
- trading_service: 3 training RPCs (served by monitoring_service)
- api_gateway monitoring_proxy: 13 system health RPCs (Task 4)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:34:09 +01:00
jgrusewski
de4170bffc Merge branch 'feature/hyperopt-improvements'
DQN hyperopt: TPE optimizer, 45D→25D search space, drawdown circuit breaker, CUDA sync fix.
PPO improvements: 14D search space, symlog, DAPO clipping, adaptive entropy, percentile scaling,
curiosity port, reward shaping, ExO-PPO trajectory replay, composite risk-adjusted reward.

2726 ml tests pass, 0 clippy errors.
2026-03-03 20:23:06 +01:00
jgrusewski
4b15108895 feat(ppo): wire reward shaping, composite reward, trajectory replay into hyperopt
Integrate three standalone PPO modules into the hyperopt training loop:
- PPORewardShaper: hold penalty + rolling Sharpe + diversity bonus per step
- CompositeReward: risk-adjusted reward (downside dev + differential return)
- TrajectoryReplayBuffer: ExO-PPO M=4 rollouts with IS-weighted replay

Also fixes GAE hardcoded gamma=0.99/lambda=0.95 — now uses hyperopt params.

2726 tests pass, 0 clippy errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:20:48 +01:00
jgrusewski
ed1ab8ed88 feat: create consolidated proto/ directory at workspace root
Merge monitoring_service training metrics into trading_service system health
monitoring.proto. All 11 proto files now in one canonical location.

Merged monitoring.proto has 13 RPCs (10 system + 3 training) with all
message types from both source protos preserved. Added cpu_percent,
memory_used_mb, memory_total_mb fields to GetLiveTrainingMetricsResponse.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:15:11 +01:00
jgrusewski
ba8fb8eedd feat(ppo): wire symlog, adaptive entropy, percentile scaling into training loop
Integrate all PPO improvement modules into the core training paths:
- Symlog value predictions in compute_value_loss (MLP + LSTM)
- Adaptive entropy auto-tuning replaces fixed entropy_coeff
- Percentile P5/P95 advantage scaling for heavy-tailed returns
- DAPO clip_epsilon_high wired in all 7 PPOConfig construction sites
- Shape mismatch fix in adaptive_entropy (unsqueeze scalar)

2726 tests pass, 0 clippy errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:12:00 +01:00
jgrusewski
df93b4c534 docs: fxt 2.0 design and implementation plan
Clean rewrite into full-scale operations platform.
Single proto/ root, monitoring_service removed,
CLI + MCP + cockpit TUI with purple/cyan theme.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:11:21 +01:00
jgrusewski
50b75b8a5f feat(ppo): curiosity port + reward shaping + ExO-PPO replay + composite reward
Phase 6: CuriosityModule wired into PPO hyperopt (14D). Intrinsic reward
from forward dynamics prediction error scales by curiosity_weight param.

Phase 7: PPORewardShaper with hold penalty (discourages flat position),
rolling Sharpe (20-step window), diversity bonus (smooth quadratic
entropy). 8 tests.

Phase 8: ExO-PPO trajectory replay buffer (M=4 FIFO). Importance-weighted
surrogate with exponential attenuation outside clip bounds (alpha=5).
4x sample efficiency over standard PPO. 10 tests.

Phase 9: CompositeReward with annualized return, downside deviation
penalty, and differential return vs SMA baseline. 10 tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:48:48 +01:00
jgrusewski
2ac4525399 feat(ppo): enable DAPO asymmetric clipping by default (clip_epsilon_high=0.28)
Clip range [1-0.2, 1+0.28] = [0.8, 1.28] allows larger policy updates
toward profitable actions while being conservative about penalizing
exploration. ByteDance DAPO 2025 — 50% faster convergence.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:25:04 +01:00
jgrusewski
235cee5b50 feat(ppo): expand search space 7D→13D + symlog + adaptive entropy + percentile scaling
Phase 1: PPOParams expanded with gae_gamma, gae_lambda, mini_batch_size,
max_grad_norm, max_position_absolute, clip_epsilon_high. All wired into
PPOConfig construction. CUDA cleanup with tensor readback sync.

Phase 2: Symlog value transform (DreamerV3) — sign(x)*ln(|x|+1) for
compressing large financial returns while preserving sign. 13 tests.

Phase 4: Adaptive entropy coefficient (SAC-style) — learnable log(alpha)
auto-tuned via dual gradient descent toward target entropy. 9 tests.

Phase 5: Percentile advantage scaling — EMA-tracked P5/P95 for robust
normalization of heavy-tailed financial returns. 11 tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:23:57 +01:00
jgrusewski
6d0182d77e feat(hyperopt): make TPE the default optimizer
Change --optimizer default from "pso" to "tpe" since TPE has better
sample efficiency in 25D spaces. Fix clippy let_underscore_must_use
on CUDA sync tensor readback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:50:02 +01:00
jgrusewski
c29fafbbb6 feat(hyperopt): reduce DQN search space from 45D to 25D
Fix 20 exotic parameters to validated defaults, keeping only the 25
that genuinely affect trading performance. This makes both PSO and
TPE dramatically more effective at exploring the parameter space.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:42:37 +01:00
jgrusewski
903e690e9a feat(hyperopt): wire TPE optimizer into pipeline with --optimizer flag
Add optimize_with_tpe() function that uses Tree-Parzen Estimator for
Bayesian hyperparameter optimization. Add --optimizer=tpe CLI flag
to hyperopt_baseline_rl binary (default: pso for backward compat).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:40:03 +01:00
jgrusewski
7e2545bf92 fix(ml): use training_dtype in curiosity module instead of hardcoded F32
Replace DType::F32 with training_dtype(&device) for action one-hot
encoding and state embedding conversion. On BF16 devices, model
weights are BF16 but inputs were F32, causing dtype mismatch errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:39:04 +01:00
jgrusewski
012bf3dc00 fix(hyperopt): replace sleep-based CUDA cleanup with synchronize
Force CUDA synchronization between trials by creating a tiny tensor and
reading it back (forces cudaDeviceSynchronize). This ensures GPU memory
from dropped models is actually freed before the next trial starts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:35:41 +01:00
jgrusewski
10163bb167 fix(hyperopt): narrow max_position [1,4] and add 20% drawdown circuit breaker
Tighten max_position_absolute search range from [4,8] to [1,4] to
prevent catastrophic leverage during hyperopt. Add drawdown circuit
breaker to PortfolioTracker that force-closes positions at >20%
drawdown and refuses new trades while flat.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:30:29 +01:00
jgrusewski
6c8fc7b1c1 feat(hyperopt): implement TPE (Tree-Parzen Estimator) optimizer with KDE and LHS
Add a standalone TPE optimizer for Bayesian hyperparameter optimization that
replaces PSO by modeling good/bad trial distributions with per-dimension
kernel density estimates. Includes Latin Hypercube Sampling for initial
exploration, Silverman bandwidth selection, log-sum-exp numerical stability,
and JSON-based trial persistence. 15 tests covering splits, bounds, KDE
density, convergence on 1D/2D objectives, and history serialization.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:29:33 +01:00
jgrusewski
1dac9b0556 fix(ml): cast NoisyNet noise tensors to training dtype (BF16)
sample_noise(), sigma init, disable_noise(), and epsilon buffers all
used hardcoded DType::F32. When weights are BF16 on Ampere+ CUDA,
this caused dtype mismatch in mul/add operations during forward pass.

Fix: use training_dtype(device) for all noise-related tensors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:26:50 +01:00
jgrusewski
a0a2a1d736 docs: add hyperopt improvements design and implementation plan
A+B approach: smooth penalties + position limits + CUDA cleanup +
search space reduction (45D→25D) + TPE optimizer replacing PSO.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 18:17:23 +01:00
jgrusewski
4f6e893d2b Merge branch 'worktree-bf16-training' 2026-03-03 17:49:35 +01:00
jgrusewski
864808e056 fix(ml): add ensure_training_dtype boundary casts to all model forward methods
After converting all VarBuilder sites from F32 to training_dtype (BF16 on
Ampere+ GPUs), input tensors from callers remain F32, causing dtype
mismatches in matmul/add/mul operations. This commit adds systematic
boundary casts across all 10 model architectures:

- Input boundary: ensure_training_dtype() at each model forward() entry
- Output boundary: to_dtype(F32) at each model forward() exit
- Internal intermediates: hidden state init, gradient extraction,
  positional encodings, causal masks, SSM state matrices, B-spline
  basis values all cast to match computation dtype
- Ensemble adapters: ensure_training_dtype after Tensor::from_vec

36 files, +293/-72 lines. 2640 tests pass, 0 failures, 0 clippy warnings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 17:42:41 +01:00
jgrusewski
dc8ee1f630 feat(ml): BF16 VarBuilder for all 8 supervised models
Replace DType::F32 with training_dtype(&device) in VarBuilder::from_varmap
calls across TFT, Mamba2, Liquid/CfC, KAN, xLSTM, Diffusion, TGGN, TLOB.
61 sites changed across 25 files (production constructors + test helpers).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:23:03 +01:00
jgrusewski
4beef7069c feat: epoch-level financial metrics in fxt CLI
Add 11 Prometheus gauges for epoch financial metrics (Sharpe, Sortino,
win rate, max DD, profit factor, total return, avg return, total trades,
action distribution) pushed from DQN/PPO trainers at epoch end.

- common: 11 new gauges + set_epoch_financial_metrics/set_epoch_action_distribution helpers
- ml: compute_epoch_financials helper from PnL history + action counts
- ml: push from DQN trainer (full metrics) and PPO trainer (Sharpe proxy)
- proto: 11 new TrainingSession fields (36-46) + GetEpochHistory RPC
- monitoring_service: metric mapper + epoch history ring buffer (50 epochs)
- api_gateway: GetEpochHistory proxy forwarding
- fxt watch: Sharpe/Win% columns, financial summary, sparklines, action distribution
- fxt train monitor: colored financial metrics section

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:21:41 +01:00
jgrusewski
7cbcfce781 fix: restore accidentally deleted bf16 plan files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:21:07 +01:00
jgrusewski
6febee532f feat(ml): BF16 VarBuilder for all DQN networks and layers
Replace DType::F32 with training_dtype(&device) in all VarBuilder::from_varmap
calls across 16 DQN files (~55 call sites). This enables automatic BF16 weight
initialization on Ampere+ GPUs while keeping F32 on CPU and older hardware.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:20:15 +01:00
jgrusewski
392655d5fb fix: add GetEpochHistory to api_gateway proxy + clippy fixes
- Implement GetEpochHistory forwarding in MonitoringServiceProxy
- Fix clippy integer suffix style (0usize → 0_usize)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:20:11 +01:00
jgrusewski
4e0225e090 feat(ml): BF16 VarBuilder, checkpoints, and training tensors for PPO
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:16:07 +01:00
jgrusewski
d0dd3af2f1 feat(ml): BF16 CUDA pipeline (replay buffer, weights, data upload)
- gpu_replay_buffer: allocate states/next_states with training_dtype(),
  cast incoming batches at ingestion boundary
- gpu_weights: cast BF16 model weights to F32 before extraction for
  CUDA f32 kernels in both extract_one() and sync_one()
- mod.rs: cast DqnGpuData, GpuBufferPool, PpoGpuData uploads to
  training_dtype(); cast portfolio tensors to match features dtype;
  cast bar_target_values readback to F32

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:14:31 +01:00
jgrusewski
4accdded0f feat(ml): BF16 training tensors in DQN loss and trainer
Cast state tensors to BF16 (via training_dtype()) at all DQN network
input sites: compute_loss_internal states/next_states, select_actions_batch,
curiosity module state/next_state, validation batch, and Q-value logging
batch. Non-network tensors (actions, rewards, dones, weights) are left
as F32 since they participate in loss math, not forward passes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:14:09 +01:00
jgrusewski
45487206bd fix(ml): allow BF16/F16 in Mamba2 scalar_tensor helper
Previously scalar_tensor() rejected BF16 and F16 with an error,
blocking BF16 training for Mamba2. Now BF16/F16 scalars are created
as F32 then cast to the target dtype, matching Candle's internal
precision requirements while supporting half-precision training.

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