Files
OBLITERATUS/obliteratus/experiments/inputs.py
Joseph Magly 8bdd844e09 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
2026-11-25 13:45:14 -05:00

153 lines
7.4 KiB
Python

"""Resolve spec inputs and refuse models that carry intervention state.
A baseline observation must run on an unmodified model. Any registered module
hook (global or per-module), a surgery marker, or adapter state other than
``none`` (or a known PEFT state with every adapter disabled or inactive) is
refused before anything is generated.
"""
from types import SimpleNamespace
from obliteratus.analysis.capture_identity import (
adapter_identity, capture_tokenizer_identity, checkpoint_identity, parameter_dtype,
require_dense_device, weight_fingerprint,
)
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",
"_global_backward_hooks", "_global_backward_pre_hooks")
class InterventionStateRefused(ValueError):
"""The model carries hooks, surgery markers or adapter state a baseline must not inherit."""
def require_unmodified(model):
"""Return the adapter identity of a hook-free, unmodified model or refuse it."""
from torch.nn.modules import module as torch_module
for name in _GLOBAL_HOOKS:
if getattr(torch_module, name, None):
raise InterventionStateRefused(f"Global module hooks are registered ({name})")
for path, module in model.named_modules():
for attr in _MODULE_HOOKS:
if getattr(module, attr, None):
raise InterventionStateRefused(
f"Module {path or '<root>'} has registered {attr.strip('_')}; a baseline "
"cannot run with intervention or observer hooks attached")
if getattr(model, "_obliteratus_surgery_invalid", False):
raise InterventionStateRefused("Model is marked as modified by an interrupted surgery")
adapter = adapter_identity(model)
if adapter["state"] == "none":
return adapter
if adapter["state"] == "peft" and (adapter["disabled"]
or not any(a["active"] for a in adapter["adapters"])):
return adapter
raise InterventionStateRefused(
f"Adapter state {adapter['state']!r} is not a baseline: "
f"{adapter.get('reason', 'active adapters are enabled')}")
def default_pack_resolver(ref):
from obliteratus.concepts.cli import _resolve
return _resolve(ref)
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. 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":
try:
handle.model.to(model["device"])
except BaseException as error:
cleanup_during_error(handle, error)
raise
return handle
def resolve_dataset(spec, pack_resolver):
"""Resolve the pack, verify pinned identities and build the scoring tasks."""
reference = spec["dataset"]
pack = (pack_resolver or default_pack_resolver)(reference["pack"])
if reference["pack_sha256"] is not None and pack.sha256 != reference["pack_sha256"]:
raise SpecError(f"Pack sha256 {pack.sha256} differs from the spec's pinned pack")
dataset = pack.dataset()
if dataset.revision != reference["revision"]:
raise SpecError(f"Dataset revision {dataset.revision} differs from the spec; "
"write a new spec for changed data")
tasks = []
for item in spec["tasks"]:
examples, receipt = examples_from_dataset(
dataset, reference["role"], item["target_field"], path=item["path"],
allow_locked_test=reference["allow_locked_test"])
scorer = ScorerSpec(item["scorer"]["id"], item["scorer"]["version"])
tasks.append(ScoringTask(item["name"], scorer, examples, source=receipt))
summary = {"pack": {"ref": reference["pack"], "sha256": pack.sha256},
"revision": dataset.revision, "content_digest": dataset.content_digest,
"partition_digest": dataset.partition_digest, "role": reference["role"],
"locked_test_acknowledged": reference["role"] == "test"}
return dataset, tasks, summary
def model_identity(spec, model, tokenizer, adapter, *, weight_digest=None):
"""Verify dense execution on the spec's device, dtype and revision; return the identity.
The identity records the realized device (``cpu`` or ``cuda:N``) and a
weight fingerprint, so weights edited in place under the same id and
revision give a different identity. ``sampled`` mode (the default) only
detects edits that touch a sampled element; ``full`` hashes every element.
The mode comes from ``model.fingerprint`` in the spec unless overridden.
"""
device = require_dense_device(model, spec["model"].get("device", "cpu"))
dtype = parameter_dtype(model)
if dtype != spec["model"]["dtype"]:
raise SpecError(f"Loaded model dtype {dtype} differs from spec dtype {spec['model']['dtype']}")
ident = checkpoint_identity(model, spec["model"]["id"], dtype)
pinned = spec["model"]["revision"]
if pinned is not None and ident["model_revision"] != pinned:
raise SpecError(f"Loaded model revision {ident['model_revision']} differs from {pinned}")
mode = weight_digest or spec["model"].get("fingerprint", "sampled")
return {"checkpoint": ident, "tokenizer": capture_tokenizer_identity(tokenizer),
"adapter": adapter, "device": device,
"weights": weight_fingerprint(model, mode=mode)}
def execution_identity(spec, model, tokenizer, adapter):
"""The observed model identity on the spec's device (same as ``model_identity``)."""
return model_identity(spec, model, tokenizer, adapter)
def capture_sites(model, indices):
"""Map spec layer indices to decoder layer modules."""
from obliteratus.strategies.utils import get_layer_modules
config = getattr(model, "config", None)
handle = SimpleNamespace(model=model, architecture=getattr(config, "model_type", None),
num_layers=getattr(config, "num_hidden_layers", None))
layers = get_layer_modules(handle)
if any(index >= len(layers) for index in indices):
raise SpecError(f"Capture site outside the model's {len(layers)} decoder layers")
return {f"layer.{index}": layers[index] for index in indices}
def encode(tokenizer, prompt, add_special_tokens=True):
"""One unpadded prompt as model inputs (``input_ids`` and ``attention_mask``).
``add_special_tokens=False`` is passed only for text that already carries
its special tokens (a rendered chat template).
"""
import torch
extra = {} if add_special_tokens else {"add_special_tokens": False}
encoded = tokenizer(prompt, return_tensors="pt", **extra)
ids = encoded["input_ids"]
mask = encoded.get("attention_mask") if hasattr(encoded, "get") else None
return {"input_ids": ids, "attention_mask": torch.ones_like(ids) if mask is None else mask}