File size: 10,921 Bytes
cb8c6af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Single-request online controllers for ModelClinic Experiment 001D.

The hook counts input-token rows independently in each target layer.  When a
prompt is replayed, it leaves all but the final fixed-prefix token untouched;
the controller begins at that final token and continues during decode.  The
runner uses one request at a time so each hook state has an unambiguous
relative continuation position.
"""

from __future__ import annotations

from typing import Mapping

import torch
import torch.nn.functional as F


LAYERS = (15, 19)


def expected_active_positions(generated_token_ids, eos_token_id=None) -> int:
    """Return vLLM hook rows expected for a generated output.

    vLLM 0.33.0 forwards the terminal EOS once more through the model when it
    is included in ``RequestOutput.token_ids``.  That final row has no sampled
    successor, but it is a real hook execution and should be counted.
    """
    token_ids = [int(value) for value in generated_token_ids]
    terminal_eos_seen = eos_token_id is not None and int(eos_token_id) in token_ids
    return len(token_ids) + int(terminal_eos_seen)


def _find_down_projection(model, layer: int):
    suffix = f"layers.{layer}.mlp.down_proj"
    matches = [(name, module) for name, module in model.named_modules() if name.endswith(suffix)]
    if len(matches) != 1:
        raise RuntimeError(f"expected exactly one {suffix}, found {[name for name, _ in matches]}")
    return matches[0]


def _tensor_from(config: Mapping, key: str, device: torch.device) -> torch.Tensor:
    value = config[key]
    return torch.as_tensor(value, device=device, dtype=torch.float32)


def install_controller_hooks(model, config: Mapping) -> list[dict]:
    """Install a base, observer, edit, constant, dynamic, or donor controller.

    `prefix_length` is the complete frozen token-prefix length.  The first
    active model input is its final token, so `active_start = prefix_length-1`.
    Donor coefficient arrays are frozen before target generation and indexed
    by relative active position; they never inspect target future tokens.
    """
    mode = str(config["mode"])
    prefix_length = int(config["prefix_length"])
    if prefix_length < 1:
        raise ValueError("prefix_length must be positive")
    if mode not in {"base", "observe", "edit", "constant", "dynamic", "donor"}:
        raise ValueError(f"unknown controller mode: {mode}")
    installed = []
    try:
        for layer in LAYERS:
            name, module = _find_down_projection(model, layer)
            if hasattr(module, "_modelclinic_e001d_handle"):
                raise RuntimeError(f"an Experiment 001D hook is already installed on {name}")
            device = module.weight.device
            data = config["layers"][str(layer)]
            direction = _tensor_from(data, "direction", device)
            gate_vector = _tensor_from(data, "gate_vector", device)
            if direction.ndim != 1 or gate_vector.ndim != 1:
                raise ValueError(f"layer {layer} direction and gate vector must be 1D")
            if direction.numel() != module.weight.shape[0]:
                raise ValueError(f"layer {layer} direction width mismatch")
            if gate_vector.numel() != module.weight.shape[1]:
                raise ValueError(f"layer {layer} gate-vector width mismatch")
            state = {
                "mode": mode,
                "layer": layer,
                "prefix_length": prefix_length,
                "active_start": prefix_length - 1,
                "positions_seen": 0,
                "active_positions": 0,
                "gate_scalar_values": [],
                "donor_scalar_values": [],
                "perturbation_norm_values": [],
                "base_output_norm_values": [],
                "relative_perturbation_norm_values": [],
                "hook_calls": 0,
                "direction": direction,
                "gate_vector": gate_vector,
                "constant": float(data.get("constant", 0.0)),
                "donor_coefficients": [float(x) for x in data.get("donor_coefficients", [])],
                "donor_scale": float(data.get("donor_scale", 1.0)),
                "donor_offset": float(data.get("donor_offset", 0.0)),
            }
            edited_weight = None
            if mode == "edit":
                from safetensors import safe_open

                edited_path = str(config["edited_checkpoint_path"])
                key = f"model.language_model.layers.{layer}.mlp.down_proj.weight"
                with safe_open(edited_path, framework="pt", device="cpu") as handle:
                    edited_weight = handle.get_tensor(key).to(device=device, dtype=module.weight.dtype)
                if tuple(edited_weight.shape) != tuple(module.weight.shape):
                    raise ValueError(f"layer {layer} edited weight shape mismatch")
                state["edited_weight"] = edited_weight

            if mode == "donor" and not state["donor_coefficients"]:
                raise ValueError(f"layer {layer} donor stream is empty")

            def hook(_module, args, output, _state=state):
                x = args[0]
                y = output[0] if isinstance(output, tuple) else output
                if x.shape[:-1] != y.shape[:-1]:
                    raise RuntimeError(
                        f"layer {_state['layer']} input/output leading dimensions differ: "
                        f"{tuple(x.shape)} vs {tuple(y.shape)}"
                    )
                xf = x.reshape(-1, x.shape[-1])
                yf = y.reshape(-1, y.shape[-1])
                if xf.shape[0] != yf.shape[0]:
                    raise RuntimeError("flattened input/output token-row counts differ")
                result = yf.clone() if _state["mode"] in {"edit", "constant", "dynamic", "donor"} else yf
                for row in range(xf.shape[0]):
                    absolute_position = _state["positions_seen"]
                    _state["positions_seen"] += 1
                    _state["hook_calls"] += 1
                    if absolute_position < _state["active_start"]:
                        continue
                    active_index = absolute_position - _state["active_start"]
                    current_scalar = torch.dot(
                        xf[row].float(), _state["gate_vector"]
                    )
                    _state["gate_scalar_values"].append(current_scalar.detach())
                    base_norm = torch.linalg.vector_norm(yf[row].float())
                    _state["base_output_norm_values"].append(base_norm.detach())
                    applied_scalar = None
                    delta = None
                    if _state["mode"] == "edit":
                        edited = F.linear(xf[row : row + 1], _state["edited_weight"])[0]
                        delta = edited.float() - yf[row].float()
                        result[row] = edited
                    elif _state["mode"] == "constant":
                        applied_scalar = _state["constant"]
                        delta = applied_scalar * _state["direction"]
                    elif _state["mode"] == "dynamic":
                        applied_scalar = current_scalar
                        delta = applied_scalar * _state["direction"]
                    elif _state["mode"] == "donor":
                        if active_index >= len(_state["donor_coefficients"]):
                            raise RuntimeError(
                                f"layer {_state['layer']} donor stream ended at {active_index}"
                            )
                        raw_donor = _state["donor_coefficients"][active_index]
                        applied_scalar = (
                            _state["donor_scale"] * raw_donor + _state["donor_offset"]
                        )
                        donor_tensor = torch.as_tensor(
                            applied_scalar, device=xf.device, dtype=torch.float32
                        )
                        _state["donor_scalar_values"].append(donor_tensor.detach())
                        delta = donor_tensor * _state["direction"]
                    elif _state["mode"] in {"base", "observe"}:
                        delta = torch.zeros_like(_state["direction"])
                    if delta is None:
                        raise RuntimeError("controller did not produce an update")
                    delta = delta.to(device=yf.device, dtype=yf.dtype)
                    delta_norm = torch.linalg.vector_norm(delta.float())
                    _state["perturbation_norm_values"].append(delta_norm.detach())
                    _state["relative_perturbation_norm_values"].append(
                        (delta_norm / base_norm.clamp_min(1e-12)).detach()
                    )
                    if _state["mode"] in {"constant", "dynamic", "donor"}:
                        result[row] = yf[row] + delta
                    _state["active_positions"] += 1
                shaped = result.reshape_as(y)
                if isinstance(output, tuple):
                    return (shaped, *output[1:])
                return shaped

            handle = module.register_forward_hook(hook)
            module._modelclinic_e001d_handle = handle
            module._modelclinic_e001d_state = state
            installed.append({"module": name, "layer": layer, "mode": mode})
    except Exception:
        remove_controller_hooks(model)
        raise
    return installed


def read_controller_stats(model) -> dict:
    result = {}
    tensor_fields = {
        "gate_scalar_values": "gate_scalar",
        "donor_scalar_values": "donor_scalar",
        "perturbation_norm_values": "perturbation_norm",
        "base_output_norm_values": "base_output_norm",
        "relative_perturbation_norm_values": "relative_perturbation_norm",
    }
    for _name, module in model.named_modules():
        state = getattr(module, "_modelclinic_e001d_state", None)
        if state is None:
            continue
        row = {}
        for key, value in state.items():
            if key in {"direction", "gate_vector", "edited_weight"} or key in tensor_fields:
                continue
            row[key] = value
        for source_key, output_key in tensor_fields.items():
            values = state[source_key]
            if values:
                row[output_key] = torch.stack(values).detach().float().cpu().tolist()
            else:
                row[output_key] = []
        result[str(state["layer"])] = row
    return result


def remove_controller_hooks(model) -> list[str]:
    removed = []
    for name, module in model.named_modules():
        handle = getattr(module, "_modelclinic_e001d_handle", None)
        if handle is None:
            continue
        handle.remove()
        delattr(module, "_modelclinic_e001d_handle")
        delattr(module, "_modelclinic_e001d_state")
        removed.append(name)
    return removed