Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions ignition/cli/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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"),
Expand Down
41 changes: 35 additions & 6 deletions ignition/preparation/host_ranks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand All @@ -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,
Expand Down
147 changes: 147 additions & 0 deletions tests/preparation/test_host_ranks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()