From 92b977d5d2cf40262edb354b9207413a0e9fec51 Mon Sep 17 00:00:00 2001 From: Artem Matskevych <52060443+Reederey87@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:49:45 -0500 Subject: [PATCH] fix(ignition): forward recipe b12x_environment to multi-host peer ranks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why this change is needed: Multi-host preparation (`ignition export --ranks` and `ignition debug-serve --ranks` paired with `ignition join`) applies `plan.recipe.b12x_environment` on rank zero in `ignition/cli/serve.py`, whereas remote peers running `join` call `environment.apply(configuration, (gpu,))` with an empty b12x mapping before contacting rank zero. `environment.apply` invokes `runtime_patches.apply()`, which imports `b12x.preparation` through `workers.register_hooks()`, so recipe-declared `B12X_*` settings (such as `B12X_W4A16_A4_PREFILL=1` on `glm53` or `B12X_W4A16_SMALL_M_HOST_BARRIER_RESET=0` on `kimi3`/`kimi31`) never reach remote ranks unless manually exported on every peer host. On multi-host tensor-parallel exports this causes rank zero and remote ranks to prepare with asymmetric b12x environment settings. What changed: - `ignition/preparation/host_ranks.py`: - Added `_validate_b12x_environment` enforcing the same `B12X_*` string-value contract as `Recipe.__post_init__` (`ignition/declaration.py`). - Added an optional `b12x_environment=()` parameter to `HostRendezvous.__init__`, validated before binding the listening socket, and included `"b12x_environment"` in the control-channel admission JSON reply in `HostRendezvous._admit`. - Updated `knock` to validate `reply.get("b12x_environment", {})` (closing the control socket without opening an executor connection on rejection) and return `(control, executor, b12x_environment)`. - `ignition/cli/serve.py`: - Passed `b12x_environment=model.recipe.b12x_environment` into `HostRendezvous` in both `_export_hosts` and `debug_serve`. - Reordered `join` to compute `source_identity()` and call `knock(...)` before calling `environment.apply(configuration, (gpu,), b12x_environment)`—matching rank zero's ordering—and closing both sockets if `environment.apply` raises. - `tests/preparation/test_host_ranks.py`: - Added tests covering multi-rank propagation, pre-bind rejection of invalid settings, peer-side rejection and socket cleanup on malformed replies, `join` applying received `B12X_*` variables before `runtime_patches.apply()` and `serve_peer()`, and socket cleanup when `environment.apply` fails. Claimed benefit: Every rank in a multi-host preparation or export session receives and applies the recipe's declared `b12x_environment` before PyTorch, Triton, or `b12x` is imported, matching single-host rank inheritance without manual per-host environment variables or new CLI flags. Evidence and limitations: - Ran `pytest tests/cli tests/preparation/test_host_ranks.py tests/preparation/test_checkpoint_source.py` on Linux aarch64 with `flare_heliopause` and `protoc` (`CUDA_VISIBLE_DEVICES=""`): 195 passed, 0 failed. - Limitations: Live multi-host CUDA export (`FLARE_RUN_TP_CUDA_TESTS=1`) was not re-executed on this commit; CPU tests exercise the real `HostRendezvous`, `knock`, and `ignition.cli.serve.join` entry points over loopback sockets with stubbed GPU discovery and `serve_peer`. Design-Signed-Off-By: Artem Matskevych; design-review=2e5b Signed-off-by: Artem Matskevych <52060443+Reederey87@users.noreply.github.com> --- ignition/cli/serve.py | 17 +++- ignition/preparation/host_ranks.py | 41 ++++++-- tests/preparation/test_host_ranks.py | 147 +++++++++++++++++++++++++++ 3 files changed, 194 insertions(+), 11 deletions(-) diff --git a/ignition/cli/serve.py b/ignition/cli/serve.py index 260181f0f..2902c8f57 100644 --- a/ignition/cli/serve.py +++ b/ignition/cli/serve.py @@ -193,7 +193,8 @@ def _export_hosts(args): rendezvous = HostRendezvous(args.rendezvous, args.ranks, identity=source_identity(), topology=local_topology(local[0]), checkpoint_fabric=_checkpoint_fabric(args), - checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value) + checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value, + b12x_environment=model.recipe.b12x_environment) with phase(progress, "Wait for tensor-parallel hosts") as stage: topologies = rendezvous.accept(report=stage.update) gpus = tuple(topology_gpu(topology, index) for index, topology in enumerate(topologies)) @@ -415,7 +416,8 @@ def debug_serve(args) -> int: rendezvous = HostRendezvous(args.rendezvous, args.ranks, identity=source_identity(), topology=local_topology(local[0]), checkpoint_fabric=_checkpoint_fabric(args), - checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value) + checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value, + b12x_environment=model.recipe.b12x_environment) with phase(progress, "Wait for tensor-parallel hosts") as stage: topologies = rendezvous.accept(report=stage.update) gpus = tuple(topology_gpu(topology, index) for index, topology in enumerate(topologies)) @@ -542,10 +544,15 @@ def progress(message): if not 0 <= args.gpu < len(host.gpus): raise UsageError(f"--gpu {args.gpu} names a GPU this host does not have") gpu = host.gpus[args.gpu] - environment.apply(configuration, (gpu,)) identity = source_identity() - control, executor = knock(args.rendezvous, args.rank, args.ranks, identity=identity, - topology=local_topology(gpu), report=progress) + control, executor, b12x_environment = knock(args.rendezvous, args.rank, args.ranks, identity=identity, + topology=local_topology(gpu), report=progress) + try: + environment.apply(configuration, (gpu,), b12x_environment) + except BaseException: + executor.close() + control.close() + raise serve_peer(control, executor, args.rank, args.ranks, hub_cache=hub_cache, progress=progress, export_staging=configuration.directory("export_staging"), identity=identity, core_cache=configuration.directory("core_cache"), diff --git a/ignition/preparation/host_ranks.py b/ignition/preparation/host_ranks.py index 10211d9d7..685f6d410 100644 --- a/ignition/preparation/host_ranks.py +++ b/ignition/preparation/host_ranks.py @@ -190,6 +190,21 @@ def watch(): return thread +def _validate_b12x_environment(b12x_environment): + """Validate and copy recipe b12x environment settings before sending or applying them.""" + if not isinstance(b12x_environment, dict): + try: + items = dict(b12x_environment) + except (TypeError, ValueError) as error: + raise ValueError("b12x settings name B12X_ variables with string values") from error + else: + items = dict(b12x_environment) + if any(not isinstance(name, str) or not name.startswith("B12X_") or not isinstance(value, str) + for name, value in items.items()): + raise ValueError("b12x settings name B12X_ variables with string values") + return items + + @dataclass class _Peer: rank: int @@ -202,9 +217,10 @@ class HostRendezvous: """Rank zero's listener: admits one process per peer rank, each on its own host.""" def __init__(self, address, world, *, identity, topology, checkpoint_token_file="~/.config/flare/agent.token", - checkpoint_fabric=None): + checkpoint_fabric=None, b12x_environment=()): if world not in (2, 3, 4, 6): raise ValueError("multi-host tensor parallelism requires two, three, four, or six ranks") + self.b12x_environment = _validate_b12x_environment(b12x_environment) self.address, self.world = parse_address(address), world self.identity, self.topology = identity, topology self.checkpoint_token_file = checkpoint_token_file @@ -272,7 +288,8 @@ def reject(reason): if rank in self.peers: reject(f"rank {rank} has already joined") self.peers[rank] = _Peer(rank, hello["topology"], sock) - send_json(sock, {"accepted": True, "session": self.session}) + send_json(sock, {"accepted": True, "session": self.session, + "b12x_environment": self.b12x_environment}) sock.settimeout(None) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if report is not None: @@ -563,7 +580,11 @@ def __exit__(self, kind, value, traceback): def knock(address, rank, world, *, identity, topology, timeout=600.0, report=None): - """Join rank zero's rendezvous, retrying until it listens; returns the control and executor sockets.""" + """Join rank zero's rendezvous, retrying until it listens. + + Returns the control socket, executor socket, and validated recipe `b12x_environment` + dictionary sent by rank zero during admission. + """ host, port = parse_address(address) deadline = time.monotonic() + timeout @@ -587,11 +608,19 @@ def connect(hello): control, reply = connect({"protocol": PROTOCOL, "channel": "control", "rank": rank, "world": world, "identity": identity, "topology": topology}) - executor, _ = connect({"protocol": PROTOCOL, "channel": "executor", "rank": rank, "world": world, - "session": reply["session"]}) + try: + raw_env = reply.get("b12x_environment", {}) + if not isinstance(raw_env, dict): + raise ValueError("b12x settings name B12X_ variables with string values") + b12x_environment = _validate_b12x_environment(raw_env) + executor, _ = connect({"protocol": PROTOCOL, "channel": "executor", "rank": rank, "world": world, + "session": reply["session"]}) + except BaseException: + control.close() + raise if report is not None: report(f"joined rank zero at {host}:{port} as rank {rank} of {world}") - return control, executor + return control, executor, b12x_environment def serve_peer(control, executor, rank, world, *, hub_cache, progress=None, export_staging=None, diff --git a/tests/preparation/test_host_ranks.py b/tests/preparation/test_host_ranks.py index 74925762e..50d7b3e98 100644 --- a/tests/preparation/test_host_ranks.py +++ b/tests/preparation/test_host_ranks.py @@ -329,3 +329,150 @@ def __init__(self, *args): group, None, options={}, export_id='export', images=None, storage=SimpleNamespace(host_regions=[]), publisher=object()) assert side_effects == [], f"peer or workspace side effects: {side_effects}" + + +def test_rendezvous_forwards_recipe_b12x_environment_to_every_peer(): + expected = {"B12X_W4A16_A4_PREFILL": "1", "B12X_W4A16_SMALL_M_HOST_BARRIER_RESET": "0"} + owner = HostRendezvous("127.0.0.1:0", 3, identity="same", topology=topology("zero"), + b12x_environment=expected) + address = f"127.0.0.1:{owner.listener.getsockname()[1]}" + results = [] + peers = [threading.Thread(target=join, args=(address, rank, 3), kwargs={"results": results}) + for rank in (1, 2)] + for peer in peers: + peer.start() + owner.accept(timeout=10) + for peer in peers: + peer.join() + assert len(results) == 2 + for control, executor, received in results: + assert received == expected + executor.close() + control.close() + for peer in owner.peers.values(): + peer.executor.close() + peer.control.close() + + +@pytest.mark.parametrize("bad_env", [ + {"CUDA_VISIBLE_DEVICES": "0"}, + {"B12X_W4A16_A4_PREFILL": 1}, + "not-a-mapping", +]) +def test_rendezvous_rejects_invalid_b12x_environment_before_binding(bad_env, monkeypatch): + bound = False + + def fail_if_bound(*args, **kwargs): + nonlocal bound + bound = True + raise AssertionError("socket.create_server should not run for invalid b12x_environment") + + monkeypatch.setattr(host_ranks.socket, "create_server", fail_if_bound) + with pytest.raises(ValueError, match="B12X_"): + HostRendezvous("127.0.0.1:0", 2, identity="same", topology=topology("zero"), + b12x_environment=bad_env) + assert not bound + + +def test_knock_rejects_invalid_b12x_environment_and_closes_control_socket(): + import socket + + listener = socket.create_server(("127.0.0.1", 0), reuse_port=False) + port = listener.getsockname()[1] + accepted = [] + + def server(): + sock, _ = listener.accept() + accepted.append(sock) + host_ranks.receive_json(sock) + host_ranks.send_json(sock, {"accepted": True, "session": "bad", + "b12x_environment": {"PATH": "/unexpected"}}) + # Peer must close its control socket without opening an executor connection. + assert sock.recv(1) == b"" + sock.close() + listener.close() + + thread = threading.Thread(target=server) + thread.start() + try: + with pytest.raises(ValueError, match="B12X_"): + knock(f"127.0.0.1:{port}", 1, 2, identity="same", topology=topology("peer1"), timeout=5) + finally: + thread.join(timeout=5) + assert len(accepted) == 1 + + +def test_join_applies_received_b12x_environment_before_runtime_patches_and_serve_peer(tmp_path, monkeypatch): + import os + from types import SimpleNamespace + from ignition import runtime_patches + from ignition.cli import serve + from ignition.cli.config import Configuration + from ignition.planning import Gpu + + expected = {"B12X_W4A16_A4_PREFILL": "1"} + owner = HostRendezvous("127.0.0.1:0", 2, identity="same", topology=topology("zero"), + b12x_environment=expected) + address = f"127.0.0.1:{owner.listener.getsockname()[1]}" + events = [] + monkeypatch.setattr(os, "environ", os.environ.copy()) + monkeypatch.delenv("B12X_W4A16_A4_PREFILL", raising=False) + monkeypatch.setattr(Configuration, "load", lambda path: Configuration(tmp_path / "config.toml", {}, False)) + monkeypatch.setattr(serve.Host, "discover", classmethod(lambda cls: SimpleNamespace( + gpus=(Gpu(0, "NVIDIA GB10", "GPU-peer1", 1 << 37, 1 << 36, (12, 1)),), restriction=None))) + monkeypatch.setattr(host_ranks, "source_identity", lambda: "same") + monkeypatch.setattr(host_ranks, "local_topology", lambda gpu: topology("peer1")) + monkeypatch.setattr(runtime_patches, "apply", lambda: events.append( + ("runtime_patches", os.environ.get("B12X_W4A16_A4_PREFILL")))) + + def fake_serve_peer(control, executor, rank, world, **kwargs): + events.append(("serve_peer", os.environ.get("B12X_W4A16_A4_PREFILL"))) + executor.close() + control.close() + + monkeypatch.setattr(host_ranks, "serve_peer", fake_serve_peer) + accept_thread = threading.Thread(target=owner.accept, kwargs={"timeout": 10}) + accept_thread.start() + args = SimpleNamespace(config=None, gpu=0, rendezvous=address, rank=1, ranks=2) + try: + assert serve.join(args) == 0 + finally: + accept_thread.join(timeout=10) + for peer in owner.peers.values(): + peer.executor.close() + peer.control.close() + assert events == [("runtime_patches", "1"), ("serve_peer", "1")] + + +def test_join_closes_rendezvous_sockets_when_environment_apply_fails(tmp_path, monkeypatch): + from types import SimpleNamespace + from ignition.cli import environment, serve + from ignition.cli.config import Configuration + from ignition.planning import Gpu + + owner = HostRendezvous("127.0.0.1:0", 2, identity="same", topology=topology("zero"), + b12x_environment={"B12X_W4A16_A4_PREFILL": "1"}) + address = f"127.0.0.1:{owner.listener.getsockname()[1]}" + monkeypatch.setattr(Configuration, "load", lambda path: Configuration(tmp_path / "config.toml", {}, False)) + monkeypatch.setattr(serve.Host, "discover", classmethod(lambda cls: SimpleNamespace( + gpus=(Gpu(0, "NVIDIA GB10", "GPU-peer1", 1 << 37, 1 << 36, (12, 1)),), restriction=None))) + monkeypatch.setattr(host_ranks, "source_identity", lambda: "same") + monkeypatch.setattr(host_ranks, "local_topology", lambda gpu: topology("peer1")) + monkeypatch.setattr(environment, "apply", lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("boom"))) + accept_thread = threading.Thread(target=owner.accept, kwargs={"timeout": 10}) + accept_thread.start() + args = SimpleNamespace(config=None, gpu=0, rendezvous=address, rank=1, ranks=2) + try: + with pytest.raises(RuntimeError, match="boom"): + serve.join(args) + accept_thread.join(timeout=10) + peer = owner.peers[1] + peer.control.settimeout(5) + peer.executor.settimeout(5) + assert peer.control.recv(1) == b"" + assert peer.executor.recv(1) == b"" + finally: + for peer in owner.peers.values(): + peer.executor.close() + peer.control.close() +