diff --git a/CHANGELOG.md b/CHANGELOG.md index 46282597..2bebc86d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -92,8 +92,11 @@ confidence-interval, and canonical substring-protocol behavior. `tokenizer_vocabulary_sha256` parameter (omitted when unset, so existing recipe digests are unchanged) and enforces the same guard with no opt-out, as does the legacy `obliteratus run` study runner. Recipe steps and studies that use - unpinned ID-only operations now fail. A config pin that cannot be verified - is recorded as `pin_unverifiable`. Residual discovery refuses to pin a base + unpinned ID-only operations now fail. With `--allow-unpinned-id-operations`, + a config pin that cannot be verified is recorded as `pin_unverifiable`; + without the opt-out it fails. `VocabSurgeryStrategy.apply_all` enforces the + same guard itself (opt-in with `allow_unpinned_id_operations=True`) and + records it in its receipt. Residual discovery refuses to pin a base config's ID-only operations whose tokenizer it cannot verify. - `vocab-surgery apply` promotes its checkpoint with an atomic no-replace rename (`renameat2(RENAME_NOREPLACE)` on Linux), so even an empty directory created @@ -103,10 +106,15 @@ confidence-interval, and canonical substring-protocol behavior. or deletes a file once published: if a later file conflicts or fails, the published files stay and the error names them as a possibly incomplete set. A `vocab-surgery apply` checkpoint is never rolled back once promoted; a later - parent-directory sync failure is reported and the complete checkpoint stays - in place. An interrupted promotion is reported without moving or deleting - the destination or the staging path. The default `atomic_checkpoint_directory` behavior used by other - callers is unchanged. + parent-directory sync failure is reported, and nothing is rolled back or + removed. An interrupted promotion is reported without moving or deleting + the destination or the staging path; a `KeyboardInterrupt` or `SystemExit` + stays one, with the outcome attached as a note. A file whose discovery + publish was interrupted is named as one that may have been published. Failed + checkpoint staging is removed through a directory descriptor held since + creation, so a directory another process recreates at the staging path is + left alone (this applies to every `atomic_checkpoint_directory` caller); its + default behavior is otherwise unchanged. - `vocab-surgery apply` and `discover` no longer overwrite an output that a concurrent run created after the initial existence check (#602). The checkpoint destination is rechecked under the commit lock, and discovery files are diff --git a/docs/VOCABULARY_ROW_EDITS.md b/docs/VOCABULARY_ROW_EDITS.md index abf4212e..34eed595 100644 --- a/docs/VOCABULARY_ROW_EDITS.md +++ b/docs/VOCABULARY_ROW_EDITS.md @@ -321,10 +321,12 @@ An unset pin is omitted from normalized params, so existing recipes keep their canonical digests. The legacy study runner (`obliteratus run` with `name: vocab_surgery`) applies -the same guard when it enumerates the operations, also with no opt-out. The -lower-level `VocabSurgeryStrategy.resolve`, `apply_batch` and `apply_all` -methods do not apply it; callers of those methods must check the tokenizer -themselves. +the same guard when it enumerates the operations, also with no opt-out. +`VocabSurgeryStrategy.apply_all` applies it too and records it in the receipt; +it fails closed unless given `expected_tokenizer_sha256=` or +`allow_unpinned_id_operations=True`. The lower-level `resolve` and +`apply_batch` methods do not apply it; callers of those methods must check the +tokenizer themselves. The legacy study runner also accepts `name: vocab_surgery` and evaluates all resolved operations as one composed batch before restoring the snapshot. diff --git a/obliteratus/models/offload_surgery.py b/obliteratus/models/offload_surgery.py index 9df98818..fad8639d 100644 --- a/obliteratus/models/offload_surgery.py +++ b/obliteratus/models/offload_surgery.py @@ -183,6 +183,9 @@ def logical_values_identical( to an offloaded one neither raises a device mismatch nor materializes a full extra copy; the peak is bounded by ``value_compare_peak_bytes``. Returns ``None`` when the values are unavailable (``meta`` placeholders). + Values of rank other than 2 are walked through views (leading-index slices + for higher ranks), never reshaped, because reshaping a non-contiguous + accelerator tensor would copy it whole. """ if first.shape != second.shape or first.dtype != second.dtype: return False @@ -190,9 +193,13 @@ def logical_values_identical( return None if first.numel() == 0: return True - if first.ndim != 2: - rows = first.shape[0] if first.ndim > 2 else 1 - first, second = first.reshape(rows, -1), second.reshape(rows, -1) + if first.ndim > 2: + for index in range(first.shape[0]): + if not logical_values_identical(first[index], second[index], chunk_bytes=chunk_bytes): + return False + return True + while first.ndim < 2: + first, second = first.unsqueeze(0), second.unsqueeze(0) rows, cols = first.shape elements = max(1, chunk_bytes // first.element_size()) if cols <= elements: diff --git a/obliteratus/persistence_contracts.py b/obliteratus/persistence_contracts.py index 5237849b..3fb128fd 100644 --- a/obliteratus/persistence_contracts.py +++ b/obliteratus/persistence_contracts.py @@ -393,10 +393,75 @@ def _rollback_checkpoint_commit( _sync_directory(destination.parent) -def _cleanup_failed_staging(staging: Path) -> None: - """Remove failed staging without masking the transaction's primary error.""" +def _open_directory_handle(path: Path) -> int | None: + """Hold ``path`` open as a directory for descriptor-based cleanup, where supported. + + An open descriptor pins the directory's inode, so no other directory can + take its identity while it is held. Returns ``None`` on platforms without + descriptor-relative removal (``shutil.rmtree.avoids_symlink_attacks``). + """ + if not shutil.rmtree.avoids_symlink_attacks: # pragma: no cover - Windows/no openat + return None + flags = ( + os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_CLOEXEC", 0) + ) try: - _remove_checkpoint_path(staging) + return os.open(path, flags) + except OSError: # pragma: no cover - defensive; falls back to pathname cleanup + return None + + +def _names_held_directory(path: Path, handle: int) -> bool: + """Return whether ``path`` still names the directory ``handle`` holds.""" + held = os.fstat(handle) + try: + current = os.stat(path, follow_symlinks=False) + except FileNotFoundError: + return False + return (current.st_dev, current.st_ino) == (held.st_dev, held.st_ino) + + +def _remove_held_directory(path: Path, handle: int) -> None: + """Remove the directory ``handle`` holds, but only while ``path`` still names it. + + If ``path`` is gone or names a different directory, nothing is removed: the + held directory may have been promoted elsewhere, and whatever another + process put at ``path`` is not ours. Otherwise the contents are removed + relative to the held descriptor, never by re-resolving ``path``. + """ + if not _names_held_directory(path, handle): + if _path_exists(path): + logger.warning( + "Checkpoint staging path %s no longer names this write's staging " + "directory; it was left in place", + path, + ) + return + for name in os.listdir(handle): + try: + mode = os.stat(name, dir_fd=handle, follow_symlinks=False).st_mode + if stat.S_ISDIR(mode): + shutil.rmtree(name, dir_fd=handle) + else: + os.unlink(name, dir_fd=handle) + except FileNotFoundError: + pass + if _names_held_directory(path, handle): + os.rmdir(path) + + +def _cleanup_failed_staging(staging: Path, handle: int | None = None) -> None: + """Remove failed staging without masking the transaction's primary error. + + With a held directory ``handle`` only that directory is removed, never a + different one another process created at the same pathname. + """ + try: + if handle is None: + _remove_checkpoint_path(staging) + else: + _remove_held_directory(staging, handle) except OSError as cleanup_error: logger.warning( "Checkpoint write failed, and staging directory %s could not be " @@ -439,7 +504,14 @@ def atomic_checkpoint_directory( (``FileExistsError`` or ``NoReplaceRenameUnsupported``) leaves both the destination and the staging pathname untouched, since the rename may have happened and another process may have reused the staging name, and raises - ``RuntimeError`` naming both for inspection. + ``RuntimeError`` naming both for inspection. Cancellation + (``KeyboardInterrupt``, ``SystemExit`` and other non-``Exception`` + failures) after the attempt is re-raised unchanged, with that message + attached as a note. + + Failed staging is removed through a descriptor held since it was created, + so a directory another process recreates at the staging pathname is never + removed (platforms without descriptor-based removal use the pathname). """ destination = Path(destination) destination.parent.mkdir(parents=True, exist_ok=True) @@ -449,6 +521,7 @@ def atomic_checkpoint_directory( dir=destination.parent, ), ) + staging_handle = _open_directory_handle(staging) backup: Path | None = None published_no_replace = False rename_attempted = False @@ -492,20 +565,27 @@ def atomic_checkpoint_directory( if not replace_existing: # There was no destination before, so there is nothing to # restore; never move or delete anything after the attempt. + # The destination may since have been swapped by a writer + # that bypasses the lock, so only what we did is reported. if published_no_replace: - raise RuntimeError( + outcome = ( f"Checkpoint was published to {destination}, but syncing " f"{destination.parent} failed, so the rename may not survive a " - "crash. The complete checkpoint was left in place and nothing was " - "rolled back.", - ) from commit_error - if rename_attempted: - raise RuntimeError( + f"crash. Nothing was rolled back or removed; inspect {destination}." + ) + elif rename_attempted: + outcome = ( f"Publishing the checkpoint to {destination} was interrupted, so it " "is unknown whether it was published. Nothing was rolled back or " - f"removed; inspect {destination} and {staging}.", - ) from commit_error - raise + f"removed; inspect {destination} and {staging}." + ) + else: + raise + if not isinstance(commit_error, Exception): + # Keep a cancellation a cancellation. + commit_error.add_note(outcome) + raise + raise RuntimeError(outcome) from commit_error try: _rollback_checkpoint_commit( destination, @@ -538,8 +618,11 @@ def atomic_checkpoint_directory( ) except BaseException: if not (published_no_replace or rename_attempted): - _cleanup_failed_staging(staging) + _cleanup_failed_staging(staging, staging_handle) raise + finally: + if staging_handle is not None: + os.close(staging_handle) def _publish_file_no_replace(temporary: Path, destination: Path) -> None: @@ -574,12 +657,14 @@ def write_new_text_files(files: Mapping[Path, str], *, encoding: str = "utf-8") nothing that might belong to another writer is touched. If a later file conflicts (``FileExistsError``) or publishing fails, the files already published stay in place and the error names them, because the set may be - incomplete. Only private temporary files are removed. Publication is not + incomplete. A file whose publication was interrupted is named as one that + may have been published. Only private temporary files are removed. Publication is not crash-safe either: a crash can leave published files without the rest and hidden ``...tmp`` files beside them. """ temporaries: dict[Path, Path] = {} published: list[Path] = [] + attempted: Path | None = None try: for destination, text in files.items(): destination = Path(destination) @@ -592,17 +677,28 @@ def write_new_text_files(files: Mapping[Path, str], *, encoding: str = "utf-8") stream.flush() os.fsync(stream.fileno()) for destination, temporary in temporaries.items(): + # Recorded before publishing: until it is confirmed, an + # interruption leaves it unknown whether this file appeared. + attempted = destination try: _publish_file_no_replace(temporary, destination) except FileExistsError as error: + attempted = None # definitely refused raise FileExistsError( f"Output already exists: {destination}" + _published_note(published), ) from error + except OSError: + attempted = None # the link and rename calls failed: nothing appeared + raise published.append(destination) + attempted = None _sync_directory(destination.parent) except BaseException as error: - if published and not isinstance(error, FileExistsError): + if (published or attempted is not None) and not isinstance(error, FileExistsError): note = _published_note(published).lstrip("; ") + if attempted is not None: + uncertain = f"{attempted} may have been published and was left in place" + note = f"{note}; {uncertain}" if note else uncertain logger.error("Publishing stopped: %s", note) error.add_note(note) raise diff --git a/obliteratus/strategies/vocab_surgery.py b/obliteratus/strategies/vocab_surgery.py index 2242a848..e07687bc 100644 --- a/obliteratus/strategies/vocab_surgery.py +++ b/obliteratus/strategies/vocab_surgery.py @@ -464,12 +464,23 @@ def _config_tie_flag(handle: ModelHandle, output_module: nn.Module) -> bool | No by the text config. Any owning flag that says tied, including a disagreement between aliases or between a config and its text config, means tied: an ambiguous tie must fail closed, never resolve to "untied". - Less specific configs are consulted only when the owning ones declare - nothing. + A path whose owner declares no flag at all (in its config or its text + config) is treated like a root-owned path, so the top-level configs speak + for it; otherwise a silent owner beside an untied one would hide a tied + top-level flag. Less specific configs are consulted only when the owning + ones declare nothing. """ model = handle.model top_level = [config for config in (getattr(model, "config", None), handle.config) if config is not None] + + def flags_of(configs: list[Any]) -> set[bool]: + found = set() + for config in configs: + found.update(flag for flag in (_flag(config), _flag(_text_config(config))) + if flag is not None) + return found + owners: list[Any] = [] root_owned = False paths = [path for path, module in model.named_modules(remove_duplicate=False) @@ -486,18 +497,12 @@ def _config_tie_flag(handle: ModelHandle, output_module: nn.Module) -> bool | No if config is not None and all(config is not top for top in top_level): owner_config = config break - if owner_config is None: + if owner_config is None or not flags_of([owner_config]): + # A silent owner defers to the top level, like a root-owned path. root_owned = True elif all(owner_config is not seen for seen in owners): owners.append(owner_config) - def flags_of(configs: list[Any]) -> set[bool]: - found = set() - for config in configs: - found.update(flag for flag in (_flag(config), _flag(_text_config(config))) - if flag is not None) - return found - owning = flags_of(owners + (top_level if root_owned or not paths else [])) if owning: return True in owning @@ -1190,10 +1195,28 @@ class VocabSurgeryStrategy(AblationStrategy): def apply_all( self, handle: ModelHandle, config: VocabSurgeryConfig | dict[str, Any] | None = None, *, edit_memory_bytes: int | None = None, + expected_tokenizer_sha256: str | None = None, + allow_unpinned_id_operations: bool = False, + opt_out_name: str = "allow_unpinned_id_operations", ) -> dict[str, Any]: + """Resolve and apply every operation of ``config``. + + Enforces the fail-closed ID-only tokenizer guard itself, so a caller + that skipped ``authorize_id_only_operations`` still cannot edit rows + chosen only by ID against an unverified tokenizer. The guard record is + written to the receipt's ``id_only_operation_guard``. + """ resolved_config = VocabSurgeryConfig.from_value(config) + id_only_guard = authorize_id_only_operations( + resolved_config, handle.tokenizer, + expected_tokenizer_sha256=expected_tokenizer_sha256, + allow_unpinned=allow_unpinned_id_operations, + opt_out_name=opt_out_name, + ) specs, skipped = self.resolve(handle, resolved_config) - return self.apply_batch( + receipt = self.apply_batch( handle, specs, skipped=skipped, config=resolved_config, edit_memory_bytes=edit_memory_bytes, ) + record_id_only_guard(receipt, id_only_guard) + return receipt diff --git a/obliteratus/vocab_surgery_cli.py b/obliteratus/vocab_surgery_cli.py index 2496f584..d0662dbd 100644 --- a/obliteratus/vocab_surgery_cli.py +++ b/obliteratus/vocab_surgery_cli.py @@ -15,7 +15,6 @@ from obliteratus.strategies.vocab_surgery import ( chat_template_digest, check_tokenizer_vocabulary_pin, load_vocab_surgery_config, - record_id_only_guard, tokenizer_vocabulary_digest, ) from obliteratus.strategies.vocab_surgery_discovery import ( @@ -159,8 +158,13 @@ def _apply(args, console) -> int: ) elif id_only_guard["status"] == "config_pin_mismatch_ignored": console.print(f"[yellow]{id_only_guard['warning']}; continuing[/]") - receipt = VocabSurgeryStrategy().apply_all(handle, config) - record_id_only_guard(receipt, id_only_guard) + # apply_all re-checks the same guard and records it in the receipt. + receipt = VocabSurgeryStrategy().apply_all( + handle, config, + expected_tokenizer_sha256=getattr(args, "expected_tokenizer_sha256", None), + allow_unpinned_id_operations=getattr(args, "allow_unpinned_id_operations", False), + opt_out_name="--allow-unpinned-id-operations", + ) # The early existence check fails fast; this one, under the commit lock, # keeps a concurrent run's checkpoint from being replaced. with atomic_checkpoint_directory(args.output_dir, replace_existing=False) as staged: diff --git a/tests/test_checkpoint_atomicity.py b/tests/test_checkpoint_atomicity.py index e2e501f0..c215b4f5 100644 --- a/tests/test_checkpoint_atomicity.py +++ b/tests/test_checkpoint_atomicity.py @@ -300,7 +300,12 @@ def test_atomic_checkpoint_reports_staging_cleanup_failure_without_masking_write raise PermissionError("simulated cleanup denial") return real_remove(path) + def fail_held_staging_cleanup(path, _handle): + raise PermissionError("simulated cleanup denial") + monkeypatch.setattr(persistence, "_remove_checkpoint_path", fail_staging_cleanup) + # Staging is removed through its held directory descriptor where supported. + monkeypatch.setattr(persistence, "_remove_held_directory", fail_held_staging_cleanup) with pytest.raises(OSError, match="simulated write failure"): with _atomic_checkpoint_directory(destination) as staging: (staging / "partial.bin").write_bytes(b"partial") diff --git a/tests/test_distributed_export_contracts.py b/tests/test_distributed_export_contracts.py index 2df53755..8908b721 100644 --- a/tests/test_distributed_export_contracts.py +++ b/tests/test_distributed_export_contracts.py @@ -781,7 +781,7 @@ def test_uncertain_cleanup_is_voted_and_keeps_hidden_nonloadable_attempt(mocked_ from obliteratus.distributed.surgery import ExciseTransactionState case = mocked_export_world - monkeypatch.setattr(persistence, "_cleanup_failed_staging", lambda path: None) + monkeypatch.setattr(persistence, "_cleanup_failed_staging", lambda *_args: None) def fault(point, sequence): if point == "writer_before" and case.context.rank == 0: @@ -863,7 +863,7 @@ def test_atomic_validation_failure_with_failed_cleanup_leaves_no_canonical_weigh case = mocked_export_world source_before = {path.name: path.read_bytes() for path in case.source.iterdir()} - monkeypatch.setattr(persistence, "_cleanup_failed_staging", lambda path: None) + monkeypatch.setattr(persistence, "_cleanup_failed_staging", lambda *_args: None) def fault(point, sequence): if point == "manifest_validated" and case.context.rank == 0: diff --git a/tests/test_distributed_export_gloo.py b/tests/test_distributed_export_gloo.py index d3fbf7dd..8852c3ed 100644 --- a/tests/test_distributed_export_gloo.py +++ b/tests/test_distributed_export_gloo.py @@ -478,7 +478,7 @@ def _worker( if mode == "timeout": active_config = replace(active_config, stage_timeout_seconds=1) if mode == "cleanup_failure": - persistence_module._cleanup_failed_staging = lambda _path: None + persistence_module._cleanup_failed_staging = lambda *_args: None if mode == "backup_cleanup_failure": original_remove = persistence_module._remove_checkpoint_path diff --git a/tests/test_offload_surgery.py b/tests/test_offload_surgery.py index 7e3a79b7..ce5ce1b3 100644 --- a/tests/test_offload_surgery.py +++ b/tests/test_offload_surgery.py @@ -800,3 +800,27 @@ def test_failed_commit_restores_changed_aliases_and_preserves_untouched_aliases( assert writes == [*expected_writes, "weight"] assert module.weight.device.type == "meta" assert id(module.weight) == parameter_identity + + +def test_logical_values_identical_walks_higher_rank_values_without_reshaping(monkeypatch): + """Non-rank-2 values are compared through views, never a full reshape copy (#655).""" + first = torch.arange(2 * 3 * 4, dtype=torch.float32).reshape(2, 3, 4).permute(2, 0, 1) + same = first.clone().permute(0, 1, 2) + different = first.clone() + different[3, 1, 2] = -1.0 + vector = torch.arange(6, dtype=torch.float32) + scalar = torch.tensor(1.5) + assert not first.is_contiguous() + + def no_reshape(self, *shape): + raise AssertionError("logical_values_identical must not reshape its operands") + + monkeypatch.setattr(torch.Tensor, "reshape", no_reshape) + compare = offload_surgery.logical_values_identical + assert compare(first, same, chunk_bytes=8) is True + assert compare(first, different, chunk_bytes=8) is False + assert compare(first, different) is False + assert compare(vector, vector.clone(), chunk_bytes=8) is True + assert compare(vector, vector.flip(0)) is False + assert compare(scalar, scalar.clone()) is True + assert compare(scalar, torch.tensor(2.5)) is False diff --git a/tests/test_persistence_contracts.py b/tests/test_persistence_contracts.py index 0e505efa..cafac4cf 100644 --- a/tests/test_persistence_contracts.py +++ b/tests/test_persistence_contracts.py @@ -1135,8 +1135,8 @@ def test_published_no_replace_checkpoint_is_never_rolled_back( assert state["failed"] assert str(raised.value) == ( f"Checkpoint was published to {destination}, but syncing {tmp_path} failed, so the " - "rename may not survive a crash. The complete checkpoint was left in place and " - "nothing was rolled back." + "rename may not survive a crash. Nothing was rolled back or removed; inspect " + f"{destination}." ) assert str(raised.value.__cause__) == "injected parent directory sync failure" assert sorted(path.name for path in destination.iterdir()) == ["winner.txt"] @@ -1162,7 +1162,7 @@ def test_published_no_replace_checkpoint_never_cleans_a_recreated_staging_path( destination, another_writer_recreates_the_staging_path, ) monkeypatch.setattr(persistence, "_sync_directory", sync) - with pytest.raises(RuntimeError, match="nothing was rolled back"): + with pytest.raises(RuntimeError, match="Nothing was rolled back or removed"): with persistence.atomic_checkpoint_directory( destination, replace_existing=False, ) as staging: @@ -1207,19 +1207,20 @@ def test_interrupted_no_replace_promotion_never_rolls_back_or_cleans_staging( raise _InterruptAfterRename() monkeypatch.setattr(persistence, "_rename_no_replace", rename_then_interrupt) - with pytest.raises(RuntimeError) as raised: + # A cancellation stays a cancellation: it is re-raised with the outcome as + # a note instead of being converted into a RuntimeError (#649). + with pytest.raises(_InterruptAfterRename) as raised: with persistence.atomic_checkpoint_directory(destination, replace_existing=False) as staging: (staging / "model.bin").write_bytes(b"ours") staging = seen["staging"] assert (destination / "model.bin").read_bytes() == b"ours" assert (staging / "theirs.txt").read_text(encoding="utf-8") == "other writer" - assert isinstance(raised.value.__cause__, _InterruptAfterRename) - assert str(raised.value) == ( + assert raised.value.__notes__ == [ f"Publishing the checkpoint to {destination} was interrupted, so it is unknown " f"whether it was published. Nothing was rolled back or removed; inspect " - f"{destination} and {staging}." - ) + f"{destination} and {staging}.", + ] def test_failed_no_replace_promotion_never_touches_a_foreign_destination(tmp_path, monkeypatch): @@ -1258,3 +1259,118 @@ def test_definite_no_replace_conflict_still_removes_unpublished_staging(tmp_path assert list(destination.iterdir()) == [] assert sorted(path.name for path in tmp_path.iterdir()) == [".checkpoint.lock", "checkpoint"] + + +# ── #649: cancellation, interrupted discovery publishing, fd-held staging cleanup ── + + +@pytest.mark.parametrize("interrupt", [KeyboardInterrupt, SystemExit]) +def test_cancelled_parent_sync_after_no_replace_publish_stays_a_cancellation( + tmp_path, monkeypatch, portable_no_replace_rename, interrupt, +): + destination = tmp_path / "checkpoint" + real_sync = persistence._sync_directory + + def cancel_after_promotion(path): + if path == destination.parent and (destination / "model.bin").is_file(): + raise interrupt() + real_sync(path) + + monkeypatch.setattr(persistence, "_sync_directory", cancel_after_promotion) + with pytest.raises(interrupt) as raised: + with persistence.atomic_checkpoint_directory(destination, replace_existing=False) as staging: + (staging / "model.bin").write_bytes(b"ours") + + assert raised.value.__notes__ == [ + f"Checkpoint was published to {destination}, but syncing {tmp_path} failed, so the " + f"rename may not survive a crash. Nothing was rolled back or removed; inspect " + f"{destination}.", + ] + assert (destination / "model.bin").read_bytes() == b"ours" + + +def test_exclusive_text_files_name_a_file_interrupted_mid_publish_as_maybe_published( + tmp_path, monkeypatch, +): + first = tmp_path / "config.json" + second = tmp_path / "report.json" + real_publish = persistence._publish_file_no_replace + + def publish_then_interrupt(temporary, destination): + real_publish(temporary, destination) + if destination == second: + raise KeyboardInterrupt() + + monkeypatch.setattr(persistence, "_publish_file_no_replace", publish_then_interrupt) + with pytest.raises(KeyboardInterrupt) as raised: + persistence.write_new_text_files({first: "config\n", second: "report\n"}) + + assert raised.value.__notes__ == [ + f"already published and left in place (the set may be incomplete): {first}; " + f"{second} may have been published and was left in place", + ] + assert second.read_text(encoding="utf-8") == "report\n" + + +def test_exclusive_text_files_name_a_lone_interrupted_file_as_maybe_published( + tmp_path, monkeypatch, +): + only = tmp_path / "config.json" + + def interrupted(_temporary, _destination): + raise KeyboardInterrupt() + + monkeypatch.setattr(persistence, "_publish_file_no_replace", interrupted) + with pytest.raises(KeyboardInterrupt) as raised: + persistence.write_new_text_files({only: "config\n"}) + assert raised.value.__notes__ == [f"{only} may have been published and was left in place"] + + +@pytest.mark.skipif( + not persistence.shutil.rmtree.avoids_symlink_attacks, + reason="no descriptor-based directory removal on this platform", +) +def test_definite_no_replace_refusal_never_cleans_a_recreated_staging_path( + tmp_path, monkeypatch, caplog, +): + destination = tmp_path / "checkpoint" + seen = {} + + def staging_recreated_then_refused(source, target): + # Another process deletes our staging directory, recreates the same + # name with its own data, and the rename is then definitely refused. + persistence.shutil.rmtree(source) + source.mkdir() + (source / "theirs.txt").write_text("other writer", encoding="utf-8") + seen["staging"] = source + target.mkdir() + raise FileExistsError(17, "File exists", str(target)) + + monkeypatch.setattr(persistence, "_rename_no_replace", staging_recreated_then_refused) + with pytest.raises(FileExistsError, match="already exists"): + with persistence.atomic_checkpoint_directory(destination, replace_existing=False) as staging: + (staging / "model.bin").write_bytes(b"ours") + + assert (seen["staging"] / "theirs.txt").read_text(encoding="utf-8") == "other writer" + assert any("no longer names" in message for message in caplog.messages) + + +@pytest.mark.skipif( + not persistence.shutil.rmtree.avoids_symlink_attacks, + reason="no descriptor-based directory removal on this platform", +) +def test_failed_staging_cleanup_removes_nested_contents_through_the_held_directory(tmp_path): + destination = tmp_path / "checkpoint" + outside = tmp_path / "outside" + outside.mkdir() + (outside / "sentinel").write_text("preserve", encoding="utf-8") + with pytest.raises(OSError, match="injected write failure"): + with persistence.atomic_checkpoint_directory(destination) as staging: + (staging / "nested" / "deeper").mkdir(parents=True) + (staging / "nested" / "deeper" / "shard.bin").write_bytes(b"partial") + (staging / "link").symlink_to(outside, target_is_directory=True) + raise OSError("injected write failure") + + assert not staging.exists() + assert (outside / "sentinel").read_text(encoding="utf-8") == "preserve" + assert sorted(path.name for path in tmp_path.iterdir()) == ["outside"] diff --git a/tests/test_strategies.py b/tests/test_strategies.py index 5906de8a..274341ff 100644 --- a/tests/test_strategies.py +++ b/tests/test_strategies.py @@ -604,6 +604,7 @@ class TestVocabSurgery: with pytest.raises(ValueError, match="embeddings are tied"): strat.apply_all(handle, config=vs_config) + # An ID-only row against a mock tokenizer that cannot be fingerprinted. summary = strat.apply_all(handle, config=VocabSurgeryConfig( include_defaults=False, allow_tied_output_edit=True, @@ -613,7 +614,7 @@ class TestVocabSurgery: "input_alpha": 0.0, "label": "explicit shared row edit", }], - )) + ), allow_unpinned_id_operations=True) assert summary["weights_tied"] is True assert summary["embed_rows_modified"] == 0 assert summary["unembed_rows_modified"] == 1 diff --git a/tests/test_vocab_surgery.py b/tests/test_vocab_surgery.py index 49e4091b..545a9479 100644 --- a/tests/test_vocab_surgery.py +++ b/tests/test_vocab_surgery.py @@ -55,6 +55,15 @@ class TinyTokenizer: return reverse[token_ids[0]] +def _apply_unpinned(handle, config=None, **kwargs): + """Apply edits whose ID-only rows these fixtures cannot pin (tokenizers without + a fingerprintable vocabulary), opting in as ``--allow-unpinned-id-operations`` does. + """ + return VocabSurgeryStrategy().apply_all( + handle, config, allow_unpinned_id_operations=True, **kwargs, + ) + + def test_discovery_uses_control_lift_and_builds_editable_config(): tokenizer = TinyTokenizer() candidates = discover_tokens_from_responses( @@ -320,7 +329,7 @@ def test_overlapping_input_rows_swap_from_the_same_snapshot(reverse): {"source_id": source, "target_id": target, "input_alpha": 1.0, "output_scale": None} for source, target in [(7, 8), (8, 7)] ] - VocabSurgeryStrategy().apply_all(handle, {"operations": operations[::-1] if reverse else operations}) + _apply_unpinned(handle, {"operations": operations[::-1] if reverse else operations}) expected = before.clone() expected[[7, 8]] = before[[8, 7]] assert torch.equal(handle.model.get_input_embeddings().weight, expected) @@ -414,7 +423,7 @@ def test_bfloat16_dtype_is_preserved(): handle = _make_vocab_surgery_handle() handle.model.to(torch.bfloat16) before_dtype = handle.model.lm_head.weight.dtype - receipt = VocabSurgeryStrategy().apply_all(handle, VocabSurgeryConfig( + receipt = _apply_unpinned(handle, VocabSurgeryConfig( include_defaults=False, operations=[{ "source": "cannot", "target": "can", @@ -466,7 +475,7 @@ def test_offloaded_embedding_and_output_rows_use_authoritative_backing_maps(): model_name="tiny-offloaded", task="causal_lm", ) - receipt = VocabSurgeryStrategy().apply_all(handle, VocabSurgeryConfig( + receipt = _apply_unpinned(handle, VocabSurgeryConfig( include_defaults=False, operations=[{ "source_id": 1, @@ -613,9 +622,9 @@ def test_disk_offloaded_tied_weights_enforce_tie_policy(tmp_path, layout): strategy = VocabSurgeryStrategy() with pytest.raises(ValueError, match="tied"): - strategy.apply_all(handle, {"operations": [{"source_id": 3, "output_scale": 0.5}]}) + _apply_unpinned(handle, {"operations": [{"source_id": 3, "output_scale": 0.5}]}) with pytest.raises(ValueError, match="tied"): - strategy.apply_all(handle, {"operations": [{ + _apply_unpinned(handle, {"operations": [{ "source_id": 3, "target_id": 4, "output_scale": None, "input_alpha": 0.5, }]}) for module in (embed, head): @@ -647,7 +656,7 @@ def test_offloaded_tie_status_that_cannot_be_established_fails_closed(tmp_path): handle, embed, head = _offloaded_tied_handle(tmp_path, "per_module", declare_tie=False) original = _logical(head, handle.model) with pytest.raises(ValueError, match="cannot establish"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -663,10 +672,10 @@ def test_offloaded_config_declared_tie_without_metadata_enforces_policy(tmp_path tmp_path, "per_module", declare_tie=False, config=config, ) with pytest.raises(ValueError, match="tied"): - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 3, "output_scale": 0.5}, ]}) - receipt = VocabSurgeryStrategy().apply_all(handle, { + receipt = _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) assert receipt["tensors"]["tied"] is True @@ -680,7 +689,7 @@ def test_offloaded_declared_tie_with_divergent_values_fails_closed(tmp_path): transaction = resolve_logical_parameter(head, search_roots=(handle.model,)) transaction.commit(transaction.tensor + 1) with pytest.raises(Exception, match="disagree"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -774,7 +783,7 @@ def test_over_budget_resident_edit_is_refused_before_any_write(): handle = _make_vocab_surgery_handle() before = handle.model.lm_head.weight.detach().clone() with pytest.raises(ValueError, match="edit memory budget"): - VocabSurgeryStrategy().apply_all( + _apply_unpinned( handle, {"operations": [{"source_id": 100, "output_scale": 0.5}]}, edit_memory_bytes=16, ) assert torch.equal(handle.model.lm_head.weight, before) @@ -788,10 +797,10 @@ def test_default_edit_budget_uses_available_host_memory(monkeypatch): config = {"operations": [{"source_id": 100, "output_scale": 0.5}]} monkeypatch.setattr(vocab_surgery, "available_host_bytes", lambda: 64) with pytest.raises(ValueError, match="host fraction"): - VocabSurgeryStrategy().apply_all(handle, config) + _apply_unpinned(handle, config) assert torch.equal(handle.model.lm_head.weight, before) monkeypatch.setattr(vocab_surgery, "available_host_bytes", lambda: 1024**3) - receipt = VocabSurgeryStrategy().apply_all(handle, config) + receipt = _apply_unpinned(handle, config) assert receipt["unembed_rows_modified"] == 1 @@ -837,7 +846,7 @@ def test_over_budget_offloaded_edit_is_refused_before_full_matrix_commit(tmp_pat lambda self, value: commits.append(value)) monkeypatch.setattr(offload_surgery._WriteTarget, "read", recording_read) with pytest.raises(ValueError, match="edit memory budget"): - VocabSurgeryStrategy().apply_all( + _apply_unpinned( handle, {"operations": [{"source_id": 3, "output_scale": 0.5}]}, edit_memory_bytes=matrix_bytes, ) @@ -852,7 +861,7 @@ def test_over_budget_offloaded_edit_is_refused_before_full_matrix_commit(tmp_pat def test_edit_memory_budget_must_be_a_positive_integer(value): handle = _make_vocab_surgery_handle() with pytest.raises(ValueError, match="edit_memory_bytes"): - VocabSurgeryStrategy().apply_all( + _apply_unpinned( handle, {"operations": [{"source_id": 100, "output_scale": 0.5}]}, edit_memory_bytes=value, ) @@ -974,7 +983,7 @@ def test_settled_untied_mixed_placement_never_compares_matrix_values(tmp_path, m head_before = _logical(model.head, model) embed_before = model.embed.weight.detach().clone() monkeypatch.setattr(torch, "equal", device_strict_equal) - receipt = VocabSurgeryStrategy().apply_all(handle, _UNTIED_EDIT) + receipt = _apply_unpinned(handle, _UNTIED_EDIT) _assert_untied_edit(handle, model, receipt, head_before, embed_before) @@ -994,7 +1003,7 @@ def test_undetermined_tie_compares_values_in_bounded_cpu_chunks(tmp_path, monkey return real_equal(a, b) monkeypatch.setattr(torch, "equal", recording_equal) - receipt = VocabSurgeryStrategy().apply_all(handle, _UNTIED_EDIT) + receipt = _apply_unpinned(handle, _UNTIED_EDIT) monkeypatch.undo() assert calls, "undetermined tie status must be settled by comparing values" for shape, device_a, device_b in calls: @@ -1019,7 +1028,7 @@ def test_tie_metadata_that_omits_the_pair_overrides_a_tied_top_level_flag(tmp_pa ) head_before = _logical(model.head, model) embed_before = _logical(model.embed, model) - receipt = VocabSurgeryStrategy().apply_all(handle, _UNTIED_EDIT) + receipt = _apply_unpinned(handle, _UNTIED_EDIT) _assert_untied_edit(handle, model, receipt, head_before, embed_before) @@ -1027,19 +1036,19 @@ def test_composite_config_untied_at_both_levels_edits_as_untied(tmp_path): handle, model = _pair_handle(tmp_path, ties={}, config=_composite_config(top=False, text=False)) head_before = _logical(model.head, model) embed_before = _logical(model.embed, model) - receipt = VocabSurgeryStrategy().apply_all(handle, _UNTIED_EDIT) + receipt = _apply_unpinned(handle, _UNTIED_EDIT) _assert_untied_edit(handle, model, receipt, head_before, embed_before) def _assert_refused_then_shared_tied_edit(model, handle): original = _logical(model.head, model) with pytest.raises(ValueError, match="tied"): - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 3, "output_scale": 0.5}, ]}) for module in (model.embed, model.head): assert torch.equal(_logical(module, model), original) - receipt = VocabSurgeryStrategy().apply_all(handle, { + receipt = _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) assert receipt["tensors"]["tied"] is True @@ -1109,7 +1118,7 @@ def test_link_bearing_tie_map_that_never_mentions_the_pair_is_undetermined(tmp_p handle, model = _wrapped_pair_handle(tmp_path, {"aux.weight": "other.weight"}) original = _logical(model.head, model) with pytest.raises(ValueError, match="cannot establish"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -1123,12 +1132,12 @@ def test_composite_text_config_tied_overrides_untied_top_level_flag(tmp_path): ) original = _logical(model.head, model) with pytest.raises(ValueError, match="tied"): - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 3, "output_scale": 0.5}, ]}) for module in (model.embed, model.head): assert torch.equal(_logical(module, model), original) - receipt = VocabSurgeryStrategy().apply_all(handle, { + receipt = _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) assert receipt["tensors"]["tied"] is True @@ -1142,7 +1151,7 @@ def test_head_owning_submodel_config_precedes_composite_flags(tmp_path): ) head_before = _logical(model.head, model) embed_before = _logical(model.embed, model) - receipt = VocabSurgeryStrategy().apply_all(handle, _UNTIED_EDIT) + receipt = _apply_unpinned(handle, _UNTIED_EDIT) _assert_untied_edit(handle, model, receipt, head_before, embed_before) @@ -1152,7 +1161,7 @@ def test_pair_tie_metadata_overrides_untied_config_flags(tmp_path): config=_composite_config(top=False, text=False), ) with pytest.raises(ValueError, match="tied"): - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 3, "output_scale": 0.5}, ]}) @@ -1163,7 +1172,7 @@ def test_flag_declared_tie_with_divergent_offloaded_values_fails_closed(tmp_path head_before = _logical(model.head, model) embed_before = _logical(model.embed, model) with pytest.raises(Exception, match="disagree"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -1175,7 +1184,7 @@ def test_empty_tie_metadata_without_flag_is_undetermined(tmp_path): handle, model = _pair_handle(tmp_path, identical=True, ties={}) original = _logical(model.head, model) with pytest.raises(ValueError, match="cannot establish"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -1211,7 +1220,7 @@ def test_resident_second_matrix_commit_failure_restores_both_matrices(monkeypatc # and fails; call 3 restores them; call 4 rolls back the output rows. state = _failing_index_copy(monkeypatch, fail_calls={2}) with pytest.raises(RuntimeError, match="injected index_copy_ failure 2"): - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 100, "target_id": 112, "output_scale": 0.5, "input_alpha": 0.5}, ]}) monkeypatch.undo() @@ -1231,7 +1240,7 @@ def test_resident_row_rollback_failure_marks_model_invalid(monkeypatch): # rolls the already-committed output rows back. _failing_index_copy(monkeypatch, fail_calls={2, 3}) with pytest.raises(OffloadRollbackError, match="rollback incomplete") as raised: - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 100, "target_id": 112, "output_scale": 0.5, "input_alpha": 0.5}, ]}) monkeypatch.undo() @@ -1240,7 +1249,7 @@ def test_resident_row_rollback_failure_marks_model_invalid(monkeypatch): assert model._obliteratus_surgery_invalid is True assert torch.equal(model.lm_head.weight, output_before) with pytest.raises(OffloadRollbackError, match="invalid"): - VocabSurgeryStrategy().apply_all(handle, {"operations": [ + _apply_unpinned(handle, {"operations": [ {"source_id": 100, "output_scale": 0.5}, ]}) @@ -1311,7 +1320,7 @@ def test_tie_metadata_naming_an_embedding_alias_links_the_pair(tmp_path): def test_tie_map_naming_only_one_side_of_the_pair_is_undetermined(tmp_path): handle, model = _pair_handle(tmp_path, identical=True, ties={"lm_head.weight": "aux.weight"}) with pytest.raises(ValueError, match="cannot establish"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -1338,7 +1347,7 @@ def test_identical_matrices_with_nan_rows_are_not_read_as_untied(tmp_path): model_name="tiny-nan", task="causal_lm") head_before = model.head.weight.detach().clone() with pytest.raises(ValueError, match="cannot establish"): - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -2360,7 +2369,7 @@ def test_tied_offloaded_commit_failing_on_the_second_alias_restores_both(tmp_pat monkeypatch.setattr(offload_surgery._WriteTarget, "write", failing_write) with pytest.raises(Exception, match="rolled back") as raised: - VocabSurgeryStrategy().apply_all(handle, { + _apply_unpinned(handle, { "operations": [{"source_id": 3, "output_scale": 0.5}], "allow_tied_output_edit": True, }) @@ -2373,3 +2382,73 @@ def test_tied_offloaded_commit_failing_on_the_second_alias_restores_both(tmp_pat for module in (embed, head): assert torch.equal(_logical(module, handle.model), original) assert not getattr(handle.model, "_obliteratus_surgery_invalid", False) + + +# ── #649 / #655 follow-ups: ID-only guard inside apply_all, silent-owner alias ── + + +def test_apply_all_enforces_the_id_only_guard_itself(): + from obliteratus.models.loader import ModelHandle + + model = _PairModel() + handle = ModelHandle(model=model, tokenizer=TinyTokenizer(), + config=SimpleNamespace(model_type="tiny", vocab_size=8), + model_name="tiny-pair", task="causal_lm") + before = model.head.weight.detach().clone() + edit = {"operations": [{"source_id": 3, "output_scale": 0.5}]} + # A direct caller that skipped authorization still cannot edit rows chosen + # only by ID against an unverified tokenizer. + with pytest.raises(ValueError, match="ID-only operation"): + VocabSurgeryStrategy().apply_all(handle, edit) + assert torch.equal(model.head.weight, before) + + receipt = VocabSurgeryStrategy().apply_all(handle, edit, allow_unpinned_id_operations=True) + assert receipt["id_only_operation_guard"]["status"] == "unpinned_allowed" + assert receipt["id_only_operation_guard"]["allow_unpinned_id_operations"] is True + torch.testing.assert_close(model.head.weight[3], before[3] * 0.5) + + +class _SilentOwnerAliasModel(torch.nn.Module): + """A head under sub-model A (no tie flag) and sub-model B (untied); top says tied.""" + + def __init__(self): + super().__init__() + torch.manual_seed(0) + self.embed = torch.nn.Embedding(8, 4) + head = torch.nn.Linear(4, 8, bias=False) + with torch.no_grad(): + head.weight.copy_(self.embed.weight) + self.silent = torch.nn.Module() + self.silent.config = SimpleNamespace(model_type="silent") + self.silent.lm_head = head + self.untied = torch.nn.Module() + self.untied.config = SimpleNamespace(tie_word_embeddings=False) + self.untied.lm_head = head + self.config = SimpleNamespace(model_type="tiny", vocab_size=8, tie_word_embeddings=True) + + @property + def head(self): + return self.silent.lm_head + + def get_input_embeddings(self): + return self.embed + + def get_output_embeddings(self): + return self.silent.lm_head + + +def test_silent_owner_alias_path_takes_the_top_level_tie_flag(tmp_path): + from accelerate.big_modeling import disk_offload + + from obliteratus.models.loader import ModelHandle + from obliteratus.strategies.vocab_surgery import _config_tie_flag + + model = _SilentOwnerAliasModel() + handle = ModelHandle(model=model, tokenizer=TinyTokenizer(), config=model.config, + model_name="tiny-silent-owner", task="causal_lm") + # Path A's owner declares nothing, so it falls back to the top-level flag + # like a root-owned path; that tied flag must win over B's untied one. + assert _config_tie_flag(handle, model.head) is True + disk_offload(model.embed, tmp_path / "embed", execution_device=torch.device("cpu")) + disk_offload(model.head, tmp_path / "head", execution_device=torch.device("cpu")) + _assert_refused_then_shared_tied_edit(model, handle)