Skip to content

Unblock lossless KV compression across Ignition, selene-manager, and Helios Green Contexts - #709

Merged
lukealonso merged 2 commits into
mainfrom
unblock-end-to-end-lossless-kv-compr
Dec 3, 2026
Merged

lukealonso merged 2 commits into
mainfrom
unblock-end-to-end-lossless-kv-compr

Conversation

@lukealonso

Copy link
Copy Markdown
Collaborator

Why

Flare's lossless KV checkpoint compression (--lossless-kv-compression cpu using ZKV1/v1/64-pivots and --lossless-kv-compression gpu using GKV1/v2/64-pivots-rans32) is blocked at three sequential gates across Ignition, selene-manager, and Helios (addresses #701 and #698):

  1. Ignition contract authoring (ignition/preparation/contract.py): selene/src/shared/codec_layout.rs defines 11 field encodings with strict block-byte divisibility and alignment requirements (selene/src/shared/codec.rs), yet contract.codec_layout exposed no typed enum or export-time validation, hardcoded buffer="state_pool", and iterated every entry in regions without skipping CONTINUATION_STATE. Recipes whose regions list includes CONTINUATION_STATE either raised KeyError("state_pool") or emitted duplicate overlapping state_pool fields rejected by Selene Plan::new.
  2. Single-host TP>=2 pooled compression in selene-manager (selene-manager/src/pool/): selene already supports single-process multi-GPU (TP>=2) packed v4 pooling, and selene-manager identifies multi-process sessions via session.ranks.is_some() (populated when OpenSession.rank_secret is nonempty). However, store_bridge.rs (PutBegin) and claims.rs (PinAck grant) checked descriptor.ranks.len() >= 2, rejecting every single-host TP>=2 packed put and peer DRAM export. Conversely, core.rs, lookup.rs, and claims.rs did not negotiate raw-only or exclude packed records (including all-literal v4 records) for true multi-process sessions.
  3. GPU codec startup deadlock and SM contention on persistent-worker cores (helios/src/runtime_core/, helios/src/server/runtime.rs): On cores that partition a GPU with CUDA Green Contexts for a resident persistent worker, two hazards occur under --lossless-kv-compression gpu:

Reserving a third disjoint SM Green Context partition for GPU codec execution on persistent-worker cores (only when offload and GPU compression are both active) physically isolates codec kernels from cooperative compute SMs while leaving off and cpu modes on the existing 2-way split with zero SMs lost.

What changed

1. Typed, CONTINUATION_STATE-safe codec_layout in Ignition (ignition/preparation/contract.py, tests/preparation/test_codec_layout.py)

  • Before: codec_layout(pool, regions, buffers, *, field_encoding=None) accepted untyped integers, hardcoded "state_pool", and emitted a page field for every entry in regions.
  • After:
    • Added CodecEncoding(IntEnum) matching all 11 Selene IDs with block_bytes and offset_alignment properties.
    • Added export-time validation (_validate_codec_encoding) rejecting non-integers, booleans, unknown IDs, lengths not divisible by block_bytes, and FLOAT32_MATRIX_128 offsets not 4-byte aligned.
    • Added conservative default_field_encoding(name, dtype, shape) classifying FP32 *.recurrent (..., 128, 128) matrices, BF16 *.convolution / *_convolution (..., 10|16), other BF16 fields, and defaulting all remaining fields to BYTES.
    • Updated codec_layout(pool, regions, buffers, *, field_encoding=None, state_buffer=None) to skip CONTINUATION_STATE entries in regions, resolve the row buffer from CONTINUATION_STATE or explicit state_buffer, sort and bounds-check pool.layout.regions, and reject duplicate or conflicting buffer names. Calling codec_layout with field_encoding=None continues to return None.

2. Multi-process vs. single-host TP>=2 packed pooling in selene-manager (selene-manager/src/pool/{core,store_bridge,lookup,claims}.rs, selene-manager/tests/packed.rs, selene-manager/tests/support/pool.rs)

  • Before: store_bridge.rs refused PutBegin.packed whenever descriptor.ranks.len() >= 2; claims.rs refused packed peer PinAck grants whenever descriptor.ranks.len() >= 2; core.rs negotiated packed capabilities for multi-process sessions; lookup.rs and claims.rs did not filter packed holdings for multi-process requesters or sources.
  • After:
    • store_bridge.rs refuses PutBegin.packed only when self.sessions[&sid].ranks.is_some().
    • claims.rs refuses packed peer PinAck grants only when claim.mp.req.layout.world() > 1 || claim.mp.src.layout.world() > 1.
    • core.rs retains offered_codec for RankAttach consistency and reconnect checks while negotiating codec = None whenever ranks.is_some() (so both SessionOpened.codec and RankAttached.codec signal raw-only).
    • lookup.rs and claims.rs (claim_begin and get_answer) pass None codec capabilities to permits_holding/permits_offer whenever requester or source is multi-process, excluding all packed records (including all-literal v4 records and misbehaving multi-process peer holdings) while keeping raw v3 records accessible.

3. Disjoint GPU codec Green Context and startup ordering/drain in Helios (helios/src/runtime_core/{persistent_worker,mod,model,memory}.rs, helios/src/server/runtime.rs, helios/src/server/runtime/phase_tests.rs, docs/prefix-cache-offload.md)

  • Before: GreenContextPartition always split the device into two groups (worker + compute); model.rs passed rank.execution_context() to prepare_offload, memory.rs passed self.ranks[0].execution_context() as pool registration_context, and server/runtime.rs called crate::offload::open after RankExecutor::new launched persistent workers.
  • After:
    • Extended plan_sm_split and GreenContextPartition::create with reserve_codec_partition: bool (enabled only when options.prefix_cache.enabled() && !model.gpu_codec_cubins.is_empty()). When enabled, cuDevSmResourceSplit creates three disjoint structured SM partitions: worker, one minimal aligned codec partition, and compute backfill (preserving 16-CTA co-scheduling alignment with baseline fallback). Devices lacking enough SMs for three partitions fail cleanly with an error recommending --lossless-kv-compression cpu. When compression is off or cpu, the 2-way split is unchanged.
    • Added NativeResources::offload_context() returning partition.codec_context when present and self.context otherwise; updated model.rs (prepare_offload) to pass rank.offload_context(), memory.rs (registration_context) to pass self.ranks[0].context, and release_reservations_and_context to recognize codec_context during teardown.
    • In helios/src/server/runtime.rs, moved crate::offload::open(...) ahead of RankExecutor::new(...) (after the binding.sharded() check) so cuModuleLoadData completes before any persistent worker kernel starts. Extracted fn close_store(...) preserving ManuallyDrop slab retention on drain error, panic, or undrained executor, and invoked it on all three early-error paths (RankExecutor::new, RequestScheduler::new, scheduler configuration) before signaling readiness failure.
    • Updated docs/prefix-cache-offload.md to document the 3-way Green Context partition, startup ordering, and single-host TP>=2 vs. multi-process pooled compression rules.

Claimed benefit and result

  • Ignition: Companion recipe PRs in local-inference-lab/hyperflare-recipes and local-inference-lab/hyperflare-jetson-recipes can declare validated ModelContract.cache.codec_layout across all model families, including recipes that include CONTINUATION_STATE in regions.
  • selene-manager: Single-host TP>=2 deployments can retire, recover, and peer-export compressed v4 checkpoints over SHM and TCP while multi-process sessions remain isolated on raw v3 transfers.
  • Helios GPU codec on persistent-worker cores:

Supporting evidence

  • SM120 3-way Green Context + real GpuRankCodec CUDA test (PATH="/opt/cuda/bin:$PATH" CUDA_VISIBLE_DEVICES=6 cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- persistent_worker::tests::cuda_green_context_three_way_gpu_codec_runs_concurrently_with_persistent_worker_and_cooperative_compute --ignored --nocapture --test-threads=1): 1 passed (verified 3-way split, pre-worker cuModuleLoadData, concurrent persistent worker + full-grid cooperative barrier + real kv_codec_gpu.cu bit-exact encode/decode, and clean drain/teardown).
  • Python + CUDA tests (FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=6 pytest tests/preparation/test_codec_layout.py tests/preparation/test_core_boundary.py tests/test_kv_codec.py tests/cli -q): 163 passed, 0 failed, 0 skipped.
  • Rust test suites (--locked --release):
    • eos: 12 passed, 0 failed.
    • selene --features test-support: 553 passed, 0 failed.
    • selene-manager --features test-support: 408 passed, 0 failed, 1 ignored across all unit and integration suites, including 12/12 in tests/packed.rs (single_host_tp2_packed_put_stores_and_serves_over_shm_and_tcp, single_host_tp2_peer_dram_packed_export_succeeds_over_shm_and_tcp, multi_process_tp2_stays_raw_only_and_excludes_packed_records).
    • helios --features runtime-core,server --lib: 1,835 passed, 48 ignored (all 20 targeted persistent_worker, codec_layout_tests, and close_store drain tests passed; 6 chat-template tests failed solely because FLARE_TEST_TEMPLATE_DIR was unset).
    • flare: 255 passed, 0 failed (247 lib + 7 packed_canonical_download + 1 reference_workflows; 2 localhost hub::tests:: flaked under parallel load and passed cleanly on re-run).
    • flare-cli: 246 passed, 0 failed, 3 ignored.
  • TLA+ lifecycle verification (python3 verification/helios-lifecycle/check.py --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar): passed across all 8 TLA+ models (Lifecycle, RankProtocol, DispatchRing, OffloadTransfer, CacheOwnership, Speculation, ResponseLifecycle, CheckpointReservation) and Rust conformance tests.
  • Unrun checks and material limitations:
    • End-to-end SM103 core export and flare run --lossless-kv-compression gpu at B>=2 were not run (no SM103 GPU or exported model checkpoints on this SM120 host).
    • Helios chat-template tests requiring FLARE_TEST_TEMPLATE_DIR were not run.
    • Pre-existing persistent_worker::tests::cuda_* tests hardcode fixed device VA 0x800_0000_0000, which collides with CUDA UVA placement (0x7f34...) on this 16-GPU host and were left untouched.

Discord: lukealonso

…Helios Green Contexts

Why

End-to-end lossless KV checkpoint compression (`--lossless-kv-compression cpu`
using `ZKV1/v1/64-pivots` and `--lossless-kv-compression gpu` using
`GKV1/v2/64-pivots-rans32`) fails at three independent gates:

1. Ignition contract authoring (`ignition/preparation/contract.py`):
   `selene/src/shared/codec_layout.rs` defines 11 field encodings with strict
   block-byte divisibility and alignment rules (`selene/src/shared/codec.rs`),
   yet `contract.codec_layout` exposed no typed enum or validation, hardcoded
   `buffer="state_pool"`, and iterated every entry in `regions` without
   skipping `CONTINUATION_STATE`. Recipes that place `CONTINUATION_STATE` inside
   `regions` either hit `KeyError("state_pool")` or emitted duplicate
   overlapping `state_pool` fields rejected by Selene `Plan::new`.
2. Shared pooling in `selene-manager` (`selene-manager/src/pool/`):
   `selene` supports packed v4 pooling for single-host multi-GPU tensor-parallel
   instances (`TP>=2`), and `selene-manager` distinguishes multi-process
   sessions from single-process sessions by `session.ranks.is_some()` (set when
   `OpenSession.rank_secret` is nonempty). However, `store_bridge.rs` (`PutBegin`)
   and `claims.rs` (`PinAck` grant) checked `descriptor.ranks.len() >= 2`,
   rejecting every single-host TP>=2 packed put and peer export. Conversely,
   `core.rs`, `lookup.rs`, and `claims.rs` did not negotiate raw-only or exclude
   packed records (including all-literal v4 records) for true multi-process
   sessions.
3. GPU codec execution on persistent-worker cores (`helios/src/runtime_core/`,
   `helios/src/server/runtime.rs`):
   On cores that partition the GPU with CUDA Green Contexts for a resident
   persistent worker, two hazards occur under `--lossless-kv-compression gpu`:
   - `Runtime::start` constructed `RankExecutor::new` (launching the persistent
     worker graph) before calling `crate::offload::open`, which invokes
     `cuModuleLoadData` to load `kv_codec_gpu.cubin`. Calling `cuModuleLoadData`
     while a persistent worker kernel is resident deadlocks inside the CUDA
     driver (#698).
   - `NativeModel::prepare_offload` passed `rank.execution_context()` (the
     compute green context) to `GpuRankCodec`. Launching batched GPU codec
     kernels on either the compute green context or the device primary context
     (which overlaps 100% of compute SMs) contends with full-grid cooperative
     compute kernels, collapsing decode throughput and hanging multi-request
     batches (#701).

What changed

1. Ignition (`ignition/preparation/contract.py`, `tests/preparation/test_codec_layout.py`):
   - Before: `codec_layout(pool, regions, buffers, *, field_encoding=None)`
     accepted arbitrary untyped integers, hardcoded `"state_pool"`, and treated
     every `regions` item as a paged plane.
   - After: Added `CodecEncoding(IntEnum)` matching all 11 Selene IDs with
     `block_bytes` and `offset_alignment` properties, added export-time
     validation (`_validate_codec_encoding`) checking integer type, valid ID,
     positive block-multiple length, and 4-byte matrix offset alignment, added
     conservative `default_field_encoding(name, dtype, shape)`, and updated
     `codec_layout` (with optional `state_buffer=None`) to skip
     `CONTINUATION_STATE` regions, resolve the row buffer from
     `CONTINUATION_STATE` or `state_buffer`, sort and bounds-check row regions,
     and reject duplicate or conflicting buffers. Calling `codec_layout` with
     `field_encoding=None` continues to return `None`.

2. `selene-manager` (`selene-manager/src/pool/{core,store_bridge,lookup,claims}.rs`,
   `selene-manager/tests/packed.rs`, `selene-manager/tests/support/pool.rs`):
   - Before: `store_bridge.rs` and `claims.rs` gated packed puts and peer
     exports on `descriptor.ranks.len() >= 2`; `core.rs` echoed negotiated codec
     capabilities to multi-process sessions, and `lookup.rs`/`claims.rs` did not
     filter packed holdings by multi-process requester or source.
   - After: `store_bridge.rs` gates packed `PutBegin` on
     `self.sessions[&sid].ranks.is_some()`, and `claims.rs` gates packed peer
     `PinAck` grants on `claim.mp.req.layout.world() > 1 || claim.mp.src.layout.world() > 1`.
     `core.rs` keeps `offered_codec` for `RankAttach` and reconnect consistency
     checks while negotiating `codec = None` when `ranks.is_some()`. `lookup.rs`
     and `claims.rs` (`claim_begin` and `get_answer`) pass `None` codec
     capabilities to `permits_holding`/`permits_offer` whenever requester or
     source is multi-process, excluding all packed records (including
     all-literal v4 records) while leaving raw v3 records accessible.

3. Helios Green Contexts & startup drain (`helios/src/runtime_core/{persistent_worker,mod,model,memory}.rs`,
   `helios/src/server/runtime.rs`, `helios/src/server/runtime/phase_tests.rs`,
   `docs/prefix-cache-offload.md`):
   - Before: `GreenContextPartition` split the device into two partitions
     (`worker` + `compute`); `model.rs` passed `rank.execution_context()` to
     `prepare_offload`, `memory.rs` passed `self.ranks[0].execution_context()`
     as pool `registration_context`, and `server/runtime.rs` opened the host
     prefix store after `RankExecutor::new` started the persistent worker.
   - After: `plan_sm_split` and `GreenContextPartition::create` accept
     `reserve_codec_partition: bool` (enabled only when
     `options.prefix_cache.enabled() && !model.gpu_codec_cubins.is_empty()`).
     When enabled, `cuDevSmResourceSplit` creates three disjoint structured SM
     partitions (`worker`, one minimal aligned `codec` partition, and `compute`
     backfill preserving 16-CTA co-scheduling alignment with baseline fallback);
     devices too small for three partitions return an error recommending
     `--lossless-kv-compression cpu`. When compression is `off` or `cpu`, the
     existing 2-way split is unchanged (0 SMs lost). Added
     `NativeResources::offload_context()` returning `codec_context` when present
     and `self.context` otherwise, updated `model.rs` (`prepare_offload`) to use
     `offload_context()`, updated `memory.rs` (`registration_context`) to use
     `self.ranks[0].context`, and updated teardown to handle `codec_green_ctx`.
     In `helios/src/server/runtime.rs`, moved `crate::offload::open(...)` ahead
     of `RankExecutor::new(...)` (after the `binding.sharded()` guard) and
     extracted `fn close_store(...)` preserving `ManuallyDrop` slab retention on
     drain errors, panics, or undrained executors across all three early startup
     error paths before signaling readiness failure.

Claimed benefit and result

- Ignition exposes a validated, `CONTINUATION_STATE`-safe `codec_layout` helper
  so companion recipe repositories can emit valid `ModelContract.cache.codec_layout`
  across all model families.
- Single-host TP>=2 instances can store, recover, and peer-export packed v4
  checkpoints through `selene-manager` over SHM and TCP while multi-process
  sessions stay raw-only.
- On a persistent-worker core with `--lossless-kv-compression gpu`, loading
  `kv_codec_gpu.cubin` completes before persistent-worker launch and GPU codec
  kernels run on physically disjoint SMs. Measured in a component SM120 CUDA
  concurrency test on an NVIDIA RTX PRO 6000 Blackwell (188 SMs, 3-way split
  8 worker + 8 codec + 172 compute): concurrent cooperative compute sustained
  135,922.6 steps/s (baseline 7.6 us/step, 136,046 steps in 1.0 s, zero hangs)
  alongside 251 bit-exact 1.06 MiB `GKV1` encode+decode rounds (266.4 MiB/s
  combined encode+decode, 5.98x ratio). Whole-model SM103 serving speedup and
  multi-request B>=2 throughput are expected results pending SM103 qualification.

Supporting evidence and limitations

- SM120 CUDA test (`CUDA_VISIBLE_DEVICES=6`, RTX PRO 6000 Blackwell):
  `persistent_worker::tests::cuda_green_context_three_way_gpu_codec_runs_concurrently_with_persistent_worker_and_cooperative_compute`
  passed with real `ignition/preparation/kv_codec_gpu.cu` cubin.
- Python + CUDA tests (`FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=6` on
  `tests/preparation/test_codec_layout.py`, `tests/preparation/test_core_boundary.py`,
  `tests/test_kv_codec.py`, `tests/cli`): 163 passed, 0 skipped.
- Rust test suites (`--locked --release`):
  - `eos`: 12 passed.
  - `selene --features test-support`: 553 passed.
  - `selene-manager --features test-support`: 408 passed, 1 ignored (including
    12/12 in `tests/packed.rs` covering single-host TP2 packed put, TP2 peer
    DRAM packed export over SHM/TCP, and multi-process TP2 exclusion).
  - `helios --features runtime-core,server --lib`: 1,835 passed, 48 ignored
    (including all 20 targeted `persistent_worker`, `codec_layout_tests`, and
    `close_store` tests; 6 chat-template tests failed because
    `FLARE_TEST_TEMPLATE_DIR` was unset).
  - `flare`: 255 passed (247 lib + 7 `packed_canonical_download` + 1
    `reference_workflows`; 2 localhost `hub::tests::` flaked under parallel
    load and passed cleanly on re-run).
  - `flare-cli`: 246 passed, 3 ignored.
- TLA+ formal verification (`verification/helios-lifecycle/check.py` with
  `tla2tools-1.7.4.jar`): all 8 TLA+ models and Rust conformance checks passed
  with 0 errors.
- Limitations / unrun checks: Live SM103 Parallax `flare run` with exported
  cores at `B>=2` was not run (no SM103 hardware or exported model checkpoints
  on this host). Helios chat-template tests requiring `FLARE_TEST_TEMPLATE_DIR`
  were not run. Existing `persistent_worker::tests::cuda_*` tests with
  hardcoded `0x800_0000_0000` fixed VA collide with CUDA UVA placement on this
  16-GPU host and were not modified.

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 709.
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:preparation Ignition checkpoint loading, tuning, compilation, capture, and export. area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. bug Something isn't working duplicate This issue or pull request already exists 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 3, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The three fixes are real root-cause fixes and the riskiest inverse-guard hypotheses are disproved by the callee definitions. One verified code defect remains — the new codec Green Context never receives the core's recorded CUDA context limits/cache configuration while both sibling green contexts do — plus two normative documents the PR leaves contradicting or incomplete about behavior it changes. No blocker, no hot-path regression, no wire/format change.

  • Blockers: 0 · Should fix: 3 · Subtract/Simplify: 4 · Nits: 6
Walkthrough
  • ignition/preparation/contract.py: CodecEncoding(IntEnum) (11 ids, block bytes, 4-byte alignment only for FLOAT32_MATRIX_128), _validate_codec_encoding (:208), default_field_encoding (:232), and codec_layout(..., state_buffer=None) that skips CONTINUATION_STATE (:264), resolves the row buffer (:280), sorts + bounds-checks row regions (:284-298) and rejects duplicate buffers (:299-305).
  • selene-manager/src/pool/{store_bridge,claims,core,lookup}.rs: packed put/PinAck/claim/lookup permission now keyed on session shape (ranks.is_some()) or slice-layout world() > 1; core.rs:641-651 negotiates codec = None for multi-process while keeping offered_codec for reconnect.
  • helios/src/runtime_core/persistent_worker.rs: plan_sm_split(..., reserve_codec_partition) emits worker + optional codec + backfill compute groups with codec_index/compute_index; GreenContextPartition gains codec_green_ctx/codec_context/codec_sm_count, created at :284-311/:355-396 and destroyed at :451-475.
  • helios/src/runtime_core/{mod,model,memory}.rs: offload_context() (mod.rs:1416-1421) = codec_context else the rank base context; prepare_offload uses it (model.rs:969); pool registration_context becomes ranks[0].context (memory.rs:1010); teardown recognizes codec_context (mod.rs:1641).
  • helios/src/server/runtime.rs: crate::offload::open (:683) now precedes RankExecutor::new (:699); free fn close_store (:1172) called on all three early-error paths (:706, :719, :783) with error.get_or_insert preserving the original error.
  • docs/prefix-cache-offload.md: documents the third partition, pre-worker cuModuleLoadData, and single-host TP≥2 vs multi-process packed rules.
Merge Risk: Medium · up to eb6c1e1
Pre-merge checks: ✅ 3 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: No injection or instruction-like content; cuda.rs:471 keeps HOST_REGISTER_PORTABLE so the base-context registration stays visible from the codec context; the Discord: lukealonso line is required metadata (design-review principle 17).
  • ✅ Charter & value fit: Root-cause fix per layer, no per-model branches, no new flags/dependencies, no .proto/wire/format change (packed v4 and raw v3 bytes untouched); description carries all four required parts plus a limitations section.
  • ⚠️ Related / duplicate / conflict check: Open Open host prefix store before RankExecutor::new() to avoid cuModuleLoadData deadlock with persistent GPU workers #698 duplicates the runtime.rs startup-ordering fix this PR also implements (its review asked for exactly this close_store ownership work); fix(selene-manager): harden multi-rank packed handling, protocol validation, and resource reclamation #612's world >= 2 guard is narrowed; selene,helios: add write-side NVMe and pool spill profitability gate #694 edits claims.rs adjacently. The diff also carries Prompt::preserve_message_anchor (runtime.rs:47-52, :288) that this PR does not describe.
  • ⚠️ Tests & verification evidence: TLA+ 8 models + conformance and Layer-1 --release suites reported (not independently reproducible here); the new 3-way CUDA test is #[ignore]d and single-host SM120 component-level, while SM103 flare run --lossless-kv-compression gpu at B>=2 was not run — correctly disclosed, not claimed as measured.

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

Want a frontier second opinion? If these findings look noisy, request a one-time SuperAgent Review on eb6c1e1 (~3–4 min; re-adjudicates existing findings without re-running discovery).

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

…, and helpers

Why

- `NativeResources::prepare_kernels` applied recorded CUDA context limits and
  cache configuration to the primary, worker, and compute Green Contexts, but
  omitted `partition.codec_context`. Under `--lossless-kv-compression gpu`,
  `kv_codec_gpu` kernels and offload DMA streams ran with driver defaults on
  persistent-worker cores rather than the core's recorded context settings.
- Two normative specifications contradicted or omitted behavior changed in this
  branch: `docs/runtime-core-design.md` still specified a two-group Green
  Context split and two-context settings/teardown, and `selene-manager/PROTOCOL.md`
  did not specify that single-process sessions (including single-host `TP >= 2`)
  remain packed-capable while multi-process sessions negotiate raw-only and
  exclude packed holdings/offers.
- Secondary review items identified duplicated `selene-manager` capability
  gating (including an implicit source-world assumption in `get_answer`),
  `numbers.Integral` scalar rejection in `ignition.preparation.contract`,
  unreachable `state_buffer` validation when `row_regions` is empty, an implicit
  `row_buffer` collision check, a `0` sentinel in `plan_sm_split`, and a
  duplicated `TestFiles` fixture in `persistent_worker.rs`.

What changed

- Helios (`helios/src/runtime_core/{mod,model,persistent_worker}.rs`):
  - After storing `self.green_partition = Some(partition)`, call
    `apply_context_settings(&driver, codec_context, &core.context)?` whenever
    `codec_context` is non-null.
  - Assert recorded `CU_LIMIT_STACK_SIZE` (`4096`) on `worker_context`,
    `compute_context`, and `codec_context` in the 3-way SM120 CUDA test.
  - Compute `reserve_codec_partition` directly from
    `options.prefix_cache.enabled() && options.prefix_cache.compression == KvCompression::Gpu`.
  - Use `Option<u32>` for `aligned_codec` in `plan_sm_split` and clarify the
    small-SM error message.
  - Hoist a single `TestFiles` fixture in `persistent_worker::tests`.
- `selene-manager` (`selene-manager/src/pool/{core,lookup,claims}.rs`):
  - Extracted `packed_caps(&self.sessions, requester_sid, multi_process)` and
    routed `lookup.rs`, `claims.rs::claim_begin`, and `claims.rs::get_answer`
    through it, checking both `claim.mp.req.layout.world() > 1` and
    `claim.mp.src.layout.world() > 1` in `get_answer`.
- Ignition (`ignition/preparation/contract.py`,
  `tests/preparation/test_codec_layout.py`):
  - Accepted `numbers.Integral` (still rejecting `bool`) for codec encodings,
    offsets, and lengths.
  - Validated `state_buffer` before the empty `row_regions` early return and
    separated continuation-buffer collision checks from duplicate paged buffer
    checks, with unit tests covering all three.
- Normative docs (`docs/runtime-core-design.md`, `selene-manager/PROTOCOL.md`):
  - Documented the 2-way vs 3-way Green Context split, context settings and
    teardown for `codec_context`, pre-worker `offload::open`, and the
    single-process vs multi-process revision-4 packed rules.

Verification

- SM120 CUDA (`CUDA_VISIBLE_DEVICES=6`, RTX PRO 6000 Blackwell):
  `cuda_green_context_three_way_gpu_codec_runs_concurrently_with_persistent_worker_and_cooperative_compute`
  passed (`worker=8, codec=8, compute=172` SMs; `CU_LIMIT_STACK_SIZE=4096` verified
  on all three Green Contexts; concurrent cooperative compute `134,996.0 steps/s`
  alongside 250 bit-exact `GKV1` encode+decode rounds, `265.5 MiB/s`, `5.98x`).
- Rust (`--locked --release`):
  - `selene-manager --features test-support`: full suite passed (including 12/12
    in `tests/packed.rs`).
  - `helios --features runtime-core,server --lib`: `persistent_worker::tests`
    (9 passed), `runtime::phase_tests` (129 passed), `codec_layout_tests` (6 passed).
  - `RUSTFLAGS="-D warnings" cargo check --locked --all-targets` passed with
    0 warnings on `selene-manager` and `helios`.
- Python: `pytest tests/preparation/test_codec_layout.py tests/preparation/test_core_boundary.py`
  (12 passed).

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b
@lukealonso

Copy link
Copy Markdown
Collaborator Author

Addressed the review findings in commit e899a4fe:

  • Codec Green Context settings (helios/src/runtime_core/mod.rs, persistent_worker.rs): NativeResources::prepare_kernels now applies recorded CUDA context limits and cache configuration (apply_context_settings) to partition.codec_context when present (after storing self.green_partition = Some(partition) so driver errors still release the partition on drop). Extended the 3-way SM120 CUDA test to record CU_LIMIT_STACK_SIZE = 4096 and assert it across worker_context, compute_context, and codec_context.
  • Normative specifications (docs/runtime-core-design.md, selene-manager/PROTOCOL.md): Updated docs/runtime-core-design.md for the 2-way vs 3-way Green Context split, context settings and teardown across all created green contexts, codec_context offload/codec binding, and pre-worker offload::open. Updated selene-manager/PROTOCOL.md to specify the single-process (including single-host TP >= 2) vs multi-process revision-4 negotiation, PutBegin.packed refusal, and lookup/claim/export exclusion rules.
  • Simplifications and validation refinements:
    • Hoisted a single TestFiles fixture in helios/src/runtime_core/persistent_worker.rs, replaced the 0 sentinel for aligned_codec in plan_sm_split with Option<u32>, and expressed reserve_codec_partition in helios/src/runtime_core/model.rs directly from options.prefix_cache.enabled() && options.prefix_cache.compression == KvCompression::Gpu.
    • Consolidated selene-manager packed-capability gating in selene-manager/src/pool/core.rs (packed_caps) across lookup.rs, claims.rs::claim_begin, and claims.rs::get_answer (checking both claim.mp.req.layout.world() > 1 and claim.mp.src.layout.world() > 1 in get_answer).
    • Accepted numbers.Integral scalars (still rejecting bool) in ignition/preparation/contract.py, moved state_buffer validation ahead of the empty row_regions early return, and separated continuation-buffer collision checks from duplicate paged buffer checks (tests/preparation/test_codec_layout.py).
  • Two nits left unchanged:
    • pool.layout.row_bytes is a live attribute defined on StateLayout in ignition/components/state.py and consumed by ignition/components/state_transfer.py; the bounds check stays intact.
    • Prompt::preserve_message_anchor is not touched by this branch (git diff 3d1614cc..HEAD contains zero occurrences; it landed on main earlier in #697).

Verification on e899a4fe:

  • SM120 CUDA (CUDA_VISIBLE_DEVICES=6, RTX PRO 6000 Blackwell): cuda_green_context_three_way_gpu_codec_runs_concurrently_with_persistent_worker_and_cooperative_compute passed (worker=8, codec=8, compute=172 SMs; CU_LIMIT_STACK_SIZE = 4096 verified on all three Green Contexts; concurrent cooperative compute 134,996.0 steps/s alongside 250 bit-exact GKV1 rounds, 265.5 MiB/s, 5.98x).
  • Rust (--locked --release): selene-manager --features test-support full suite passed (including 12/12 in tests/packed.rs); helios --features runtime-core,server --lib passed (persistent_worker::tests 9/9, server::runtime::phase_tests 129/129, codec_layout_tests 6/6); RUSTFLAGS="-D warnings" cargo check --locked --all-targets clean on both crates.
  • Python: pytest tests/preparation/test_codec_layout.py tests/preparation/test_core_boundary.py (12 passed).

@flare-autobot

@lukealonso
lukealonso merged commit cb191a9 into main Dec 3, 2026
3 checks passed
lukealonso added a commit to local-inference-lab/hyperflare-recipes that referenced this pull request Dec 3, 2026
Why

Helios requires a declared `ModelContract.cache.codec_layout` at startup
whenever `--lossless-kv-compression cpu` or `--lossless-kv-compression gpu` is
enabled (`helios/src/runtime_core/memory.rs`), and Ignition only embeds the
compiled `kv_codec_gpu.cubin` module during core export when `codec_layout` is
present (`ignition/preparation/runtime_core.py`). Previously, only `glm53`
emitted `codec_layout`; the other 14 recipe contract modules (covering 15 model
directories, including `kimi3`/`kimi31`) omitted it, causing every exported
core from those families to fail startup under lossless KV compression.

Depends on NVIDIA/hyperflare-inference#709, which adds
`CodecEncoding(IntEnum)`, `default_field_encoding`, export-time block-size and
alignment validation, and `CONTINUATION_STATE`-safe `codec_layout` handling in
`ignition.preparation.contract`. Merge that Flare PR (and bump the pinned
`ignition` revision) before merging this PR.

What changed

- Added `codec_layout=c.codec_layout(pool, regions, buffers, field_encoding=...)`
  to all 14 previously missing recipe `contract.py` modules and updated
  `glm53/contract.py` to use `c.CodecEncoding` and `c.default_field_encoding`:
  - `glm53`: preserves exact wire IDs (`LATENT_528=40`, `INDEX_132=41`,
    `FLOAT32_MATRIX_128=1`, `CONVOLUTION_20=20`, `BFLOAT16=2`, `BYTES=0`) via
    `CodecEncoding` and `default_field_encoding`.
  - `kimi3` (shared with `kimi31`, folding in #42): classifies `layer*.latent`
    uint8 `(128 * 576,)` and `draft*.latent` FP8 `(window % 128 == 0, 576)` as
    `LATENT_576=48`, `layer*.indexer` uint8 `(128 * 132,)` as `INDEX_132=41`,
    uint8-backed BF16 `draft*.latent` `(128 * 576 * 2,)` as `BFLOAT16=2`, and
    delegates KDA `.recurrent`/`.convolution`/BF16 fields to
    `default_field_encoding`.
  - `deepseek41`: classifies `*.window` (`WINDOW_FP4=45`) and `*.latent_page`
    (`LATENT_FP4=47`) matching `tests/fixtures/codec_geometry/deepseek41.contract.pb`.
  - `deepseek4`: classifies C4 `*.index_page` (`INDEX_132=41`) and delegates
    remaining fields to `default_field_encoding`.
  - `qwen38`: classifies `(64, 2, 256)` FP8 `*.main_k_cache`/`*.main_v_cache`
    as `FP8_PAGE_512=42` on TP1 and `BYTES=0` on TP2, matching both
    `qwen38-tp1` and `qwen38-tp2` codec geometry fixtures.
  - `qwen38_dense`, `ergo`, `gemma4`, `inkling2`, `mimo_v2`, `minimax_m3`,
    `muse_spark`, `nemotron_h`, `step5`: classify 512-byte-row FP8 KV pages
    and rings as `FP8_PAGE_512=42` (plus uint8-backed BF16 `draft*.{key,value}`
    pages as `BFLOAT16=2` in `ergo` and `inkling2`), and delegate recurrent,
    convolution, and BF16 fields to `default_field_encoding` (ensuring BF16
    `.recurrent` in `nemotron_h` selects `BFLOAT16=2`, not `FLOAT32_MATRIX_128`).
  - `inkling2_parallax`: delegates directly to `default_field_encoding` (BF16
    histories/hidden states use `BFLOAT16=2`, 2048-stride interleaved FP8 KV
    planes stay `BYTES=0`).
- Added `tests/recipes/test_fleet_codec_layout.py` verifying protobuf
  `ModelContract` round-trip and every Selene `Plan::new` invariant across all
  15 recipe contract modules, including Kimi K3/K3.1 negative matching,
  Qwen3.8 TP1 vs. TP2, DeepSeek-V4.1/V4, Inkling2/Parallax `CONTINUATION_STATE`
  handling, and Nemotron-H BF16 `.recurrent` classification.

Claimed benefit and result

All 15 recipe contracts (16 recipe directories) in `hyperflare-recipes` now
emit validated `ModelContract.cache.codec_layout` metadata so newly exported
cores embed `kv_codec_gpu.cubin` and qualify for both `--lossless-kv-compression
cpu` and `--lossless-kv-compression gpu` in Helios.

Supporting evidence and limitations

- Ran CPU unit tests against the paired Flare worktree
  (`PYTHONPATH=<flare-worktree>:<recipes-worktree> pytest tests/recipes/test_fleet_codec_layout.py tests/recipes/test_glm53_codec_layout.py -q`):
  12 passed (5/5 fleet tests covering all 15 recipes + 7/7 GLM-5.3 tests).
- Limitations / unrun checks: Full GPU core exports (`ignition export`) and
  live `flare run --lossless-kv-compression cpu|gpu` serving benchmarks were
  not run for each recipe in this session (no checkpoints on this host).
  `tests/preparation/test_native_recipe_contract.py` requires `flare_heliopause`
  built with `--features qualification` and was not run.

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=6fcc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:preparation Ignition checkpoint loading, tuning, compilation, capture, and export. area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. bug Something isn't working duplicate This issue or pull request already exists 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