diff --git a/docs/multi-host.md b/docs/multi-host.md index 7c711be0e..cb87ed225 100644 --- a/docs/multi-host.md +++ b/docs/multi-host.md @@ -363,8 +363,10 @@ On `hertz`: For four hosts, use `--ranks 4` and start peer ranks 1, 2, and 3. Rank zero admits each peer once, serves checkpoint metadata and selected byte ranges, -and coordinates preparation. Peers do not create full checkpoint shards. -Keep checkpoint source files unchanged during loading. +and coordinates preparation. During admission, rank zero sends the recipe's +`b12x_environment` settings so each peer applies them alongside its own local +`kernel_cache` before importing preparation libraries. Peers do not create full +checkpoint shards. Keep checkpoint source files unchanged during loading. RoCEnante collectives give up on a peer after about 20 s, which suits serving. While compiled forwards warm, the rank that compiled a forward meets its Triton @@ -411,9 +413,13 @@ throughput separately for each peer. Cache hits skip bulk payload transfer. Each rank loads its weights and prepares its graphs. Forward compilation is shared across ranks, and compiled artifacts go to the ranks that need them. -Peers send export manifests; rank zero requests missing payload files, -assembles the core, signs it, and zstd-compresses executable resources. Temporary -staging is removed after use; reusable cached blobs remain. +`ForwardCache` keys each host's compiled-forward cache on execution-relevant +`B12X_*` settings and excludes host-local cache directories, worker counts, +RDMA device selectors, and logging flags, so distinct hosts share identical +relative cache keys. Peers send export manifests; rank zero requests missing +payload files, assembles the core, signs it, and zstd-compresses executable +resources. Temporary staging is removed after use; reusable cached blobs +remain. GLM-5.3 Flash supports `--no-context-parallel` to replicate attention pages and `--no-stream-overlap` to serialize concurrent branches. These are preparation diff --git a/ignition/cli/serve.py b/ignition/cli/serve.py index 260181f0f..2cdfa863e 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,12 +544,19 @@ 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: + control.close() + executor.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"), + kernel_cache=configuration.directory("kernel_cache"), checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value) return 0 diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index de4ce78cd..7d561d55c 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -10,8 +10,11 @@ import operator import os import pickle +import struct import sys import tempfile +import warnings +import zipfile import zlib from concurrent.futures import FIRST_COMPLETED, wait from contextlib import ExitStack, contextmanager, nullcontext @@ -42,6 +45,69 @@ _DEFERRED_BINDINGS = ContextVar("flare_deferred_bindings", default=False) _CHECK_BINDINGS = ContextVar("flare_check_bindings", default=False) +_NON_EXECUTION_B12X_ENV = frozenset({ + "B12X_COLLECTIVE_BARRIER_TIMEOUT", + "B12X_COMPILE_CACHE_DIR", + "B12X_COMPILE_DISK_CACHE", + "B12X_COMPILE_MEMORY_CACHE", + "B12X_COMPILE_MEMORY_CACHE_SIZE", + "B12X_COMPILE_SPEC_MEMO", + "B12X_COMPILE_WORKERS", + "B12X_PREPARATION_TRACE_DIR", + "B12X_PRINT_COMPILE_PROGRESS", + "B12X_ROCE_CACHE_DIR", + "B12X_ROCE_GID_INDEX", + "B12X_ROCE_HCA", + "B12X_TIMING", + "B12X_TIMING_THRESHOLD_MS", +}) + +_CORRUPT_ARTIFACT_ERRORS = ( + EOFError, + pickle.UnpicklingError, + struct.error, + zlib.error, + zipfile.BadZipFile, +) + + +def _b12x_forward_env(): + """Return sorted execution-relevant B12X_* environment bindings for forward cache identity.""" + return tuple(sorted( + (name, value) + for name, value in os.environ.items() + if name.startswith("B12X_") + and name not in _NON_EXECUTION_B12X_ENV + and not name.startswith("B12X_LOG_") + )) + + +def _atomic_write_file(path, writer): + """Write a binary file via a sibling temporary file, closing it before rename or cleanup.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + file = tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False) + temporary = Path(file.name) + try: + with file: + writer(file) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def _save_compiled_function(artifact, path): + """Write a compiled forward archive via a sibling temporary file and atomic rename.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False) as file: + temporary = Path(file.name) + try: + artifact.save_compiled_function(str(temporary)) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + def _load_inductor(data, original, *, frozen=False): runtime_patches.apply() @@ -209,15 +275,7 @@ def build(code_parts, closure_args): if path.is_file(): return pickle.loads(path.read_bytes()) result = original(code_parts, closure_args) - root.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile(dir=root, suffix='.tmp', delete=False) as file: - temporary = Path(file.name) - try: - pickle.dump(result, file) - file.close() - os.replace(temporary, path) - finally: - temporary.unlink(missing_ok=True) + _atomic_write_file(path, lambda file: pickle.dump(result, file)) return result token = _GUARD_TENSOR_MODE.set(torch._subclasses.FakeTensorMode()) @@ -809,10 +867,7 @@ def current(path, digest): dist.broadcast_object_list(payload, src=ranks[index], group=group) if path in missing: target = _resolve_shared_path(root, path) - target.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile(dir=target.parent, suffix=".tmp", delete=False) as file: - file.write(payload[0]) - os.replace(file.name, target) + _atomic_write_file(target, lambda file: file.write(payload[0])) missing.discard(path) @@ -832,8 +887,9 @@ def __init__(self, *, namespace, device, root=None, headroom_bytes=0, options=No self.options = MappingProxyType(_compile_options(options)) properties = torch.cuda.get_device_properties(device) options = {name: value for name, value in self.options.items() if name != 'compile_threads'} - key = hashlib.sha256(pickle.dumps((namespace, options, torch_key(), runtime_patches.identity(), - properties.name, properties.major, properties.minor, properties.multi_processor_count))) + key = hashlib.sha256(pickle.dumps((namespace, options, _b12x_forward_env(), torch_key(), + runtime_patches.identity(), properties.name, properties.major, properties.minor, + properties.multi_processor_count))) for source in (Path(__file__).resolve().parents[1], Path(flashinfer.__file__).resolve().parent): for path in sorted(source.rglob('*.py')): if source.name == 'ignition' and (path.name == '__main__.py' @@ -1119,14 +1175,7 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi name, variant, forward = work[index] path = self._path(forward, name=f"{name}.{variant}", signature=signatures[name]) job = jobs / f"{path.stem}.forward" - with tempfile.NamedTemporaryFile(dir=jobs, suffix='.tmp', delete=False) as file: - temporary = Path(file.name) - try: - pickle.dump((dumps(forward), str(path)), file) - file.close() - os.replace(temporary, job) - finally: - temporary.unlink(missing_ok=True) + _atomic_write_file(job, lambda file: pickle.dump((dumps(forward), str(path)), file)) sent.append((borrower, str(job))) # The borrower compiles it before every rank gathers the outcome below. paths[name, variant] = path.relative_to(self.root).as_posix(), True @@ -1260,7 +1309,7 @@ def finish(): rel_path, _ = paths[name, variant] local_path = _resolve_shared_path(self.root, rel_path) if compilers[name, variant] == share: - bound.artifact.save_compiled_function(str(local_path)) + _save_compiled_function(bound.artifact, local_path) published.append(rel_path) if stream: selected[name] = DeferredCompiledForward( @@ -1306,9 +1355,30 @@ def _allocation_sizes(self, path): return sizes def _load(self, forward, path, *, required=False, before_run=None): - with bind_device(self.device, freeze_tuning=self.options.get( - 'triton.autotune_at_compile_time', False)), path.open('rb') as file: - artifact = torch.compiler.load_compiled_function(file) + path = Path(path) + try: + file = path.open('rb') + except FileNotFoundError: + if required: + raise + return None + try: + with file, bind_device(self.device, freeze_tuning=self.options.get( + 'triton.autotune_at_compile_time', False)): + artifact = torch.compiler.load_compiled_function(file) + except _CORRUPT_ARTIFACT_ERRORS as error: + if required: + raise + warnings.warn( + f"discarding corrupt compiled forward cache entry {path}: {type(error).__name__}: {error}", + RuntimeWarning, + stacklevel=2, + ) + try: + path.unlink(missing_ok=True) + except OSError: + pass + return None # Bound forwards remain live for the complete catalog. Collect young # deserialization temporaries here; scan the retained heap once at each # preparation phase boundary instead of once per restored forward. @@ -1382,7 +1452,7 @@ def report(operation): source_identity=self.root.name) path.parent.mkdir(parents=True, exist_ok=True) if not hasattr(bound.artifact._artifacts.compiled_fn.artifact, '_flare_graph'): - bound.artifact.save_compiled_function(str(path)) + _save_compiled_function(bound.artifact, path) cached = bound.cache_hit bound = self._load(bound.owner, path, required=True, before_run=before_run) bound.cache_hit = cached @@ -1391,5 +1461,5 @@ def report(operation): selections.warm(bound, warmup, before_run=before_run) selections.freeze(bound) report("saving compiled forward") - bound.artifact.save_compiled_function(str(path)) + _save_compiled_function(bound.artifact, path) return bound diff --git a/ignition/preparation/collectives.py b/ignition/preparation/collectives.py index 76c165770..eb09754a2 100644 --- a/ignition/preparation/collectives.py +++ b/ignition/preparation/collectives.py @@ -209,17 +209,18 @@ def identity(name): entries = [] - def selected(plan, key): + def selected(plan, key, name, variant=()): if is_composite_plan(plan): for count, child in plan_variants(plan).items(): - selected(child, (key, count)) + selected(child, (key, count), name, (*variant, count)) else: config = plan.selection.config - entries.append((plan, key, plan.contract.config_payload(config), config)) + entries.append((plan, key, (name, variant, plan.component_id), + plan.contract.config_payload(config), config)) for request in requests: if request.collective is None: - selected(request.plan, identity(request.name)) + selected(request.plan, identity(request.name), request.name) return entries @@ -395,32 +396,54 @@ def agree_selections(self, selections): f"{differing[:3]}; preparing again adopts rank zero's tuning decisions") def reconcile_selections(self, requests): - """Choose one actual configuration for matching declarations across ranks. + """Choose one actual configuration for matching requests or declarations across ranks. Unsharded remainder components in unequal catalogs (or catalogs on heterogeneous hardware) still need matching scratch layouts before - compiled forwards are shared. + compiled forwards are shared. Matching by request name first ensures + rank-divergent declarations for the same request adopt rank zero's + configuration, while portable declaration matching covers shared plans + whose request names differ across ranks. """ entries = _selected_plan_catalog(requests) - local = {} - for _, key, payload, config in entries: - local.setdefault(key, {}).setdefault(payload, config) + local = [(decl_key, name_key, payload, config) + for _, decl_key, name_key, payload, config in entries] gathered = [None] * len(self.ranks) dist.all_gather_object(gathered, local, group=self.group) - chosen, participants = {}, {} - for catalog in gathered: - for key, values in catalog.items(): - chosen.setdefault(key, next(iter(values.items()))) - participants[key] = participants.get(key, 0) + 1 - common = {key for key, count in participants.items() if count > 1} - changed = any(payload != chosen[key][0] - for catalog in gathered for key, values in catalog.items() if key in common - for payload in values) + chosen_decl, decl_participants = {}, {} + chosen_name, name_participants = {}, {} + for rank_entries in gathered: + seen_decl, seen_name = set(), set() + for decl_key, name_key, payload, config in rank_entries: + chosen_decl.setdefault(decl_key, (payload, config)) + if decl_key not in seen_decl: + seen_decl.add(decl_key) + decl_participants[decl_key] = decl_participants.get(decl_key, 0) + 1 + chosen_name.setdefault(name_key, (payload, config)) + if name_key not in seen_name: + seen_name.add(name_key) + name_participants[name_key] = name_participants.get(name_key, 0) + 1 + common_decl = {key for key, count in decl_participants.items() if count > 1} + common_name = {key for key, count in name_participants.items() if count > 1} + + def target_for(decl_key, name_key): + if name_key in common_name: + return chosen_name[name_key] + if decl_key in common_decl: + return chosen_decl[decl_key] + return None + + changed = any( + (target := target_for(decl_key, name_key)) is not None and payload != target[0] + for rank_entries in gathered + for decl_key, name_key, payload, _ in rank_entries + ) configs = {} - for plan, key, payload, _ in entries: - if key in common and payload != chosen[key][0]: - config = chosen[key][1] - if plan in configs and plan.contract.config_payload(configs[plan]) != chosen[key][0]: + for plan, decl_key, name_key, payload, _ in entries: + target = target_for(decl_key, name_key) + if target is not None and payload != target[0]: + target_payload, config = target + if plan in configs and plan.contract.config_payload(configs[plan]) != target_payload: raise ValueError("one plan has conflicting rank-shared configurations") configs[plan] = config return configs, changed diff --git a/ignition/preparation/compile_pool.py b/ignition/preparation/compile_pool.py index 9310c88f3..32f76d501 100644 --- a/ignition/preparation/compile_pool.py +++ b/ignition/preparation/compile_pool.py @@ -6,10 +6,8 @@ import multiprocessing import os -import tempfile from concurrent.futures import ProcessPoolExecutor from dataclasses import dataclass -from pathlib import Path import torch @@ -101,7 +99,7 @@ def allocate_workers(resources, counts, hosts): @_defer_full_collection() def _compile_forward(payload, device, options, path, num_threads, grad_enabled): runtime_patches.apply() - from .aot import aot_forward + from .aot import _save_compiled_function, aot_forward from .device_binding import bind_device from .forward_metadata import loads @@ -112,15 +110,7 @@ def _compile_forward(payload, device, options, path, num_threads, grad_enabled): with bind_device(device): forward = loads(payload) artifact = aot_forward(forward, options=options) - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False) as file: - temporary = Path(file.name) - try: - artifact.save_compiled_function(str(temporary)) - os.replace(temporary, path) - finally: - temporary.unlink(missing_ok=True) + _save_compiled_function(artifact, path) class CompilePool: diff --git a/ignition/preparation/host_ranks.py b/ignition/preparation/host_ranks.py index 10211d9d7..1409b6db2 100644 --- a/ignition/preparation/host_ranks.py +++ b/ignition/preparation/host_ranks.py @@ -32,13 +32,13 @@ import threading import time import traceback -from dataclasses import dataclass +from dataclasses import dataclass, is_dataclass, replace from datetime import timedelta from pathlib import Path from .source_identity import source_identity -PROTOCOL = 5 +PROTOCOL = 6 # Peers wait here while rank zero compiles the complete serving catalog. _PREPARATION_TIMEOUT = timedelta(hours=2) _HANDSHAKE_SECONDS = 30 @@ -198,17 +198,39 @@ class _Peer: executor: socket.socket | None = None +def _validate_b12x_environment(environment): + if not environment: + return {} + resolved = dict(environment) + if any(not isinstance(name, str) or not name.startswith("B12X_") + or name == "B12X_COMPILE_CACHE_DIR" or not isinstance(value, str) + for name, value in resolved.items()): + raise ValueError("b12x environment settings must map non-cache B12X_ names to string values") + return resolved + + +def _remap_peer_config(config, *, kernel_cache): + if config is None or kernel_cache is None or not hasattr(config, "kernel_cache"): + return config + local_cache = Path(kernel_cache) + if is_dataclass(config) and not isinstance(config, type): + return replace(config, kernel_cache=local_cache) + setattr(config, "kernel_cache", local_cache) + return config + + 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.address, self.world = parse_address(address), world self.identity, self.topology = identity, topology self.checkpoint_token_file = checkpoint_token_file self.checkpoint_fabric = checkpoint_fabric + self.b12x_environment = _validate_b12x_environment(b12x_environment) self.session = secrets.token_hex(16) self.listener = socket.create_server(self.address, reuse_port=False) self.peers = {} @@ -272,7 +294,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 +586,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` mapping sent during admission. + """ host, port = parse_address(address) deadline = time.monotonic() + timeout @@ -587,15 +614,20 @@ 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: + b12x_environment = _validate_b12x_environment(reply.get("b12x_environment")) + 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, - core_cache=None, + core_cache=None, kernel_cache=None, checkpoint_token_file="~/.config/flare/agent.token", identity=None): """Prepare one peer from owned checkpoint metadata and requested source ranges, report memory, and serve until coordinated drain. @@ -632,7 +664,8 @@ def serve_peer(control, executor, rank, world, *, hub_cache, progress=None, expo source_scope = source.activate() snapshot = source_scope.__enter__() assignment = receive_object(control) - config, prepare = assignment["config"], assignment["prepare"] + config = _remap_peer_config(assignment["config"], kernel_cache=kernel_cache) + prepare = assignment["prepare"] store_host, store_port = assignment["store"] _use_interface(control.getsockname()[0]) import torch.distributed as dist @@ -686,7 +719,8 @@ def serve_peer(control, executor, rank, world, *, hub_cache, progress=None, expo if progress is not None: progress(f"exporting rank {rank}") context = export_options(peer_cache, no_weights=settings.no_weights, - reuse_weights=settings.reuse_weights, remote_cache=True) + reuse_weights=settings.reuse_weights, remote_cache=True, + kernel_cache=kernel_cache) with context: core = export_model(model, recorder, storage, path, options=options, bundle_only=True, sources=True) diff --git a/tests/preparation/test_forward_artifact_sharing.py b/tests/preparation/test_forward_artifact_sharing.py index 8c67f54ab..49b5cf13d 100644 --- a/tests/preparation/test_forward_artifact_sharing.py +++ b/tests/preparation/test_forward_artifact_sharing.py @@ -127,7 +127,7 @@ class _CompilerMetadata: class _Artifact: - def __init__(self, execute): + def __init__(self, execute, payload=b""): from inspect import signature from types import SimpleNamespace @@ -145,12 +145,13 @@ def __init__(self, execute): runtime_env=SimpleNamespace(closure=()), guard_manager=GuardManagerWrapper(root=guards), compiled_fn=backend, guards_state=b"portable guards", compiler_graph=_CompilerMetadata()) self.fn = execute + self.payload = payload def __call__(self, owner): self.fn(owner) def save_compiled_function(self, path): - assert Path(path).exists() + Path(path).write_bytes(self.payload) def _replace_gpu_preparation(): @@ -258,7 +259,7 @@ def submit_payload(self, payload, path): compile_pool.compiler_resources = lambda *args, **kwargs: compile_pool.CompilerResources( int(capacity), 40 << 30, 16, 32 << 30, 8 << 30) aot.ForwardCache._load = lambda self, forward, path, required=False, before_run=None: aot.BoundForward( - _Artifact(lambda owner: None), forward, True) + _Artifact(lambda owner: None, Path(path).read_bytes()), forward, True) aot.ForwardCache._allocation_sizes = lambda self, path: () dist.init_process_group("gloo", init_method=f"file://{store}", rank=rank, world_size=world) cache = aot.ForwardCache.__new__(aot.ForwardCache) diff --git a/tests/preparation/test_forward_cache_sources.py b/tests/preparation/test_forward_cache_sources.py index 89325e736..125d0d1d1 100644 --- a/tests/preparation/test_forward_cache_sources.py +++ b/tests/preparation/test_forward_cache_sources.py @@ -137,3 +137,150 @@ def test_frontend_contract_validates_tool_delimiters(): tool_open=bad_open, tool_close=bad_close, ) + + +def test_forward_cache_hashes_execution_b12x_env_and_ignores_host_paths(tmp_path, monkeypatch): + monkeypatch.setattr(aot.torch.cuda, "get_device_properties", lambda device: + SimpleNamespace(name="SM121", major=12, minor=1, multi_processor_count=48)) + for name in list(aot.os.environ): + if name.startswith("B12X_"): + monkeypatch.delenv(name, raising=False) + + def root(): + return aot.ForwardCache(namespace={"model": "example"}, device="cuda:0", root=tmp_path).root + + base = root() + # Host-local cache dirs, worker counts, and logging flags must not perturb cache identity. + monkeypatch.setenv("B12X_COMPILE_CACHE_DIR", str(tmp_path / "host-a")) + monkeypatch.setenv("B12X_COMPILE_WORKERS", "4") + monkeypatch.setenv("B12X_LOG_CUTE_COMPILES", "1") + assert root() == base + monkeypatch.setenv("B12X_COMPILE_CACHE_DIR", str(tmp_path / "host-b")) + assert root() == base + + # Execution-affecting B12X_* variables must partition the forward cache. + monkeypatch.setenv("B12X_W4A16_A4_PREFILL", "1") + with_a4 = root() + assert with_a4 != base + monkeypatch.setenv("B12X_W4A16_SMALL_M_HOST_BARRIER_RESET", "0") + with_both = root() + assert with_both != with_a4 and with_both != base + + +def test_save_compiled_function_is_atomic_on_write_failure(tmp_path): + target = tmp_path / "forward.bin" + target.write_bytes(b"existing-good-bytes") + + class FailingArtifact: + def save_compiled_function(self, destination): + aot.Path(destination).write_bytes(b"partial") + raise OSError("disk full") + + with pytest.raises(OSError, match="disk full"): + aot._save_compiled_function(FailingArtifact(), target) + + assert target.read_bytes() == b"existing-good-bytes" + assert list(tmp_path.glob("*.tmp")) == [] + + class WorkingArtifact: + def save_compiled_function(self, destination): + aot.Path(destination).write_bytes(b"replacement-bytes") + + aot._save_compiled_function(WorkingArtifact(), target) + assert target.read_bytes() == b"replacement-bytes" + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_atomic_write_file_closes_handle_before_cleanup_and_preserves_target(tmp_path, monkeypatch): + target = tmp_path / "payload.bin" + target.write_bytes(b"existing-bytes") + opened = [] + unlink_closed_state = [] + original_named_tmp = aot.tempfile.NamedTemporaryFile + original_unlink = aot.Path.unlink + + def tracked_tmp(*args, **kwargs): + file = original_named_tmp(*args, **kwargs) + opened.append(file) + return file + + def tracked_unlink(self, *args, **kwargs): + if opened and self == aot.Path(opened[-1].name): + unlink_closed_state.append(opened[-1].closed) + return original_unlink(self, *args, **kwargs) + + monkeypatch.setattr(aot.tempfile, "NamedTemporaryFile", tracked_tmp) + monkeypatch.setattr(aot.Path, "unlink", tracked_unlink) + + def failing_writer(file): + file.write(b"partial") + raise OSError("write failed") + + with pytest.raises(OSError, match="write failed"): + aot._atomic_write_file(target, failing_writer) + + assert unlink_closed_state == [True] + assert target.read_bytes() == b"existing-bytes" + assert list(tmp_path.glob("*.tmp")) == [] + + aot._atomic_write_file(target, lambda file: file.write(b"new-bytes")) + assert target.read_bytes() == b"new-bytes" + assert list(tmp_path.glob("*.tmp")) == [] + + +def test_forward_cache_recovers_from_corrupt_cached_bin_on_restore(tmp_path, monkeypatch): + import errno + import pickle + + cache = aot.ForwardCache.__new__(aot.ForwardCache) + cache.device = aot.torch.device("cpu") + cache.options = {} + + missing = tmp_path / "missing.bin" + assert cache._load(lambda: None, missing, required=False) is None + with pytest.raises(FileNotFoundError): + cache._load(lambda: None, missing, required=True) + + corrupt = tmp_path / "corrupt.bin" + corrupt.write_bytes(b"truncated-not-a-valid-compiled-forward") + + # Opportunistic restore (required=False) warns, unlinks corrupt archives, and returns a miss. + with pytest.warns(RuntimeWarning, match="corrupt.bin"): + assert cache._load(lambda: None, corrupt, required=False) is None + assert not corrupt.exists() + + # Unlink failure (e.g., read-only cache directory) still returns a cache miss instead of crashing. + corrupt.write_bytes(b"truncated-not-a-valid-compiled-forward") + original_unlink = aot.Path.unlink + monkeypatch.setattr(aot.Path, "unlink", lambda self, *a, **kw: (_ for _ in ()).throw(PermissionError("rofs"))) + try: + with pytest.warns(RuntimeWarning, match="corrupt.bin"): + assert cache._load(lambda: None, corrupt, required=False) is None + finally: + monkeypatch.setattr(aot.Path, "unlink", original_unlink) + assert corrupt.exists() + + # Required loads (fresh compile or peer transfer) must still fail loudly and preserve the file. + with pytest.raises(pickle.UnpicklingError): + cache._load(lambda: None, corrupt, required=True) + assert corrupt.exists() + + # Non-archive faults (OOM, I/O, CUDA/runtime errors, contract violations) must propagate and preserve the file. + for failure in ( + aot.torch.OutOfMemoryError("cuda oom"), + MemoryError("host oom"), + OSError(errno.ENOSPC, "no space left on device"), + RuntimeError("unsupported bundled Inductor serialization wrappers"), + ValueError("compiled native launches must use runtime kernel bindings"), + ): + monkeypatch.setattr(aot.torch.compiler, "load_compiled_function", + lambda _file, exc=failure: (_ for _ in ()).throw(exc)) + with pytest.raises(type(failure)): + cache._load(lambda: None, corrupt, required=False) + assert corrupt.exists() + + # Non-FileNotFoundError open failures (e.g. PermissionError) propagate without deleting the file. + monkeypatch.setattr(aot.Path, "open", lambda self, *a, **kw: (_ for _ in ()).throw(PermissionError("denied"))) + with pytest.raises(PermissionError, match="denied"): + cache._load(lambda: None, corrupt, required=False) + assert corrupt.exists() diff --git a/tests/preparation/test_host_ranks.py b/tests/preparation/test_host_ranks.py index 74925762e..b5e68a607 100644 --- a/tests/preparation/test_host_ranks.py +++ b/tests/preparation/test_host_ranks.py @@ -329,3 +329,273 @@ 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_host_rendezvous_validates_and_transmits_b12x_environment(): + import socket + + 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]}" + assert owner.b12x_environment == expected + + results = [] + peer = threading.Thread(target=join, args=(address, 1), kwargs={"results": results}) + peer.start() + try: + owner.accept(timeout=10) + peer.join(timeout=10) + assert len(results) == 1 and isinstance(results[0], tuple) + control, executor, received = results[0] + try: + assert received == expected + finally: + control.close() + executor.close() + finally: + for admitted in owner.peers.values(): + for sock in (admitted.control, admitted.executor): + if sock is not None: + sock.close() + owner.listener.close() + + for bad in ({"OTHER_VAR": "1"}, {"B12X_COMPILE_CACHE_DIR": "/tmp/x"}, {"B12X_FLAG": 1}): + with pytest.raises(ValueError, match="b12x environment"): + HostRendezvous("127.0.0.1:0", 2, identity="same", topology=topology("zero"), + b12x_environment=bad) + + # knock rejects malformed b12x_environment from rank zero and closes its control socket. + listener = socket.create_server(("127.0.0.1", 0)) + port = listener.getsockname()[1] + + def bad_server(): + conn, _ = listener.accept() + with conn: + host_ranks.receive_json(conn) + host_ranks.send_json(conn, { + "accepted": True, + "session": "s", + "b12x_environment": {"B12X_COMPILE_CACHE_DIR": "/bad"}, + }) + + server = threading.Thread(target=bad_server) + server.start() + try: + with pytest.raises(ValueError, match="b12x environment"): + knock(f"127.0.0.1:{port}", 1, 2, identity="same", topology=topology("peer1"), timeout=5) + finally: + server.join(timeout=5) + listener.close() + + +def test_join_applies_b12x_environment_after_knock_before_importing_b12x(tmp_path, monkeypatch): + from pathlib import Path + from types import SimpleNamespace + + from ignition.cli import serve + from ignition.cli.config import Configuration + + peer_cache = tmp_path / "peer-kernels" + cfg_path = tmp_path / "config.toml" + cfg_path.write_text(f'[paths]\nkernel_cache = "{peer_cache.as_posix()}"\n') + config = Configuration.load(cfg_path) + gpu = SimpleNamespace(index=0, name="NVIDIA GB10", uuid="GPU-peer", total_bytes=1 << 37, + free_bytes=1 << 36, capability=(12, 1)) + events = [] + + class FakeSocket: + def __init__(self): + self.closed = False + + def close(self): + self.closed = True + + control, executor = FakeSocket(), FakeSocket() + monkeypatch.setattr(serve.Configuration, "load", lambda path: config) + monkeypatch.setattr(serve.Host, "discover", lambda: SimpleNamespace(gpus=(gpu,))) + monkeypatch.setattr(host_ranks, "source_identity", lambda: (events.append("source_identity") or "id")) + monkeypatch.setattr(host_ranks, "local_topology", lambda g: {"host": "peer"}) + + def fake_knock(*args, **kwargs): + events.append("knock") + return control, executor, {"B12X_W4A16_A4_PREFILL": "1"} + + def fake_apply(cfg, gpus, b12x=()): + events.append(("environment.apply", tuple(gpus), dict(b12x))) + + def fake_serve_peer(ctrl, exec_, rank, world, **kwargs): + events.append(("serve_peer", Path(kwargs["kernel_cache"]))) + + monkeypatch.setattr(host_ranks, "knock", fake_knock) + monkeypatch.setattr(serve.environment, "apply", fake_apply) + monkeypatch.setattr(host_ranks, "serve_peer", fake_serve_peer) + + args = SimpleNamespace(config=cfg_path, gpu=0, rendezvous="127.0.0.1:29630", rank=1, ranks=2) + assert serve.join(args) == 0 + assert events == [ + "source_identity", + "knock", + ("environment.apply", (gpu,), {"B12X_W4A16_A4_PREFILL": "1"}), + ("serve_peer", peer_cache), + ] + + # If environment.apply fails after knock, join closes both rendezvous sockets. + control2, executor2 = FakeSocket(), FakeSocket() + monkeypatch.setattr(host_ranks, "knock", lambda *a, **kw: (control2, executor2, {"B12X_W4A16_A4_PREFILL": "1"})) + monkeypatch.setattr(serve.environment, "apply", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("apply boom"))) + with pytest.raises(RuntimeError, match="apply boom"): + serve.join(args) + assert control2.closed and executor2.closed + + +def test_join_does_not_import_b12x_or_torch_before_environment_apply(tmp_path): + import subprocess + import sys + + code = r''' +import sys +from pathlib import Path +from types import SimpleNamespace +from ignition.cli import serve +from ignition.cli.config import Configuration +from ignition.preparation import host_ranks + +tmp = Path(sys.argv[1]) +cfg = Configuration.load(tmp / "config.toml") +gpu = SimpleNamespace(index=0, name="NVIDIA GB10", uuid="GPU-peer", total_bytes=1 << 37, + free_bytes=1 << 36, capability=(12, 1)) +serve.Configuration.load = lambda path: cfg +serve.Host.discover = lambda: SimpleNamespace(gpus=(gpu,)) +host_ranks.source_identity = lambda: "id" +host_ranks.local_topology = lambda g: {"host": "peer"} +host_ranks.knock = lambda *a, **kw: (SimpleNamespace(close=lambda: None), SimpleNamespace(close=lambda: None), + {"B12X_W4A16_A4_PREFILL": "1"}) + +def check_apply(configuration, gpus, b12x=()): + assert "torch" not in sys.modules, "torch imported before environment.apply" + assert "b12x" not in sys.modules, "b12x imported before environment.apply" + assert "flashinfer" not in sys.modules, "flashinfer imported before environment.apply" + assert dict(b12x) == {"B12X_W4A16_A4_PREFILL": "1"} + +serve.environment.apply = check_apply +host_ranks.serve_peer = lambda *a, **kw: None +args = SimpleNamespace(config=tmp / "config.toml", gpu=0, rendezvous="127.0.0.1:29630", rank=1, ranks=2) +assert serve.join(args) == 0 +''' + (tmp_path / "config.toml").write_text("") + result = subprocess.run([sys.executable, "-c", code, str(tmp_path)], + capture_output=True, text=True, timeout=30) + assert result.returncode == 0, result.stderr + + +def test_serve_peer_remaps_kernel_cache_and_forwards_export_options(tmp_path, monkeypatch): + import contextlib + import signal + from pathlib import Path + from types import SimpleNamespace + import flare_heliopause + import torch.distributed as dist + + from ignition.preparation import checkpoint_source as transport, core_snapshot, runtime_core + from ignition.preparation.bootstrap import BasePreparationConfig + + rank0_cache = tmp_path / "rank0-host" / "kernels" + peer_cache = tmp_path / "peer-host" / "kernels" + observed = {} + + def prepare(snapshot, config, *, rank, group, progress=None): + observed["rank"] = rank + observed["kernel_cache"] = config.kernel_cache + return SimpleNamespace(memory_report={}, manifest=lambda: None, close=lambda: None) + + class FakeSource: + def __init__(self, *args, **kwargs): + self.stats = {"payload_bytes": 0} + self.streams = 1 + self.channel_stats = [] + + def activate(self): + return contextlib.nullcontext(tmp_path) + + def finish(self, *, keep_transport=False): + pass + + def report(self): + return {"transport": "test", "payload_seconds": 0.0, "payload_gbps": 0.0} + + def close_transport(self): + pass + + def close(self): + pass + + class FakeStage: + def __init__(self, destination, staging, cache): + self.path = str(tmp_path / "stage") + (tmp_path / "stage").mkdir(exist_ok=True) + + def rank_path(self, rank): + return str(tmp_path / "stage" / f"rank-{rank}.json") + + def close(self): + pass + + class Control: + def getsockname(self): + return "127.0.0.1", 0 + + def close(self): + pass + + def fake_export_model(*args, **kwargs): + active = core_snapshot._OPTIONS.get() + observed["export_kernel_cache"] = active.kernel_cache + observed["export_remote_cache"] = active.remote_cache + observed["export_no_weights"] = active.no_weights + return SimpleNamespace(memory_inventory={}, native_output=None) + + config = BasePreparationConfig(kernel_cache=rank0_cache) + assignment = { + "config": config, + "prepare": prepare, + "store": ("127.0.0.1", 1234), + "exporting": False, + } + commands = iter(( + ("checkpoint-source", None), + assignment, + ("export", {}, core_snapshot.ExportOptions(tmp_path / "rank0-core", no_weights=True, kernel_cache=rank0_cache)), + "close", + )) + + monkeypatch.setattr(transport, "RemoteSource", FakeSource) + monkeypatch.setattr(transport, "token", lambda path: b"test" * 8) + monkeypatch.setattr(host_ranks, "_watch_until_closed", lambda *args, **kwargs: None) + monkeypatch.setattr(host_ranks, "_use_interface", lambda *args: None) + monkeypatch.setattr(host_ranks, "receive_object", lambda *args: next(commands)) + monkeypatch.setattr(host_ranks, "send_object", lambda *args: None) + monkeypatch.setattr(host_ranks, "send_export_sources", lambda *args, **kwargs: None) + monkeypatch.setattr(flare_heliopause, "NativeExportStage", FakeStage) + monkeypatch.setattr(runtime_core, "export_model", fake_export_model) + monkeypatch.setattr(dist, "TCPStore", lambda *args, **kwargs: None) + monkeypatch.setattr(dist, "init_process_group", lambda *args, **kwargs: None) + monkeypatch.setattr(dist, "destroy_process_group", lambda: None) + + previous = signal.getsignal(signal.SIGINT) + try: + host_ranks.serve_peer( + Control(), SimpleNamespace(close=lambda: None), 1, 2, + hub_cache=tmp_path, export_staging=tmp_path, core_cache=tmp_path / "peer-core", + kernel_cache=peer_cache, identity="test", + ) + finally: + signal.signal(signal.SIGINT, previous) + + assert observed == { + "rank": 1, + "kernel_cache": Path(peer_cache), + "export_kernel_cache": peer_cache, + "export_remote_cache": True, + "export_no_weights": True, + } diff --git a/tests/preparation/test_tuning_shards.py b/tests/preparation/test_tuning_shards.py index 938d89819..8a4c13e20 100644 --- a/tests/preparation/test_tuning_shards.py +++ b/tests/preparation/test_tuning_shards.py @@ -259,3 +259,70 @@ def agree_selections(self, selections): assert ("prepare", True, (0, (0,))) in events assert ("agree_selections", [{"width": 2}]) in events assert shard_calls == [(1, (0, 1)), (0, (0,)), (1, (0, 1))] + + +def _gloo_reconcile_divergent_worker(rank, store_path, queue): + from datetime import timedelta + import torch.distributed as dist + + dist.init_process_group("gloo", init_method=f"file://{store_path}", rank=rank, world_size=2, + timeout=timedelta(seconds=30)) + try: + coordinator = CollectivePreparation(dist.group.WORLD) + # Same request name, divergent portable declaration across ranks (size=32 vs size=48) + # and different selected configs (1 on rank 0, 2 on rank 1). + divergent = request("decode1.layer10.moe.experts", 32 if rank == 0 else 48) + object.__setattr__( + divergent.plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=1 if rank == 0 else 2)), + ) + # Different request name across ranks, matching portable declaration (size=64). + aliased = request(f"rank{rank}.shared_decl", 64) + object.__setattr__( + aliased.plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=1 if rank == 0 else 2)), + ) + configs, changed = coordinator.reconcile_selections((divergent, aliased)) + assert changed is True + if rank == 0: + assert configs == {} + else: + assert configs == {divergent.plan: 1, aliased.plan: 1} + for plan, cfg in configs.items(): + object.__setattr__( + plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=cfg)), + ) + # Once ranks agree on configs (even with divergent declarations), reconcile_selections is a no-op. + configs_after, changed_after = coordinator.reconcile_selections((divergent, aliased)) + assert changed_after is False + assert configs_after == {} + # After adopting rank zero's config, agree_selections passes for the divergent request name. + coordinator.agree_selections([ + {"name": divergent.name, "component": divergent.plan.component_id, + "config": divergent.plan.contract.config_payload(divergent.plan.selection.config).to_dict()} + ]) + queue.put((rank, "ok")) + except BaseException as exc: + queue.put((rank, repr(exc))) + raise + finally: + dist.destroy_process_group() + + +def test_reconcile_selections_matches_divergent_declarations_by_request_name(tmp_path): + ctx = torch.multiprocessing.get_context("spawn") + queue = ctx.Queue() + store = tmp_path / "gloo_reconcile_store" + procs = [ctx.Process(target=_gloo_reconcile_divergent_worker, args=(rank, str(store), queue)) + for rank in range(2)] + for p in procs: + p.start() + for p in procs: + p.join(timeout=30) + assert [p.exitcode for p in procs] == [0, 0] + results = dict(queue.get(timeout=5) for _ in range(2)) + assert results == {0: "ok", 1: "ok"}