From 27fd8d7f1dcd05cc4dd785550899cd2433a6b2b1 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 05:54:12 +0800 Subject: [PATCH] HF export staging is private to each island process; tests keep out of ~/yeto-output The verl and Miles island exports staged in one fixed directory under the system temp dir (yeto-hf-export/round-). Two island processes on one host exporting the same round shared it: one export's cleanup ran inside the other's write, and an island's store could get the other island's weights. Each process now stages in its own mkdtemp directory; each Megatron island driver names its own staging directory for its ranks. Tests: the launcher-built syncer commands get a tmp_path --dispense-log, the island entry parse writes its event tape under tmp_path, and the home guard also refuses in-process writes to the real ~/yeto-output and local child processes whose command line names it. Co-Authored-By: Claude Opus 5.5 --- tests/conftest.py | 13 ++- tests/test_prod_defaults_argv.py | 15 ++- tests/test_rl_algorithm_provenance.py | 3 + tests/test_rl_dense_sweep_real_syncer.py | 4 +- tests/test_rl_hetero_sim_e2e.py | 4 +- tests/test_rl_hf_export.py | 10 +- tests/test_rl_k31_synced_cpu.py | 4 +- tests/test_rl_split_parameter_layout.py | 4 +- tests/test_rl_sync_route_launch.py | 4 +- ...test_rl_syncer_kill_resume_live_learner.py | 4 +- tests/test_rl_verl_megatron.py | 10 +- tests/test_verl_decoupled.py | 4 +- tests/test_verl_full_parameter_launch.py | 4 +- tests/test_verl_full_parameter_sync.py | 4 +- tests/test_verl_miles_parity.py | 66 ++++++++++- tests/test_yeto_home_guard.py | 47 ++++++++ tests/yeto_home_guard.py | 108 ++++++++++++++++-- yeto/rl/adapters/miles/entry.py | 8 +- yeto/rl/adapters/verl/hf_export.py | 8 +- yeto/rl/adapters/verl/megatron_ports.py | 10 +- yeto/rl/engine/hf_export.py | 15 +++ 21 files changed, 299 insertions(+), 50 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 2963825d8..f81b42fae 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -171,23 +171,24 @@ def pytest_runtest_protocol(self, item, nextitem): def _report_yeto_home(session) -> None: - """End of the outermost session: a refused write to the real ~/.yeto fails it; an entry - there that is new or changed since the start (a child process, or another process on - this machine) is a warning.""" + """End of the outermost session: a refused write to the real ~/.yeto or ~/yeto-output + (in this process, or a child named it) fails it; an entry there that is new or changed + since the start (a child process, or another process on this machine) is a warning.""" errors, warnings = _home_guard.session_report() tr = session.config.pluginmanager.get_plugin("terminalreporter") write = (lambda line: tr.write_line(line)) if tr is not None else print if tr is not None and (errors or warnings): tr.ensure_newline() if warnings: - write(f"WARNING real ~/.yeto changed during the session ({len(warnings)} entries; not from this " - "process: a child process, or another run / test session on this machine):") + write(f"WARNING real ~/.yeto or ~/yeto-output changed during the session ({len(warnings)} entries; " + "not from this process: a child process, or another run / test session on this machine):") for line in warnings[:_home_guard.WARN_LIST_MAX]: write(f" {line}") if len(warnings) > _home_guard.WARN_LIST_MAX: write(f" ... {len(warnings) - _home_guard.WARN_LIST_MAX} more") if errors: - write(f"ERROR tests tried to write the real ~/.yeto ({len(errors)} refused; tests/yeto_home_guard.py):") + write(f"ERROR tests tried to write the real ~/.yeto or ~/yeto-output ({len(errors)} refused; " + "tests/yeto_home_guard.py):") for line in errors[:_home_guard.WARN_LIST_MAX]: write(f" {line}") if len(errors) > _home_guard.WARN_LIST_MAX: diff --git a/tests/test_prod_defaults_argv.py b/tests/test_prod_defaults_argv.py index c3521afa0..ac74fac48 100644 --- a/tests/test_prod_defaults_argv.py +++ b/tests/test_prod_defaults_argv.py @@ -159,9 +159,10 @@ def _entry_argv(run: str, env: dict, module: str = MILES_ENTRY) -> list[str]: return [env.get(t[1:], t) if t.startswith("$") and t[1:].isidentifier() else t for t in tokens] -def _island_parses(run: str, env: dict, monkeypatch, capsys) -> types.SimpleNamespace: +def _island_parses(run: str, env: dict, monkeypatch, capsys, tmp_path) -> types.SimpleNamespace: """The island's parser and its compat group, with only ``env`` of what this process - has from conftest (the island runs elsewhere).""" + has from conftest (the island runs elsewhere). Its event tape (``~/yeto-output`` of + the island's node) is written under ``tmp_path``, not this host's home.""" from yeto.hw.catalog import COMPAT_GROUP_ENV from yeto.rl.adapters.miles import island_entry @@ -174,6 +175,8 @@ def _island_parses(run: str, env: dict, monkeypatch, capsys) -> types.SimpleName args = island_entry.parse_args(argv) except SystemExit as stop: raise AssertionError(f"the island entry refused its argv: {capsys.readouterr().err[-2000:]}") from stop + if getattr(args, "event_tape", None): + args.event_tape = str(tmp_path / Path(args.event_tape).name) group = island_entry._island_compat_group(args) return types.SimpleNamespace(args=args, group=group, argv=argv) @@ -199,7 +202,7 @@ def test_the_customer_modal_island_entry_parses_with_only_its_own_environment(tm spec, task = _island_task(args) assert spec.cloud == "modal" cfg = build_modal_island_config(args, spec, 0, task, "10.0.0.1:29400") - island = _island_parses(cfg.run_script, {**cfg.envs, "LEARNER_ID": "0"}, monkeypatch, capsys) + island = _island_parses(cfg.run_script, {**cfg.envs, "LEARNER_ID": "0"}, monkeypatch, capsys, tmp_path) assert island.group == "nvidia-b300" assert island.args.rl_single_island_no_sync and island.args.inner_lr == float(args.inner_lr) @@ -218,7 +221,7 @@ def test_the_customer_ssh_island_entry_parses_with_only_the_node_environment(cas env = sti.node_env(ssh_spec, 0, {}) script = sti.start_script(ssh_spec, 0, env, sti.remote_paths("r", "island-0", 0), container="c0") assert "export YETO_RL_COMPAT_GROUP=nvidia-b300" in script # the node's job gets it - island = _island_parses(ssh_spec.run_script, {**env, "LEARNER_ID": "0"}, monkeypatch, capsys) + island = _island_parses(ssh_spec.run_script, {**env, "LEARNER_ID": "0"}, monkeypatch, capsys, tmp_path) assert island.group == "nvidia-b300" @@ -343,7 +346,7 @@ def test_each_fleet_island_launch_passes_with_production_defaults(example, tmp_p spec, task = _island_task(args) modal = build_modal_island_config(args, spec, 0, task, "10.0.0.1:29400") parsed = _island_parses(modal.run_script, {**modal.envs, "LEARNER_ID": str(island.learner)}, - monkeypatch, capsys) + monkeypatch, capsys, tmp_path) assert int(parsed.args.learner_id) == island.learner assert parsed.group == "nvidia-h100" assert asked["hub"] @@ -368,7 +371,7 @@ def test_a_sky_island_entry_parses_with_only_the_task_environment(tmp_path, monk assert spec.cloud == "aws" envs = {**task.envs, **{k: str(v) for k, v in (getattr(task, "secrets", None) or {}).items()}} parsed = _island_parses(task.run, {**envs, "LEARNER_ID": "0", "SYNCER_ADDR": "10.0.0.1:29400"}, - monkeypatch, capsys) + monkeypatch, capsys, tmp_path) assert parsed.group == "nvidia-h100" diff --git a/tests/test_rl_algorithm_provenance.py b/tests/test_rl_algorithm_provenance.py index 315da9655..231687bee 100644 --- a/tests/test_rl_algorithm_provenance.py +++ b/tests/test_rl_algorithm_provenance.py @@ -928,6 +928,9 @@ def test_modal_two_islands_with_syncer_rebuild_tapes_and_fail_closed(monkeypatch from yeto.rl import event_echo monkeypatch.setattr(runs, "RUNS_DIR", tmp_path / "runs") + # the teardown copies the dispenser log of a syncer on this machine (~/yeto-output): + # this run's machine is the test's own home, not the developer's + monkeypatch.setenv("HOME", str(tmp_path / "home")) def island_log(island, finalized): lines = ["[x] startup noise"] diff --git a/tests/test_rl_dense_sweep_real_syncer.py b/tests/test_rl_dense_sweep_real_syncer.py index 007998c89..9d4f02b0b 100644 --- a/tests/test_rl_dense_sweep_real_syncer.py +++ b/tests/test_rl_dense_sweep_real_syncer.py @@ -22,6 +22,7 @@ from free_ports import free_port from process_groups import group_popen, kill_group from test_rl_algorithm_provenance import _fake_sky, _launcher_args, _no_modal_listing # noqa: F401 +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.fragments import MERGE_RDA, Fragment, FragmentLayout from yeto.protocol import ( DTYPE_F32, @@ -74,7 +75,8 @@ def _start_syncer(binary: Path, tmp_path: Path, *extra: str, command = (command .replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) assert "--policy-sweep-fragments 2" in command and "--require-profile-binding" in command process = group_popen(["bash", "-c", command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) diff --git a/tests/test_rl_hetero_sim_e2e.py b/tests/test_rl_hetero_sim_e2e.py index 72535b237..8e4f4e4e0 100644 --- a/tests/test_rl_hetero_sim_e2e.py +++ b/tests/test_rl_hetero_sim_e2e.py @@ -22,6 +22,7 @@ from process_groups import group_popen, kill_group from test_rl_algorithm_provenance import _fake_sky, _no_modal_listing # noqa: F401 from test_rl_algorithm_provenance import _launcher_args as _provenance_launcher_args +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.rl.adapters.miles import buffer_rollout as br from yeto.rl.adapters.sampler_engines.fake import (FAKE_IDENTITY, FakeEngine, _unit, fake_identity, fake_sampler_fleet) @@ -133,7 +134,8 @@ def _start_decoupled_syncer(binary, workdir, islands, total_steps, *options): port = free_port() command = (command.replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(workdir / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(workdir / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(workdir / "tape.jsonl")) + .replace(DISPENSE_LOG, str(workdir / "task-dispense.jsonl"))) log = (workdir / "syncer.log").open("w") process = group_popen(["bash", "-c", command], stdout=log, stderr=subprocess.STDOUT, text=True) return process, port, layout, command diff --git a/tests/test_rl_hf_export.py b/tests/test_rl_hf_export.py index b28a4ebbd..5dfcfad67 100644 --- a/tests/test_rl_hf_export.py +++ b/tests/test_rl_hf_export.py @@ -332,7 +332,9 @@ def write(rollout_id, directory): # ---------------------------------------------------------------- Miles wiring -def test_miles_island_writes_with_every_rank_on_one_node_else_rank0(tmp_path): +def test_miles_island_writes_with_every_rank_on_one_node_else_rank0(tmp_path, monkeypatch): + import tempfile + from yeto.rl.adapters.miles.entry import hf_exports_for from yeto.rl.adapters.miles.release_plugin import WRITE_FULL_CHECKPOINT @@ -341,6 +343,9 @@ def test_miles_island_writes_with_every_rank_on_one_node_else_rank0(tmp_path): export_hf=lambda rollout_id, path: calls.append(("export_hf", rollout_id, path))) runner = SimpleNamespace(run=lambda value: value) config = {"rounds": "2,final", "store": str(tmp_path / "hf")} + system_tmp = tmp_path / "system-tmp" + system_tmp.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(system_tmp)) assert hf_exports_for(SimpleNamespace(), actor_model=actor, runner=runner) is None exports = hf_exports_for(SimpleNamespace(yeto_rl_hf_exports=config, actor_num_nodes=1, lora_rank=0), actor_model=actor, runner=runner, environ={}) @@ -352,6 +357,9 @@ def test_miles_island_writes_with_every_rank_on_one_node_else_rank0(tmp_path): actor_model=actor, runner=runner, environ={}) across.write(1, tmp_path / "d") assert calls == [("export_hf", 1, str(tmp_path / "d"))] + # each island process stages in a directory of its own under the system temp dir + assert exports.staging != across.staging and {exports.staging.parent, across.staging.parent} == {system_tmp} + assert exports.staging.name.startswith("yeto-hf-export-") and exports.staging.is_dir() with pytest.raises(ValueError, match="full weights"): hf_exports_for(SimpleNamespace(yeto_rl_hf_exports=config, lora_rank=8), actor_model=actor, runner=runner) diff --git a/tests/test_rl_k31_synced_cpu.py b/tests/test_rl_k31_synced_cpu.py index e6aa9fee7..937f6a46e 100644 --- a/tests/test_rl_k31_synced_cpu.py +++ b/tests/test_rl_k31_synced_cpu.py @@ -43,6 +43,7 @@ from process_groups import group_popen, kill_group from test_rl_algorithm_provenance import _fake_sky, _launcher_args, _no_modal_listing # noqa: F401 from test_rl_k31_e2e_cpu import EP, MOE_LAYERS, NUM_EXPERTS, NUM_TRAINABLE, Bucket, _hf_config +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.rl.adapters.miles import island_entry, pins from yeto.rl.adapters.miles.models.kimi_k31 import release as k31_release from yeto.rl.adapters.miles.models.partial_experts import selection as sel @@ -500,7 +501,8 @@ def _start_syncer(binary: Path, tmp_path: Path, learners: int): port = free_port() command = (command.replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) assert f"--learners {learners} --quorum 1" in command and "--outer-lr 1.0 --outer-momentum 0.0" in command log_file = tmp_path / "syncer.log" with log_file.open("w") as out: diff --git a/tests/test_rl_split_parameter_layout.py b/tests/test_rl_split_parameter_layout.py index 90d920c6a..e6b8325ad 100644 --- a/tests/test_rl_split_parameter_layout.py +++ b/tests/test_rl_split_parameter_layout.py @@ -42,6 +42,7 @@ ) from test_rl_algorithm_provenance import _fake_sky, _launcher_args, _no_modal_listing # noqa: F401 +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.fragments import MERGE_AVG, MERGE_RDA from yeto.protocol import DTYPE_F32, DTYPE_F32_PUSH_I8, DTYPE_FLAG_TENSOR_BLOCKS, SyncerClient from yeto.rl.adapters.miles.models.chunked_full_parameter import ( @@ -233,7 +234,8 @@ def _start_syncer(binary: Path, tmp_path: Path, fragments: int, *extra: str): command = (command .replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) process = group_popen(["bash", "-c", command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) return process, port, launcher.rl_syncer_profile(args, LEARNERS).sha256 diff --git a/tests/test_rl_sync_route_launch.py b/tests/test_rl_sync_route_launch.py index d1fd7f9c0..ef849c8fa 100644 --- a/tests/test_rl_sync_route_launch.py +++ b/tests/test_rl_sync_route_launch.py @@ -35,6 +35,7 @@ syncer_binary, # noqa: F401 ) from test_rl_k31_synced_cpu import STORE, _island_hmac_key, _selection, _tis_spec # noqa: F401 +from yeto.launch.dispense_evidence import DISPENSE_LOG LAYOUT = "e" * 64 TWO = "modal:2xh100,modal:2xh100" @@ -213,7 +214,8 @@ def _routed_syncer(binary, tmp_path, *, total_steps: int): port = free_port() command = (command.replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) log = tmp_path / "syncer.log" with log.open("w") as out: process = group_popen(["bash", "-c", command], stdout=out, stderr=subprocess.STDOUT, text=True) diff --git a/tests/test_rl_syncer_kill_resume_live_learner.py b/tests/test_rl_syncer_kill_resume_live_learner.py index adacfb264..e078f7ee0 100644 --- a/tests/test_rl_syncer_kill_resume_live_learner.py +++ b/tests/test_rl_syncer_kill_resume_live_learner.py @@ -26,6 +26,7 @@ SHAPES, _layout, _plan, _run_island, needs_cargo, syncer_binary, ) from test_rl_algorithm_provenance import _launcher_args +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.final_marker import read_checkpoint_global_step from yeto.rl.engine.full_parameter_stream import LAZY_CAPTURE_ENV @@ -49,7 +50,8 @@ def _syncer_command(binary, tmp_path, *, fragments: int, rounds: int, port: int) command = launcher.role_syncer_commands(args, 2, binary=str(binary))["actor"] command = (command.replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) assert "--resume" in command and "--checkpoint-every 1" in command return command, launcher.rl_syncer_profile(args, 2).sha256 diff --git a/tests/test_rl_verl_megatron.py b/tests/test_rl_verl_megatron.py index 43ca3dbf2..a597961e9 100644 --- a/tests/test_rl_verl_megatron.py +++ b/tests/test_rl_verl_megatron.py @@ -715,7 +715,11 @@ def save_hf_weights(self, module, path): worker = SimpleNamespace(actor=SimpleNamespace(engine=SimpleNamespace(module=[object()], bridge=_Bridge()))) store = tmp_path / "store" - config = {"rounds": "1,final", "store": str(store)} + # the driver names the island's staging directory; every rank gets the name + drivers = [mp.MegatronHfExports(SimpleNamespace(), {"rounds": "1,final", "store": str(store)}) for _ in range(2)] + names = [driver.config["staging"] for driver in drivers] + assert names[0] != names[1] and all(name.startswith(f"{mp.HF_STAGING}-") for name in names) + config = drivers[0].config record = mp.remote_hf_export(worker, config, 0, 1, True, str(model)) assert record["ok"] and record["round"] == 1 and record["files"] == 3, record out = store / "round-1" @@ -723,13 +727,13 @@ def save_hf_weights(self, module, path): assert (out / "model-00001-of-00001.safetensors").read_bytes() == b"w" * 8 assert not (out / "model-00001-of-00013.safetensors").exists() assert json.loads((store / "final.json").read_text())["path"] == "round-1" - assert not (staging_root / mp.HF_STAGING / "round-1").exists() # the staging copy is deleted + assert (staging_root / names[0]).is_dir() and not (staging_root / names[0] / "round-1").exists() # deleted monkeypatch.setattr(torch.distributed, "is_initialized", lambda: True) monkeypatch.setattr(torch.distributed, "get_rank", lambda: 3) monkeypatch.setattr(torch.distributed, "barrier", lambda: None) assert mp.remote_hf_export(worker, config, 1, 2, False, str(model)) is None - joined = staging_root / mp.HF_STAGING / "round-2" + joined = staging_root / names[0] / "round-2" assert (joined / "model-00001-of-00001.safetensors").is_file() assert not (joined / ".complete").exists() and not (joined / "config.json").exists() diff --git a/tests/test_verl_decoupled.py b/tests/test_verl_decoupled.py index 09e1db915..d81b63bf4 100644 --- a/tests/test_verl_decoupled.py +++ b/tests/test_verl_decoupled.py @@ -25,6 +25,7 @@ from test_rl_algorithm_provenance import _fake_sky, _launcher_args, _no_modal_listing # noqa: F401 from test_verl_full_parameter_sync import needs_cargo, syncer_binary # noqa: F401 - fixture from verl_island_fakes import ISLAND_ARGV, drive_trainer, modules, run_island_entry, stub_verl_and_ray +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.rl.adapters.verl import decoupled_session as ds from yeto.rl.adapters.verl import island_entry from yeto.rl.adapters.verl.publish import lora_checksum @@ -296,7 +297,8 @@ def test_two_launcher_built_verl_islands_run_decoupled_fragments_through_the_rea command = (launcher.role_syncer_commands(args, 2, binary=str(syncer_binary))["actor"] .replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) plans = [] for learner_id in range(2): parsed, _ignored = island_entry.parse_args(_island_argv(args, learner_id, f"127.0.0.1:{port}")) diff --git a/tests/test_verl_full_parameter_launch.py b/tests/test_verl_full_parameter_launch.py index e6ccbf8ea..20b2c5fa2 100644 --- a/tests/test_verl_full_parameter_launch.py +++ b/tests/test_verl_full_parameter_launch.py @@ -24,6 +24,7 @@ from test_verl_full_parameter_sync import ( # noqa: F401 - syncer_binary is a fixture MAX_FRAGMENT_BYTES, SHAPES, _run_dict, _run_island, needs_cargo, syncer_binary, ) +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.rl.adapters.verl import full_parameter as fp from yeto.rl.adapters.verl import full_parameter_stream as vfs from yeto.rl.adapters.verl import island_entry @@ -226,7 +227,8 @@ def test_two_launcher_built_verl_islands_run_async_rounds_through_the_real_synce command = (launcher.role_syncer_commands(args, 2, binary=str(syncer_binary))["actor"] .replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) assert "--final-cut-payload manifest" in command and "--quorum 1" in command plans = [] for learner_id in range(2): diff --git a/tests/test_verl_full_parameter_sync.py b/tests/test_verl_full_parameter_sync.py index c370857a7..fa60aa340 100644 --- a/tests/test_verl_full_parameter_sync.py +++ b/tests/test_verl_full_parameter_sync.py @@ -25,6 +25,7 @@ from free_ports import free_port from process_groups import group_popen, kill_group from test_rl_algorithm_provenance import _fake_sky, _launcher_args, _no_modal_listing # noqa: F401 +from yeto.launch.dispense_evidence import DISPENSE_LOG from yeto.protocol import MSG_BCAST_FRAGMENT from yeto.rl.adapters.verl import full_parameter as fp from yeto.rl.adapters.verl import full_parameter_stream as vfs @@ -377,7 +378,8 @@ def _start_syncer(binary: Path, tmp_path: Path, *, fragments: int, rounds: int, port = free_port() command = (command.replace(f"--port {launcher.SYNCER_PORT}", f"--port {port}") .replace(launcher.RL_SYNCER_CHECKPOINT, str(tmp_path / "state.ckpt")) - .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl"))) + .replace(launcher.RL_SYNCER_EVENT_TAPE, str(tmp_path / "tape.jsonl")) + .replace(DISPENSE_LOG, str(tmp_path / "task-dispense.jsonl"))) process = group_popen(["bash", "-c", command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) return process, port, launcher.rl_syncer_profile(args, 2).sha256 diff --git a/tests/test_verl_miles_parity.py b/tests/test_verl_miles_parity.py index 8c72560c6..7adcca87a 100644 --- a/tests/test_verl_miles_parity.py +++ b/tests/test_verl_miles_parity.py @@ -21,6 +21,7 @@ import json import socket import subprocess +import tempfile import threading import time from pathlib import Path @@ -322,7 +323,16 @@ def test_the_writer_exports_every_parameter_in_the_model_dtype(tmp_path, model_d assert (out / "model.safetensors").exists() is False -def test_one_file_when_the_model_fits_and_the_round_lands_in_the_store(tmp_path, model_dir): +@pytest.fixture +def system_tmp(tmp_path, monkeypatch): + """The system temp dir of this test (the exports stage under it), not the host's.""" + root = tmp_path / "system-tmp" + root.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(root)) + return root + + +def test_one_file_when_the_model_fits_and_the_round_lands_in_the_store(tmp_path, model_dir, system_tmp): from safetensors.torch import load_file from yeto.rl.adapters.verl.hf_export import hf_round_exports @@ -332,6 +342,7 @@ def test_one_file_when_the_model_fits_and_the_round_lands_in_the_store(tmp_path, store = tmp_path / "store" / "hf" / "island0" exports = hf_round_exports({"rounds": "final", "store": str(store)}, group=group, model_path=model_dir, run=vfs._LoopRunner().run, environ={}) + assert exports.staging.parent == system_tmp and exports.staging.name.startswith("yeto-hf-export-") assert exports.due(5, final=True) and not exports.due(5, final=False) record = exports.export(5, policy_version=6, final=True) assert record["ok"] and record["round"] == 6, record @@ -339,6 +350,59 @@ def test_one_file_when_the_model_fits_and_the_round_lands_in_the_store(tmp_path, assert (landed / ".complete").is_file() and not (landed / INDEX_FILE).exists() assert sorted(load_file(str(landed / "model.safetensors"))) == sorted(SHAPES) assert json.loads((store / "final.json").read_text())["round"] == 6 + assert list(exports.staging.iterdir()) == [] # the staging copy is deleted + + +class _MeetingGroup: + """An island's group whose first parameter export waits until the other island's + export got there too: both write the same round at the same time.""" + + def __init__(self, group, barrier): + self._group, self._barrier, self._met = group, barrier, False + + def export_parameters(self, names): + if not self._met: + self._met = True + self._barrier.wait(timeout=30) + return self._group.export_parameters(names) + + def __getattr__(self, name): + return getattr(self._group, name) + + +def test_two_islands_on_one_host_export_the_same_round_at_the_same_time(tmp_path, model_dir, system_tmp): + """Two island processes on one host (or two test sessions) share the system temp dir. + Each stages in its own directory, so neither export removes the other's files while + it writes them.""" + from safetensors.torch import load_file + + from yeto.rl.adapters.verl.hf_export import hf_round_exports + + barrier = threading.Barrier(2) + models = [_Model(seed=5), _Model(seed=6)] + exports = [hf_round_exports({"rounds": "final", "store": str(tmp_path / "store" / "hf" / f"island{i}")}, + group=_MeetingGroup(vfs.VerlFullParameterGroup(_Island(model)), barrier), + model_path=model_dir, run=vfs._LoopRunner().run, environ={}) + for i, model in enumerate(models)] + records = [None, None] + + def export(i): + records[i] = exports[i].export(5, policy_version=6, final=True) + + threads = [threading.Thread(target=export, args=(i,)) for i in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=60) + assert not barrier.broken and [t.is_alive() for t in threads] == [False, False] + for i, model in enumerate(models): + assert records[i]["ok"], records[i] + landed = tmp_path / "store" / "hf" / f"island{i}" / "round-6" + loaded = load_file(str(landed / "model.safetensors")) + for name, value in model.values().items(): + assert torch.equal(loaded[name], value.to(torch.bfloat16)), (i, name) + assert list(exports[i].staging.iterdir()) == [] + assert exports[0].staging != exports[1].staging and {e.staging.parent for e in exports} == {system_tmp} def test_the_export_dtype_follows_the_config(tmp_path): diff --git a/tests/test_yeto_home_guard.py b/tests/test_yeto_home_guard.py index a4ecaae84..8869730dc 100644 --- a/tests/test_yeto_home_guard.py +++ b/tests/test_yeto_home_guard.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import sys from pathlib import Path import pytest @@ -35,3 +36,49 @@ def test_a_write_under_the_real_root_is_refused_and_recorded(tmp_path, monkeypat assert (real / "runs").is_dir() and not list((real / "runs").iterdir()) assert [event for _test, event, _path in guard._state["violations"]] == ["os.mkdir", "open"] assert (tmp_path / "elsewhere.json").write_text("{}") == 2 # outside the root: untouched + + +def test_the_real_yeto_output_is_guarded_in_this_process(tmp_path, monkeypatch): + output = tmp_path / "home" / guard.OUTPUT_DIR + output.mkdir(parents=True) + monkeypatch.setitem(guard._state, "guarded", (str(tmp_path / "home" / ".yeto"), str(output))) + monkeypatch.setitem(guard._state, "violations", []) + with pytest.raises(PermissionError, match="real ~/yeto-output"): + (output / "rl-island-0.jsonl").write_text("{}") + assert [event for _test, event, _path in guard._state["violations"]] == ["open"] + homes = {os.environ.get("HOME") or "", guard.pwd.getpwuid(os.getuid()).pw_dir} - {""} + assert {os.path.join(os.path.abspath(home), guard.OUTPUT_DIR) for home in homes} <= set(guard._real_roots()) + + +def test_a_child_that_names_the_real_yeto_output_is_refused(tmp_path, monkeypatch): + import subprocess + + home = tmp_path / "home" + output = home / guard.OUTPUT_DIR + monkeypatch.setitem(guard._state, "guarded", (str(home / ".yeto"), str(output))) + monkeypatch.setitem(guard._state, "violations", []) + monkeypatch.setenv("HOME", str(home)) + command = "yeto-syncer --dispense --dispense-log ~/yeto-output/task-dispense.jsonl" + with pytest.raises(PermissionError, match="real ~/yeto-output"): + subprocess.run(["bash", "-c", f"echo {command}"], check=True) + with pytest.raises(PermissionError): + subprocess.Popen([sys.executable, "-c", "pass", f"--event-tape={output}/rl-island-0.jsonl"]) + with pytest.raises(PermissionError): + subprocess.run("echo $HOME/yeto-output/x ${HOME}/yeto-output/y", shell=True, check=True) + assert [event for _test, event, _path in guard._state["violations"]] == ["subprocess"] * 3 + assert not output.exists() + # paths of another home, or under tmp_path, are the test's own + elsewhere = {**os.environ, "HOME": str(tmp_path / "node-home")} + subprocess.run(["bash", "-c", f"echo {command}"], env=elsewhere, check=True, capture_output=True) + subprocess.run(["echo", str(tmp_path / guard.OUTPUT_DIR), "~/yeto-outputs", "node:yeto-output/"], + check=True, capture_output=True) + # another machine's ~/yeto-output: an rsync or ssh argument, or a remote spec in a shell line + subprocess.run(["true", "node:~/yeto-output/task-dispense.jsonl"], check=True) + subprocess.run(["bash", "-c", "true node:~/yeto-output/rl-island-0.jsonl"], check=True) + ssh = tmp_path / "ssh" # runs its command line on the node, not here + ssh.write_text("#!/bin/sh\nexit 0\n") + ssh.chmod(0o755) + subprocess.run([str(ssh), "node", "mkdir -p ~/yeto-output && cat ~/yeto-output/yeto-tape.jsonl"], check=True) + assert len(guard._state["violations"]) == 3 + with pytest.raises(PermissionError): # past a wrapper, the shell still runs it here + subprocess.run(["timeout", "60", "bash", "-c", f"echo {command}"], check=True) diff --git a/tests/yeto_home_guard.py b/tests/yeto_home_guard.py index c4c3f61a2..cabeefde3 100644 --- a/tests/yeto_home_guard.py +++ b/tests/yeto_home_guard.py @@ -1,4 +1,4 @@ -"""Keep the test session out of the developer's real ``~/.yeto``. +"""Keep the test session out of the developer's real ``~/.yeto`` and ``~/yeto-output``. The run registry, the resource and cost ledgers, the ``run up`` state, the NC pool state and the ssh control sockets all live under ``~/.yeto``, and most of them are @@ -11,13 +11,20 @@ reads. HOME itself is left alone: the syncer tests build with the caller's own rustup/cargo (tests/syncer_build.py). -:func:`install_guard` then watches the real ``~/.yeto`` two ways: +:func:`install_guard` then watches the real ``~/.yeto`` and ``~/yeto-output`` (where +the launcher's commands put a node's syncer tape, checkpoint and dispenser log, and an +island its event tape: ``~`` is the node's home) three ways: * in this process, an audit hook refuses (``PermissionError``) every write, create, - rename or delete under it and records the test that tried; any such attempt fails + rename or delete under them and records the test that tried; any such attempt fails the session (:func:`session_report`), also when the code under test swallowed the error; -* for child processes, a snapshot of every entry's mtime and size at the start is +* a child process (``subprocess.Popen``) whose command line names the real + ``~/yeto-output`` (its absolute path, or ``~/``, ``$HOME/`` or ``${HOME}/`` with the + child's ``HOME`` the real one) is refused the same way: a launcher-built syncer + command whose ``--dispense-log`` a test did not point at ``tmp_path`` appended to the + host's ``~/yeto-output/task-dispense.jsonl`` in every session; +* for other child processes, a snapshot of every entry's mtime and size at the start is compared at the end. New or changed entries are reported as a warning only: another process on this machine (a real run, another checkout's test session) may have written them. @@ -27,7 +34,9 @@ import os import pwd +import re import shutil +import subprocess import sys import tempfile from pathlib import Path @@ -55,6 +64,12 @@ "os.utime", "os.chmod", "os.symlink", "os.link", "shutil.rmtree"}) _WRITE_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND WARN_LIST_MAX = 30 +OUTPUT_DIR = "yeto-output" # a node's ~/yeto-output (yeto.launch.syncer, rl_island_task) +# ~/yeto-output in a command line, as the child's shell resolves it (a word of its own or +# an option's value; ``node:~/yeto-output`` is another machine's) +_HOME_OUTPUT = re.compile(r"(?:^|(?<=[\s='\"]))(?:~|\$HOME|\$\{HOME\})/" + OUTPUT_DIR + r"(?![\w.-])") +# the children that run a command line on this machine: a shell, Python, the syncer +_LOCAL_RUNNERS = re.compile(r"^(?:ba|z|da|k)?sh$|^python[\d.]*$|^yeto-syncer") _state: dict = {"root": None, "owned": False, "guarded": (), "snapshot": {}, "violations": [], "test": "", "installed": False} @@ -84,13 +99,21 @@ def _real_roots() -> tuple[str, ...]: homes = {os.environ.get("HOME") or "", pwd.getpwuid(os.getuid()).pw_dir} roots = [] for home in sorted(h for h in homes if h): - root = os.path.join(os.path.abspath(home), ".yeto") - if _state["root"] is not None and os.path.abspath(str(_state["root"])).startswith(root + os.sep): - continue # an isolated root under it (TMPDIR in HOME) is ours to write - roots.append(root) + for name in (".yeto", OUTPUT_DIR): + root = os.path.join(os.path.abspath(home), name) + if _state["root"] is not None and os.path.abspath(str(_state["root"])).startswith(root + os.sep): + continue # an isolated root under it (TMPDIR in HOME) is ours to write + roots.append(root) return tuple(roots) +def _label(path: str) -> str: + for root in _state["guarded"]: + if path == root or path.startswith(root + os.sep): + return f"~/{os.path.basename(root)}" + return "~/.yeto" + + def _snapshot(roots) -> dict[str, tuple[int, int]]: snap: dict[str, tuple[int, int]] = {} for root in roots: @@ -140,18 +163,83 @@ def _audit(event: str, args: tuple) -> None: if event == "os.mkdir" and os.path.isdir(path): continue # mkdir(exist_ok=True) of what is there writes nothing _state["violations"].append((_state["test"], event, path)) - raise PermissionError(f"test isolation: {event} under the real ~/.yeto refused: {path} " + raise PermissionError(f"test isolation: {event} under the real {_label(path)} refused: {path} " f"(tests/yeto_home_guard.py; point the path at tmp_path or its env override)") +_WRAPPERS = {"timeout", "env", "nice", "stdbuf", "setsid", "exec"} + + +def _program(words: list[str]) -> str: + """The program a command line runs, past ``timeout 60``, ``env A=1`` and the like.""" + for word in words: + name = os.path.basename(word) + if name in _WRAPPERS or word.startswith("-") or "=" in word or word.replace(".", "").isdigit(): + continue + return name + return "" + + +def child_output(args, env, *, shell: bool = False) -> str | None: + """The real ~/yeto-output that a child's command line names (``args``, ``env`` and + ``shell`` as given to ``subprocess.Popen``; ``env`` None: this process's), or None. + Only a child that runs it here counts (a shell, Python, the syncer): an ``ssh`` or + ``rsync`` argument names a path of another machine.""" + outputs = [root for root in _state["guarded"] if os.path.basename(root) == OUTPUT_DIR] + if not outputs: + return None + if isinstance(args, (str, bytes, os.PathLike)): + text = os.fsdecode(args) + words = text.split() + else: + try: + words = [os.fsdecode(arg) for arg in args] + except TypeError: + return None + text = " ".join(words) + if not shell and not _LOCAL_RUNNERS.search(_program(words)): + return None + for root in outputs: + if re.search(re.escape(root) + r"(?![\w.-])", text): + return root + home = (os.environ if env is None else env).get("HOME") + if home and os.path.join(os.path.abspath(home), OUTPUT_DIR) in outputs: + found = _HOME_OUTPUT.search(text) + if found: + return found.group(0) + return None + + +def _guard_popen() -> None: + real_init = subprocess.Popen.__init__ + + def __init__(self, args, *a, **kw): + # env is Popen's 11th positional parameter (the 10th after args); by keyword otherwise + named = child_output(args, a[9] if len(a) >= 10 else kw.get("env"), + shell=bool(a[7] if len(a) >= 8 else kw.get("shell"))) + if named is not None: + _state["violations"].append((_state["test"], "subprocess", named)) + raise PermissionError( + f"test isolation: a child process would write the real ~/yeto-output ({named} in its " + "command line): point that path at tmp_path (a launcher-built syncer command: replace " + "its --dispense-log, --event-tape and --checkpoint-path) or give the child its own HOME " + "(tests/yeto_home_guard.py)") + real_init(self, args, *a, **kw) + + __init__.yeto_home_guard = True + subprocess.Popen.__init__ = __init__ + + def install_guard() -> None: - """Snapshot the real ~/.yeto and start refusing in-process writes to it (once per process).""" + """Snapshot the real ~/.yeto and ~/yeto-output and start refusing in-process writes to + them and child processes that name ~/yeto-output (once per process).""" if _state["installed"]: return _state["installed"] = True _state["guarded"] = _real_roots() _state["snapshot"] = _snapshot(_state["guarded"]) sys.addaudithook(_audit) + _guard_popen() def set_current_test(nodeid: str) -> None: diff --git a/yeto/rl/adapters/miles/entry.py b/yeto/rl/adapters/miles/entry.py index cbf53077b..1c254fa22 100644 --- a/yeto/rl/adapters/miles/entry.py +++ b/yeto/rl/adapters/miles/entry.py @@ -24,7 +24,6 @@ import os import subprocess import sys -import tempfile import time from collections.abc import Awaitable, Callable, Mapping, Sequence from typing import Any, NamedTuple @@ -735,9 +734,6 @@ def data_position_log_for(miles_args: Any, sync: Any, *, learner_id: int) -> Any slot=getattr(miles_args, "yeto_rl_data_slot", None)) -HF_EXPORT_STAGING = "yeto-hf-export" # under the system temp dir (local disk) - - def hf_exports_for(miles_args: Any, *, actor_model: Any, runner: Any, environ: Mapping[str, str] | None = None) -> Any: """``--rl-export-hf-rounds`` (``yeto.rl.engine.hf_export``): the island's @@ -747,7 +743,7 @@ def hf_exports_for(miles_args: Any, *, actor_model: Any, runner: Any, config = getattr(miles_args, "yeto_rl_hf_exports", None) if not config: return None - from yeto.rl.engine.hf_export import EXPORT_HF_FLAG, ExportRounds, HfRoundExports + from yeto.rl.engine.hf_export import EXPORT_HF_FLAG, ExportRounds, HfRoundExports, private_staging from yeto.rl.engine.resume import store_for from .publish import lora_mode @@ -759,7 +755,7 @@ def hf_exports_for(miles_args: Any, *, actor_model: Any, runner: Any, return HfRoundExports(ExportRounds.parse(config["rounds"]), store_for(config["store"], environ=environ), full_checkpoint_writer(actor_model, runner, all_ranks=one_node, base_dir=_hf_dir(miles_args)), - staging=Path(tempfile.gettempdir()) / HF_EXPORT_STAGING) + staging=private_staging()) def _hf_dir(miles_args: Any) -> Path | None: diff --git a/yeto/rl/adapters/verl/hf_export.py b/yeto/rl/adapters/verl/hf_export.py index 3de60a495..975cd3c5c 100644 --- a/yeto/rl/adapters/verl/hf_export.py +++ b/yeto/rl/adapters/verl/hf_export.py @@ -55,7 +55,6 @@ from .hf_checkpoint_keys import FLOAT_TAGS, BaseExport, base_export, checkpoint_tensor -HF_EXPORT_STAGING = "yeto-hf-export" # under the system temp dir (local disk) SHARD_BYTES = 4 << 30 # export-dtype bytes per safetensors file INDEX_FILE = "model.safetensors.index.json" # Weight files of the source checkpoint (never copied: the export writes its own). @@ -282,11 +281,8 @@ def hf_round_exports(config: Mapping[str, Any], *, group: Any, model_path: str | environ: Mapping[str, str] | None = None): """The island's ``HfRoundExports`` from the plan's ``hf_exports`` section (``{"rounds", "store"}``, :func:`.full_parameter_stream.full_parameter_extras`).""" - import tempfile - - from yeto.rl.engine.hf_export import ExportRounds, HfRoundExports + from yeto.rl.engine.hf_export import ExportRounds, HfRoundExports, private_staging from yeto.rl.engine.resume import store_for return HfRoundExports(ExportRounds.parse(config["rounds"]), store_for(config["store"], environ=environ), - VerlHfWriter(group, model_path, run=run), - staging=Path(tempfile.gettempdir()) / HF_EXPORT_STAGING) + VerlHfWriter(group, model_path, run=run), staging=private_staging()) diff --git a/yeto/rl/adapters/verl/megatron_ports.py b/yeto/rl/adapters/verl/megatron_ports.py index 04a2b8577..41fa729b0 100644 --- a/yeto/rl/adapters/verl/megatron_ports.py +++ b/yeto/rl/adapters/verl/megatron_ports.py @@ -319,7 +319,9 @@ def remote_hf_export(worker_dict, config: dict, rollout_id: int, policy_version: worker = _inner_worker(worker_dict) rank = int(torch.distributed.get_rank()) if torch.distributed.is_initialized() else 0 - staging = Path(tempfile.gettempdir()) / HF_STAGING + # the island's own staging directory (MegatronHfExports names it): every rank of this + # island joins it, another island process on the host has another one + staging = Path(tempfile.gettempdir()) / str(config.get("staging") or HF_STAGING) def write(_rollout_id: int, directory: Path) -> None: _save_hf(worker, Path(directory), model_path, rank) @@ -481,10 +483,14 @@ class MegatronHfExports: export runs on the trainer workers (:func:`remote_hf_export`).""" def __init__(self, island: MegatronIsland, config: dict): + import uuid + from yeto.rl.engine.hf_export import ExportRounds self.island = island - self.config = dict(config) + # One staging directory name per island driver, the same on every trainer rank + # (they all write into it): two islands on one host stage apart. + self.config = {**dict(config), "staging": f"{HF_STAGING}-{uuid.uuid4().hex[:16]}"} self.rounds = ExportRounds.parse(self.config["rounds"]) def due(self, rollout_id: int, *, final: bool) -> bool: diff --git a/yeto/rl/engine/hf_export.py b/yeto/rl/engine/hf_export.py index f425ce780..e38134867 100644 --- a/yeto/rl/engine/hf_export.py +++ b/yeto/rl/engine/hf_export.py @@ -27,6 +27,12 @@ directory with the marker is complete and committed: readers (another container's mount) read only directories with the marker. The staging copy is deleted. +* Staging: each island process stages in a directory of its own under the + system temp dir (:func:`private_staging`, ``yeto-hf-export-``). Two + island processes on one host (two islands, or two test sessions) export the + same round at the same time without removing each other's files: a fixed + directory there would be shared, and one export's cleanup ran inside the + other's write. * Upload failures: removing a directory that is not there is no error (a first export). A failed upload (remove, put, marker) runs again after :data:`UPLOAD_RETRY_S` seconds, :data:`UPLOAD_ATTEMPTS` attempts in all. @@ -52,6 +58,7 @@ import json import shutil +import tempfile import time from collections.abc import Callable from dataclasses import dataclass @@ -66,6 +73,7 @@ # marker in the staging directory, and the reader's marker in the store COMPLETE_MARKER = ".complete" FINAL_POINTER = "final.json" +STAGING_PREFIX = "yeto-hf-export" # private_staging: /yeto-hf-export- UPLOAD_ATTEMPTS = 3 # one upload and two retries UPLOAD_RETRY_S = (10.0, 30.0) # the waits before the second and the third attempt KEEP_FAILED = 2 # staging copies kept after failed uploads, per island process @@ -127,6 +135,13 @@ def _json(fields: dict[str, Any]) -> bytes: return json.dumps(fields, sort_keys=True).encode("utf-8") +def private_staging(prefix: str = STAGING_PREFIX) -> Path: + """A new staging directory under the system temp dir that only this process uses + (module doc, Staging): ``-``, made atomically, never one another + process on the host made.""" + return Path(tempfile.mkdtemp(prefix=f"{prefix}-")) + + class HfRoundExports: """The exports of one island process (module doc).