Files
OBLITERATUS/tests/test_external_directions.py
Joseph Magly 70c9fc041a fix(directions): require a declared norm kind and matching prompt counts
Refuses to overwrite an existing output and documents row and strength semantics.
2026-12-02 09:41:01 -05:00

186 lines
10 KiB
Python

"""CPU contracts for model-free external capture distillation."""
import hashlib
import json
import subprocess
import sys
import pytest
import torch
from safetensors.torch import load_file, save_file
from obliteratus.external_directions import distill
def capture(tmp_path, *, include_final=False):
path = tmp_path / "capture"
path.mkdir()
harmful = torch.tensor([[9., 0.], [3., 4.], [0., 2.], [1., 1.]])
if not include_final:
harmful = harmful[:3]
rows = len(harmful)
tensors = {"harmful_mean": harmful, "harmless_mean": torch.zeros_like(harmful),
"harmful_count": torch.full((rows,), 2, dtype=torch.int64),
"harmless_count": torch.full((rows,), 3, dtype=torch.int64)}
manifest = {"schema": "obliteratus.engine_capture.v1", "model_path": "model", "model_revision": "rev",
"engine": "vllm", "engine_version": "v1", "tensor_parallel_size": 1,
"num_layers": 3, "hidden_size": 2, "num_experts": None,
"position": "last_prompt_token", "include_final": include_final,
"harmful_prompts_sha256": "a" * 64, "harmless_prompts_sha256": "b" * 64,
"n_harmful": 2, "n_harmless": 3, "created_utc": "2026-01-01T00:00:00Z"}
write_capture(path, tensors, manifest)
return path, tensors, manifest
def write_capture(path, tensors, manifest):
save_file(tensors, str(path / "capture.safetensors"))
manifest["capture_sha256"] = hashlib.sha256((path / "capture.safetensors").read_bytes()).hexdigest()
(path / "capture.json").write_text(json.dumps(manifest))
def test_round_trip_cli_and_analytic_directions(tmp_path):
source, _, manifest = capture(tmp_path)
out = tmp_path / "out"
subprocess.run([sys.executable, "-m", "obliteratus.external_directions", "--capture", str(source),
"--out", str(out)], check=True)
result = json.loads((out / "directions.json").read_text())
tensors = load_file(str(out / "directions.safetensors"))
assert result["source_capture_manifest"] == manifest
assert result["source_capture_sha256"] == manifest["capture_sha256"]
assert result["identity"] == "external-capture-manifest-bound"
assert result["schema"] == "obliteratus.directions.v1"
assert result["method"] == "diff_in_means"
assert result["directions_sha256"] == hashlib.sha256((out / "directions.safetensors").read_bytes()).hexdigest()
assert result["selected_layers"] == [1, 2]
torch.testing.assert_close(tensors["strength"], torch.tensor([9., 5., 2.]))
torch.testing.assert_close(tensors["direction"], torch.tensor([[0., 0.], [0.6, 0.8], [0., 1.]]))
torch.testing.assert_close(tensors["direction"][1:].norm(dim=1), torch.ones(2))
def test_selection_and_final_row(tmp_path):
source, _, _ = capture(tmp_path, include_final=True)
assert distill(source, tmp_path / "top", top_k=1)["selected_layers"] == [1]
assert distill(source, tmp_path / "explicit", layers=[0, 3], min_strength=2)["selected_layers"] == [0]
assert distill(source, tmp_path / "final", layers=[3])["selected_layers"] == [3]
with pytest.raises(ValueError, match="no nonzero"):
distill(source, tmp_path / "none", min_strength=100)
with pytest.raises(ValueError, match="invalid layer"):
distill(source, tmp_path / "bad", layers=[4])
@pytest.mark.parametrize("problem", ["digest", "schema", "zero", "nan", "shape", "dtype"])
def test_reject_invalid_capture(tmp_path, problem):
source, tensors, manifest = capture(tmp_path)
if problem == "digest":
manifest["capture_sha256"] = "0" * 64
(source / "capture.json").write_text(json.dumps(manifest))
elif problem == "schema":
manifest["schema"] = "wrong"
(source / "capture.json").write_text(json.dumps(manifest))
else:
if problem == "zero":
tensors["harmful_count"][0] = 0
elif problem == "nan":
tensors["harmless_mean"][0, 0] = float("nan")
elif problem == "shape":
tensors["harmful_mean"] = tensors["harmful_mean"][:2]
else:
tensors["harmful_count"] = tensors["harmful_count"].int()
write_capture(source, tensors, manifest)
with pytest.raises(ValueError):
distill(source, tmp_path / "out")
assert not (tmp_path / "out").exists()
def test_router_counts_and_unspecified_revision(tmp_path):
source, tensors, manifest = capture(tmp_path, include_final=True)
manifest["num_experts"] = 2
manifest["model_revision"] = None
tensors["router_counts_harmful"] = torch.zeros((3, 2), dtype=torch.int64)
tensors["router_counts_harmless"] = torch.zeros((3, 2), dtype=torch.int64)
write_capture(source, tensors, manifest)
assert distill(source, tmp_path / "out")["source_capture_manifest"] == manifest
def test_normalized_capture_divides_by_norm_weight(tmp_path):
import json as _json
import hashlib as _hl
import torch as _torch
from safetensors.torch import save as _save
from obliteratus.external_directions import distill as _distill
rows, hidden = 3, 4
weight = _torch.tensor([[1.0, 2.0, 4.0, 0.5]] * rows)
harmless = _torch.zeros(rows, hidden)
raw = _torch.tensor([0.0, 1.0, 0.0, 0.0]) # residual-space difference along channel 1
harmful = (raw * weight[0]).repeat(rows, 1) # what a normalized capture would see
data = _save({"harmful_mean": harmful, "harmless_mean": harmless,
"harmful_count": _torch.ones(rows, dtype=_torch.int64),
"harmless_count": _torch.ones(rows, dtype=_torch.int64), "norm_weight": weight})
cap = tmp_path / "cap"; cap.mkdir(); (cap / "capture.safetensors").write_bytes(data)
manifest = {"schema": "obliteratus.engine_capture.v1", "model_path": "m", "model_revision": None, "engine": "vllm",
"engine_version": "x", "tensor_parallel_size": 1, "num_layers": rows, "hidden_size": hidden,
"num_experts": None, "position": "last_prompt_token", "include_final": False,
"representation": "attn_input_normalized", "norm_kind": "rmsnorm_scale", "harmful_prompts_sha256": "0" * 64,
"harmless_prompts_sha256": "0" * 64, "n_harmful": 1, "n_harmless": 1,
"capture_sha256": _hl.sha256(data).hexdigest(), "created_utc": "2026-12-01T00:00:00Z"}
(cap / "capture.json").write_text(_json.dumps(manifest))
result = _distill(cap, tmp_path / "out", layers=[1])
from safetensors.torch import load_file as _load
direction = _load(str(tmp_path / "out" / "directions.safetensors"))["direction"][1]
assert _torch.allclose(direction, raw / raw.norm(), atol=1e-6)
assert result["selected_layers"] == [1]
manifest["representation"] = "residual"
(cap / "capture.json").write_text(_json.dumps(manifest))
import pytest as _pytest
with _pytest.raises(ValueError, match="norm_weight"):
_distill(cap, tmp_path / "out2", layers=[1])
def test_normalized_capture_masks_near_zero_norm_weight(tmp_path):
from safetensors.torch import save
from obliteratus.external_directions import NORM_WEIGHT_MASK_THRESHOLD
rows, hidden = 2, 4
weight = torch.tensor([[1.0, 2.0, 0.0, 6.9e-7], [1.0, 1.0, 1.0, 1.0]])
harmful = torch.tensor([[0.0, 2.0, 5.0, 3.0], [1.0, 0.0, 0.0, 0.0]])
harmless = torch.tensor([[0.0, 0.0, 9.0, -8.0], [0.0, 0.0, 0.0, 0.0]])
data = save({"harmful_mean": harmful, "harmless_mean": harmless,
"harmful_count": torch.ones(rows, dtype=torch.int64),
"harmless_count": torch.ones(rows, dtype=torch.int64), "norm_weight": weight})
cap = tmp_path / "cap"
cap.mkdir()
(cap / "capture.safetensors").write_bytes(data)
manifest = {"schema": "obliteratus.engine_capture.v1", "model_path": "m", "model_revision": None,
"engine": "vllm", "engine_version": "x", "tensor_parallel_size": 1, "num_layers": rows,
"hidden_size": hidden, "num_experts": None, "position": "last_prompt_token",
"include_final": False, "representation": "attn_input_normalized", "norm_kind": "rmsnorm_scale",
"harmful_prompts_sha256": "0" * 64, "harmless_prompts_sha256": "0" * 64,
"n_harmful": 1, "n_harmless": 1, "capture_sha256": hashlib.sha256(data).hexdigest(),
"created_utc": "2026-12-01T00:00:00Z"}
(cap / "capture.json").write_text(json.dumps(manifest))
for kind in (None, "one_plus_weight"):
(cap / "capture.json").write_text(json.dumps(dict(manifest, norm_kind=kind)))
with pytest.raises(ValueError, match="norm_kind"):
distill(cap, tmp_path / "out", layers=[0, 1])
(cap / "capture.json").write_text(json.dumps(dict(manifest, n_harmful=5)))
with pytest.raises(ValueError, match="prompt count"):
distill(cap, tmp_path / "out", layers=[0, 1])
(cap / "capture.json").write_text(json.dumps(manifest))
result = distill(cap, tmp_path / "out", layers=[0, 1])
with pytest.raises(FileExistsError):
distill(cap, tmp_path / "out", layers=[0, 1])
direction = load_file(str(tmp_path / "out" / "directions.safetensors"))["direction"]
assert torch.equal(direction[0], torch.tensor([0.0, 1.0, 0.0, 0.0]))
assert torch.isfinite(direction).all()
assert result["norm_weight_mask"] == {"threshold": NORM_WEIGHT_MASK_THRESHOLD, "masked_total": 2,
"masked_by_row": {"0": [2, 3]}}
assert json.loads((tmp_path / "out" / "directions.json").read_text())["norm_weight_mask"]["masked_total"] == 2
bad = weight.clone()
bad[1, 0] = float("nan")
data = save({"harmful_mean": harmful, "harmless_mean": torch.zeros(rows, hidden),
"harmful_count": torch.ones(rows, dtype=torch.int64),
"harmless_count": torch.ones(rows, dtype=torch.int64), "norm_weight": bad})
(cap / "capture.safetensors").write_bytes(data)
manifest["capture_sha256"] = hashlib.sha256(data).hexdigest()
(cap / "capture.json").write_text(json.dumps(manifest))
with pytest.raises(ValueError, match="norm_weight"):
distill(cap, tmp_path / "out2", layers=[1])