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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions ignition/preparation/aot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
4 changes: 2 additions & 2 deletions ignition/preparation/rank_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
7 changes: 6 additions & 1 deletion ignition/preparation/source_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
11 changes: 8 additions & 3 deletions ignition/preparation/tuning_replicas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand All @@ -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")
Expand All @@ -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)
Expand Down
130 changes: 118 additions & 12 deletions tests/preparation/test_forward_cache_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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})


Expand Down Expand Up @@ -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