diff --git a/docs/model-preparation.md b/docs/model-preparation.md index 3a3c5a6a0..a876e818f 100644 --- a/docs/model-preparation.md +++ b/docs/model-preparation.md @@ -236,13 +236,20 @@ overrides that setting. Omitting both retains automatic sizing, including shared-memory limits on DGX Spark. Forward compilation allocates workers across each host after checking cached -forwards. Ranks without a worker lend missing forwards to other -ranks on that host; every serving rank binds and captures its full catalog. +forwards, grouped by GPU product name so every active GPU SKU group on a host +is seeded with at least one compiler worker before surplus workers are +distributed. Admission raises `ValueError` if a host's effective CPU worker +limit (for example under a tight CPU affinity mask, cgroup limit, or +`compile_threads` cap) is smaller than its active SKU group count. Ranks +without a worker lend missing forwards only to peers on the same host with the +same GPU product name; every serving rank binds and captures its full catalog. Concurrency uses a 32 GiB host-RAM estimate per worker, plus device storage on -integrated GPUs. When that estimate admits no worker, one worker per host may -start under the 2 GiB minimum host allowance plus integrated device storage. -These allowances estimate compiler demand; actual peaks depend on the forward. -Linux cgroup-v2 memory limits also constrain the available RAM used for admission. +integrated GPUs. When a host has a single active SKU group and that estimate +admits no worker, one worker may start under the 2 GiB minimum host allowance +plus integrated device storage; hosts with multiple active SKU groups require +the full per-worker estimate for each seeded worker. These allowances estimate +compiler demand; actual peaks depend on the forward. Linux cgroup-v2 memory +limits also constrain the available RAM used for admission. On integrated GPUs, kernel tuning is divided into memory-bounded jobs. The terminal dashboard shows the active job number and total job count, with a diff --git a/docs/preparation-development.md b/docs/preparation-development.md index e877cd20a..4ac3a187e 100644 --- a/docs/preparation-development.md +++ b/docs/preparation-development.md @@ -348,27 +348,38 @@ ranks without local remainders still join completion and failure relays. independent kernel candidates retain corresponding-rank sharding across replicas. Preparation-time search ends before graph handoff. -- **Compile tensor-parallel forwards once, sharded across ranks.** Pass the - preparation coordinator to `capture_forwards`. Each forward variant compiles - once, on a rank that selects it, from that rank's own forward; on one host, a - rank without variants left, or without room for a compiler, compiles another - rank's variant from that rank's traced forward metadata. Compiler pools are - budgeted for their host's ranks and close when their local and borrowed work - finishes, before ranks exchange completion results. Ranks on one host share its cache directory; - ranks on other hosts receive the artifacts they lack. Every rank loads the same - artifacts, binds its tensors and native handles, and participates in ordered - warmup and local capture. Inductor's first owner-process warmup may tune the - same generated kernel independently on several ranks. At each complete-forward - boundary, ranks adopt one measured selection and compiled kernel for each exact - generated source and candidate contract, with only the CUDA ordinal normalized. - The first canonical selection remains authoritative across the complete catalog. - A second warmup verifies the frozen selections before capture; cached artifacts - retain those selections on single-rank and tensor-parallel reloads. No selection - exchange occurs inside a forward or a native collective. Keep shard offsets and native handles in runtime - bindings when they do not change the computation. For distinct rank behavior, - select a variant key through `compilation_variant` on each rank. Every - selected variant must compile before collective warmup; ranks must not retrace - or compile on a binding mismatch. +- **Compile tensor-parallel forwards once per variant and GPU product name, + sharded across ranks.** Pass the preparation coordinator to `capture_forwards`. + All ranks in a tensor-parallel group must share the same CUDA compute + capability; cross-architecture rank groups are rejected before compilation. + Cache roots and `publication.lock` acquisitions are partitioned per + `(host, GPU product name)` pair in deterministic sorted order, keeping + un-suffixed artifact filenames inside each GPU product name's cache root. + Each `(compilation_variant, GPU product name)` key compiles once, on a rank + that selects it, from that rank's own forward; on one host, a rank without + variants left, or without room for a compiler, compiles a same-SKU peer's + variant from that peer's traced forward metadata. Compiler pools are budgeted + per host across active GPU product-name subgroups and close when their local + and borrowed work finishes, before ranks exchange completion results. Ranks + sharing a host and GPU product name share that cache directory; ranks on + other hosts receive only the artifacts they lack under their own cache root. + Every rank loads the artifacts for its `(compilation_variant, GPU product name)` + key, binds its tensors and native handles, and participates in ordered warmup + and local capture. During warmup, ranks verify identical Inductor kernel + inventories within each `(compilation_variant, GPU product name)` group. + Inductor's first owner-process warmup may tune the same generated kernel + independently on several ranks. At each complete-forward boundary, ranks + adopt one measured selection and compiled kernel for each exact generated + source and candidate contract, with only the CUDA ordinal normalized. The + first canonical selection remains authoritative across the complete catalog. + A second warmup verifies the frozen selections before capture; cached + artifacts retain those selections on single-rank and tensor-parallel reloads. + No selection exchange occurs inside a forward or a native collective. Keep + shard offsets and native handles in runtime bindings when they do not change + the computation. For distinct rank behavior, select a variant key through + `compilation_variant` on each rank. Every selected variant must compile + before collective warmup; ranks must not retrace or compile on a binding + mismatch. Load, warm, freeze, and save one forward at a time in descending order of largest compiler-planned CUDA allocation (breaking ties by total planned bytes, then catalog order, using the maximum request sizes across ranks). Release diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index 29597f280..be5355e71 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -695,16 +695,19 @@ def finish(rank, extra=0): assigned[idlest].append(assigned[busiest].pop()) -def _share_artifacts(owned, group, ranks): +def _share_artifacts(owned, group, ranks, root=None): """Copy every rank's compiled forwards to ranks on other hosts, which load them by the same path. `owned[i]` lists the artifacts rank `ranks[i]` compiled. Each rank keeps its own cache directory; a rank receives only artifacts it lacks or whose contents differ from their - compiler's. + compiler's. When `root` is provided, each rank fetches only peer artifacts located directly + inside `root` so multi-host mixed-SKU launches do not write foreign-SKU files into unlocked + cache directories. """ import torch.distributed as dist me = ranks.index(dist.get_rank()) + target_root = None if root is None else Path(root).resolve() digests = [None] * len(ranks) dist.all_gather_object(digests, {path: hashlib.sha256(Path(path).read_bytes()).hexdigest() for path in owned[me]}, group=group) @@ -716,7 +719,9 @@ def current(path, digest): return False missing = {path for index, compiled in enumerate(digests) if index != me - for path, digest in compiled.items() if not current(path, digest)} + for path, digest in compiled.items() + if (target_root is None or Path(path).resolve().parent == target_root) + and not current(path, digest)} wanted = [None] * len(ranks) dist.all_gather_object(wanted, sorted(missing), group=group) wanted = set().union(*wanted) @@ -772,26 +777,31 @@ def prepare(self, forward, *, name, signature, progress=None): @contextmanager def _publication_lock(self, coordinator=None): - """Hold this host's cache against other launches from compilation through binding. + """Hold every participating cache root against other launches from compilation through binding. Cached variants share filenames, so another launch must not replace a catalog still in - use. Ranks on one host share its cache directory: the host's first rank holds the lock for - all of them. No rank compiles before every host's lock is held, and no host releases it + use. Ranks sharing a `(host, resolved_root)` pair share that cache directory, while ranks + with distinct GPU product names on one host may use separate cache roots: the first rank + for each distinct `(host, resolved_root)` acquires its lock in deterministic sorted order. + No rank compiles before every participating lock is held, and no holder releases its lock before every rank has bound its forwards. """ - host, hosts, holder = None, [None], True + key, keys, holder = None, [None], True if coordinator is not None: import torch.distributed as dist index = coordinator.ranks.index(dist.get_rank()) - host = coordinator.hosts[index] - holder = coordinator.hosts.index(host) == index - hosts = sorted(set(coordinator.hosts)) + key = (coordinator.hosts[index], str(self.root.resolve())) + gathered = [None] * len(coordinator.ranks) + dist.all_gather_object(gathered, key, group=coordinator.group) + holder = gathered.index(key) == index + keys = sorted(set(gathered)) lock = None try: - # Hosts lock in one order, so launches sharing hosts cannot each hold a lock the other awaits. - for turn in hosts: - if holder and turn == host: + # Distinct (host, cache root) pairs lock in one order so mixed-SKU cache roots on one + # host are each protected without risking deadlock across concurrent launches. + for turn in keys: + if holder and turn == key: self.root.mkdir(parents=True, exist_ok=True) lock = FileLock(self.root / 'publication.lock') lock.acquire() @@ -903,42 +913,59 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi before_run): """Compile the catalog for a rank group, then bind and warm it on every rank. - Compiled forwards serve every rank, so the catalog compiles once: each forward variant a - rank selects through `compilation_variant` compiles on a rank that selects it, from that - rank's own forward, unless an idle rank on the same host borrows it and compiles it from - the owner's traced forward metadata. Compiler pools are budgeted for the host's ranks. - Ranks on one host share its cache directory; a rank on another host receives the - artifacts it lacks from the ranks that compiled them. Every rank then binds the same - artifacts. + Each forward compiles once per `(compilation_variant, gpu_name)` key using un-suffixed + on-disk filenames inside each SKU's GPU-partitioned `self.root`, while cross-architecture + rank groups are rejected. Each `(compilation_variant, gpu_name)` compiles on a rank that + selects it, from that rank's own forward, unless an idle peer on the same host with the + same GPU product name borrows it and compiles it from the owner's traced forward metadata. + Compiler pools are budgeted per host across active GPU product-name subgroups. Ranks + sharing a host and GPU product name share that cache directory; a rank on another host + receives only the artifacts it lacks under its own `self.root` from the peer that compiled + its variant. """ import torch.distributed as dist from ignition.progress import phase from .compile_pool import CompilePool, allocate_workers, compiler_resources - from .inductor_tuning import InductorSelections + from .inductor_tuning import InductorSelections, cuda_device_identity group, ranks = coordinator.group, coordinator.ranks share = ranks.index(dist.get_rank()) + gpu_name, capability = cuda_device_identity(self.device) + identities = [None] * len(ranks) + dist.all_gather_object(identities, (gpu_name, capability), group=group) + gpu_names = [name for name, _ in identities] + capabilities = {cap for _, cap in identities} + if len(capabilities) > 1: + ordered = sorted(capabilities, key=lambda cap: (cap is None, cap)) + raise RuntimeError( + f"tensor-parallel ranks span incompatible CUDA architectures: {ordered}" + ) + + def _variant_key(forward): + return (getattr(forward, "compilation_variant", "shared"), gpu_name) + selections = [None] * len(ranks) - dist.all_gather_object(selections, {name: getattr(forward, "compilation_variant", "shared") + dist.all_gather_object(selections, {name: _variant_key(forward) for name, forward in functions.items()}, group=group) if any(chosen.keys() != selections[0].keys() for chosen in selections): raise RuntimeError("ranks prepared different forward catalogs") compilers = _variant_compilers(selections) - work = [(name, variant, functions[name]) for (name, variant), compiler in compilers.items() if compiler == share] + work = [(name, variant_key, functions[name]) for (name, variant_key), compiler in compilers.items() if compiler == share] selected, outcome, error, compiler, paths, lent, sent = {}, (None, None), None, None, {}, set(), [] loans = [] with ExitStack() as scope: stage = scope.enter_context(phase(progress, "Compile model forwards", total=len(work))) compiler_scope = scope.enter_context(ExitStack()) # Variants that only one rank selects, such as rank zero's sampling, can leave that rank most of - # the catalog. Ranks on one host share its cache, so a rank lends forwards it cannot restore, whether - # missing or bound differently by another launch, to ranks whose compilers would otherwise finish - # first; the borrower compiles the owner's metadata. + # the catalog. Ranks sharing a host and GPU product name share a cache, so a rank lends forwards + # it cannot restore, whether missing or bound differently by another launch, to same-SKU peers on + # the same host whose compilers would otherwise finish first; the borrower compiles the owner's + # metadata. restored, missing = {}, [] try: - for index, (name, variant, forward) in enumerate(work): + for index, (name, variant_key, forward) in enumerate(work): with _guard_code_cache(self.root / 'guards'): - bound, path = self._restore(forward, name=f"{name}.{variant}", signature=signatures[name], + bound, path = self._restore(forward, name=f"{name}.{variant_key[0]}", signature=signatures[name], deferred=materialize is not None, before_run=None if before_run is None else lambda name=name: before_run(name)) if bound is None: @@ -966,11 +993,16 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi if failures: raise RuntimeError(f"forward compiler resource collection failed: {failures}") counts = [count for count, _, _ in demand] - workers = allocate_workers([resources for _, resources, _ in demand], counts, coordinator.hosts) + workers = allocate_workers( + [resources for _, resources, _ in demand], counts, coordinator.hosts, groups=gpu_names + ) stage.update(f"{sum(workers)} compiler workers; per rank {workers}") assigned = [[] for _ in ranks] - for host in dict.fromkeys(coordinator.hosts): - members = [index for index, name in enumerate(coordinator.hosts) if name == host] + for host, dev_name in dict.fromkeys(zip(coordinator.hosts, gpu_names)): + members = [ + index for index, (h_name, g_name) in enumerate(zip(coordinator.hosts, gpu_names)) + if h_name == host and g_name == dev_name + ] if not any(counts[index] for index in members): continue local = _balance_compilations([counts[index] for index in members], @@ -989,8 +1021,8 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi jobs = self.root / 'lent' jobs.mkdir(parents=True, exist_ok=True) for borrower, index in loans: - name, variant, forward = work[index] - path = self._path(forward, name=f"{name}.{variant}", signature=signatures[name]) + name, variant_key, forward = work[index] + path = self._path(forward, name=f"{name}.{variant_key[0]}", signature=signatures[name]) job = jobs / f"{path.stem}.forward" with tempfile.NamedTemporaryFile(dir=jobs, suffix='.tmp', delete=False) as file: temporary = Path(file.name) @@ -1002,7 +1034,7 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi temporary.unlink(missing_ok=True) sent.append((borrower, str(job))) # The borrower compiles it before every rank gathers the outcome below. - paths[name, variant] = str(path), True + paths[name, variant_key] = str(path), True except Exception as failure: error = error or f"{type(failure).__name__}: {failure}" mailed = [None] * len(ranks) @@ -1014,7 +1046,7 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi pending = [] def finish(): - name, variant, bound, path = _completed(pending) + name, variant_key, bound, path = _completed(pending) if bound.pending is not None: bound.pending.result() elif materialize is None: @@ -1022,18 +1054,18 @@ def finish(): selected[name] = bound if name is not None: # Each forward's path, and whether this launch compiled it rather than restoring it. - paths[name, variant] = str(path), bound.pending is not None + paths[name, variant_key] = str(path), bound.pending is not None stage.update(advance=1) - for index, (name, variant, forward) in enumerate(work): - if (name, variant) in lent: + for index, (name, variant_key, forward) in enumerate(work): + if (name, variant_key) in lent: continue if index in restored: bound, path = restored[index] else: - path = self._path(forward, name=f"{name}.{variant}", signature=signatures[name]) + path = self._path(forward, name=f"{name}.{variant_key[0]}", signature=signatures[name]) bound = BoundForward(None, forward, False, compiler.submit(forward, path)) - pending.append((name, variant, bound, path)) + pending.append((name, variant_key, bound, path)) if compiler is not None and len(pending) >= compiler.workers: finish() for job in borrowed: @@ -1067,10 +1099,10 @@ def finish(): restored.clear() bound = None paths = {key: value for compiled, _ in outcomes for key, value in compiled.items()} - # Ranks on one host compiled into its cache directory; only other hosts lack their shares. + # Ranks on one host compiled into their SKU cache directories; other hosts fetch only files under self.root. if coordinator.spans_hosts: _share_artifacts([sorted({path for path, _ in compiled.values()}) for compiled, _ in outcomes], - group, ranks) + group, ranks, root=self.root) error, sizes = None, None try: release_unused() @@ -1078,7 +1110,7 @@ def finish(): materialize() sizes = { name: (selected[name].capture_allocation_sizes if name in selected - else self._allocation_sizes(paths[name, getattr(forward, "compilation_variant", "shared")][0])) + else self._allocation_sizes(paths[name, _variant_key(forward)][0])) for name, forward in functions.items() } except Exception as failure: @@ -1097,7 +1129,7 @@ def finish(): failure = None try: if name not in selected: - path, compiled = paths[name, getattr(forward, "compilation_variant", "shared")] + path, compiled = paths[name, _variant_key(forward)] with _guard_code_cache(self.root / 'guards'): selected[name] = self._load(forward, Path(path), required=True, before_run=None if before_run is None else lambda name=name: before_run(name)) @@ -1120,9 +1152,9 @@ def finish(): failure = None try: selections.freeze(bound) - variant = getattr(forward, 'compilation_variant', 'shared') - if compilers[name, variant] == share: - path, _ = paths[name, variant] + variant_key = _variant_key(forward) + if compilers[name, variant_key] == share: + path, _ = paths[name, variant_key] bound.artifact.save_compiled_function(path) published.append(path) released += bound.prepare_capture() @@ -1135,7 +1167,7 @@ def finish(): stage.update(f"{released >> 20} MiB portable state released; guards and kernel owners retained") release_unused() if coordinator.spans_hosts: - _share_artifacts(selections._gather(published), group, ranks) + _share_artifacts(selections._gather(published), group, ranks, root=self.root) return selected def _allocation_sizes(self, path): diff --git a/ignition/preparation/compile_pool.py b/ignition/preparation/compile_pool.py index 3e5106dd0..20267cfc7 100644 --- a/ignition/preparation/compile_pool.py +++ b/ignition/preparation/compile_pool.py @@ -59,37 +59,68 @@ def compiler_resources(device, *, headroom_bytes=0, options=None, compile_worker max(host_memory._HEADROOM_BYTES, headroom_bytes if shared else 0)) -def allocate_workers(resources, counts, hosts): - """Admit forward compiler workers once per host, including zero-worker owners.""" +def allocate_workers(resources, counts, hosts, groups=None): + """Admit forward compiler workers once per host, including zero-worker owners. + + When `groups` is provided (for example GPU product names on a mixed-SKU + host), each active `(host, group)` subgroup is seeded with at least one + worker before surplus workers are distributed across active subgroups. + """ workers = [0] * len(resources) + groups = hosts if groups is None else groups for host in dict.fromkeys(hosts): members = [rank for rank, name in enumerate(hosts) if name == host] jobs = sum(counts[rank] for rank in members) if not jobs: continue + active_groups = [ + subgroup + for subgroup in ( + [rank for rank in members if groups[rank] == group] + for group in dict.fromkeys(groups[rank] for rank in members) + ) + if any(counts[rank] for rank in subgroup) + ] available = min(resources[rank].available for rank in members) headroom = max(resources[rank].headroom for rank in members) limit = min(jobs, min(resources[rank].limit for rank in members)) + if limit < len(active_groups): + raise ValueError( + f"host {host!r} has {len(active_groups)} active compiler groups but worker limit {limit}" + ) remaining = available - headroom - for _ in range(limit): - able = [rank for rank in members if workers[rank] < resources[rank].capacity + # Seed one worker per active group so no active SKU on a mixed host is starved. + for subgroup in active_groups: + able = [rank for rank in subgroup if workers[rank] < resources[rank].capacity + and resources[rank].worker_bytes <= remaining] + if able: + rank = min(able, key=lambda rank: (workers[rank], rank)) + workers[rank] += 1 + remaining -= resources[rank].worker_bytes + continue + if len(active_groups) == 1: + # Small forwards can fit below the concurrency estimate. Preserve one worker on + # a host with a single active group under the minimum allowance. + able = [rank for rank in subgroup if resources[rank].capacity + and resources[rank].worker_bytes - host_memory.FORWARD_WORKER_BYTES + + host_memory._WORKER_BYTES <= remaining] + if able: + rank = able[0] + workers[rank] += 1 + remaining -= (resources[rank].worker_bytes - host_memory.FORWARD_WORKER_BYTES + + host_memory._WORKER_BYTES) + if any(not any(workers[rank] for rank in subgroup) for subgroup in active_groups): + raise MemoryError(f"host {host!r} has {jobs} missing forwards but no capacity for a forward compiler " + f"({available >> 20} MiB available host memory, {headroom >> 20} MiB headroom)") + active_members = [rank for subgroup in active_groups for rank in subgroup] + for _ in range(limit - len(active_groups)): + able = [rank for rank in active_members if workers[rank] < resources[rank].capacity and resources[rank].worker_bytes <= remaining] if not able: break rank = min(able, key=lambda rank: (workers[rank], rank)) workers[rank] += 1 remaining -= resources[rank].worker_bytes - if not any(workers[rank] for rank in members): - # Small forwards can fit below the concurrency estimate. Preserve one worker per host - # under the minimum allowance without multiplying that allowance by the rank count. - able = [rank for rank in members if resources[rank].capacity - and resources[rank].worker_bytes - host_memory.FORWARD_WORKER_BYTES - + host_memory._WORKER_BYTES <= remaining] - if able: - workers[able[0]] = 1 - else: - raise MemoryError(f"host {host!r} has {jobs} missing forwards but no capacity for a forward compiler " - f"({available >> 20} MiB available host memory, {headroom >> 20} MiB headroom)") return workers diff --git a/ignition/preparation/inductor_tuning.py b/ignition/preparation/inductor_tuning.py index fb062daeb..e2e93975f 100644 --- a/ignition/preparation/inductor_tuning.py +++ b/ignition/preparation/inductor_tuning.py @@ -18,6 +18,14 @@ from .device_binding import _device_source, _freeze_tuning_winners +def cuda_device_identity(device): + """Return `(product_name, compute_capability)` for a CUDA device, or `('', None)` otherwise.""" + resolved = torch.device(device) + if resolved.type != "cuda" or not torch.cuda.is_available(): + return "", None + return torch.cuda.get_device_name(resolved), tuple(torch.cuda.get_device_capability(resolved)) + + def _selected(tuner): from torch._inductor.runtime.triton_heuristics import StaticTritonCompileResult @@ -236,8 +244,10 @@ def run(*args, **kwargs): def warm(self, bound, warmup, *, before_run=None): bindings = self.forwards[id(bound)][2] inventory = sorted({identity for identity, _, _ in bindings.values()}) + gpu_name, _ = cuda_device_identity(self.device) + variant_key = (getattr(bound.owner, 'compilation_variant', 'shared'), gpu_name) variants = {} - for variant, identities in self._gather((getattr(bound.owner, 'compilation_variant', 'shared'), inventory)): + for variant, identities in self._gather((variant_key, inventory)): if variant in variants and variants[variant] != identities: raise RuntimeError(f"equivalent compiled forward variant {variant!r} has different Inductor kernels") variants[variant] = identities diff --git a/tests/preparation/test_mixed_gpu_inductor_keying.py b/tests/preparation/test_mixed_gpu_inductor_keying.py new file mode 100644 index 000000000..c9c888a64 --- /dev/null +++ b/tests/preparation/test_mixed_gpu_inductor_keying.py @@ -0,0 +1,452 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Compiled forward sharing and Inductor validation across mixed-SKU and cross-architecture GPUs.""" + +import hashlib +import multiprocessing +import os +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +from filelock import FileLock, Timeout + +from ignition.preparation import aot, compile_pool, inductor_tuning +from tests.preparation.test_forward_artifact_sharing import _Artifact, _Forward, _Pool, _replace_gpu_preparation + +MAXQ = "NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition" +WORKSTATION = "NVIDIA RTX PRO 6000 Blackwell Workstation Edition" + + +def _sku_root(base, gpu_name): + """Mirror `ForwardCache.__init__`, which hashes the GPU product name into `self.root`.""" + return Path(base) / hashlib.sha256(gpu_name.encode()).hexdigest()[:12] + + +def _expected_bin_names(root): + cache = aot.ForwardCache.__new__(aot.ForwardCache) + cache.root = root + return sorted( + cache._path(_Forward("shared"), name=f"{name}.shared", signature=name).name + for name in "abcd" + ) + + +def _prepare_rank(rank, world, store, base, identities, hosts, outcome, available_gib=128, precached_skus=()): + import torch.distributed as dist + + try: + gpu_name, capability = identities[rank] + compiled_owners = [] + variant_names = [] + + class RecordingPool(_Pool): + def submit_payload(self, payload, path): + from ignition.preparation.forward_metadata import loads + + owner_rank = loads(payload).rank + assert identities[owner_rank][0] == gpu_name, "lent forward crossed GPU SKUs" + compiled_owners.append(owner_rank) + return super().submit_payload(payload, path) + + original_path = aot.ForwardCache._path + + def recording_path(self, forward, *, name, signature): + variant_names.append(name) + return original_path(self, forward, name=name, signature=signature) + + compile_pool.CompilePool = RecordingPool + _replace_gpu_preparation() + compile_pool.compiler_resources = lambda *args, **kwargs: compile_pool.CompilerResources( + 1, available_gib << 30, 16, 32 << 30, 8 << 30 + ) + inductor_tuning.cuda_device_identity = lambda device: (gpu_name, capability) + aot.ForwardCache._path = recording_path + aot.ForwardCache._load = lambda self, forward, path, required=False, before_run=None: aot.BoundForward( + _Artifact(lambda owner: None), forward, True + ) + aot.ForwardCache._allocation_sizes = lambda self, path: () + spans_hosts = len(set(hosts)) > 1 + if spans_hosts: + host_dir = base / hosts[rank] + os.chdir(host_dir) + sku_root = _sku_root(Path("forwards"), gpu_name) + else: + sku_root = _sku_root(base, gpu_name) + sku_root.mkdir(parents=True, exist_ok=True) + dist.init_process_group("gloo", init_method=f"file://{store}", rank=rank, world_size=world) + cache = aot.ForwardCache.__new__(aot.ForwardCache) + cache.root, cache.device, cache.headroom_bytes, cache.options = sku_root, "cpu", 0, aot.MappingProxyType({}) + cache.compile_workers = None + cache.lock_gpu_clocks = False + functions = {name: _Forward("shared") for name in "abcd"} + for forward in functions.values(): + forward.rank = rank + if gpu_name in precached_skus: + for name, forward in functions.items(): + original_path(cache, forward, name=f"{name}.shared", signature=name).write_text("cached") + dist.barrier() + coordinator = SimpleNamespace( + group=dist.group.WORLD, + ranks=tuple(range(world)), + hosts=hosts, + spans_hosts=spans_hosts, + local_ranks=world if not spans_hosts else hosts.count(hosts[rank]), + barrier=lambda key, ranks: dist.monitored_barrier(group=dist.group.WORLD), + ) + selected = cache._prepare_ranks( + functions, + {name: name for name in functions}, + coordinator, + progress=None, + materialize=lambda: None, + warmup=nullcontext, + before_run=None, + ) + outcome.put((rank, ("ok", sorted(selected), sorted(compiled_owners), sorted(set(variant_names))))) + except Exception as error: # noqa: BLE001 - The parent asserts on rank failures. + outcome.put((rank, ("error", f"{type(error).__name__}: {error}"))) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +def _run_prepare( + tmp_path, + identities, + *, + available_gib=128, + precached_skus=(), + hosts=None, + cache_base=None, + store_name="store", +): + context = multiprocessing.get_context("fork") + hosts = ("host",) * len(identities) if hosts is None else tuple(hosts) + base = tmp_path / "forwards" if cache_base is None else Path(cache_base) + if len(set(hosts)) > 1: + for host in set(hosts): + (base / host / "forwards").mkdir(parents=True, exist_ok=True) + else: + base.mkdir(parents=True, exist_ok=True) + outcome = context.Queue() + processes = [ + context.Process( + target=_prepare_rank, + args=( + rank, + len(identities), + tmp_path / store_name, + base, + identities, + hosts, + outcome, + available_gib, + precached_skus, + ), + ) + for rank in range(len(identities)) + ] + try: + for process in processes: + process.start() + results = dict(outcome.get(timeout=90) for _ in processes) + for process in processes: + process.join(timeout=30) + assert process.exitcode == 0 + if len(set(hosts)) > 1: + artifacts = { + host: sorted(str(path.relative_to(base / host / "forwards")) + for path in (base / host / "forwards").rglob("*.bin")) + for host in sorted(set(hosts)) + } + else: + artifacts = { + gpu_name: sorted(path.name for path in _sku_root(base, gpu_name).glob("*.bin")) + for gpu_name in dict.fromkeys(name for name, _ in identities) + } + return results, artifacts + finally: + for process in processes: + if process.is_alive(): + process.terminate() + process.join(timeout=30) + + +def test_cuda_device_identity_returns_empty_for_cpu(): + assert inductor_tuning.cuda_device_identity("cpu") == ("", None) + assert inductor_tuning.cuda_device_identity(torch.device("cpu")) == ("", None) + + +def test_mixed_sku_same_architecture_keys_forwards_and_isolates_lending(tmp_path): + identities = ((MAXQ, (12, 0)), (WORKSTATION, (12, 0)), (MAXQ, (12, 0)), (WORKSTATION, (12, 0))) + results, artifacts = _run_prepare(tmp_path, identities) + all_variants = set() + for rank in range(4): + status, selected, compiled_owners, variant_names = results[rank] + assert status == "ok", selected + assert selected == list("abcd") + all_variants.update(variant_names) + # Every compiled forward belongs to a rank with the same SKU. + assert all(identities[owner][0] == identities[rank][0] for owner in compiled_owners) + # Rank 3 has zero admitted workers under the 3-worker host budget and lends only to rank 1 (same SKU). + assert results[1][2] == [1, 1, 3, 3] + assert results[3][2] == [] + # Each SKU writes four un-suffixed forwards into its own GPU-partitioned cache root. + assert all_variants == {f"{name}.shared" for name in "abcd"} + assert artifacts[MAXQ] == _expected_bin_names(_sku_root(tmp_path / "forwards", MAXQ)) + assert artifacts[WORKSTATION] == _expected_bin_names(_sku_root(tmp_path / "forwards", WORKSTATION)) + + +def test_homogeneous_cache_is_reused_by_mixed_sku_run_without_recompilation(tmp_path): + shared_base = tmp_path / "shared_forwards" + ws_root = _sku_root(shared_base, WORKSTATION) + maxq_root = _sku_root(shared_base, MAXQ) + + homo_results, homo_artifacts = _run_prepare( + tmp_path, + ((WORKSTATION, (12, 0)), (WORKSTATION, (12, 0))), + cache_base=shared_base, + store_name="store_homo", + ) + for rank in range(2): + status, selected, _, variant_names = homo_results[rank] + assert status == "ok", selected + assert selected == list("abcd") + assert set(variant_names) <= {f"{name}.shared" for name in "abcd"} + assert homo_artifacts[WORKSTATION] == _expected_bin_names(ws_root) + + mixed_results, mixed_artifacts = _run_prepare( + tmp_path, + ((MAXQ, (12, 0)), (WORKSTATION, (12, 0)), (MAXQ, (12, 0)), (WORKSTATION, (12, 0))), + cache_base=shared_base, + store_name="store_mixed", + ) + for rank in range(4): + status, selected, _, variant_names = mixed_results[rank] + assert status == "ok", selected + assert selected == list("abcd") + assert set(variant_names) <= {f"{name}.shared" for name in "abcd"} + # Workstation ranks reuse the homogeneous cache with zero compilations; only MAXQ compiles. + assert mixed_results[1][2] == [] + assert mixed_results[3][2] == [] + assert sorted(mixed_results[0][2] + mixed_results[2][2]) == [0, 0, 2, 2] + assert mixed_artifacts[WORKSTATION] == _expected_bin_names(ws_root) + assert mixed_artifacts[MAXQ] == _expected_bin_names(maxq_root) + + +@pytest.mark.parametrize("available_gib", [12, 39, 40, 41, 42, 71]) +def test_allocate_workers_is_monotonic_and_rejects_underbudgeted_multi_sku_hosts(available_gib): + resources = [compile_pool.CompilerResources(1, available_gib << 30, 16, 32 << 30, 8 << 30)] * 4 + groups = [MAXQ, MAXQ, WORKSTATION, WORKSTATION] + with pytest.raises(MemoryError, match="no capacity"): + compile_pool.allocate_workers(resources, [2, 2, 2, 2], ["host"] * 4, groups=groups) + + +def test_allocate_workers_admits_single_active_group_under_minimum_allowance(): + resources = [compile_pool.CompilerResources(1, 10 << 30, 16, 32 << 30, 8 << 30)] * 4 + # Only WORKSTATION has missing forwards, so the single active SKU group uses the 2 GiB fallback. + assert compile_pool.allocate_workers( + resources, [0, 0, 2, 2], ["host"] * 4, groups=[MAXQ, MAXQ, WORKSTATION, WORKSTATION] + ) == [0, 0, 1, 0] + # A homogeneous host with one active group preserves the same 2 GiB fallback. + assert compile_pool.allocate_workers( + resources[:2], [2, 2], ["host"] * 2, groups=[WORKSTATION, WORKSTATION] + ) == [1, 0] + + +def test_contiguous_mixed_sku_seeds_each_active_group_under_tight_budget(tmp_path): + # 72 GiB available - 8 GiB headroom = 64 GiB -> exactly 2 workers at 32 GiB each. + resources = [compile_pool.CompilerResources(1, 72 << 30, 16, 32 << 30, 8 << 30)] * 4 + groups = [MAXQ, MAXQ, WORKSTATION, WORKSTATION] + assert compile_pool.allocate_workers(resources, [2, 2, 2, 2], ["host"] * 4, groups=groups) == [1, 0, 1, 0] + + identities = ((MAXQ, (12, 0)), (MAXQ, (12, 0)), (WORKSTATION, (12, 0)), (WORKSTATION, (12, 0))) + results, artifacts = _run_prepare(tmp_path, identities, available_gib=72) + for rank in range(4): + status, selected, compiled_owners, _ = results[rank] + assert status == "ok", selected + assert selected == list("abcd") + assert all(identities[owner][0] == identities[rank][0] for owner in compiled_owners) + assert results[0][2] == [0, 0, 1, 1] + assert results[1][2] == [] + assert results[2][2] == [2, 2, 3, 3] + assert results[3][2] == [] + assert len(artifacts[MAXQ]) == 4 + assert len(artifacts[WORKSTATION]) == 4 + + +def test_allocate_workers_rejects_worker_limit_smaller_than_active_sku_groups(): + # Ample host RAM (128 GiB) with a worker cap of 1 across 2 active GPU SKU groups must report + # the worker-limit conflict explicitly rather than raising a misleading MemoryError. + resources = [compile_pool.CompilerResources(1, 128 << 30, 1, 32 << 30, 8 << 30)] * 4 + groups = [MAXQ, MAXQ, WORKSTATION, WORKSTATION] + with pytest.raises(ValueError, match="2 active compiler groups but worker limit 1"): + compile_pool.allocate_workers(resources, [2, 2, 2, 2], ["host"] * 4, groups=groups) + + +def test_cached_sku_withholds_workers_so_compiling_sku_receives_host_budget(tmp_path): + # MAXQ ranks are fully cached; WORKSTATION ranks compile under a 1-worker (40 GiB) host budget. + identities = ((MAXQ, (12, 0)), (MAXQ, (12, 0)), (WORKSTATION, (12, 0)), (WORKSTATION, (12, 0))) + results, artifacts = _run_prepare(tmp_path, identities, available_gib=40, precached_skus=(MAXQ,)) + for rank in range(4): + status, selected, _, _ = results[rank] + assert status == "ok", selected + assert selected == list("abcd") + assert results[0][2] == [] + assert results[1][2] == [] + assert results[2][2] == [2, 2, 3, 3] + assert results[3][2] == [] + assert len(artifacts[MAXQ]) == 4 + assert len(artifacts[WORKSTATION]) == 4 + + +def test_two_host_mixed_sku_share_artifacts_isolates_foreign_cache_roots(tmp_path): + identities = ((MAXQ, (12, 0)), (WORKSTATION, (12, 0))) + hosts = ("host_a", "host_b") + results, artifacts = _run_prepare(tmp_path, identities, hosts=hosts) + for rank in range(2): + status, selected, _, variant_names = results[rank] + assert status == "ok", selected + assert selected == list("abcd") + assert set(variant_names) == {f"{name}.shared" for name in "abcd"} + maxq_dir = _sku_root(Path("forwards"), MAXQ).name + ws_dir = _sku_root(Path("forwards"), WORKSTATION).name + assert not (tmp_path / "forwards" / "host_a" / "forwards" / ws_dir).exists() + assert not (tmp_path / "forwards" / "host_b" / "forwards" / maxq_dir).exists() + assert len(artifacts["host_a"]) == 4 + assert all(entry.startswith(f"{maxq_dir}/") for entry in artifacts["host_a"]) + assert len(artifacts["host_b"]) == 4 + assert all(entry.startswith(f"{ws_dir}/") for entry in artifacts["host_b"]) + + +def _lock_rank(rank, world, store, roots, outcome): + import torch.distributed as dist + + try: + dist.init_process_group("gloo", init_method=f"file://{store}", rank=rank, world_size=world) + cache = aot.ForwardCache.__new__(aot.ForwardCache) + cache.root = roots[rank] + coordinator = SimpleNamespace(group=dist.group.WORLD, ranks=tuple(range(world)), hosts=("host",) * world) + with cache._publication_lock(coordinator): + dist.barrier(group=dist.group.WORLD) + locked = {} + if rank == 0: + for path in sorted(set(roots)): + probe = FileLock(path / "publication.lock", timeout=0) + try: + probe.acquire() + except Timeout: + locked[path.name] = True + else: + probe.release() + locked[path.name] = False + dist.barrier(group=dist.group.WORLD) + outcome.put((rank, ("ok", locked))) + except Exception as error: # noqa: BLE001 - Parent inspects rank failures. + outcome.put((rank, ("error", f"{type(error).__name__}: {error}"))) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +def test_publication_lock_acquires_every_distinct_cache_root_on_same_host(tmp_path): + context = multiprocessing.get_context("fork") + roots = (tmp_path / "maxq", tmp_path / "workstation", tmp_path / "maxq", tmp_path / "workstation") + outcome = context.Queue() + processes = [ + context.Process(target=_lock_rank, args=(rank, 4, tmp_path / "store", roots, outcome)) + for rank in range(4) + ] + try: + for process in processes: + process.start() + results = dict(outcome.get(timeout=60) for _ in processes) + for process in processes: + process.join(timeout=30) + assert process.exitcode == 0 + assert results[0] == ("ok", {"maxq": True, "workstation": True}) + assert all(status == "ok" for status, _ in results.values()) + finally: + for process in processes: + if process.is_alive(): + process.terminate() + process.join(timeout=30) + + +def test_homogeneous_gpus_preserve_unsuffixed_forward_sharing(tmp_path): + identities = ((WORKSTATION, (12, 0)), (WORKSTATION, (12, 0))) + results, artifacts = _run_prepare(tmp_path, identities) + all_variants = set() + for rank in range(2): + status, selected, _, variant_names = results[rank] + assert status == "ok", selected + assert selected == list("abcd") + all_variants.update(variant_names) + # Homogeneous ranks share four un-suffixed compiled artifacts across the group. + assert artifacts[WORKSTATION] == _expected_bin_names(_sku_root(tmp_path / "forwards", WORKSTATION)) + assert all_variants == {f"{name}.shared" for name in "abcd"} + + +@pytest.mark.parametrize("second_identity", [("NVIDIA GB10", (12, 1)), ("", None)]) +def test_cross_architecture_ranks_are_rejected_before_forward_sharing(tmp_path, second_identity): + identities = ((WORKSTATION, (12, 0)), second_identity) + results, artifacts = _run_prepare(tmp_path, identities) + for rank in range(2): + status, detail = results[rank] + assert status == "error" + assert "incompatible CUDA architectures" in detail + assert all(files == [] for files in artifacts.values()) + + +def _stub_inductor_warm(monkeypatch, gpu_name, capability, gathered_variants, gathered_actual): + monkeypatch.setattr(inductor_tuning, "cuda_device_identity", lambda device: (gpu_name, capability)) + monkeypatch.setattr(torch.cuda, "current_stream", lambda device: SimpleNamespace(synchronize=lambda: None)) + selections = inductor_tuning.InductorSelections("cpu") + gather_replies = iter([gathered_variants, [None], [None], [None], gathered_actual]) + recorded_gathers = [] + + def fake_gather(value): + recorded_gathers.append(value) + return next(gather_replies) + + selections._gather = fake_gather + selections._reconcile = lambda bindings: None + callable_bound = type("_Bound", (), {"owner": _Forward("shared"), "__call__": lambda self: None})() + selections.forwards[id(callable_bound)] = (SimpleNamespace(_tuning_frozen=False), None, {}) + return selections, callable_bound, recorded_gathers + + +def test_inductor_warm_accepts_distinct_inventories_for_mixed_sku_same_architecture(monkeypatch): + selections, bound, recorded = _stub_inductor_warm( + monkeypatch, + MAXQ, + (12, 0), + [ + (("shared", MAXQ), ["kernel_maxq"]), + (("shared", WORKSTATION), ["kernel_ws"]), + ], + [{}, {}], + ) + selections.warm(bound, nullcontext) + assert recorded[0] == (("shared", MAXQ), []) + + +def test_inductor_warm_rejects_same_sku_inventory_mismatch(monkeypatch): + selections, bound, recorded = _stub_inductor_warm( + monkeypatch, + MAXQ, + (12, 0), + [ + (("shared", MAXQ), ["kernel_a"]), + (("shared", MAXQ), ["kernel_b"]), + ], + [{}, {}], + ) + with pytest.raises(RuntimeError, match="different Inductor kernels"): + selections.warm(bound, nullcontext) + assert recorded[0] == (("shared", MAXQ), [])