File size: 8,471 Bytes
87cc7f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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