Skip to content

fix(ignition): reconcile divergent multi-host selections, propagate peer b12x env and kernel cache, and harden ForwardCache - #668

Merged
lukealonso merged 1 commit into
mainfrom
unify-tuning-cache-identity-and-mult
Dec 3, 2026
Merged

lukealonso merged 1 commit into
mainfrom
unify-tuning-cache-identity-and-mult

Conversation

@lukealonso

@lukealonso lukealonso commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Multi-host preparation (ignition export --ranks N paired with ignition join, and multi-host ignition debug-serve --ranks N) fails or risks cache corruption across three coupled paths:

  1. Multi-host autotune non-convergence (Multi-host default autotune still fails kernel agreement after #631 was marked as completed #651): agree_selections (ignition/preparation/collectives.py) checks kernel agreement by request.name, whereas reconcile_selections keyed entries solely by portable_declaration(plan) and skipped any declaration with participants <= 1. Whenever rank-local state caused a request's declaration to differ between ranks, reconcile_selections left both ranks' selections untouched and agree_selections failed again on every retry.
  2. Dropped Recipe.b12x_environment and leaked config.kernel_cache on peer hosts: Rank zero applies plan.recipe.b12x_environment (for example B12X_W4A16_A4_PREFILL=1 on GLM-5.3 and B12X_W4A16_SMALL_M_HOST_BARRIER_RESET=0 on Kimi) via environment.apply before importing torch, triton, or b12x (ignition/cli/serve.py). On peers, HostRendezvous (ignition/preparation/host_ranks.py) did not transmit b12x_environment, and join() called environment.apply before knock() (which invoked runtime_patches.apply() and imported b12x.preparation before connecting to rank zero). serve_peer also passed rank zero's pickled config.kernel_cache unmodified into prepare(...) and did not forward the peer's local kernel_cache into peer export_options(...).
  3. ForwardCache environment omission, non-atomic .bin persistence, and corrupt-archive crashes: ForwardCache.__init__ (ignition/preparation/aot.py) omitted execution-relevant B12X_* environment variables from its SHA-256 cache root key, allowing compiled forwards prepared under different b12x kernel flags to collide. Three ForwardCache save sites wrote .bin archives directly with save_compiled_function(str(path)) without atomic rename, three inline temp-file writers unlinked sibling temp files while handles were still open, and ForwardCache._load(..., required=False) raised instead of recovering as a cache miss when loading a truncated or corrupt .bin archive.

This PR pairs with local-inference-lab/flashinfer#199, which bumps collided b12x candidate_contract_version counters, adds deterministic AST/source fingerprinting to TuningContract, gates unused split_fc1_scales / shared_input_scales flags in MoeDecodeQuery, and lands flashinfer#67. Neither PR requires the other to merge first.

What changed

  • Request-name-first selection reconciliation (ignition/preparation/collectives.py):
    • Before: _selected_plan_catalog discarded request names and reconcile_selections reconciled only entries whose portable_declaration(plan) appeared on more than one rank.
    • After: _selected_plan_catalog records (request.name, variant, plan.component_id) (using a flat tuple variant path (*variant, count) for nested composite plans) alongside portable_declaration(plan) for non-collective requests (request.collective is None). reconcile_selections matches shared request names across ranks first so rank-divergent declarations for the same request adopt rank zero's selected configuration before agree_selections, and falls back to portable_declaration matching for shared declarations whose request names differ across ranks. Both changed and local configs use one target_for resolver so all ranks enter or skip the reconcile pass in lockstep while preserving component_id safety.
  • Peer b12x_environment admission propagation and local kernel_cache remapping (ignition/preparation/host_ranks.py, ignition/cli/serve.py, docs/multi-host.md):
    • Before: HostRendezvous (PROTOCOL = 5) sent no b12x_environment, join() ran environment.apply(configuration, (gpu,)) before knock(), and serve_peer forwarded rank zero's config.kernel_cache unmodified and omitted kernel_cache from peer export_options.
    • After: HostRendezvous (PROTOCOL = 6) accepts and validates b12x_environment (rejecting non-B12X_ keys, B12X_COMPILE_CACHE_DIR, and non-string values; wired from model.recipe.b12x_environment in _export_hosts and debug_serve) and sends it in the _admit JSON reply. knock() validates and returns (control, executor, b12x_environment), closing control on failure. join() calls source_identity() and knock() before environment.apply(configuration, (gpu,), b12x_environment) (closing both sockets on error) so b12x and b12x.preparation see rank zero's recipe settings before import, and passes the peer's local kernel_cache to serve_peer. serve_peer remaps config.kernel_cache to Path(kernel_cache) and passes kernel_cache into peer export_options(...). Documented this behavior under "Prepare the core" in docs/multi-host.md.
  • ForwardCache keying, atomic persistence, and corrupt-archive recovery (ignition/preparation/aot.py, ignition/preparation/compile_pool.py):
    • Before: ForwardCache.__init__ hashed (namespace, options, torch_key(), runtime_patches.identity(), device_properties), three ForwardCache .bin save sites wrote directly without atomic rename, compile_pool._compile_forward duplicated the sibling-temp save helper, three inline temp-file writers in aot.py unlinked temp files inside open with blocks, and _load(..., required=False) failed on corrupt .bin archives during restore.
    • After: ForwardCache.__init__ includes sorted execution-relevant B12X_* bindings (_b12x_forward_env(), excluding host-local cache directories, worker counts, RDMA device selectors, and logging flags so distinct hosts keep identical relative cache roots). Extracted _atomic_write_file(path, writer) (closing file handles before rename or temp cleanup) for guard cache, _share_artifacts, and lent-job writes, and shared _save_compiled_function(artifact, path) across all three ForwardCache save sites and compile_pool._compile_forward. Updated ForwardCache._load(..., required=False) to open the file outside archive error handling (treating FileNotFoundError as a miss), close the handle before unlinking, catch only genuine archive/deserialization faults (EOFError, pickle.UnpicklingError, struct.error, zlib.error, zipfile.BadZipFile), emit a RuntimeWarning naming the path and error, guard unlink(missing_ok=True) against OSError, and propagate OSError, MemoryError, torch.OutOfMemoryError, RuntimeError, and ValueError without deleting the cached .bin.
  • Compatibility and cache impact: Bumping preparation rendezvous PROTOCOL from 5 to 6 keeps the wire-version constant aligned with the _admit reply schema (mismatched checkouts are also rejected by source_identity()). Hashing _b12x_forward_env() into ForwardCache.root triggers a one-time forward recompile for recipes that declare b12x_environment (such as GLM-5.3 and Kimi). No Helios runtime, Protobuf schema, or exported model-core format changes.
  • Tests (tests/preparation/):
    • test_tuning_shards.py: 2-rank Gloo test covering reconcile_selections across rank-divergent declarations sharing request.name, differing request names sharing portable_declaration, fixed-point changed is False once aligned, and agree_selections passing.
    • test_host_ranks.py: HostRendezvous -> knock loopback admission validation/rejection tests, serve.join() ordering and socket-cleanup tests, a clean-subprocess check verifying torch/b12x/flashinfer are not imported before environment.apply, and serve_peer tests covering config.kernel_cache remapping and peer export_options(..., remote_cache=True, kernel_cache=peer_cache) without mutating process-global os.environ.
    • test_forward_cache_sources.py: B12X_* keying inclusion/exclusion tests, _save_compiled_function and _atomic_write_file closed-handle-before-cleanup atomic write tests, and _load coverage for FileNotFoundError, corrupt-archive RuntimeWarning + unlink, read-only unlink PermissionError, required=True propagation, and non-archive error propagation (torch.OutOfMemoryError, MemoryError, ENOSPC OSError, RuntimeError, ValueError, and open PermissionError).
    • test_forward_artifact_sharing.py: updated _Artifact.save_compiled_function test double to write its loaded payload bytes.

Expected result

  • Multi-host peer ranks apply rank zero's recipe.b12x_environment before importing preparation libraries (torch, triton, b12x) and store compiled forwards under their own host-local kernel_cache.
  • When per-rank declarations still diverge for the same request.name, reconcile_selections converges peers to rank zero's selection before agree_selections.
  • ForwardCache isolates compiled forwards across differing execution-relevant B12X_* settings (with a one-time recompile for recipes declaring b12x_environment), writes cache files atomically with closed-handle cleanup, and warns and recovers from corrupt .bin archives without deleting valid entries on transient I/O, OOM, CUDA, or contract faults.

Validation and limitations

Rebased onto origin/main (cb191a93) and validated using /home/luke/projects/flare/.venv/bin/python (editable FlashInfer 5c41b6ebd) with PYTHONPATH=. from the worktree root:

  • Targeted preparation & CLI CPU suites (CUDA_VISIBLE_DEVICES="" pytest tests/preparation/test_host_ranks.py tests/preparation/test_forward_cache_sources.py tests/preparation/test_forward_artifact_sharing.py tests/preparation/test_forward_compile_options.py tests/preparation/test_compile_pool.py tests/preparation/test_tuning_shards.py tests/preparation/test_tuning_replicas.py tests/preparation/test_checkpoint_source.py tests/preparation/test_dcp_selection_groups.py tests/preparation/test_core_boundary.py tests/cli/ -v): 325 passed, 0 failed (58.0 s).
  • Full CPU pytest suite (CUDA_VISIBLE_DEVICES="" pytest tests/ -q): 2515 passed, 458 skipped, 3 failed (4m48s). All 15 tests in tests/preparation/test_native_processes.py passed (plus 100/100 standalone [orphan] iterations). The 3 local failures stem from running against the shared /home/luke/projects/flare/.venv environment rather than this diff:
    • test_source_identity.py::test_heliopause_build_source_identity_matches_workspace_sources: flare_heliopause in the shared venv was compiled against an older checkout's helios/src.
    • test_runtime_triton.py::test_replaces_stock_architecture_probe_with_pointer_width_key: the shared venv's Triton install already returns the patched platform_key.
    • test_inspect_forward_kernels.py::test_inspect_forward_kernels_reads_saved_aot_artifact: host symlink /home/luke/.cache/flare/kernels -> /data/cache/flare/kernels-default lacks its target; rerunning with a writable HOME passed (1 passed in 6.3 s).
  • Single-GPU SM120 CUDA tests (FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=0, RTX PRO 6000 Blackwell, across test_inductor_tuning_cuda.py, test_capture_order_cuda.py, test_scratch_cuda.py, test_graph_local_scratch_cuda.py, test_recorded_export_graph_cuda.py, test_capture_cublas_workspace_cuda.py): 18 passed, 5 skipped (torchrun-gated TP2 cases), 0 failed (105.0 s).
  • TP2 distributed SM120 CUDA tests (FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=0,1 torchrun --standalone --nproc_per_node=2 -m pytest tests/preparation/test_inductor_tuning_cuda.py -k "tp2 or distributed" -v): 5 passed, 0 failed (50.5 s).
  • Not run: Rust crate tests (no Rust files modified), live 2-host GB10 SM121 TP2 ignition export + ignition join of GLM-5.3, and paired local-inference-lab/flashinfer#199. End-to-end resolution of Multi-host default autotune still fails kernel agreement after #631 was marked as completed #651 on live 2× GB10 hardware remains to be confirmed on that hardware.

Related: #651
Paired FlashInfer PR: local-inference-lab/flashinfer#199

Discord: lukealonso

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 668.
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:rocenante RoCEnante cross-host GPU collectives and RoCE transport. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 1, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

PR #668 cleanly fixes three real multi-host prep defects—request-name-first selection reconciliation, peer b12x_environment / local kernel_cache propagation, and ForwardCache B12X keying with atomic .bin persistence—and has no hard blockers. Before merge: tighten ForwardCache._load's overly broad corrupt-cache handler, stop the new serve_peer test from leaking B12X_* into process-global os.environ, and don't auto-close #651 until it's confirmed on live 2× GB10.

  • Blockers: 0 · Should fix: 3 · Subtract/Simplify: 2 · Nits: 4
Walkthrough
  • Request-name-first reconciliation (collectives.py:196-224, 398-449): _selected_plan_catalog records (request.name, variant, plan.component_id) alongside portable_declaration(plan); reconcile_selections prefers shared name_key matches before falling back to decl_key, using one target_for helper for both changed and configs so all ranks enter or skip the reconcile pass in lockstep while preserving component-ID safety and DCP subgroup independence (request.collective is None).
  • Peer b12x_environment & local kernel_cache (host_ranks.py:201-239, 313-381, 625-720; serve.py:197, 420, 554): HostRendezvous accepts and validates model.recipe.b12x_environment (wired from _export_hosts and debug_serve), transmits it to peers before assignment unpickling (and again inside assignment); serve_peer applies it, remaps config.kernel_cache to the peer's local kernel_cache passed by join, and forwards kernel_cache into peer export_options.
  • ForwardCache keying, atomic writes, corrupt-.bin recovery (aot.py:47-100, 870-877, 897-899, 1326, 1371-1380, 1454, 1463): __init__ hashes execution-relevant B12X_* env vars via _b12x_forward_env(); all three direct save_compiled_function(str(path)) sites become sibling-temp _save_compiled_function; _share_artifacts cleans up temps; _load(..., required=False) treats _CORRUPT_ARTIFACT_ERRORS as a cache miss with unlink.
  • Tests (test_tuning_shards.py:264-325, test_host_ranks.py:334-438, test_forward_cache_sources.py:65-140, test_forward_artifact_sharing.py:130-154, 261-262): Adds a 2-rank Gloo reconcile test, rendezvous env validation and serve_peer env/cache-remapping tests, ForwardCache keying / atomic-save / corrupt-load tests, and makes _Artifact.save_compiled_function write real payload bytes.
Merge Risk: Medium · up to d4d7b2d
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
Should Fix (3)

1. Narrow _CORRUPT_ARTIFACT_ERRORS, log dropped artifacts, guard unlink (aot.py:64-76, 1371-1380)

  • _load(..., required=False) wraps both path.open('rb') and torch.compiler.load_compiled_function(file) (which runs _load_inductor at aot.py:103-144—Triton cubin disk writes, CUDA module deserialization, and the ValueError/RuntimeError contract checks at lines 111 and 128) in except _CORRUPT_ARTIFACT_ERRORS, which includes OSError and RuntimeError.
  • Any transient I/O error (EIO, ENOSPC, EMFILE) or non-OOM CUDA driver RuntimeError silently deletes a valid compiled .bin with no warning and forces a full recompile. On a read-only cache (EROFS/EACCES), Path(path).unlink(missing_ok=True) at line 1379 raises an uncaught OSError from inside the handler, turning a recoverable miss into a hard crash.
  • MemoryError in isinstance(error, (MemoryError, torch.OutOfMemoryError)) at line 1377 is unreachable: MemoryError is not a subclass of any _CORRUPT_ARTIFACT_ERRORS member (only torch.OutOfMemoryError, a RuntimeError subclass, can reach it).
  • Fix: Keep path.open('rb') outside the corrupt-archive handler (or handle FileNotFoundError separately); narrow the tuple to genuine archive/deserialization errors (EOFError, pickle.UnpicklingError, struct.error, zlib.error, zipfile.BadZipFile, plus only the specific ValueError/RuntimeError from truncated load_compiled_function headers if observed—not blanket OSError/RuntimeError); emit a warning naming path and error before unlinking; wrap unlink(missing_ok=True) in try/except OSError; drop the dead MemoryError check (keep torch.OutOfMemoryError only if RuntimeError remains in the tuple).

2. Fix the process-global os.environ leak and test gaps (test_host_ranks.py:361-362, 426-438; test_forward_cache_sources.py:136-140)

  • In test_serve_peer_applies_b12x_environment_and_remaps_kernel_cache, monkeypatch.delenv("B12X_W4A16_A4_PREFILL", raising=False) and monkeypatch.delenv("B12X_W4A16_SMALL_M_HOST_BARRIER_RESET", raising=False) are no-ops when those keys start absent, so pytest registers no teardown restoration. serve_peer then calls os.environ.update(...) directly, leaking both B12X_* vars into os.environ for all later tests in the same worker—directly perturbing _b12x_forward_env() and ForwardCache.root.
  • In test_forward_cache_recovers_from_corrupt_cached_bin_on_restore (test_forward_cache_sources.py:136-140), mocking MemoryError never enters the handler, leaving the torch.OutOfMemoryError carve-out at aot.py:1377 untested.
  • Neither host_ranks.py:718-719 (forwarding kernel_cache into peer export_options) nor reconcile_selections returning changed is False on agreeing ranks is covered.
  • Fix: Restore os.environ in the serve_peer test (e.g., monkeypatch.setenv(k, "") then monkeypatch.delenv(k), or restore in finally:), test torch.OutOfMemoryError in test_forward_cache_sources.py, and add focused assertions for peer export_options(..., kernel_cache=...) and reconcile_selections with agreeing ranks (changed is False).

3. Do not auto-close #651 before live 2× GB10 verification

Subtract / Simplify (2)

1. Collapse the duplicate b12x_environment transmission and remove the unused prepare(..., b12x_environment=None) param (host_ranks.py:313-314, 325-326, 377, 666-668; test_host_ranks.py:400-412)

  • prepare sends ("b12x-environment", b12x_env) at lines 345-347 before assignment = receive_object(control) (line 665, which unpickles assignment["prepare"] and imports the recipe and its b12x operator modules), then sends the identical dict again inside assignment["b12x_environment"] at line 377, where serve_peer validates and applies it a second time at lines 666-668. Because the early command is always sent when b12x_env is non-empty, the assignment copy can never carry anything new (the test at test_host_ranks.py:400-412 only exercises both paths by fabricating different dicts that HostRendezvous.prepare cannot produce).
  • Separately, b12x_environment=None on prepare (:314, 325-326) has no caller (rank_group.py:286 calls ranks.prepare(...) without it).
  • Fix: Keep the early ("b12x-environment", b12x_env) command as the single channel, drop "b12x_environment" from assignment and lines 666-668, remove the unused kwarg (use self.b12x_environment directly), and update the serve_peer test to assert one realistic message.

2. Consolidate duplicated atomic-write blocks and fix the open-handle unlink in _share_artifacts (aot.py:90-100, 270-277, 870-877, 1185-1192; compile_pool.py:115-123)

  • _save_compiled_function (aot.py:90-100) is byte-identical to compile_pool.py:115-123 (which already imports from .aot at line 104), and aot.py retains three inline NamedTemporaryFile + os.replace + unlink blocks (:270-277, :870-877, :1185-1192), including the one this PR edited.
  • At aot.py:870-877, try: ... finally: temporary.unlink(missing_ok=True) sits inside with tempfile.NamedTemporaryFile(...) as file:, so if file.write fails before file.close(), the handle is still open during unlink (PermissionError on Windows, masking the original write error).
  • Fix: Have compile_pool.py:115-123 call _save_compiled_function, and move try/finally outside the with block at aot.py:870-877 (or extract one shared atomic-write helper in aot.py).
Nits (4)
  • Wire protocol version hygiene (host_ranks.py:41): PROTOCOL stays 5 while adding the new ("b12x-environment", b12x_env) control message. In CLI usage source_identity() (source_identity.py:95) hashes all of ignition/ including host_ranks.py and rejects mismatched checkouts in _admit (host_ranks.py:292-293), so stale peers cannot reach prepare(). Still, bumping PROTOCOL to 6 keeps the wire-version constant accurate for any caller passing a custom identity.
  • Nested composite variant key (collectives.py:212-215): Passing (variant, count) instead of overwriting variant with count makes name_key collision-free even if composite plans are ever nested.
  • Deduping decl_key in reconcile_selections (collectives.py:409-412): Flattening local sends duplicate decl_key tuples across layers instead of deduplicating them as before; on a ~1.5k-request catalog this is only a few MiB once at the end of tuning, but interning unique decl_keys before all_gather_object would keep the wire payload small.
  • Docs (docs/multi-host.md): Consider a short note that rank zero now propagates recipe.b12x_environment and each peer uses its own local kernel_cache.
Dropped on verification (9)
  • F1 (stale peer passes _admit and crashes) → Nit: source_identity() hashes the entire ignition/ tree (host_ranks.py:292-293, serve.py:193, 416, 548, source_identity.py:44-49, 95), so mismatched checkouts are rejected in _admit before prepare() runs.
  • F4 (B12X_COMPILE_CACHE_DIR rejected in __init__, peers retry knock 600 s) → Dropped: failing fast on rank zero before binding the listener matches every other pre-rendezvous check in _export_hosts (serve.py:180-192), and no recipe sets that var.
  • F5 (tuning.py:504-518 re-prepares all jobs unsharded) → Dropped: tuning.py is untouched by fix(ignition): reconcile divergent multi-host selections, propagate peer b12x env and kernel cache, and harden ForwardCache #668 (introduced in Fix externalized core signing, stream-0 weight race, export I/O, and multi-host tuning #647); Pass 2 hits warm selection caches for unchanged plans; and the proposed fix ("iterate only jobs whose plans ∩ configs is non-empty") would deadlock rank 0 (configs == {}) against rank 1 inside collective coordinator.prepare.
  • F6 (tuning.py:551-564 double-counts tuning_report) → Dropped: pre-existing Fix externalized core signing, stream-0 weight race, export I/O, and multi-host tuning #647 behavior, untouched by this PR; summing elapsed_seconds across both passes is accurate wall time.
  • F7 (memory-critical all-gather blowup in collectives.py:409-412) → Nit: ~1.3k small tuples is a few MiB once per preparation run, not a GB10 OOM hazard.
  • F8 (use recipe-only b12x_environment instead of ambient _b12x_forward_env()) → Dropped: ForwardCache is constructed in capture.py:118 without the recipe object, and hashing ambient B12X_* flags also protects manual CLI/benchmark overrides from silent collisions.
  • F9 (early ("b12x-environment", ...) cannot precede import-time reads) → Corrected: environment.apply at serve.py:547 imports b12x.preparation (environment.py:74, runtime_patches/workers.py:27), not the recipe module or its operator/kernel modules—those import during receive_object(control) (host_ranks.py:665); the early command genuinely precedes them and the assignment copy is the redundant one.
  • Subtraction 3 (collapse _validate_b12x_environment) → Dropped: HostRendezvous/serve_peer accept arbitrary dicts (including over the wire) rather than Recipe instances, so a 9-line check before os.environ.update is sensible boundary hygiene.
  • Subtraction 4 (delete _remap_peer_config's setattr fallback) → Dropped: recipes live in an external repo (local-inference-lab/hyperflare-recipes, AGENTS.md:9-13), so a 2-line fallback for mutable non-dataclass configs cannot be proven unreachable from this repo alone.

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.

@nepenth

nepenth commented Dec 2, 2026

Copy link
Copy Markdown

Strong +1 from hardware testing on 2× GB10 (SM121) multi-host TP2 with GLM-5.3-Flash-FP4-Local (v0.5.0):

  1. Divergent multi-host selections: We hit the exact same agree_selections non-convergence loop across TP-sharded CSF/MoE plans (1,648 differing selections on GLM-5.3 TP2) because reconcile_selections keyed on portable_declaration while agree_selections checked by request.name. Reconciling by request name resolved it cleanly.
  2. Dropped Recipe.b12x_environment on peer hosts: Without B12X_W4A16_A4_PREFILL=1 propagated to rank 1, rank 1 silently prepared BF16-activation W4A16 prefill instead of A4 prefill, stalling every layer's all-reduce and causing a +33% cold prefill regression (18.4 s vs 12.6 s at 32k context) as well as --reuse-weights layout mismatches (device-57). Propagating B12X_W4A16_A4_PREFILL=1 to both ranks restored full speed and --reuse-weights compatibility (49 s re-exports).

Both fixes in this PR match the exact root causes we independently diagnosed and verified on SM121 TP2 hardware.

@Reederey87

Copy link
Copy Markdown

Confirming the same multi-host B12X_W4A16_A4_PREFILL=1 gap independently on 2× NVIDIA DGX Spark (GB10 / SM121) exporting nvidia/GLM-5.3-Flash-FP4-Local (76348ddb) at TP2 (hyperflare-recipes@339ca580, flashinfer@e34540cc7): without manually exporting B12X_W4A16_A4_PREFILL=1 on rank 1 (ignition join), peer preparation omitted the recipe's b12x_environment. With B12X_W4A16_A4_PREFILL=1 active on both ranks (plus --context-parallel --row-shard-prefill --row-shard-attention), cold prefill measured 2,353–2,538 tok/s across 8k–128k (c1–c8) and 980k cold exact retrieval completed in 466.4 s (2,100 tok/s). Closed #675 in favor of this PR.

One small import-order detail noticed while reviewing ignition/cli/serve.py here:

  • In join(), environment.apply(configuration, (gpu,)) (line 545) runs before knock() and serve_peer().
  • environment.apply() calls runtime_patches.apply(), which invokes workers.register_hooks() → from b12x.preparation import register_worker_initializer (ignition/runtime_patches/workers.py:27).
  • That means b12x and b12x.preparation are already imported before serve_peer() receives ("b12x-environment", b12x_env).

For B12X_W4A16_A4_PREFILL (read dynamically from os.environ during preparation), applying it in serve_peer() before unpickling assignment works fine; for any future b12x_environment variable cached by b12x at module import time (per ignition/cli/environment.py:7), setting it inside serve_peer() would still happen after b12x.preparation is imported unless environment.apply on the peer waits until after receiving b12x_environment (or register_hooks is deferred). Flagging in case you want to address or note that invariant here.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

PR #668 cleanly fixes three real multi-host preparation defects (request-name-first reconciliation, peer b12x_environment / local kernel_cache propagation, ForwardCache B12X keying with atomic .bin persistence), and head d6a0069 rebases cleanly onto main. It still ships two concrete safety/test-isolation bugs from Round 1: ForwardCache._load destructively unlinks valid .bin artifacts on transient OSError/CUDA/_load_inductor faults, and the new serve_peer test permanently leaks B12X_* variables into process-global os.environ.

  • Blockers: 2 · Should fix: 2 · Subtract/Simplify: 2 · Nits: 4
Walkthrough
  • Request-name-first selection reconciliation (ignition/preparation/collectives.py:196-224, 398-449): _selected_plan_catalog records (request.name, variant, plan.component_id) alongside portable_declaration(plan) for non-collective requests (request.collective is None). reconcile_selections matches shared name_keys across ranks first before falling back to shared decl_keys, using a single target_for helper for both changed and configs so all ranks enter or skip Pass 2 in lockstep while preserving component-ID safety.
  • Peer b12x_environment propagation & local kernel_cache remapping (ignition/preparation/host_ranks.py:201-239, 313-381, 625-726; ignition/cli/serve.py:193-197, 416-420, 551-555): HostRendezvous validates and stores model.recipe.b12x_environment (rejecting non-B12X_ keys, B12X_COMPILE_CACHE_DIR, and non-string values) and sends it to peers before assignment (and again inside assignment). serve_peer applies it to os.environ, remaps config.kernel_cache to the peer's local kernel_cache passed from join, and forwards kernel_cache into peer export_options.
  • ForwardCache keying, atomic .bin persistence, and corrupt-load recovery (ignition/preparation/aot.py:47-100, 868-878, 897-899, 1326, 1371-1380, 1454, 1463): ForwardCache.__init__ mixes sorted execution-relevant B12X_* bindings (_b12x_forward_env()) into its SHA-256 root key; all three direct save_compiled_function call sites switch to sibling-temp _save_compiled_function; _share_artifacts adds temp-file cleanup; _load(..., required=False) catches _CORRUPT_ARTIFACT_ERRORS, unlinks the .bin, and returns None.
  • Tests (tests/preparation/test_tuning_shards.py:264-325, tests/preparation/test_host_ranks.py:334-439, tests/preparation/test_forward_cache_sources.py:142-218, tests/preparation/test_forward_artifact_sharing.py:130-154, 261-262): Adds a 2-rank Gloo reconciliation test, rendezvous env validation and serve_peer env/cache-remapping tests, ForwardCache B12X keying / atomic-save / corrupt-load tests, and real payload writes in _Artifact.save_compiled_function.
Merge Risk: Medium · up to d6a0069
  • Preparation-only blast radius: All edits are confined to ignition/preparation/, ignition/cli/serve.py, and tests/preparation/; no Helios runtime, Protobuf schema, or exported model-core format changes. Note that with #695 merged on main, reconcile_selections also runs for serving-replica --tuning-gpus sessions (ignition/preparation/tuning.py:521-535).
  • Destructive cache-recovery and one-time re-key: Hashing _b12x_forward_env() into ForwardCache.root (ignition/preparation/aot.py:897-899) triggers a one-time forward recompile for recipes declaring b12x_environment (e.g., GLM-5.3, Kimi). More critically, _load(..., required=False) (aot.py:64-76, 1371-1380) catches blanket OSError/RuntimeError/ValueError around both path.open('rb') and _load_inductor and destructively unlinks the cached .bin without logging.
  • Open-PR conflict horizon: Rebase resolved the #667 overlap cleanly (host_ranks.py:723-725), leaving active file overlap with open #597 (aot.py), #678 (aot.py and tests/preparation/test_forward_cache_sources.py), and #671 (host_ranks.py and tests/preparation/test_forward_artifact_sharing.py).
Pre-merge checks: ✅ 1 passed · ⚠️ 3 warnings
  • ✅ Security / malicious screen: No credential exposure, shell injection, or untrusted input escalation; _validate_b12x_environment restricts peer environment updates to non-cache B12X_* string bindings.
  • ⚠️ Charter & value fit: Cleanly scoped to Ignition preparation/CLI with no per-model branches or runtime flags and targets a reproducible cross-node bug (#651), but _CORRUPT_ARTIFACT_ERRORS silently swallows and deletes on unexplained OSError/RuntimeError faults (against charter #397).
  • ⚠️ Related / duplicate / conflict check: Rebased cleanly onto merged #667 and #695, and supersedes closed #675 (though without carrying over #675's stricter pre-import ordering in join). Coordinates with open #597, #678 (aot.py, test_forward_cache_sources.py), and #671 (host_ranks.py, test_forward_artifact_sharing.py).
  • ⚠️ Tests & verification evidence: Author ran 192 preparation CPU tests against paired flashinfer#199 and 136 CLI CPU tests; CI (.github/workflows/python-cpu.yml:29-33) validates against pinned flashinfer (pyproject.toml:47, rev = "5a8ceed80ccc58e11a4d49ccc910f52967699c09"). The new serve_peer test leaks B12X_* into os.environ, torch.OutOfMemoryError is untested, and head d6a0069 has not yet been run on live 2× GB10 hardware.

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.

…eer b12x env and kernel cache, and harden ForwardCache

Multi-host preparation (`ignition export --ranks N` paired with
`ignition join`, and multi-host `ignition debug-serve --ranks N`)
exhibited three related cache and coordination defects:
1. Multi-host autotune non-convergence (#651): `agree_selections`
   (`ignition/preparation/collectives.py`) checks kernel agreement by
   `request.name`, whereas `reconcile_selections` keyed entries solely
   by `portable_declaration(plan)` and ignored any declaration with
   `participants <= 1`. Whenever rank-local state caused a request's
   portable declaration to differ across ranks, `reconcile_selections`
   left both ranks' selections untouched and `agree_selections` failed
   again on every retry.
2. Missing `Recipe.b12x_environment` and leaked `config.kernel_cache`
   on peer hosts: Rank zero applies `plan.recipe.b12x_environment`
   before importing preparation libraries (`ignition/cli/serve.py`),
   whereas `HostRendezvous` (`ignition/preparation/host_ranks.py`) did
   not transmit those settings and `join()` called `environment.apply()`
   before connecting to rank zero (importing `b12x.preparation` via
   `runtime_patches.apply()` before any peer command arrived). Peers
   also passed rank zero's pickled `config.kernel_cache` directly into
   `prepare(...)` and did not pass their local `kernel_cache` into peer
   `export_options(...)`.
3. `ForwardCache` environment omission, non-atomic `.bin` persistence,
   and corrupt-archive crashes: `ForwardCache.__init__`
   (`ignition/preparation/aot.py`) omitted execution-relevant `B12X_*`
   variables from its SHA-256 root key, allowing compiled forwards
   prepared under differing b12x kernel flags to collide. Three `.bin`
   save sites wrote directly via `save_compiled_function(str(path))`
   without atomic replacement, inline temporary-file writes unlinked
   sibling temps while file handles were still open, and
   `ForwardCache._load(..., required=False)` raised on truncated or
   corrupt cached `.bin` files instead of recovering as a cache miss.

What changed:
- Request-name-first selection reconciliation
  (`ignition/preparation/collectives.py`):
  - Before: `_selected_plan_catalog` discarded request names and
    `reconcile_selections` reconciled only shared
    `portable_declaration(plan)` entries.
  - After: `_selected_plan_catalog` retains `(request.name, variant,
    plan.component_id)` (using a flat tuple variant path for nested
    composite plans) alongside `portable_declaration(plan)` for
    non-collective requests. `reconcile_selections` matches shared
    request names first before falling back to shared portable
    declarations, using one `target_for` resolver for both `changed`
    and `configs` so all ranks enter or skip the reconcile pass in
    lockstep while preserving `component_id` safety.
- Peer `b12x_environment` admission propagation and local
  `kernel_cache` remapping (`ignition/preparation/host_ranks.py`,
  `ignition/cli/serve.py`, `docs/multi-host.md`):
  - Before: `HostRendezvous` (protocol 5) sent no `b12x_environment`,
    `join()` ran `environment.apply()` before `knock()`, and
    `serve_peer` forwarded rank zero's `config.kernel_cache` unmodified
    and omitted `kernel_cache` from peer `export_options`.
  - After: `HostRendezvous` (protocol 6) accepts and validates
    `b12x_environment` (non-cache `B12X_*` string bindings, wired from
    `model.recipe.b12x_environment` in `_export_hosts` and
    `debug_serve`) and sends it in the `_admit` JSON reply. `knock()`
    validates and returns `(control, executor, b12x_environment)`,
    closing `control` on error. `join()` calls `source_identity()` and
    `knock()` before `environment.apply(configuration, (gpu,),
    b12x_environment)` so `b12x` and `b12x.preparation` see rank zero's
    recipe settings before import, and passes the peer's local
    `kernel_cache` to `serve_peer`. `serve_peer` remaps
    `config.kernel_cache` to `Path(kernel_cache)` and passes
    `kernel_cache` into peer `export_options(...)`. Documented this
    behavior in `docs/multi-host.md`.
- `ForwardCache` keying, atomic persistence, and corrupt-archive
  recovery (`ignition/preparation/aot.py`,
  `ignition/preparation/compile_pool.py`):
  - Before: `ForwardCache.__init__` omitted `B12X_*` settings, three
    `ForwardCache` save sites wrote `.bin` directly, `compile_pool.py`
    duplicated the sibling-temp save helper, three inline atomic-write
    blocks in `aot.py` unlinked temp files inside the open `with`
    block, and `_load(..., required=False)` raised on corrupt `.bin`
    archives.
  - After: `ForwardCache.__init__` hashes sorted execution-relevant
    `B12X_*` bindings (`_b12x_forward_env()`, excluding host-local
    cache directories, worker counts, RDMA device selectors, and
    logging flags). Added `_atomic_write_file` (closing handles before
    rename or cleanup) for guard cache, artifact sharing, and lent-job
    writes, and shared `_save_compiled_function` across `aot.py` and
    `compile_pool._compile_forward`. Updated `_load(...,
    required=False)` to open the file outside archive error handling
    (treating `FileNotFoundError` as a miss), catch only genuine
    deserialization/archive errors (`EOFError`,
    `pickle.UnpicklingError`, `struct.error`, `zlib.error`,
    `zipfile.BadZipFile`) after closing the file handle, emit a
    `RuntimeWarning` naming the path and error, guard `unlink` against
    `OSError`, and propagate `OSError`, `MemoryError`,
    `torch.OutOfMemoryError`, `RuntimeError`, and `ValueError` without
    deleting the cached `.bin`.
- Tests (`tests/preparation/test_tuning_shards.py`,
  `tests/preparation/test_host_ranks.py`,
  `tests/preparation/test_forward_cache_sources.py`,
  `tests/preparation/test_forward_artifact_sharing.py`): Added 2-rank
  Gloo reconciliation tests (divergent declarations, aliased
  declarations, converged `changed is False`, and `agree_selections`),
  rendezvous admission and `join()` import-order/socket-cleanup tests,
  `serve_peer` `kernel_cache` remapping and peer `export_options`
  tests, `ForwardCache` `B12X_*` keying, atomic-write closed-handle
  cleanup, and corrupt-vs-non-archive `_load` fault tests, and payload
  writes in `_Artifact.save_compiled_function`.

Expected result:
Multi-host peer ranks receive rank zero's `recipe.b12x_environment`
before importing `torch`/`b12x` and store compiled forwards under their
own host-local `kernel_cache`, `reconcile_selections` converges
rank-divergent declarations for shared request names before
`agree_selections` (Related: #651), and `ForwardCache` partitions
compiled forwards by execution-relevant `B12X_*` flags (causing a
one-time recompile for recipes that declare `b12x_environment`), writes
cache files atomically with closed-handle cleanup, and warns and
recovers on corrupt `.bin` archives without discarding valid entries on
transient I/O, OOM, CUDA, or contract errors.

Validation and limitations (rebased onto `origin/main` `cb191a93`, run
against editable FlashInfer `5c41b6ebd` in `/home/luke/projects/flare/.venv`):
- Targeted preparation and CLI CPU suites (325 tests across
  `test_host_ranks.py`, `test_forward_cache_sources.py`,
  `test_forward_artifact_sharing.py`, `test_forward_compile_options.py`,
  `test_compile_pool.py`, `test_tuning_shards.py`,
  `test_tuning_replicas.py`, `test_checkpoint_source.py`,
  `test_dcp_selection_groups.py`, `test_core_boundary.py`, and
  `tests/cli/`): 325 passed, 0 failed.
- Full CPU suite (`CUDA_VISIBLE_DEVICES="" pytest tests/ -q`): 2515
  passed, 458 skipped, 3 failed due to local shared-venv environment
  mismatches unrelated to this diff (`test_source_identity.py`
  comparing `flare_heliopause` built against an older checkout's
  `helios/src`, `test_runtime_triton.py` against a pre-patched Triton
  install, and `test_inspect_forward_kernels.py` hitting a dangling
  `/home/luke/.cache/flare/kernels` host symlink; rerunning
  `test_inspect_forward_kernels.py` with a writable `HOME` passed 1/1).
  All 15 tests in `tests/preparation/test_native_processes.py` passed,
  plus 100/100 standalone `[orphan]` iterations.
- Single-GPU CUDA tests on RTX PRO 6000 Blackwell SM120
  (`FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=0` across
  `test_inductor_tuning_cuda.py`, `test_capture_order_cuda.py`,
  `test_scratch_cuda.py`, `test_graph_local_scratch_cuda.py`,
  `test_recorded_export_graph_cuda.py`,
  `test_capture_cublas_workspace_cuda.py`): 18 passed, 5 skipped
  (`torchrun`-gated TP2 cases), 0 failed.
- TP2 distributed CUDA tests on 2x RTX PRO 6000 Blackwell SM120
  (`FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=0,1 torchrun
  --standalone --nproc_per_node=2 -m pytest
  tests/preparation/test_inductor_tuning_cuda.py -k "tp2 or distributed"`):
  5 passed, 0 failed.
- Not run: Rust crate tests (no Rust files modified), live 2-host GB10
  SM121 TP2 `ignition export` + `ignition join` of GLM-5.3, and paired
  `local-inference-lab/flashinfer#199` (tested against local FlashInfer
  `5c41b6ebd`). End-to-end live 2x GB10 convergence for #651 remains to
  be confirmed on hardware.

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@lukealonso
lukealonso force-pushed the unify-tuning-cache-identity-and-mult branch from d6a0069 to e09529b Compare December 3, 2026 20:54
@lukealonso

Copy link
Copy Markdown
Collaborator Author

Rebased onto main (cb191a93) and pushed e09529b8 addressing the open review items:

  1. Peer b12x_environment import ordering & single channel (thanks @Reederey87 for catching the join() import-order gap):
    • Bumped HostRendezvous PROTOCOL from 5 to 6, moved validated b12x_environment into _admit's JSON reply, and removed the duplicate ("b12x-environment", ...) frame, "b12x_environment" assignment entry, and unused HostRendezvous.prepare(..., b12x_environment=None) parameter.
    • knock() now validates and returns (control, executor, b12x_environment) (closing control on error), and serve.join() runs source_identity() and knock() before calling environment.apply(configuration, (gpu,), b12x_environment) (closing both sockets on error). Verified in a fresh subprocess test that torch, b12x, and flashinfer are not imported before environment.apply.
  2. ForwardCache._load narrowing & atomic-write consolidation (ignition/preparation/aot.py, ignition/preparation/compile_pool.py):
    • Narrowed _CORRUPT_ARTIFACT_ERRORS to (EOFError, pickle.UnpicklingError, struct.error, zlib.error, zipfile.BadZipFile).
    • Moved path.open('rb') outside archive-error handling (FileNotFoundError returns None when required=False; other OSErrors propagate), closed the file handle before unlinking, added a RuntimeWarning naming path and error, and guarded path.unlink(missing_ok=True) against OSError. OSError, MemoryError, torch.OutOfMemoryError, RuntimeError, and ValueError now propagate without deleting the cached .bin.
    • Extracted _atomic_write_file (closing handles before rename or cleanup) across _guard_code_cache, _share_artifacts, and lent-job writes, and reused _save_compiled_function in compile_pool._compile_forward.
  3. Test isolation, coverage, and docs:
    • Removed the os.environ leak in tests/preparation/test_host_ranks.py, added loopback admission + join() ordering + peer export_options(..., kernel_cache=...) tests, added _atomic_write_file closed-handle and _load torch.OutOfMemoryError/non-archive fault tests in tests/preparation/test_forward_cache_sources.py, added converged changed is False coverage in tests/preparation/test_tuning_shards.py, changed _selected_plan_catalog's composite variant key to a flat tuple path (*variant, count), updated docs/multi-host.md, and changed Fixes #651 to Related: #651 in the PR description until live 2× GB10 verification completes.
  4. Prior CI failure (test_native_processes.py::test_rank_group_shutdown_and_failure_do_not_leave_live_peers[orphan] in run 47012176541):
    • test_native_processes.py does not import any module touched by this PR. In [orphan], peers inherit driver.stderr and driver.communicate("orphan\n", timeout=10) returned with exit code 0, confirming both peers had already entered kernel exit before the 3 s /proc/{pid}/stat poll timed out. Locally, all 15 tests in test_native_processes.py passed inside the full CPU suite, plus 100/100 standalone [orphan] iterations.

@flare-autobot please re-review.

@lukealonso
lukealonso merged commit b16d168 into main Dec 3, 2026
1 check passed
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:rocenante RoCEnante cross-host GPU collectives and RoCE transport. bug Something isn't working duplicate This issue or pull request already exists performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P2 Normal bug priority: workflow failure or diagnosis with narrower impact or an available workaround. 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.

4 participants