jgrusewski 5da434ab4b fix(cuda): sync after async memcpy_dtoh in per_branch_grad_norms — direction-branch determinism
After Option C (commit 199feff4d, per-stream cublasLt handles) brought
cuBLAS-path determinism to bit-identical on magnitude-branch gradients,
direction-branch gradients still varied 8.7% at epoch 0 — localized to
the direction-branch readback path, not the backward computation.

Root cause: `per_branch_grad_norms` in
`crates/ml/src/cuda_pipeline/gpu_dqn_trainer.rs` called
`self.stream.memcpy_dtoh(&grad_buf.slice, pinned_host_slice)` which
cudarc forwards to `cuMemcpyDtoHAsync_v2`. Transfers into pinned host
memory are asynchronous w.r.t. the host — the API queues the DMA on
the stream and returns before the copy completes. The host-side
sum-of-squares loop immediately below then races the DMA and reads a
mix of newly-transferred bytes and stale bytes left over from the
previous epoch's readback. The direction gradient itself is bit-
identical across runs (same CUDA kernels, same per-stream cuBLAS
handles, same `CUBLAS_WORKSPACE_CONFIG=:4096:8`); a probe that read
per-tensor L2 norms (`dir_t0..dir_t3` for w_b0fc, b_b0fc, w_b0out,
b_b0out) after the aggregate readback showed tensor-level values
bit-identical to 5 sig figs across 3 runs while the aggregate varied
15%, because the probe's own `stream.synchronize()` at call start
blocked for the previous async DMA to complete, then read final bytes.
Magnitude tolerates the same race (~0.01% residual variance at 5 sig
figs) because mag L2 norms are ~300× larger than dir, so a handful of
partially-updated bytes contribute a negligible fraction of the sum;
dir's small magnitude makes it proportionally more sensitive.

Fix: add `self.stream.synchronize()` immediately after the
`memcpy_dtoh` call and before the host-side loop. Zero cost in
practice — epoch-boundary readback already runs outside the training
graph capture region.

Validation (3× sequential smoke runs on this HEAD, `magnitude_distribution`
test, fold 0 HEALTH_DIAG[0] grad_abs values):

    baseline (pre-fix)         after fix
    ────────────────────       ────────────────────
    dir=1.125252e-2            dir=1.373147e-2
    dir=1.129484e-2            dir=1.376011e-2
    dir=1.152756e-2            dir=1.376298e-2
    mag=3.464567e0             mag=3.464277e0
    mag=3.464559e0             mag=3.464551e0
    mag=3.464618e0             mag=3.464625e0

    dir spread: 2.4% → 0.2%    (12× improvement, dir now aligned with mag)
    mag spread: 0.002% → 0.01% (unchanged noise floor)

Direction aggregate now matches the mathematically-expected value
computed from per-tensor norms (sqrt(Σ tᵢ²) ≈ 1.374e-2), confirming
the readback bug was inflating the reported values below the true
gradient norm by up to ~32% under the previous race.

Logs: /tmp/foxhunt_smoke/dir_fix_run{1,2,3}.log

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 15:20:08 +02:00

Foxhunt

Production HFT trading system in Rust.

Architecture

The workspace contains 32 crates organized as follows:

Core Libraries (16)

Crate Purpose
trading_engine Order processing, FIX 4.4, IB TWS, SIMD, RDTSC timing
risk VaR, Kelly, circuit breakers, kill switches, compliance
risk-data Risk data types and shared structures
trading-data Trading data types
ml DQN Rainbow, PPO, TFT, Mamba2, ensemble inference
ml-data ML data types and feature definitions
data Market data ingestion and storage
backtesting Replay engine, strategy tester
adaptive-strategy Ensemble execution, microstructure analysis
common Shared types, resilience, error handling
storage S3 and local model storage
model_loader Model serialization and loading
market-data Market data feed handlers
database PostgreSQL access layer (SQLx)
config Configuration management
tli CLI commands and tooling

Services (8)

Service Purpose
backtesting_service gRPC backtesting service
broker_gateway_service FIX routing, broker connectivity
trading_service Core trading operations
ml_training_service Model training orchestration
data_acquisition_service Market data acquisition
trading_agent_service Autonomous trading agents
api_gateway gRPC API gateway with auth
web-gateway Axum REST + WebSocket gateway

Frontend

web-dashboard/ -- React 19 + TypeScript + Vite + TradingView charts.

Building

# Check compilation (no PostgreSQL required)
SQLX_OFFLINE=true cargo check --workspace

# Run tests for a specific crate
SQLX_OFFLINE=true cargo test -p <crate> --lib

# Clippy
SQLX_OFFLINE=true cargo clippy --workspace

ML Models

Four production model architectures on Candle v0.9.1 with CUDA:

  • DQN Rainbow -- Deep Q-Network with prioritized replay, dueling heads, noisy nets
  • PPO -- Proximal Policy Optimization with GAE and LSTM policies
  • TFT -- Temporal Fusion Transformer for multi-horizon forecasting
  • Mamba2 -- State space model for sequence prediction

Each model has a standalone trainer and a UnifiedTrainable adapter for the hyperopt pipeline.

Infrastructure

  • Git: Gitea at git.fxhnt.ai (Tailscale-only), Scaleway DEV1-S
  • Observability: OpenTelemetry OTLP (env OTEL_EXPORTER_OTLP_ENDPOINT)
  • Database: PostgreSQL with SQLx offline mode for CI

License

Proprietary. All rights reserved.

Description
No description provided
Readme 849 MiB
Languages
Rust 88.2%
Cuda 7.7%
Python 1.3%
Shell 1.1%
PLpgSQL 0.8%
Other 0.8%