From 8bdd844e0917dd036349761d9c677c8dd8c5f523 Mon Sep 17 00:00:00 2001 From: Joseph Magly <1159087+jmagly@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:45:14 -0500 Subject: [PATCH] fix(handles): clean up remaining ModelHandle sites and name the snapshot path once Section D of #675: the neuron lab's load() drops the previous handle and its state even when its cleanup fails (the failure is raised and nothing new is loaded); `experiments trace` cleans up its handle on success and failure without masking the trace error; default_model_factory cleans up the handle when .to(device) fails, keeping the move error; a snapshot error raised through a handle names the restore-point path once. Adds tests for the sequence refusal branch and write_step(changed=False), and registers the cleanup-site tests for inputs.py and trace_cli.py in the risk map. Refs #675 --- CHANGELOG.md | 9 ++ ci/test-risk-map.json | 6 +- obliteratus/experiments/inputs.py | 10 ++- obliteratus/experiments/trace_cli.py | 69 ++++++++------- obliteratus/models/loader.py | 9 +- obliteratus/ui_neuron_lab.py | 30 ++++--- tests/test_handle_cleanup_sites.py | 122 +++++++++++++++++++++++++++ tests/test_loader_boundaries.py | 24 +++++- 8 files changed, 227 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f03d38d..468ea022 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -92,6 +92,15 @@ confidence-interval, and canonical substring-protocol behavior. neuron-lab session resets its state and removes its storage even if model cleanup raises, noting a storage failure on the model-cleanup error. +- Remaining model-handle cleanup sites (#675): loading a model in the neuron + lab drops the previous handle and its state even when that handle's cleanup + fails (the failure is raised and nothing new is loaded); `obliteratus + experiments trace` now cleans up the model it loads, on success and on + failure, without replacing the trace error; the experiments model factory + cleans up the handle when moving it to the target device fails, keeping the + move error. A restore-point removal error raised through a handle names the + directory once instead of repeating it in the "remove manually" hint. + - Vocabulary-row edits (#665): when the nearest sub-model that owns the LM head declares no `tie_word_embeddings`, the tie decision now walks up to the next enclosing owner that declares one, and the top-level config decides only when diff --git a/ci/test-risk-map.json b/ci/test-risk-map.json index b6689b50..aebdf303 100644 --- a/ci/test-risk-map.json +++ b/ci/test-risk-map.json @@ -5122,7 +5122,8 @@ "risk_class": "cpu-contract", "risk": "experiments trace parsing, teacher-forced/free-running/qualify dispatch, label parsing, trace writing and exit codes", "required_tests": [ - "tests/test_temporal_trace_store.py" + "tests/test_temporal_trace_store.py", + "tests/test_handle_cleanup_sites.py" ], "conditional_gates": [] }, @@ -5256,7 +5257,8 @@ "tests/test_observation_runs.py", "tests/test_observation_compare_cli.py", "tests/test_observation_execution.py", - "tests/test_observation_prune.py" + "tests/test_observation_prune.py", + "tests/test_handle_cleanup_sites.py" ], "conditional_gates": [] }, diff --git a/obliteratus/experiments/inputs.py b/obliteratus/experiments/inputs.py index 15159bcd..dcd28eef 100644 --- a/obliteratus/experiments/inputs.py +++ b/obliteratus/experiments/inputs.py @@ -14,6 +14,7 @@ from obliteratus.analysis.capture_identity import ( ) from obliteratus.concepts.scoring import ScorerSpec, ScoringTask, examples_from_dataset from obliteratus.experiments.spec import SpecError +from obliteratus.handle_cleanup import cleanup_during_error _MODULE_HOOKS = ("_forward_hooks", "_forward_pre_hooks", "_backward_hooks", "_backward_pre_hooks") _GLOBAL_HOOKS = ("_global_forward_hooks", "_global_forward_pre_hooks", @@ -58,13 +59,18 @@ def default_model_factory(model): """The project's model loader: dense on CPU, no snapshot, then moved to a CUDA device. Loading on the CPU and moving afterwards avoids an accelerate device map, - which the dense-execution check refuses. + which the dense-execution check refuses. If the move fails, the handle is + cleaned up and the move error is raised (a cleanup failure is a note on it). """ from obliteratus.models.loader import load_model handle = load_model(model["id"], device="cpu", dtype=model["dtype"], revision=model["revision"], skip_snapshot=True) if model["device"] != "cpu": - handle.model.to(model["device"]) + try: + handle.model.to(model["device"]) + except BaseException as error: + cleanup_during_error(handle, error) + raise return handle diff --git a/obliteratus/experiments/trace_cli.py b/obliteratus/experiments/trace_cli.py index ed34c7d4..6e0161cb 100644 --- a/obliteratus/experiments/trace_cli.py +++ b/obliteratus/experiments/trace_cli.py @@ -1,5 +1,7 @@ """``obliteratus experiments trace``: temporal traces and cached-execution qualification.""" +from obliteratus.handle_cleanup import cleanup_on_exit + def add_trace(commands): sub = commands.add_parser( @@ -56,36 +58,39 @@ def run_trace_command(args, model_factory=None): "qualification replays a fixed sequence (teacher-forced)") handle = (model_factory or inputs.default_model_factory)( {"id": args.model, "dtype": args.dtype, "revision": args.revision, "device": "cpu"}) - model, tokenizer = handle.model, handle.tokenizer - layers = inputs.capture_sites(model, args.layer) - prompt = _ids(args.prompt_ids) if args.prompt_ids is not None else \ - inputs.encode(tokenizer, args.prompt)["input_ids"][0].tolist() - common = {"readout_name": "decoder_output", "labels": _labels(args.label)} - if args.mode == "free-running": - eos = getattr(tokenizer, "eos_token_id", None) - trace = trace_free_running(model, layers, prompt, args.max_new_tokens, cache=args.cache, - condition=args.condition, - eos_token_ids=() if eos is None else (eos,), **common) - else: - if args.continuation_ids is not None: - extra = _ids(args.continuation_ids) - elif args.continuation: - encoded = inputs.encode(tokenizer, args.continuation, add_special_tokens=False) - extra = encoded["input_ids"][0].tolist() + # The handle is cleaned up on every exit; a cleanup failure is raised on + # success and only noted while another error propagates. + with cleanup_on_exit(handle): + model, tokenizer = handle.model, handle.tokenizer + layers = inputs.capture_sites(model, args.layer) + prompt = _ids(args.prompt_ids) if args.prompt_ids is not None else \ + inputs.encode(tokenizer, args.prompt)["input_ids"][0].tolist() + common = {"readout_name": "decoder_output", "labels": _labels(args.label)} + if args.mode == "free-running": + eos = getattr(tokenizer, "eos_token_id", None) + trace = trace_free_running(model, layers, prompt, args.max_new_tokens, cache=args.cache, + condition=args.condition, + eos_token_ids=() if eos is None else (eos,), **common) else: - extra = [] - if args.qualify: - return qualify_cached_execution(model, layers, prompt + extra, len(prompt), - atol=args.atol, **common) - trace = trace_teacher_forced(model, layers, prompt + extra, len(prompt), cache=args.cache, - condition=args.condition, **common) - summary = {"mode": trace.mode, "cache": trace.cache, "condition": trace.condition, - "tokens": trace.length, "prompt_tokens": trace.prompt_tokens, - "token_ids": trace.token_ids.tolist(), "layers": list(trace.values), - "calls": [call.to_dict() for call in trace.calls], "labels": trace.labels} - if args.out: - manifest = write_trace(trace, args.out, model=model, tokenizer=tokenizer, layers=layers, - model_id=args.model, chunk_tokens=args.chunk_tokens) - summary.update(out=str(args.out), identity_sha256=manifest["identity_sha256"], - chunks=len(manifest["chunks"])) - return summary + if args.continuation_ids is not None: + extra = _ids(args.continuation_ids) + elif args.continuation: + encoded = inputs.encode(tokenizer, args.continuation, add_special_tokens=False) + extra = encoded["input_ids"][0].tolist() + else: + extra = [] + if args.qualify: + return qualify_cached_execution(model, layers, prompt + extra, len(prompt), + atol=args.atol, **common) + trace = trace_teacher_forced(model, layers, prompt + extra, len(prompt), + cache=args.cache, condition=args.condition, **common) + summary = {"mode": trace.mode, "cache": trace.cache, "condition": trace.condition, + "tokens": trace.length, "prompt_tokens": trace.prompt_tokens, + "token_ids": trace.token_ids.tolist(), "layers": list(trace.values), + "calls": [call.to_dict() for call in trace.calls], "labels": trace.labels} + if args.out: + manifest = write_trace(trace, args.out, model=model, tokenizer=tokenizer, layers=layers, + model_id=args.model, chunk_tokens=args.chunk_tokens) + summary.update(out=str(args.out), identity_sha256=manifest["identity_sha256"], + chunks=len(manifest["chunks"])) + return summary diff --git a/obliteratus/models/loader.py b/obliteratus/models/loader.py index a70af2d8..032d70a1 100644 --- a/obliteratus/models/loader.py +++ b/obliteratus/models/loader.py @@ -599,13 +599,18 @@ def release_offload_dir(holder) -> Optional[Exception]: def _rephrase_for_handle(error: Exception) -> None: - """Replace a ``DiskSnapshot.close()`` retry hint with the path to remove.""" + """Replace a ``DiskSnapshot.close()`` retry hint with the path to remove. + + The path is named once: the reason normally names it already. + """ reason = getattr(error, "close_failure_reason", None) path = getattr(error, "close_failure_path", None) if not isinstance(reason, str) or path is None: return + hint = ("remove the restore point directory manually" if str(path) in reason + else f"remove {path} manually") try: - error.args = (f"{reason}; remove {path} manually",) + error.args = (f"{reason}; {hint}",) except Exception: pass diff --git a/obliteratus/ui_neuron_lab.py b/obliteratus/ui_neuron_lab.py index 8c8d1abb..9dc5e525 100644 --- a/obliteratus/ui_neuron_lab.py +++ b/obliteratus/ui_neuron_lab.py @@ -187,18 +187,24 @@ class NeuronLabSession: raise ValueError("MPS is not available on this machine") if device == "cuda" and not torch.cuda.is_available(): raise ValueError("CUDA is not available on this machine") - # Release the previous model before allocating its replacement. - if self.handle is not None: - self.handle.cleanup() - self.handle = self.recipe = self.control = None - self.ask_lab = None - self.layers = [] - self._comparison_reference = None - self.inspection = self.comparison = None - self.recipe_file = self.experiment_file = None - self.selected_row = 1 - self.scout = self.dialogue = self.dialogue_file = None - self.prism = self.prism_file = None + # Release the previous model before allocating its replacement. If + # its cleanup fails, the error is raised (nothing new is loaded) + # but the stale handle and its state are dropped anyway, as in + # close(), so a later load or close never retries that cleanup. + previous = self.handle + try: + if previous is not None: + previous.cleanup() + finally: + self.handle = self.recipe = self.control = None + self.ask_lab = None + self.layers = [] + self._comparison_reference = None + self.inspection = self.comparison = None + self.recipe_file = self.experiment_file = None + self.selected_row = 1 + self.scout = self.dialogue = self.dialogue_file = None + self.prism = self.prism_file = None handle = load_model( model_id.strip(), device=device, dtype="float32", trust_remote_code=False, skip_snapshot=True, phase_admission=True, local_files_only=bool(local_files_only), diff --git a/tests/test_handle_cleanup_sites.py b/tests/test_handle_cleanup_sites.py index 855042dd..b81dc8af 100644 --- a/tests/test_handle_cleanup_sites.py +++ b/tests/test_handle_cleanup_sites.py @@ -511,3 +511,125 @@ def test_sequence_load_stack_cleans_up_when_building_its_result_fails(tmp_path): SimpleNamespace(load=lambda *_: handle)) handle.cleanup.assert_called_once_with() assert any(LEFT in n for n in raised.value.__notes__) + + +# --- #675 D: remaining ModelHandle sites ---------------------------------- + +def test_neuron_lab_load_drops_previous_handle_when_its_cleanup_fails(monkeypatch, tmp_path): + """#675 D1: a failing cleanup of the previous handle is raised, and the + session never keeps the stale handle or its state (nor retries the cleanup).""" + from obliteratus import ui_neuron_lab as lab + + load_model = Mock() + monkeypatch.setattr(lab, "load_model", load_model) + session = lab.NeuronLabSession(cache_directory=tmp_path) + previous = failing_handle() + session.handle, session.layers = previous, [{"layer": 0}] + session.recipe, session.inspection, session.scout = object(), object(), object() + with pytest.raises(SnapshotError, match=LEFT): + session.load("next-model") + previous.cleanup.assert_called_once_with() + load_model.assert_not_called() + assert session.handle is None and session.recipe is None and session.layers == [] + assert session.inspection is None and session.scout is None + session.close() # the dropped handle's cleanup is not retried + previous.cleanup.assert_called_once_with() + + +def _trace_args(**extra): + fields = {"model": "m", "dtype": "float32", "revision": None, "layer": [0], + "prompt": None, "prompt_ids": "1,2", "mode": "teacher-forced", + "continuation": None, "continuation_ids": None, "max_new_tokens": 4, + "cache": "uncached", "qualify": True, "atol": 1e-5, "condition": "baseline", + "label": [], "out": None, "chunk_tokens": 256} + return SimpleNamespace(**{**fields, **extra}) + + +@pytest.mark.parametrize("cleanup_fails", [False, True]) +def test_trace_cli_cleans_up_its_handle_on_success(monkeypatch, cleanup_fails): + """#675 D2: the trace command cleans up the handle it loaded.""" + from obliteratus.analysis import trace_compare + from obliteratus.experiments import inputs, trace_cli + + handle = failing_handle() if cleanup_fails else SimpleNamespace( + model=object(), tokenizer=object(), cleanup=Mock()) + monkeypatch.setattr(inputs, "capture_sites", lambda *_: ["layer"]) + monkeypatch.setattr(trace_compare, "qualify_cached_execution", lambda *_a, **_k: {"ok": 1}) + if cleanup_fails: + with pytest.raises(SnapshotError, match=LEFT): + trace_cli.run_trace_command(_trace_args(), model_factory=lambda _m: handle) + else: + assert trace_cli.run_trace_command(_trace_args(), + model_factory=lambda _m: handle) == {"ok": 1} + handle.cleanup.assert_called_once_with() + + +def test_trace_cli_cleans_up_its_handle_and_keeps_primary_error(monkeypatch): + """#675 D2: a trace failure cleans up the handle; a cleanup failure is a note.""" + from obliteratus.experiments import inputs, trace_cli + + handle = failing_handle() + original = ValueError("no such layer") + monkeypatch.setattr(inputs, "capture_sites", Mock(side_effect=original)) + with pytest.raises(ValueError) as raised: + trace_cli.run_trace_command(_trace_args(), model_factory=lambda _m: handle) + assert_primary_kept(raised, original, handle) + + +def test_default_model_factory_cleans_up_when_the_device_move_fails(monkeypatch): + """#675 D3: a failing ``.to(device)`` after the load cleans up the handle + and keeps the move error as the primary.""" + from obliteratus.experiments import inputs + from obliteratus.models import loader + + original = RuntimeError("CUDA out of memory") + handle = failing_handle(model=SimpleNamespace(to=Mock(side_effect=original))) + monkeypatch.setattr(loader, "load_model", lambda *_a, **_k: handle) + with pytest.raises(RuntimeError) as raised: + inputs.default_model_factory({"id": "m", "dtype": "float32", "revision": None, + "device": "cuda:0"}) + assert_primary_kept(raised, original, handle) + handle.model.to.assert_called_once_with("cuda:0") + + +def test_sequence_open_session_refuses_an_unbound_component_and_cleans_up(monkeypatch, + tmp_path): + """#675 D5: the SequenceRefused branch of open_session cleans up the handle.""" + from obliteratus.experiments import inputs, intervention_checks as checks + from obliteratus.experiments import sequence_eval as ev + from obliteratus.experiments.sequence import SequenceRefused + + handle = failing_handle() + monkeypatch.setattr(ev, "component_spec", lambda _c: {}) + monkeypatch.setattr(checks, "prepare", lambda *_: {}) + monkeypatch.setattr(inputs, "require_unmodified", lambda _m: None) + monkeypatch.setattr(checks, "verify_model", + lambda *_: {"record": {"vector_sha256": "rederived"}}) + plan = {"frozen": {"components": [{"run": "r", "position": 1, + "source": {"vector_sha256": "saved"}}], + "reference": {"source": str(tmp_path)}, "model": {}}} + block_loader(monkeypatch) + with pytest.raises(SequenceRefused, match="Component 1 is not bound") as raised: + ev.open_session(plan, SimpleNamespace(load=lambda *_: handle), None, tmp_path) + handle.cleanup.assert_called_once_with() + assert any(LEFT in note for note in raised.value.__notes__) + + +def test_sequence_step_weight_edit_refuses_an_unchanged_parent(monkeypatch, tmp_path): + """#675 D5: write_step with ``changed=False`` cleans up the parent handle, + then refuses the step and writes no stack.""" + from obliteratus.experiments import sequence_steps as steps + from obliteratus.experiments.sequence import SequenceRefused + + handle = SimpleNamespace(model=SimpleNamespace(named_modules=lambda: [("m", object())]), + tokenizer=object(), cleanup=Mock()) + monkeypatch.setattr(steps, "load_stack", lambda *_: handle) + monkeypatch.setattr(steps.edits, "weight_edit", lambda *_: "edit") + monkeypatch.setattr(steps.edits, "apply_weight_edit", Mock(return_value=False)) + model_io = SimpleNamespace(save=Mock()) + with pytest.raises(SequenceRefused, match="Step 2 changes no parameter of its parent"): + steps.write_step(tmp_path, {}, 2, EDITED_PARENT, WEIGHT_COMPONENT, + {"module": "m", "vector": None}, model_io) + handle.cleanup.assert_called_once_with() + model_io.save.assert_called_once() + assert not (tmp_path / "steps" / "02" / "artifact" / steps.STACK).exists() diff --git a/tests/test_loader_boundaries.py b/tests/test_loader_boundaries.py index cbd20020..c90754de 100644 --- a/tests/test_loader_boundaries.py +++ b/tests/test_loader_boundaries.py @@ -2223,7 +2223,9 @@ def test_handle_surfaced_snapshot_error_names_the_path_instead_of_a_retry(tmp_pa handle.cleanup() text = "\n".join([str(raised.value), *getattr(raised.value, "__notes__", [])]) assert "retry DiskSnapshot.close()" not in text - assert f"remove {snapshot.path} manually" in str(raised.value) + # #675 D4: the reason already names the path, so the hint does not repeat it. + assert f"remove {snapshot.path} manually" not in str(raised.value) + assert str(raised.value).endswith("; remove the restore point directory manually") assert "retry" not in handle.snapshot_policy["reason"] assert str(snapshot.path) in handle.snapshot_policy["reason"] snapshot.close() @@ -2260,5 +2262,23 @@ def test_replaced_restore_point_warning_names_the_path_instead_of_a_retry(monkey with caplog.at_level(logging.WARNING, logger=loader.logger.name): handle.snapshot() messages = [r.getMessage() for r in caplog.records if "replaced restore point" in r.getMessage()] - assert messages and all("retry" not in m and "remove /x/old manually" in m for m in messages) + assert messages and all("retry" not in m and m.count("/x/old") == 1 + and "remove the restore point directory manually" in m + for m in messages) assert handle._restore_point is replacement + + +@pytest.mark.parametrize("reason_names_path", [True, False]) +def test_rephrased_snapshot_error_names_the_path_once(reason_names_path): + """#675 D4: the handle's rewording names the path exactly once, adding it + only when the close-failure reason does not already name it.""" + from obliteratus.models.snapshot import SnapshotError + + reason = ("restore point files could not be fully removed from /x/old: path still exists" + if reason_names_path else "restore point removal did not complete") + error = SnapshotError(reason + "; retry DiskSnapshot.close() or remove the path manually") + error.close_failure_reason, error.close_failure_path = reason, "/x/old" + loader._rephrase_for_handle(error) + message = str(error) + assert message.count("/x/old") == 1 and "retry" not in message + assert message.startswith(reason) and message.endswith(" manually")