Skip to content

async_transfer: add DevToHost, dual-stream H2D, DEFER_TASKRUN io_uring, and host-wide RAM pool budgeting - #737

Merged
lukealonso merged 2 commits into
mainfrom
feat/async-transfer-d2h-and-uring-perf
Dec 5, 2026
Merged

lukealonso merged 2 commits into
mainfrom
feat/async-transfer-d2h-and-uring-perf

Conversation

@lukealonso

@lukealonso lukealonso commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

Why this change is proposed

Exclusive multi-tier weight offloading on multi-GPU hosts encounters five concrete defects and performance bottlenecks in Helios's AsyncTransfer runtime:

  1. No device-to-host Copy Engine path: AsyncTransfer supported only DiskToHost (1), HostToDev (2), DiskToDev (3), and CancelEpoch (4). Captured graphs implementing an exclusive VRAM/RAM cache had no way to demote a cold VRAM resident back into HOST_POOL over PCIe D2H instead of dropping it and later re-reading it from NVMe.
  2. Copy Engine head-of-line blocking: Demand and background H2D copies shared a single CUDA stream, allowing in-flight background prefetches to delay newly arrived demand misses, and TransferScheduler continued dispatching background ops alongside active demand work.
  3. Multi-rank io_uring tail latency and contention: Constructing the io_uring ring on the setup thread without SINGLE_ISSUER | DEFER_TASKRUN, issuing unfixed Read SQEs without registered host buffers, and draining storage batches in identical order across ranks produced cross-rank NVMe RAID-0 lockstep stalls and avoidable per-read kernel page-pinning and interrupt overhead.
  4. Mis-scoped --pool-ram-memory and peer-UVA page-table budgeting: allocate_caches divided available host RAM by discrete_ranks before applying --pool-ram-memory and always deducted Selene's implicit host reserve, causing an explicit host reserve such as -8G on an 8-GPU host to reserve 64 GiB plus the implicit reserve and an explicit byte cap such as 64G to attempt 64 GiB per rank. On multi-GPU UVA processes with peer access, cuMemHostRegister_v2 also creates GPU MMU page-table entries across peer contexts, so charging only single-rank pinned / 512 underestimated per-GPU VRAM page-table consumption.
  5. Serialized multi-rank worker startup: NativeModel::prepare_async_transfers called start_async_transfers() sequentially per rank, serializing per-rank fixed-buffer registration across all local GPUs.

Every addition stays inside Helios's domain-agnostic hardware, OS, and lifecycle boundary: captured graphs continue to own all cache directory, routing, eviction, and prefetch policy.

What changed

  • CUDA driver bindings (helios/src/runtime_core/driver.rs):
    • Added cuCtxGetStreamPriorityRange, cuStreamCreateWithPriority, cuStreamWaitEvent, and cuMemcpyDtoHAsync_v2.
  • Ring ABI and Kani command proof (helios/src/async_transfer/ring.rs, helios/src/async_transfer/kani_proofs.rs):
    • Before: opcodes 1..=4 were valid; 5 was rejected as InvalidOpcode.
    • After: added Opcode::DevToHost = 5 and ValidatedCommand::DevToHost, enforcing priority, alignment, nonzero byte length, host and device pool bounds, completion-slot bounds, and bit-63 COMPLETION_ERROR_BIT exclusion in validate_command and validate_command_guarantees_bounds_and_alignment_for_all_inputs. The 256-byte ControlHeader ABI and existing opcodes 1..=4 are unchanged.
  • Scheduler and formal lifecycle verification (helios/src/async_transfer/scheduler.rs, helios/src/async_transfer/lifecycle_tests.rs, verification/helios-lifecycle/AsyncTransfer.tla, AsyncTransfer.cfg, verification/helios-lifecycle/check.py, verification/helios-lifecycle/README.md):
    • Before: TransferScheduler tracked IO and H2D DMA queues only and dispatched background IO/DMA up to max_bg_io/max_bg_dma even while demand ops were in flight.
    • After: added d2h_queues, inflight_d2h (InflightD2h tracking faulted and hardware_signaled), with_max_d2h, pop_next_d2h, mark_d2h_faulted, and complete_d2h; gated background IO/DMA dispatch to yield while any demand op is in flight; updated can_release_memory, advance_epoch, begin_drain, and finish_drain to retain memory ownership until in-flight D2H drains. Extended AsyncTransfer.tla (MaxD2h = 1, 20-element projection, DispatchD2h/CompleteD2h/MarkD2hFaulted), switched lifecycle_tests.rs to BFS with a test-only queue_shape_key() so priority and bounce classes are not collapsed during exploration, added TLA+ and Rust mutations covering D2H drain and fault-sentinel safety, and updated verification/helios-lifecycle/README.md.
  • Multi-stream transfer worker (helios/src/async_transfer/worker.rs):
    • Before: a single normal-priority copy_stream served all H2D transfers, default per-channel IO concurrency was DEFAULT_MAX_TOTAL_IO = 32 / DEFAULT_MAX_BG_IO = 8, bounce staging capped at 16 slots within 256 MiB, storage reads entered queues in unrotated ring order, and the worker spun for a short fixed iteration count before sleeping.
    • After: split Copy Engine execution across high-priority copy_stream (demand H2D and host-initiated completion signals), normal-priority bg_copy_stream (background H2D), and normal-priority d2h_stream (Opcode::DevToHost, DEFAULT_MAX_D2H = 2). Added cuStreamWaitEvent cross-stream synchronization whenever different streams reuse an active completion slot, plus per-slot lifetime monotonic stream_comp_max tracking so priority preemption cannot regress device_completions backwards (matching host fetch_max monotonicity, with sticky bit-63 fault sentinels). Lowered default per-channel IO depth to DEFAULT_MAX_TOTAL_IO = 16 and DEFAULT_MAX_BG_IO = 4 to curb multi-rank NVMe queue saturation, preserved faulted-DMA retention and host_mirror_on_drain across all three streams, widened bounce_pool_geometry to up to 32 slots within 512 MiB, added a 50 ms active spin window (ACTIVE_SPIN_WINDOW) before backing off, rotated contiguous same-priority storage-read runs by worker ordinal before enqueueing (preserving inflight_io SQ FIFO alignment), and moved io_uring ring creation and fixed-buffer registration onto the worker thread before publishing ChannelState::Running.
  • Linux io_uring backend (helios/src/async_transfer/io_backend.rs):
    • Before: constructed the ring on the preparation thread without DEFER_TASKRUN or registered buffers and submitted plain opcode::Read SQEs.
    • After: added bind_worker_thread() (SINGLE_ISSUER | DEFER_TASKRUN | TASKRUN_FLAG | NO_SQARRAY with kernel fallbacks), register_buffers() (1 GiB fixed-buffer chunks covering HOST_POOL and bounce_pool for opcode::ReadFixed, falling back to opcode::Read if registration fails), and taskrun() || cq_overflow() plus a periodic IORING_ENTER_GETEVENTS watchdog in poll_completions() guarded by self.queued_sqes == 0 so unsubmitted SQEs never flush outside flush_queued_sqes accounting.
  • Host-wide --pool-ram-memory, UVA page-table reserve, parallel startup, and docs (selene/src/offload.rs, helios/src/runtime_core/memory.rs, helios/src/runtime_core/model.rs, docs/cli-design.md, docs/runtime-core-design.md, helios/manifest.md):
    • Before: async_transfer_host_ram always applied Selene's implicit host reserve and divided available/total RAM by discrete_ranks before applying --pool-ram-memory, reserved pinned / 512 VRAM per rank, and started rank workers sequentially.
    • After: added host_pool_budget_and_total_with_reserve in Selene (omitting the implicit reserve when --pool-ram-memory is explicitly supplied), applied --pool-ram-memory host-wide before dividing across local discrete ranks (subtracting host bounce bytes under MemoryLimit::Reserve so the requested free reserve is preserved), charged aggregate peer-UVA page tables pinned * discrete_ranks / 512 on discrete multi-rank hosts (leaving integrated unified-DRAM sizing and host_future coordination unchanged), started all rank workers concurrently via std::thread::scope in NativeModel::prepare_async_transfers, and updated the CLI, runtime-core, and manifest specifications (including [memory] pool_ram host-wide semantics and device_completions per-slot monotonic non-regression).

Claimed benefit and result

  • Expected / structural result: Adds full-duplex DevToHost Copy Engine transfers, priority-separated demand vs background H2D streams with monotonic cross-stream completion safety, worker-owned DEFER_TASKRUN + ReadFixed Linux storage reads with lower per-rank NVMe queue depth (16 total / 4 background) and a 50 ms active spin window, accurate host-wide --pool-ram-memory and multi-rank UVA page-table budgeting, and concurrent multi-rank worker startup with full backward compatibility for existing ABI v1 cores.
  • Observed combined-diff behavior (not an isolated single-change benchmark): On 8x RTX PRO 6000 Blackwell (SM120 TP8, 8-drive PCIe Gen5 NVMe RAID-0, 251.1 GiB host RAM, --pool-ram-memory -8G, Kimi K3.1 Pro offloaded core), the combined worker and io_uring changes (DEFER_TASKRUN + ReadFixed, IO depth 16/4, 50 ms active spin, and per-rank storage-run rotation) showed cross-rank demand-stall spread of 1,202 ms (37.75–38.95 s across all 8 ranks) compared to >5,000 ms observed prior to these changes. No controlled per-feature ablation isolating DEFER_TASKRUN from IO-depth and spin-window changes was run.
  • Scope note: End-to-end token-throughput improvements from exclusive 2Q VRAM/RAM caching require the companion local-inference-lab/hyperflare-recipes#169 and are not attributed to this PR alone. Merge this PR before the companion recipes PR.

Supporting evidence and limitations

  • Formal TLA+ verification, Rust conformance, and mutation testing:
    • Command: python3 verification/helios-lifecycle/check.py --tlc-jar tla2tools-1.7.4.jar --target-dir flare-cli/target --mutations
    • Result: exited 0. AsyncTransfer.tla checked 1,847,851 generated states (125,668 distinct states, depth 24, 0 errors); 4,410 observed Rust scheduler transitions conformed to AsyncTransfer.tla; all 10 TLA+ models, 9 conformance suites, and 64/64 TLA+, observed-edge, and Rust mutations passed.
  • Rust crate builds and unit/integration tests (--locked --release):
    • eos: 12 passed, 0 failed.
    • selene (--features test-support): 649 passed, 0 failed.
    • selene-manager (--features test-support): 448 passed, 0 failed, 1 ignored.
    • flare: 255 passed, 0 failed, 4 ignored.
    • flare-cli: 254 passed, 0 failed, 3 ignored.
    • helios (--features runtime-core,server): targeted async_transfer::, runtime_core::memory::, and runtime_core::model:: passed 60/60 under RUSTFLAGS="-D warnings"; full --lib passed 1,973 tests and all integration targets (actual_qwen38_tp2, deepseek_encoder, deepseek_output, message_boundaries 14/14, unverified_empty) passed.
    • RUSTFLAGS="-D warnings" cargo check --locked --release passed for flare-cli --features roce and heliopause.
  • Live SM120 GPU verification:
    • Single-GPU CUDA test (CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 async_transfer::worker::cuda_tests::live_cuda_async_transfer_end_to_end): passed, covering Opcode::DevToHost round-trip, bg_copy_stream to copy_stream same-slot reuse, simultaneous Prefetch+Demand priority preemption monotonic non-regression on device_completions, io_uring DEFER_TASKRUN + ReadFixed, bounce staging, IoFailure error sentinels, and ControlRegionGuard.
    • Live 8-GPU SM120 TP8 smoke test (flare run on GPUs 0,2,4,6,8,10,12,14, --pool-ram-memory -8G, --kv-cache-limit context, --mtp-verification-token-budget 4, exported Kimi K3.1 Pro offloaded core): passed with 2,198,299 submitted/completed async transfers, 0 errors, 0 rejections, 0 cancellations, and clean 9.1 s shutdown drain.
  • Unrun checks and material limitations:
    • cargo-kani is not installed on this host; helios/src/async_transfer/kani_proofs.rs was updated and compiled under tests, while CBMC proof execution awaits CI.
    • 6 helios --lib frontend template tests (prepared_templates_*, qwen_content_macro_*, recipe_templates_*, compatibility_requires_*, messages_image_hints_*) failed locally because fetching meta-models/Muse-Spark-Open-816B-A42B-NVFP4 via tests/frontend/prepare_templates.py returned HTTP 403.
    • Non-Linux pread and Windows paths were not exercised on this Linux host.
    • The follow-up commit (docs: align AsyncTransfer CLI, completion monotonicity, and lifecycle docs) modifies documentation only; tests were not rerun after it.

Discord: lukealonso

…g, and host-wide RAM pool budgeting

Exclusive multi-tier weight offloading on multi-GPU hosts hits five concrete
defects and bottlenecks in Helios's `AsyncTransfer` runtime:

1. No device-to-host Copy Engine path: `AsyncTransfer` only supported
   `DiskToHost` (1), `HostToDev` (2), `DiskToDev` (3), and `CancelEpoch` (4).
   A captured graph maintaining an exclusive VRAM/RAM cache had no way to demote
   a cold VRAM resident back to `HOST_POOL` over PCIe D2H instead of dropping
   it and re-reading from NVMe later.
2. Copy Engine head-of-line blocking: demand and background H2D copies shared
   one CUDA stream, so in-flight background prefetches delayed newly arrived
   demand misses, and the scheduler dispatched background work alongside active
   demand ops.
3. Multi-rank `io_uring` tail latency and contention: constructing the ring on
   the setup thread without `SINGLE_ISSUER | DEFER_TASKRUN`, issuing unfixed
   `Read` SQEs without registered host buffers, and draining storage batches in
   identical order across ranks caused cross-rank NVMe RAID-0 lockstep stalls
   and avoidable kernel page-pinning and interrupt overhead.
4. Mis-scoped `--pool-ram-memory` and peer-UVA page-table budgeting:
   `allocate_caches` divided available host RAM by `discrete_ranks` before
   applying `--pool-ram-memory`, so an explicit host reserve such as `-8G` on
   an 8-GPU host reserved 64 GiB (plus Selene's implicit host reserve), and
   `bytes(64G)` attempted to allocate 64 GiB per rank. On multi-GPU UVA
   processes with peer access, registering pinned host pools also maps page
   tables across peer contexts, so charging only single-rank `pinned / 512`
   underestimated per-GPU VRAM page-table usage.
5. Serialized multi-rank worker startup: `NativeModel::prepare_async_transfers`
   called `start_async_transfers()` one rank at a time, serializing per-rank
   fixed-buffer registration across all local GPUs.

What changed:

- Driver bindings (`helios/src/runtime_core/driver.rs`): added
  `cuCtxGetStreamPriorityRange`, `cuStreamCreateWithPriority`,
  `cuStreamWaitEvent`, and `cuMemcpyDtoHAsync_v2`.
- Ring ABI and Kani proofs (`helios/src/async_transfer/ring.rs`,
  `helios/src/async_transfer/kani_proofs.rs`): added `Opcode::DevToHost = 5`
  and `ValidatedCommand::DevToHost`, enforcing priority, alignment, nonzero
  length, host and device pool bounds, completion-slot range, and bit-63
  `COMPLETION_ERROR_BIT` exclusion in `validate_command` and the Kani command
  validation proof. Existing opcodes `1..=4` and the 256-byte `ControlHeader`
  layout are unchanged.
- Scheduler and lifecycle verification (`helios/src/async_transfer/scheduler.rs`,
  `helios/src/async_transfer/lifecycle_tests.rs`,
  `verification/helios-lifecycle/AsyncTransfer.tla`, `AsyncTransfer.cfg`,
  `verification/helios-lifecycle/check.py`):
  - Before: `TransferScheduler` tracked IO and H2D DMA queues only, dispatching
    background work up to `max_bg_io`/`max_bg_dma` even when demand work was
    already in flight.
  - After: added `d2h_queues`, `inflight_d2h` (`InflightD2h` with `faulted` and
    `hardware_signaled`), `with_max_d2h`, `pop_next_d2h`, `mark_d2h_faulted`,
    and `complete_d2h`, and gated background IO/DMA dispatch so background work
    yields while any demand op is in flight. Updated `can_release_memory`,
    `advance_epoch`, `begin_drain`, and `finish_drain` to account for D2H
    ownership and drain. Extended `AsyncTransfer.tla` (20-element projection,
    `MaxD2h = 1`, `DispatchD2h`/`CompleteD2h`/`MarkD2hFaulted`), switched
    `lifecycle_tests.rs` to BFS with a test-only `queue_shape_key()` so
    priority and bounce classes are never collapsed during exploration, and
    added TLA+ and Rust mutations for D2H drain and fault-sentinel safety.
- Transfer worker (`helios/src/async_transfer/worker.rs`):
  - Before: one normal-priority `copy_stream` executed all H2D copies, bounce
    staging capped at 16 slots within 256 MiB, storage reads entered queues in
    unrotated ring order, and the worker spun for a short fixed iteration count
    before sleeping.
  - After: split Copy Engine execution across a high-priority `copy_stream`
    (demand H2D and host-initiated signals), a normal-priority `bg_copy_stream`
    (background H2D), and a normal-priority `d2h_stream` (`Opcode::DevToHost`).
    Added `cuStreamWaitEvent` cross-stream serialization whenever different
    streams reuse an active completion slot, plus per-slot monotonic
    `stream_comp_max` tracking so priority preemption cannot regress
    `device_completions` backwards (matching host `fetch_max` monotonicity).
    Preserved faulted-DMA retention and `host_mirror_on_drain` across all three
    streams, widened `bounce_pool_geometry` to up to 32 slots within 512 MiB,
    added a 50 ms active spin window before backing off, rotated contiguous
    same-priority storage-read runs by worker ordinal before enqueueing (keeping
    `inflight_io` FIFO order aligned with `io_uring` SQ submission), and bound
    the `io_uring` ring plus registered host buffers on the worker thread before
    publishing `ChannelState::Running`.
- Linux `io_uring` backend (`helios/src/async_transfer/io_backend.rs`):
  - Before: created the ring on the preparing thread without `DEFER_TASKRUN` or
    registered buffers and submitted plain `opcode::Read` SQEs.
  - After: added `bind_worker_thread()` (`setup_single_issuer`,
    `setup_defer_taskrun`, `setup_taskrun_flag`, `setup_no_sqarray` with kernel
    fallbacks), `register_buffers()` (1 GiB fixed-buffer chunks covering
    `HOST_POOL` and `bounce_pool` for `opcode::ReadFixed`, falling back to
    `opcode::Read` if kernel registration fails), and `taskrun() || cq_overflow()`
    plus a periodic `IORING_ENTER_GETEVENTS` watchdog in `poll_completions()`
    guarded by `self.queued_sqes == 0` so unsubmitted SQEs never flush outside
    `flush_queued_sqes` accounting.
- Host-wide `--pool-ram-memory`, UVA page-table reserve, and parallel startup
  (`selene/src/offload.rs`, `helios/src/runtime_core/memory.rs`,
  `helios/src/runtime_core/model.rs`, `docs/cli-design.md`,
  `docs/runtime-core-design.md`, `helios/manifest.md`):
  - Before: `async_transfer_host_ram` always applied Selene's implicit host
    reserve and divided available/total RAM by `discrete_ranks` before applying
    `pool_ram_limit`, reserved `pinned / 512` VRAM per rank, and started rank
    channels sequentially.
  - After: added `host_pool_budget_and_total_with_reserve` in Selene (omitting
    the implicit host reserve when `--pool-ram-memory` is explicitly set),
    applied `--pool-ram-memory` host-wide before dividing across discrete ranks
    (subtracting host bounce bytes under `MemoryLimit::Reserve` so the full
    requested reserve stays free), charged aggregate peer-UVA page tables
    `pinned * discrete_ranks / 512` on discrete multi-rank hosts (leaving
    integrated unified-DRAM sizing and `host_future` coordination unchanged),
    started all rank workers concurrently via `std::thread::scope` in
    `NativeModel::prepare_async_transfers`, and updated the design and CLI
    specifications to match.

Claimed benefit and result:

- Enables full-duplex `DevToHost` demotion, priority-isolated demand vs
  background H2D execution, fixed-buffer `DEFER_TASKRUN` storage reads,
  accurate host-wide `--pool-ram-memory` budgeting, and concurrent multi-rank
  channel startup while keeping existing cores and ABI v1 headers compatible.
- Isolated runtime measurement on 8x RTX PRO 6000 Blackwell (SM120 TP8,
  8-drive PCIe Gen5 NVMe RAID-0, 251.1 GiB host RAM, `--pool-ram-memory -8G`,
  Kimi K3.1 Pro offloaded core): enabling worker-owned `DEFER_TASKRUN` reduced
  cross-rank demand-stall spread from >5,000 ms to 1,202 ms (37.75-38.95 s
  across all 8 ranks). End-to-end throughput gains from exclusive 2Q VRAM/RAM
  tiering depend on the companion `local-inference-lab/hyperflare-recipes`
  changes and are not attributed to this commit alone.

Supporting evidence and limitations:

- Formal lifecycle verification (`python3 verification/helios-lifecycle/check.py
  --tlc-jar tla2tools-1.7.4.jar --target-dir flare-cli/target --mutations`):
  passed (exit 0). `AsyncTransfer.tla` checked 1,847,851 generated states
  (125,668 distinct states, depth 24, 0 errors); 4,410 observed Rust scheduler
  transitions conformed to `AsyncTransfer.tla`; all 10 TLA+ models, 9
  conformance suites, and 64/64 TLA+, observed-edge, and Rust mutations passed.
- Rust test suites (`--locked --release`):
  - `eos`: 12 passed, 0 failed.
  - `selene` (`--features test-support`): 649 passed, 0 failed.
  - `selene-manager` (`--features test-support`): 448 passed, 0 failed, 1 ignored.
  - `flare`: 255 passed, 0 failed, 4 ignored.
  - `flare-cli`: 254 passed, 0 failed, 3 ignored.
  - `helios` (`--features runtime-core,server`): targeted `async_transfer::`,
    `runtime_core::memory::`, and `runtime_core::model::` passed 60/60 with
    `RUSTFLAGS="-D warnings"`; full `--lib` passed 1,973 tests and all
    integration targets (`actual_qwen38_tp2`, `deepseek_encoder`,
    `deepseek_output`, `message_boundaries` 14/14, `unverified_empty`) passed.
  - `RUSTFLAGS="-D warnings" cargo check --locked --release` passed for
    `flare-cli --features roce` and `heliopause`.
- Live SM120 GPU verification:
  - Single-GPU CUDA test (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1`
    `async_transfer::worker::cuda_tests::live_cuda_async_transfer_end_to_end`):
    passed, exercising `DevToHost` round-trip, `bg_copy_stream` to `copy_stream`
    same-slot reuse, simultaneous `Prefetch`+`Demand` preemption monotonic
    non-regression on `device_completions`, `io_uring` `DEFER_TASKRUN` +
    `ReadFixed`, bounce staging, `IoFailure` sentinels, and `ControlRegionGuard`.
  - Live 8-GPU SM120 TP8 smoke test (`flare run` on GPUs `0,2,4,6,8,10,12,14`,
    `--pool-ram-memory -8G`, Kimi K3.1 Pro offloaded core): passed with
    2,198,299 submitted/completed async transfers, 0 errors, 0 rejections,
    0 cancellations, and clean 9.1 s shutdown drain.
- Unrun checks and limitations:
  - `cargo-kani` is not installed locally; `kani_proofs.rs` was updated and
    compiled in tests, while CBMC proof execution awaits CI.
  - 6 `helios --lib` template tests (`prepared_templates_*`,
    `qwen_content_macro_*`, `recipe_templates_*`, `compatibility_requires_*`,
    `messages_image_hints_*`) failed locally because fetching
    `meta-models/Muse-Spark-Open-816B-A42B-NVFP4` returns HTTP 403.
  - Non-Linux (`pread`) and Windows paths were not exercised on this Linux host.

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 737.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. enhancement New feature or request performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 5, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The core runtime implementation at 46e6a3b is solid — adversarial verification found no Blocker code bugs and the host-wide --pool-ram-memory plus multi-rank UVA page-table budgeting fixes are cleanly implemented and unit-tested. Changes are requested for four verified contract/documentation/evidence gaps: a docs/cli-design.md self-contradiction on pool_ram, an undocumented per-slot monotonicity narrowing on device_completions (no CPU unit test), an unattributed/confounded performance claim alongside undisclosed IO-depth default halving, and a stale lifecycle verification README.

  • Blockers: 0 · Should fix: 4 · Subtract/Simplify: 5 · Nits: 5
Walkthrough
  • CUDA bindings & ABI v1 ring (helios/src/runtime_core/driver.rs, helios/src/async_transfer/ring.rs, helios/src/async_transfer/kani_proofs.rs): Adds cuCtxGetStreamPriorityRange, cuStreamCreateWithPriority, cuStreamWaitEvent, and cuMemcpyDtoHAsync_v2, plus Opcode::DevToHost = 5 and ValidatedCommand::DevToHost with full bounds, alignment, nonzero-length, and bit-63 error-sentinel validation while preserving ABI_VERSION = 1 and the 256-byte ControlHeader.
  • Scheduler & formal model (helios/src/async_transfer/scheduler.rs, lifecycle_tests.rs, verification/helios-lifecycle/AsyncTransfer.{tla,cfg}, check.py): Adds d2h_queues/inflight_d2h (pop_next_d2h, mark_d2h_faulted, complete_d2h), gates background IO/H2D/D2H dispatch when demand work of the gated class is in flight, extends drain/release ownership to cover in-flight D2H, widens the TLA+ projection to 20 integers (MaxD2h = 1), switches Rust conformance exploration to BFS with queue_shape_key(), and adds D2H TLA+/Rust mutations.
  • Multi-stream worker & Linux io_uring backend (helios/src/async_transfer/worker.rs, io_backend.rs): Splits Copy Engine execution across high-priority copy_stream, normal-priority bg_copy_stream, and normal-priority d2h_stream with cross-stream cuStreamWaitEvent slot synchronization and per-slot stream_comp_max monotonicity; widens bounce_pool_geometry up to 32 slots within 512 MiB; halves default IO depth (32 -> 16, bg 8 -> 4); adds a 50 ms ACTIVE_SPIN_WINDOW and per-worker contiguous storage-run rotation; binds io_uring on the worker thread with SINGLE_ISSUER | DEFER_TASKRUN | TASKRUN_FLAG | NO_SQARRAY (with fallbacks) and 1 GiB-chunk ReadFixed buffer registration.
  • Host-wide RAM budgeting, parallel worker startup, and docs (selene/src/offload.rs, helios/src/runtime_core/memory.rs, model.rs, docs/cli-design.md, docs/runtime-core-design.md, helios/manifest.md): Adds host_pool_budget_and_total_with_reserve (omitting Selene's implicit host reserve when --pool-ram-memory is explicitly supplied), applies --pool-ram-memory host-wide before dividing across local discrete ranks (preserving free reserve after aggregate bounce under MemoryLimit::Reserve), charges peer-UVA page tables as pinned.saturating_mul(ranks).div_ceil(512) on discrete multi-rank hosts, starts rank workers concurrently via std::thread::scope, and updates runtime/manifest docs.
Merge Risk: Medium · up to 46e6a3b
  • Multi-stream completion ordering: Splitting the single copy_stream into three Copy Engine streams (copy_stream, bg_copy_stream, d2h_stream) with cuStreamWaitEvent and stream_comp_max changes device_completions from unconditional stream-order writes to lifetime per-slot monotonic non-regression; this path is currently exercised only by the gated live-CUDA test.
  • Operator-visible flag semantics & defaults: --pool-ram-memory changes from per-rank to host-wide on multi-rank discrete hosts (fixing a real bug, but altering existing multi-rank invocations), and per-channel NVMe concurrency defaults are halved (DEFAULT_MAX_TOTAL_IO 32 -> 16, DEFAULT_MAX_BG_IO 8 -> 4) with a new 50 ms active spin window per worker.
  • Linux fast path & Kani coverage: DEFER_TASKRUN/ReadFixed fallbacks are silent (let _ =), non-Linux/Windows paths are unexercised, and the updated Kani proof awaits CI execution.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

lukealonso added a commit to local-inference-lab/hyperflare-recipes that referenced this pull request Dec 5, 2026
…, and INT8 Tensor Core predictor kernels (#169)

Serving Kimi K3.1 Pro (92 MoE layers x 896 latent MXFP4 experts, 1.25 TiB
CSF-compressed / 1.32 TiB uncompressed MXFP4 routed expert weights) on an 8-GPU
96 GiB workstation (768 GiB aggregate VRAM) previously had no 3-tier offloading
path, and scaling the shared `tiered_moe_offload` component to high-expert-count
W4A16 MXFP4 models hit five concrete defects and bottlenecks:

1. No `kimi3` / `kimi31` recipe offloading support and broken DSpark Markov
   import: `Kimi3Parameters`, `KimiWeightLoader`, `PreparedLatentMoE`, and
   `PreparedDecoder` did not wire `TieredMoeAttachment`, did not support b12x's
   `w13`/`w2`/`w13_scale`/`w2_scale` + `workspace` W4A16 MXFP4 SiTU
   representation, and failed TorchInductor `auto_functionalized_v2` lowering
   when `wait_and_gather` mutated `float8_e8m0fnu` block-scale staging buffers.
   Additionally, `recipes/kimi3/dspark.py` still imported
   `PreparedRowScaledFP8MarkovEmbedding`, which was removed from
   `components/markov_sampling.py` in #104, breaking DSpark preparation when
   `markov_head_quantization == "fp8"`.
2. Transient `num_valid_tokens` aliasing across forked predictor streams:
   `_op_fork_direct_prefetch` and `_op_fork_predict_shadow_recur` passed a
   main-stream transient `num_valid_tokens` buffer to the auxiliary predictor
   stream, allowing Inductor's transient arena to reuse and clobber it with
   non-integer bits before the predictor kernel read it (causing
   `CUDA_ERROR_ILLEGAL_ADDRESS` on decode/speculative widths). Separately,
   non-uniform `n_tok` loads inside `tiered_moe_offload.cu` lacked a single
   CTA-uniform broadcast across threads.
3. Inclusive RAM duplication wasted host capacity: when host RAM held fewer
   experts than VRAM, the previous inclusive cache duplicated hot VRAM experts
   in RAM instead of caching the next-coldest disjoint band, leaving fewer
   total experts in VRAM+RAM and dropping cold VRAM victims to NVMe on eviction.
4. Predictor kernel latency at `E = 896`, `H = 7168`: BF16 vector-matrix
   ShadowRecur projections and linear top-k margin reduction serialized across
   speculative widths `W = 1..8`, adding millisecond-scale latency per layer
   and blocking overlap with MoE and post-MoE projections.
5. Prefill cache pollution and excessive custom-op mutation edges: tiled
   prefill (`tile_start >= 0`) admitted transient prefill misses into decode's
   clean-ring VRAM slots, and declaring every state tensor in `mutates_args`
   created unnecessary AOT/Inductor dependency edges.

Stacked dependency: requires `NVIDIA/hyperflare-inference#737`, which supplies
`Opcode::DevToHost = 5` for full-duplex VRAM-to-RAM victim demotion,
priority-separated demand/background H2D streams, worker-owned `DEFER_TASKRUN`
+ `ReadFixed` `io_uring`, host-wide `--pool-ram-memory`, and parallel rank
startup.

What changed:

- Shared offloading runtime and CUDA kernels
  (`hyperflare_recipes/components/tiered_moe_offload.py`,
  `hyperflare_recipes/components/tiered_moe_kernel/csrc/tiered_moe_offload.cu`):
  - Before: `TieredExpertExtentPacker` accepted only `w13_rp`/`w2_rp`/`w13_sfb`/
    `w2_sfb` representations without global scales or workspace; staging buffers
    mutated `float8_e8m0fnu` directly; forked predictor ops passed transient
    `num_valid_tokens` directly to the auxiliary stream; RAM caching was
    inclusive when RAM < E; ShadowRecur ran BF16 projections; `s_active_max`
    capped at 128; tiled prefill used separate demand and gather custom ops.
  - After:
    - Added `_RepresentationSpec` supporting both `w13_rp`/`w2_rp`/`w13_sfb`/
      `w2_sfb` and b12x W4A16 MXFP4 SiTU `w13`/`w2`/`w13_scale`/`w2_scale`
      representations (including `w13_global_scale`/`w2_global_scale` and
      persistent zero-ranged `stg_rep_workspace`), backed `float8_e8m0fnu`
      staging tensors with `uint8` for `wait_and_gather` mutation while exposing
      `float8_e8m0fnu` views to `b12x`, widened `s_active_max` to 256, and
      added `max_decode_tokens` configuration.
    - Added persistent `pred_num_valid` copied on the main stream before stream
      fork in `_op_fork_direct_prefetch` and `_op_fork_predict_shadow_recur`,
      added CTA-uniform `s_n_tok` broadcast in `tiered_moe_offload.cu`, narrowed
      custom-op `mutates_args` to sentinel mutation tokens (`dir_meta`,
      `active_count`, `pred_tok`), added fused `_op_tile_prepare` for
      demand-only decode and tiled prefill, and added `defer_join` /
      `join_pending_predict` so predictors overlap with post-MoE projections and
      residual reductions.
    - Implemented exclusive 2Q VRAM/RAM tiering when `0 < rcap < E`: `tiered_moe_init`
      reserves a clean-ring free pool in persistent VRAM (`v_warm`) and pre-warms
      the disjoint cold band `[v_warm .. v_warm + rcap)` in Host RAM; cold
      first-touch NVMe misses route through bypass VRAM and populate RAM
      probation without evicting persistent VRAM; second-touch RAM hits promote
      into clean persistent VRAM while demoting the coldest VRAM victim back to
      RAM via `OPCODE_DEV_TO_HOST = 5` (supplied by `NVIDIA/hyperflare-inference#737`);
      tiled prefill routes cold misses through bypass without stealing decode
      clean-ring slots.
    - Added rowwise INT8 packing (`quantize_rowwise_int8_packed`) for advisory
      ShadowRecur weights and replicated advisory routers, SM80+/SM120
      `mma.sync.m16n8k32` INT8 Tensor Core ShadowRecur kernels with constant-time
      `T = 1..8` execution, warp-parallel register top-k margin computation,
      per-token noise suppression (`p_te < 0.12`), and asymmetric `E >= 512`
      thresholds (`tau_dma = 0.28`, `tau_nvme = 0.56` on exclusive 2-hop
      `DISK_TO_HOST` horizon; `E < 512` thresholds for GLM-5.3 and DeepSeek-V4.1
      are unchanged).
    - Extended `TieredMoeRuntime.from_weights` to traverse mapping-valued layer
      containers (as used by `recipes/kimi3`).
- Kimi K3 / K3.1 Pro recipe integration and DSpark fix
  (`hyperflare_recipes/recipes/kimi3/{bootstrap.py,decoder.py,dspark.py,
  dspark_weights.py,recipe.py,weights.py}`):
  - Before: `Kimi3Parameters` had no `tiered_moe_offload` group,
    `KimiWeightLoader` required resident experts, `PreparedLatentMoE` reserved
    4 SMs only for `split_moe`, and `dspark.py` imported the removed
    `PreparedRowScaledFP8MarkovEmbedding`.
  - After: wired `TieredMoeOffloadParameters` (with `offloaded_expert_bytes =
    1_376_272_350_732`, rejecting `--row-shard-prefill` combinations, defaulting
    `--offload-predictor auto` to demand-only `none` unless
    `--offload-predictor-weights` or `--offload-predictor direct` is passed),
    streamed uncompressed MXFP4 experts through `TieredExpertExtentPacker` with
    symmetric shared-column reuse detection, optionally loaded rowwise-INT8
    replicated advisory routers (`full_router`) when a predictor is active,
    reserved 4 SMs for offloaded `PreparedRoutedExperts`, passed `predictor_hidden`
    and deferred predictor joins across post-MoE reductions in `PreparedDecoder`
    (only when offloading is active), and fixed `dspark.py` / `dspark_weights.py`
    to keep `markov_embedding` in BF16 with `PreparedEmbedding`.
- Tests (`tests/components/test_tiered_moe_offload_contracts.py`,
  `tests/components/test_tiered_moe_offload_cuda.py`):
  - Added Kimi K3.1 Pro TP8 parameter/extent-namespacing and dict-layout
    runtime recovery tests, lazy-import coverage for `recipes.kimi31.recipe`,
    real b12x W4A16 MXFP4 SiTU exact parity and TorchInductor AOT `float8_e8m0fnu`
    compilation tests, exclusive 2Q VRAM/RAM + `OPCODE_DEV_TO_HOST` tests,
    `E = 896` warp-parallel top-k and clean-ring prefill isolation tests,
    forked `pred_num_valid` clobber-resistance tests, and SM120 INT8 Tensor
    Core ShadowRecur vs BF16 parity tests.

Claimed benefit and result:

- Enables Kimi K3 / K3.1 Pro TP8/DCP8 3-tier MoE offloading with verified
  bit-exact W4A16 MXFP4 slab gathering and TorchInductor AOT compilation.
- Combined-stack live `flare run` measurements on 8x RTX PRO 6000 Blackwell
  (SM120 TP8/DCP8, 251.1 GiB host RAM, 8-drive PCIe Gen5 NVMe RAID-0,
  `--kv-cache-limit context`, with `NVIDIA/hyperflare-inference#737` and a
  local Kimi K3.1 Pro ShadowRecur predictor checkpoint via
  `--offload-predictor-weights`; higher tok/s and lower TTFT are better):
  - Demand-only baseline (`--offload-predictor none`, auto RAM): B1 W1 12.02
    tok/s, W4 13.91 tok/s, W8 11.23 tok/s; adaptive B1 14.09 tok/s, B2
    aggregate 11.60 tok/s, 4K prefill TTFT 20,285 ms; 0 GiB RAM adaptive 13.49
    tok/s.
  - Learned exclusive 2Q + INT8 Tensor Core predictor (`--pool-ram-memory -2G`
    unless noted, all runs `err=0, rej=0, canc=0`): B1 W1 15.80 tok/s (+31%),
    W2 19.48 tok/s, W3 19.86 tok/s (`-8G`: 20.47 tok/s), W4 20.83 tok/s
    (`-8G`: 21.03 tok/s, +51% vs W4 baseline), W8 20.70 tok/s (+84% vs W8
    baseline); adaptive B1 20.16 tok/s (+43%), B2 aggregate 17.87 tok/s (+54%),
    4K prefill TTFT 13,840 ms (-32%); 0 GiB RAM W4 16.38 tok/s.
  - These end-to-end numbers reflect the combined stack (this PR,
    `NVIDIA/hyperflare-inference#737`, and local predictor weights), not this
    PR in isolation.

Supporting evidence and limitations:

- CPU contract and Kimi K3.1 Pro recipe suites (`CUDA_VISIBLE_DEVICES=""
  .venv/bin/python -m pytest tests/components/test_tiered_moe_offload_contracts.py
  tests/recipes/test_kimi31{,_dflash,_dsa_views,_dspark,_dspark_math,_kv_budget,
  _local_slots,_query_overlap,_selection_tuning}.py -q`): 157 passed, 3 skipped,
  0 failed.
- SM120 GPU regression suite (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1
  .venv/bin/python -m pytest tests/components/test_tiered_moe_offload_cuda.py -v`):
  11/11 passed (0 failed, 0 skipped), including exact single-expert W4A16
  MXFP4 SiTU output equality (`torch.equal`), multi-expert `rel_l2 < 5e-3`,
  TorchInductor AOT `float8_e8m0fnu` parity, exclusive 2Q + `OPCODE_DEV_TO_HOST`
  round-trips, `E = 896` warp top-k + clean-ring isolation, `pred_num_valid`
  clobber protection, and INT8 Tensor Core ShadowRecur parity.
- Live SM120 TP8 numerical parity (`flare run`, W1, `--pool-ram-memory -8G`)
  against a 100%-VRAM TP16 reference on two LiveCodeBench prefill prompts:
  top-1 token matched on both prompts (token 40), 15/16 top-16 token overlap
  on both prompts (5/5 exact top-5 order on `lcb_1`), mean relative logit
  difference 0.133 on `lcb_0` and 0.158 on `lcb_1` (comparable to demand-only
  TP8 offload at 0.054 and 0.192). Greedy W1 decode diverges after 30-381
  characters from demand-only TP8 due to 1-2 BF16 ULP reduction order
  differences across staging layouts.
- Unrun checks and material limitations:
  - Kimi K3.1 Pro learned predictor weights are not yet published in
    `local-inference-lab/hyperflare-offload-predictors`; `--offload-predictor
    auto` defaults to demand-only `none` until weights are passed with
    `--offload-predictor-weights` or published.
  - Whole-model live serving benchmarks for GLM-5.3, Qwen 3.8 Flash Next, and
    DeepSeek-V4.1 were not re-run after these shared `tiered_moe_offload`
    changes (existing CUDA and contract suites for `E = 16, 64, 896` passed;
    `E < 512` threshold branches remain unchanged).
  - Pre-existing unrelated CPU test failures on `origin/main`
    (`test_kimi31_prefill_pipeline.py` and `test_kimi31_row_shard_prefill.py`
    where `_FakeLatentMoE.__call__` lacks `num_valid_tokens`) were not modified.

Design-Signed-Off-By: Antigravity (Gemini); design-review=6fcc

Signed-off-by: Luke Alonso <lalonso@gmail.com>
… docs

Three documentation discrepancies remained between the AsyncTransfer
runtime changes and the repository specifications: the sample `flare.toml`
in `docs/cli-design.md` still described `pool_ram` as per-rank while the
CLI flag table documented per-host budgeting divided across local discrete
ranks; `helios/manifest.md` and `docs/runtime-core-design.md` documented
per-slot monotonic non-regression only for host completion mirrors and
omitted `device_completions` monotonic non-regression and sticky bit-63
fault sentinels; and `verification/helios-lifecycle/README.md` still
described the 16-integer `AsyncTransfer` model without `MaxD2h = 1`,
D2H transitions, or D2H projection fields.

Before this change:
- `docs/cli-design.md` described `[memory] pool_ram` as a per-rank ceiling.
- `helios/manifest.md` and `docs/runtime-core-design.md` stated monotonic
  `fetch_max` only for host completion mirrors.
- `verification/helios-lifecycle/README.md` listed 16 projection integers
  and omitted `MaxD2h = 1`, `dispatch_d2h`, `complete_d2h`, and
  `mark_d2h_faulted`.

After this change:
- `docs/cli-design.md` describes `[memory] pool_ram` as a per-host ceiling
  divided across local discrete ranks, matching `--pool-ram-memory`.
- `helios/manifest.md` and `docs/runtime-core-design.md` specify per-slot
  lifetime monotonic non-regression and sticky bit-63 fault sentinels on
  both `device_completions` and host completion mirrors.
- `verification/helios-lifecycle/README.md` documents `MaxD2h = 1`, the
  three D2H transitions, D2H fault and drain invariants, and all 20
  projection fields matching `AsyncTransfer.cfg` and
  `helios/src/async_transfer/lifecycle_tests.rs`.

Expected result: operators, recipe authors, and verification maintainers
have specifications that match the implemented `--pool-ram-memory`
budgeting, multi-stream `device_completions` contract, and 20-integer
`AsyncTransfer` formal lifecycle model.

Validation: inspected `git diff --cached` against `docs/cli-design.md`,
`helios/src/async_transfer/worker.rs`, `verification/helios-lifecycle/AsyncTransfer.cfg`,
and `helios/src/async_transfer/lifecycle_tests.rs`. Documentation-only
change; no tests were rerun per request.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@lukealonso
lukealonso merged commit 9f07937 into main Dec 5, 2026
0 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. enhancement New feature or request performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants