modelclinic-experiment-001 / code /tests /test_gate_controls.py
PratikBuilds's picture
Publish initial ModelClinic Experiment 001 archive
87cc7f2 verified
Raw History Blame Contribute Delete
8.47 kB
import pytest
import torch
import torch.nn.functional as F
from unittest.mock import patch
from src.gate_controls import (
adjustment,
calibrate_layer,
calibrate_direction,
coefficient_grid,
controller_grid,
decompose,
fit_signed_constant,
install_vllm_hooks,
make_output_hook,
read_vllm_hook_stats,
remove_vllm_hooks,
select_behavioral_controller,
)
def test_rank_one_reconstruction_and_activation_gate():
torch.manual_seed(7)
delta = torch.randn(4, 1) @ torch.randn(1, 6)
direction, gate_vector = decompose(delta)
x = torch.randn(2, 3, 6)
actual = adjustment(x, direction, gate_vector=gate_vector)
expected = F.linear(x, direction[:, None] @ gate_vector[None, :])
torch.testing.assert_close(actual, expected, atol=2e-6, rtol=2e-6)
def test_decompose_has_deterministic_sign_and_scaled_gate():
# The largest-magnitude left entry is deliberately negative.
left = torch.tensor([-0.8, 0.6])
right = torch.tensor([2.0, -3.0, 1.5])
delta = left[:, None] @ right[None, :]
direction, gate_vector = decompose(delta)
assert direction[direction.abs().argmax()] > 0
torch.testing.assert_close(direction[:, None] @ gate_vector[None, :], delta, atol=1e-6, rtol=1e-6)
torch.testing.assert_close(decompose(delta)[0], direction)
def test_signed_constant_is_mean_projection_and_changes_sign_consistently():
torch.manual_seed(11)
delta = torch.randn(5, 7)
x = torch.randn(2, 4, 7)
direction, coefficient = fit_signed_constant(delta, x)
effects = F.linear(x.reshape(-1, 7), delta)
expected = (effects @ direction).mean()
assert coefficient == pytest.approx(float(expected), abs=1e-7)
assert torch.linalg.vector_norm(direction).item() == pytest.approx(1.0, abs=1e-6)
opposite, opposite_coefficient = fit_signed_constant(delta, x, direction=-direction)
torch.testing.assert_close(opposite, direction)
assert opposite_coefficient == pytest.approx(coefficient, abs=1e-7)
def test_signed_constant_can_weight_prompt_means_equally():
delta = torch.ones(1, 1)
prompts = [torch.tensor([[-1.0], [-1.0], [-1.0]]), torch.tensor([[2.0]])]
_, token_mean = fit_signed_constant(delta, prompts, prompt_weighting="token")
_, prompt_mean = fit_signed_constant(delta, prompts, prompt_weighting="prompt")
assert token_mean == pytest.approx(-0.25)
assert prompt_mean == pytest.approx(0.5)
def test_independent_direction_calibration_does_not_infer_a_published_gate():
delta = torch.eye(2)
prompts = [torch.tensor([[1.0, 0.0]]), torch.tensor([[0.0, 3.0], [0.0, 1.0]])]
summary = calibrate_direction(
delta, prompts, torch.tensor([0.0, -2.0]), prompt_weighting="prompt"
)
assert summary["direction"] == [0.0, 1.0]
assert summary["signed_mean_coefficient"] == pytest.approx(1.0)
assert "rank1_gate_vector" not in summary
assert summary["calibration_prompts"] == 2
def test_constant_adjustment_broadcasts_across_tokens_and_preserves_dtype():
x = torch.randn(2, 3, 4, dtype=torch.bfloat16)
direction = torch.tensor([1.0, -2.0, 0.5], dtype=torch.float32)
update = adjustment(x, direction, coefficient=-0.25)
expected = torch.full((2, 3, 1), -0.25, dtype=torch.float32) * direction
torch.testing.assert_close(update.float(), expected)
assert update.dtype == x.dtype
per_position = torch.arange(6, dtype=torch.float32).reshape(2, 3)
per_position_update = adjustment(x, direction, coefficient=per_position)
torch.testing.assert_close(per_position_update.float(), per_position.unsqueeze(-1) * direction)
def test_calibration_summary_and_signed_layer_grid_are_json_safe():
torch.manual_seed(13)
delta = torch.randn(3, 5)
x = torch.randn(2, 4, 5)
summary = calibrate_layer(delta, x)
assert len(summary["direction"]) == 3
assert len(summary["rank1_gate_vector"]) == 5
assert summary["activation_tokens"] == 8
assert summary["projection_rms"] >= 0
assert summary["constant_residual_energy_fraction"] >= 0
assert summary["coefficient_grid"] == sorted(summary["coefficient_grid"])
assert summary["coefficient_grid"][0] < 0 < summary["coefficient_grid"][-1]
assert coefficient_grid(2.0) == [-4.0, -2.0, 0.0, 2.0, 4.0]
grid = controller_grid({15: 1.0, 19: 2.0})
assert len(grid) == 25
assert set(grid[0]) == {"15", "19"}
assert any(row["15"] < 0 and row["19"] > 0 for row in grid)
def test_behavioral_grid_selection_uses_score_then_stable_tie_break():
results = [
{"coefficients": {"15": -1.0, "19": 2.0}, "correct": 3},
{"coefficients": {"15": 0.0, "19": 1.0}, "correct": 4},
{"coefficients": {"15": 1.0, "19": 0.0}, "correct": 4},
]
selected = select_behavioral_controller(results, {15: 0.2, 19: 0.9})
assert selected == results[1]
def test_validation_rejects_bad_shapes_and_zero_directions():
with pytest.raises(ValueError, match="2D"):
decompose(torch.ones(5))
with pytest.raises(ValueError, match="non-zero"):
decompose(torch.zeros(2, 3))
with pytest.raises(ValueError, match="activation width"):
fit_signed_constant(torch.ones(2, 3), torch.ones(4, 2))
with pytest.raises(ValueError, match="non-zero"):
adjustment(torch.ones(2, 3), torch.zeros(4), coefficient=1.0)
with pytest.raises(ValueError, match="gate_vector width"):
adjustment(torch.ones(2, 3), torch.ones(4), gate_vector=torch.ones(5))
with pytest.raises(ValueError, match="exactly one"):
make_output_hook(torch.ones(4))
def test_output_hook_preserves_tuple_and_applies_rank_one_update():
class Identity(torch.nn.Module):
def __init__(self):
super().__init__()
self.proj = torch.nn.Linear(3, 2, bias=False)
def forward(self, x):
return self.proj(x), "aux"
module = Identity()
x = torch.randn(2, 3)
direction = torch.tensor([1.0, -0.5])
gate_vector = torch.tensor([0.25, 2.0, -1.0])
state = {}
handle = module.register_forward_hook(
make_output_hook(direction, gate_vector=gate_vector, state=state)
)
try:
output, aux = module(x)
finally:
handle.remove()
expected = module.proj(x) + adjustment(x, direction, gate_vector=gate_vector)
torch.testing.assert_close(output, expected)
assert aux == "aux"
assert state["calls"] == 1
def test_vllm_hook_helpers_install_read_and_remove_layer_controller():
class Pair(torch.nn.Module):
def __init__(self):
super().__init__()
self.weight = torch.nn.Parameter(torch.eye(3))
def forward(self, x):
return x, None
class Block(torch.nn.Module):
def __init__(self):
super().__init__()
self.mlp = torch.nn.Module()
self.mlp.down_proj = Pair()
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.layers = torch.nn.ModuleList([Block(), Block()])
model = Model()
installed = install_vllm_hooks(model, [{"layer": 1, "direction": [1.0, 0.0, 0.0], "coefficient": -0.5}])
assert installed == [{"module": "layers.1.mlp.down_proj", "layer": 1, "mode": "constant"}]
y, aux = model.layers[1].mlp.down_proj(torch.zeros(2, 3))
torch.testing.assert_close(y[:, 0], torch.full((2,), -0.5))
assert aux is None
assert read_vllm_hook_stats(model)["layers.1.mlp.down_proj"]["calls"] == 1
assert remove_vllm_hooks(model) == ["layers.1.mlp.down_proj"]
assert read_vllm_hook_stats(model) == {}
def test_output_hook_does_not_repeat_gpu_scalar_validations_per_call():
x = torch.zeros(2, 3)
output = torch.zeros(2, 2)
with patch("src.gate_controls.torch.isfinite", wraps=torch.isfinite) as finite, patch(
"src.gate_controls.torch.linalg.vector_norm", wraps=torch.linalg.vector_norm
) as norm:
hook = make_output_hook(torch.tensor([1.0, 0.0]), coefficient=-0.25)
finite_after_install = finite.call_count
norm_after_install = norm.call_count
hook(None, (x,), output)
hook(None, (x,), output)
assert finite.call_count == finite_after_install
assert norm.call_count == norm_after_install