From 90b0d315953e453c8438f0129cc5173d01fcb731 Mon Sep 17 00:00:00 2001 From: "Brandon M. Music" <266531604+brandonmmusic-max@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:08:36 -0500 Subject: [PATCH] fix(ignition): expose current_source_roots and propagate source roots to tuning replicas Commit 2acc3f3a (#670) propagated bound external recipe `source_roots` across `mp.get_context("spawn")` in `ignition.preparation.rank_group`, reading private `_EXTRA_ROOTS.get()` directly in `rank_group.py` (matching `aot.py`). Two gaps remain on `main`: 1. `ignition/preparation/aot.py` and `ignition/preparation/rank_group.py` import private `_EXTRA_ROOTS` directly from `source_identity.py` instead of calling a public accessor. 2. `ignition/preparation/tuning_replicas.py` spawns local tuning replicas via `mp.get_context("spawn")` without propagating bound `source_roots`. Although `_replica` currently calls `prepare(..., compile_forwards=False)` and exits on `TuningComplete` without reaching an in-tree `ForwardCache` or `source_identity()` call today, binding `source_roots` in `_replica` gives local spawned tuning workers the same context invariant as `rank_group._peer` if a recipe or future preparation path inspects bound source roots during tuning. Before this change, `aot.py` and `rank_group.py` imported `_EXTRA_ROOTS` directly, `source_identity.py` had no public accessor for the active `ContextVar`, and `tuning_replicas._replica` ran with an empty `source_roots` context. After this change: - `ignition/preparation/source_identity.py` adds `current_source_roots() -> tuple[tuple[str, Path], ...]` returning `_EXTRA_ROOTS.get()`, and updates `source_roots`'s docstring to cover active CLI and spawned worker contexts. - `ignition/preparation/aot.py` and `ignition/preparation/rank_group.py` call `current_source_roots()` so `_EXTRA_ROOTS` stays private to `source_identity.py` (keeping `#670`'s narrow `with bind_source_roots(...)` scope in `rank_group._peer` untouched). - `ignition/preparation/tuning_replicas.py` captures `current_source_roots()` in `prepare_recipe`, passes `extra_source_roots` as a required argument to `_replica`, and binds `with source_roots(extra_source_roots), CoreStorage(...)` around replica preparation. - `tests/preparation/test_forward_cache_sources.py` switches `_record_source_roots_prepare` to `current_source_roots()`, adds `test_current_source_roots_reflects_active_scope`, and adds `test_prepare_recipe_propagates_source_roots_to_spawned_tuning_replica` asserting both `current_source_roots()` and `ForwardCache.root` agreement between replica 0 and spawned replica 1 against the unbound baseline. Claimed result: keeps `_EXTRA_ROOTS` encapsulated behind `current_source_roots()`, brings spawned local tuning replicas to spawn-boundary parity with `rank_group._peer`, and adds real-spawn CPU regression coverage for both helpers. No model core format, Helios ABI, or single-GPU preparation behavior changes are introduced. Validation and limitations (CPU, `CUDA_VISIBLE_DEVICES=""`): - `py_compile` clean across all five modified Python files; `git diff --check` clean; `git grep _EXTRA_ROOTS` confirms zero references outside `ignition/preparation/source_identity.py`. - `pytest -v tests/preparation/test_forward_cache_sources.py tests/preparation/test_forward_cache_concurrency.py tests/preparation/test_forward_cache_root.py tests/preparation/test_core_boundary.py tests/preparation/test_native_processes.py tests/preparation/test_tuning_shards.py tests/cli/test_recipe_injection.py`: 36 passed, 0 failed, 0 skipped. - Limitations: the tuning-replica CPU test stubs `torch.cuda.set_device`, `torch.cuda.synchronize`, and `CoreStorage` while exercising real `multiprocessing.get_context("spawn")` serialization and `source_roots` rebinding; multi-GPU CUDA tuning-replica runs were not executed on CPU. Design-Signed-Off-By: Brandon M. Music; design-review=2e5b Signed-off-by: Brandon M. Music <266531604+brandonmmusic-max@users.noreply.github.com> --- ignition/preparation/aot.py | 4 +- ignition/preparation/rank_group.py | 4 +- ignition/preparation/source_identity.py | 7 +- ignition/preparation/tuning_replicas.py | 11 +- .../preparation/test_forward_cache_sources.py | 130 ++++++++++++++++-- 5 files changed, 136 insertions(+), 20 deletions(-) diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index de4ce78cd..d868578a2 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -842,9 +842,9 @@ def __init__(self, *, namespace, device, root=None, headroom_bytes=0, options=No continue key.update(str(path.relative_to(source)).encode()) key.update(path.read_bytes()) - from .source_identity import _EXTRA_ROOTS + from .source_identity import current_source_roots - for label, extra_root in _EXTRA_ROOTS.get(): + for label, extra_root in current_source_roots(): extra_root = Path(extra_root).resolve() if not extra_root.is_dir(): raise ValueError(f"bound source root {label!r} does not exist: {extra_root}") diff --git a/ignition/preparation/rank_group.py b/ignition/preparation/rank_group.py index 43c8c4084..8b813b168 100644 --- a/ignition/preparation/rank_group.py +++ b/ignition/preparation/rank_group.py @@ -292,9 +292,9 @@ def prepare_group(snapshot, config, prepare, *, progress=None, core_storage=None if dist.is_initialized(): raise RuntimeError("rank preparation requires exclusive ownership of the control group") from .module_images import ModuleImages - from .source_identity import _EXTRA_ROOTS + from .source_identity import current_source_roots - extra_roots = _EXTRA_ROOTS.get() + extra_roots = current_source_roots() recording = core_storage is not None and ModuleImages.current() is not None rendezvous = TemporaryDirectory(prefix="flare-ranks-") address = Path(rendezvous.name, "gloo").as_uri() diff --git a/ignition/preparation/source_identity.py b/ignition/preparation/source_identity.py index 93ebb23fc..3ee9985e2 100644 --- a/ignition/preparation/source_identity.py +++ b/ignition/preparation/source_identity.py @@ -14,9 +14,14 @@ ) +def current_source_roots() -> tuple[tuple[str, Path], ...]: + """Return the bound external `(label, path)` source roots for this context.""" + return _EXTRA_ROOTS.get() + + @contextmanager def source_roots(roots=()): - """Bind external `(label, path)` source roots for the duration of a CLI invocation.""" + """Bind external `(label, path)` source roots for the active CLI or spawned worker context.""" normalized = tuple((str(label), Path(path)) for label, path in roots) token = _EXTRA_ROOTS.set(normalized) try: diff --git a/ignition/preparation/tuning_replicas.py b/ignition/preparation/tuning_replicas.py index a14ed0b67..3433469c0 100644 --- a/ignition/preparation/tuning_replicas.py +++ b/ignition/preparation/tuning_replicas.py @@ -139,7 +139,7 @@ def _resolve_recipe(prepare, recipe_name): return module.RECIPE -def _replica(parent, prepare, recipe_name, snapshot, values, gpu_uuids, options): +def _replica(parent, prepare, recipe_name, snapshot, values, gpu_uuids, options, extra_source_roots): os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(gpu_uuids) from ignition import runtime_patches @@ -150,11 +150,12 @@ def _replica(parent, prepare, recipe_name, snapshot, values, gpu_uuids, options) import torch from ignition.planning import Plan from .core_storage import CoreStorage + from .source_identity import source_roots recipe = _resolve_recipe(prepare, recipe_name) plan = Plan(recipe=recipe, **values) torch.cuda.set_device(0) - with CoreStorage(world=plan.world_size) as storage: + with source_roots(extra_source_roots), CoreStorage(world=plan.world_size) as storage: try: prepare(snapshot, plan, compile_forwards=False, retain_graphs=False, progress=None, core_storage=storage, **options) @@ -170,6 +171,9 @@ def prepare_recipe(prepare, snapshot, plan, **options): return prepare(snapshot, plan, **options) if options.get("ranks") is not None: raise ValueError("local tuning replicas cannot replace multi-host preparation") + from .source_identity import current_source_roots + + extra_source_roots = current_source_roots() replicas = len(plan.tuning_gpus) // plan.world_size processes = [] context = multiprocessing.get_context("spawn") @@ -186,7 +190,8 @@ def prepare_recipe(prepare, snapshot, plan, **options): worker = context.Process(target=_replica, args=(os.getpid(), prepare, plan.recipe.name, snapshot, peer, tuple(gpu.uuid for gpu in gpus), - {"kernel_cache": options.get("kernel_cache")}), name=f"flare-tuning-{replica}") + {"kernel_cache": options.get("kernel_cache")}, + extra_source_roots), name=f"flare-tuning-{replica}") worker.start() processes.append(worker) prepared = prepare(snapshot, root, **options) diff --git a/tests/preparation/test_forward_cache_sources.py b/tests/preparation/test_forward_cache_sources.py index 89325e736..f628d4292 100644 --- a/tests/preparation/test_forward_cache_sources.py +++ b/tests/preparation/test_forward_cache_sources.py @@ -4,13 +4,19 @@ """Forward caches track execution sources independently of terminal presentation.""" -from types import SimpleNamespace +from contextlib import nullcontext +import json +from pathlib import Path +import sys +from types import MappingProxyType, SimpleNamespace import flashinfer import pytest -from ignition.preparation import aot, contract, rank_group -from ignition.preparation.source_identity import _EXTRA_ROOTS, source_roots +from ignition.declaration import Checkpoint, RankCosts, Recipe, RecipeParameters, SamplingDefaults +from ignition.planning import Gpu, Plan +from ignition.preparation import aot, contract, rank_group, tuning_replicas +from ignition.preparation.source_identity import current_source_roots, source_roots class _StubPreparedModel: @@ -26,16 +32,19 @@ def close(self): pass +def _stub_forward_cache_root(): + with pytest.MonkeyPatch.context() as patch: + patch.setattr( + aot.torch.cuda, + "get_device_properties", + lambda device: SimpleNamespace(name="SM120", major=12, minor=0, multi_processor_count=96), + ) + return str(aot.ForwardCache(namespace={"model": "example"}, device="cuda:0").root) + + def _record_source_roots_prepare(snapshot, config, *, rank, group, progress=None): - original_props = aot.torch.cuda.get_device_properties - aot.torch.cuda.get_device_properties = lambda device: SimpleNamespace( - name="SM120", major=12, minor=0, multi_processor_count=96 - ) - try: - cache_root = str(aot.ForwardCache(namespace={"model": "example"}, device="cuda:0").root) - finally: - aot.torch.cuda.get_device_properties = original_props - extra_roots = [(label, str(path)) for label, path in _EXTRA_ROOTS.get()] + cache_root = _stub_forward_cache_root() + extra_roots = [(label, str(path)) for label, path in current_source_roots()] return _StubPreparedModel({"rank": rank, "extra_roots": extra_roots, "cache_root": cache_root}) @@ -137,3 +146,100 @@ def test_frontend_contract_validates_tool_delimiters(): tool_open=bad_open, tool_close=bad_close, ) + + +def test_current_source_roots_reflects_active_scope(tmp_path): + first = tmp_path / "first_recipes" + second = tmp_path / "second_recipes" + assert current_source_roots() == () + with source_roots((("first", str(first)),)): + assert current_source_roots() == (("first", first),) + with source_roots((("second", second),)): + assert current_source_roots() == (("second", second),) + assert current_source_roots() == (("first", first),) + assert current_source_roots() == () + + +def _record_replica_source_roots(snapshot, plan, **options): + payload = { + "extra_roots": [[label, str(path)] for label, path in current_source_roots()], + "cache_root": _stub_forward_cache_root(), + } + out = Path(snapshot) / f"replica-{plan.tuning_replica.index}.json" + out.write_text(json.dumps(payload)) + if plan.tuning_replica.index > 0: + raise tuning_replicas.TuningComplete() + return SimpleNamespace(close=lambda: None) + + +_REPLICA_TEST_RECIPE = Recipe( + name="replica-source-roots-test", + served_model_name="replica-source-roots-test", + checkpoints=( + Checkpoint( + alias="replica-test", + repository="example/replica-test", + revision="ab12cd34" + "0" * 32, + architecture="ReplicaTestForCausalLM", + stored_bytes=1 << 30, + device_bytes=1 << 30, + ), + ), + context=8192, + page_tokens=64, + parameters=RecipeParameters(max_concurrency=1, max_concurrency_limit=4, prefill_chunk=4096), + ranks=MappingProxyType({1: RankCosts(1 << 20, 1 << 16, 1 << 28)}), + plain_ranks=MappingProxyType({}), + prepare=_record_replica_source_roots, + usage=lambda prepared: (), + sampling_defaults=SamplingDefaults(temperature=1.0, top_p=1.0, top_k=-1), +) + + +def _cpu_replica_entry(*args): + import torch + from ignition.preparation import core_storage + + with pytest.MonkeyPatch.context() as patch: + patch.setattr(torch.cuda, "set_device", lambda _: None) + patch.setattr(torch.cuda, "synchronize", lambda: None) + patch.setattr(core_storage, "CoreStorage", lambda **kwargs: nullcontext()) + tuning_replicas._replica(*args) + + +@pytest.mark.skipif(sys.platform != "linux", reason="tuning replica supervision requires Linux pidfds") +def test_prepare_recipe_propagates_source_roots_to_spawned_tuning_replica(tmp_path, monkeypatch): + pytest.importorskip("flare_heliopause") + external = tmp_path / "external_recipes" + external.mkdir() + (external / "recipe.py").write_text("recipe = 1\n") + baseline_root = _stub_forward_cache_root() + + gpus = ( + Gpu(0, "Test GPU", "GPU-0000", 16 << 30, 15 << 30, (12, 0)), + Gpu(1, "Test GPU", "GPU-0001", 16 << 30, 15 << 30, (12, 0)), + ) + plan = Plan( + recipe=_REPLICA_TEST_RECIPE, + checkpoint=_REPLICA_TEST_RECIPE.checkpoints[0], + gpus=(gpus[0],), + parameters=_REPLICA_TEST_RECIPE.parameters, + cache_target=8192, + cache_states=8, + pages=128, + weights_bytes=1 << 30, + graph_bytes=1 << 28, + tuning_gpus=gpus, + ) + monkeypatch.setattr(tuning_replicas, "_replica", _cpu_replica_entry) + + with source_roots((("external_recipes", external),)): + prepared = tuning_replicas.prepare_recipe(_record_replica_source_roots, tmp_path, plan) + prepared.close() + + replica0 = json.loads((tmp_path / "replica-0.json").read_text()) + replica1 = json.loads((tmp_path / "replica-1.json").read_text()) + assert replica0["extra_roots"] == [["external_recipes", str(external)]] + assert replica1["extra_roots"] == replica0["extra_roots"] + assert replica1["cache_root"] == replica0["cache_root"] + assert replica1["cache_root"] != baseline_root